d87d836e7861ce7624e4afe04443932291c64104
[occt.git] / src / BinLDrivers / BinLDrivers_DocumentRetrievalDriver.cxx
1 // Created on: 2002-10-31
2 // Created by: Michael SAZONOV
3 // Copyright (c) 2002-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16
17 #include <BinLDrivers.hxx>
18 #include <BinLDrivers_DocumentRetrievalDriver.hxx>
19 #include <BinLDrivers_DocumentSection.hxx>
20 #include <BinLDrivers_Marker.hxx>
21 #include <BinMDataStd.hxx>
22 #include <BinMDF_ADriver.hxx>
23 #include <BinMDF_ADriverTable.hxx>
24 #include <BinObjMgt_Persistent.hxx>
25 #include <CDM_Application.hxx>
26 #include <CDM_Document.hxx>
27 #include <Message_Messenger.hxx>
28 #include <FSD_BinaryFile.hxx>
29 #include <FSD_FileHeader.hxx>
30 #include <OSD_OpenFile.hxx>
31 #include <PCDM_Document.hxx>
32 #include <PCDM_ReadWriter.hxx>
33 #include <Standard_ErrorHandler.hxx>
34 #include <Standard_Stream.hxx>
35 #include <Standard_Type.hxx>
36 #include <Storage_HeaderData.hxx>
37 #include <Storage_Schema.hxx>
38 #include <TCollection_AsciiString.hxx>
39 #include <TCollection_ExtendedString.hxx>
40 #include <TDF_Attribute.hxx>
41 #include <TDF_Data.hxx>
42 #include <TDF_Label.hxx>
43 #include <TDocStd_Document.hxx>
44 #include <TDocStd_Owner.hxx>
45
46 IMPLEMENT_STANDARD_RTTIEXT(BinLDrivers_DocumentRetrievalDriver,PCDM_RetrievalDriver)
47
48 #define SHAPESECTION_POS "SHAPE_SECTION_POS:"
49 #define SIZEOFSHAPELABEL  18
50
51 #define DATATYPE_MIGRATION
52 //#define DATATYPE_MIGRATION_DEB
53 //=======================================================================
54 //function : BinLDrivers_DocumentRetrievalDriver
55 //purpose  : Constructor
56 //=======================================================================
57
58 BinLDrivers_DocumentRetrievalDriver::BinLDrivers_DocumentRetrievalDriver ()
59 {
60   myReaderStatus = PCDM_RS_OK;
61 }
62
63 //=======================================================================
64 //function : CreateDocument
65 //purpose  : pure virtual method definition
66 //=======================================================================
67
68 Handle(CDM_Document) BinLDrivers_DocumentRetrievalDriver::CreateDocument()
69 {
70   return new TDocStd_Document(PCDM_RetrievalDriver::GetFormat());
71 }
72
73 //=======================================================================
74 //function : Read
75 //purpose  :
76 //=======================================================================
77 void BinLDrivers_DocumentRetrievalDriver::Read
78                          (const TCollection_ExtendedString& theFileName,
79                           const Handle(CDM_Document)&       theNewDocument,
80                           const Handle(CDM_Application)&    theApplication)
81 {
82   std::ifstream aFileStream;
83   OSD_OpenStream (aFileStream, theFileName, std::ios::in | std::ios::binary);
84
85   if (aFileStream.is_open() && aFileStream.good())
86   {
87     Handle(Storage_Data) dData;
88     TCollection_ExtendedString aFormat = PCDM_ReadWriter::FileFormat (aFileStream, dData);
89
90     Read (aFileStream, dData, theNewDocument, theApplication);
91   }
92   else
93   {
94     myReaderStatus = PCDM_RS_OpenError;
95   }
96 }
97
98 #define MODIFICATION_COUNTER "MODIFICATION_COUNTER: "
99 #define REFERENCE_COUNTER "REFERENCE_COUNTER: "
100
101 #define START_TYPES "START_TYPES"
102 #define END_TYPES "END_TYPES"
103
104 //=======================================================================
105 //function : Read
106 //purpose  :
107 //=======================================================================
108 void BinLDrivers_DocumentRetrievalDriver::Read (Standard_IStream&               theIStream,
109                                                 const Handle(Storage_Data)&     theStorageData,
110                                                 const Handle(CDM_Document)&     theDoc,
111                                                 const Handle(CDM_Application)&  theApplication)
112 {
113   myReaderStatus = PCDM_RS_DriverFailure;
114   myMsgDriver = theApplication -> MessageDriver();
115
116   const TCollection_ExtendedString aMethStr
117     ("BinLDrivers_DocumentRetrievalDriver: ");
118
119   Handle(TDocStd_Document) aDoc =
120     Handle(TDocStd_Document)::DownCast(theDoc);
121   if (aDoc.IsNull()) {
122 #ifdef OCCT_DEBUG
123     myMsgDriver->Send (aMethStr + "error: null document", Message_Fail);
124 #endif
125     myReaderStatus = PCDM_RS_NoDocument;
126     return;
127   }
128
129   // 1. the information section
130   Handle(Storage_HeaderData) aHeaderData;
131   
132   if (!theStorageData.IsNull())
133   {
134     aHeaderData = theStorageData->HeaderData();
135   }
136
137   if (!aHeaderData.IsNull())
138   {
139     for (Standard_Integer i = 1; i <= aHeaderData->UserInfo().Length(); i++)
140     {
141       const TCollection_AsciiString& aLine = aHeaderData->UserInfo().Value(i);
142
143       if(aLine.Search(REFERENCE_COUNTER) != -1)
144       {
145         theDoc->SetReferenceCounter (aLine.Token(" ", 2).IntegerValue());
146       }
147       else if(aLine.Search(MODIFICATION_COUNTER) != -1)
148       {
149         theDoc->SetModifications (aLine.Token(" ", 2).IntegerValue());
150       }
151     }
152   }
153
154   // 1.a Version of writer
155   if (!aHeaderData->StorageVersion().IsIntegerValue()) {
156     // file has no format version
157     myMsgDriver->Send (aMethStr + "error: file has no format version", Message_Fail);
158     myReaderStatus = PCDM_RS_FormatFailure;
159     return;
160   }
161   Standard_Integer aFileVer = aHeaderData->StorageVersion().IntegerValue();
162   Standard_Integer aCurrVer = BinLDrivers::StorageVersion().IntegerValue();
163   // maintain one-way compatibility starting from version 2+
164   if (!CheckDocumentVersion(aFileVer, aCurrVer)) {
165     myReaderStatus = PCDM_RS_NoVersion;
166     // file was written with another version
167     myMsgDriver->Send (aMethStr + "error: wrong file version: " +
168                  aHeaderData->StorageVersion() + " while current is " +
169                  BinLDrivers::StorageVersion(), Message_Fail);
170     return;
171   }
172
173   // 1.b Retrieve the Types table
174   TColStd_SequenceOfAsciiString aTypeNames; //Sequence of types in file
175   const TColStd_SequenceOfAsciiString& aUserInfo = aHeaderData->UserInfo();
176   Standard_Boolean begin = Standard_False;
177   Standard_Integer i;
178   for (i=1; i <= aUserInfo.Length(); i++) {
179     //const TCollection_AsciiString& aStr = aUserInfo(i);
180     TCollection_AsciiString aStr = aUserInfo(i);
181     if (aStr == START_TYPES)
182       begin = Standard_True;
183     else if (aStr == END_TYPES)
184       break;
185     else if (begin) {
186       if ( aFileVer < 8 ) {
187 #ifdef DATATYPE_MIGRATION
188         TCollection_AsciiString  newName;       
189         if(Storage_Schema::CheckTypeMigration(aStr, newName)) {
190 #ifdef OCCT_DEBUG
191           std::cout << "CheckTypeMigration:OldType = " <<aStr << " Len = "<<aStr.Length()<<std::endl;
192           std::cout << "CheckTypeMigration:NewType = " <<newName  << " Len = "<< newName.Length()<<std::endl;
193 #endif
194           aStr = newName;
195         }
196 #endif  
197       } 
198       aTypeNames.Append (aStr);    
199     }
200   }
201   if (myDrivers.IsNull())
202     myDrivers = AttributeDrivers (myMsgDriver);
203   myDrivers->AssignIds (aTypeNames); 
204
205   // recognize types not supported by drivers
206   myMapUnsupported.Clear();
207   for (i=1; i <= aTypeNames.Length(); i++)
208     if (myDrivers->GetDriver(i).IsNull()) 
209       myMapUnsupported.Add(i);
210   if (!myMapUnsupported.IsEmpty()) {
211     myMsgDriver->Send (aMethStr + "warning: "
212                   "the following attributes have no driver:", Message_Warning);
213     for (i=1; i <= aTypeNames.Length(); i++)
214       if (myMapUnsupported.Contains(i))
215         myMsgDriver->Send (aTypeNames(i), Message_Warning);
216   }
217
218   // 2. Read document contents
219   // 2a. Retrieve data from the stream:
220   myRelocTable.Clear();
221   myRelocTable.SetHeaderData(aHeaderData);
222   mySections.Clear();
223   myPAtt.Init();
224   Handle(TDF_Data) aData = new TDF_Data();
225   std::streampos aDocumentPos = -1;
226
227   // 2b. Read the TOC of Sections
228   if (aFileVer >= 3) {
229     BinLDrivers_DocumentSection aSection;
230     do {
231       BinLDrivers_DocumentSection::ReadTOC (aSection, theIStream, aFileVer);
232       mySections.Append(aSection);
233     } while(!aSection.Name().IsEqual((Standard_CString)SHAPESECTION_POS) && !theIStream.eof());
234
235     if (theIStream.eof()) {
236       // There is no shape section in the file.
237       myMsgDriver->Send (aMethStr + "error: shape section is not found", Message_Fail);
238       myReaderStatus = PCDM_RS_ReaderException;
239       return;
240     }
241
242     aDocumentPos = theIStream.tellg(); // position of root label
243
244     BinLDrivers_VectorOfDocumentSection::Iterator anIterS (mySections);
245     for (; anIterS.More(); anIterS.Next()) {
246       BinLDrivers_DocumentSection& aCurSection = anIterS.ChangeValue();
247       if (aCurSection.IsPostRead() == Standard_False) {
248         theIStream.seekg ((std::streampos) aCurSection.Offset());
249         if (aCurSection.Name().IsEqual ((Standard_CString)SHAPESECTION_POS)) 
250           ReadShapeSection (aCurSection, theIStream);
251         else
252           ReadSection (aCurSection, theDoc, theIStream); 
253       }
254     }
255   } else { //aFileVer < 3
256     aDocumentPos = theIStream.tellg(); // position of root label
257
258     // retrieve SHAPESECTION_POS string
259     char aShapeSecLabel[SIZEOFSHAPELABEL + 1];
260     aShapeSecLabel[SIZEOFSHAPELABEL] = 0x00;
261     theIStream.read ((char*)&aShapeSecLabel, SIZEOFSHAPELABEL);// SHAPESECTION_POS
262     TCollection_AsciiString aShapeLabel(aShapeSecLabel);
263     // detect if a file was written in old fashion (version 2 without shapes)
264     // and if so then skip reading ShapeSection
265     if (aShapeLabel.Length() > 0) {
266       // version 2+(with shapes) and higher goes here
267       if(aShapeLabel.Length() <= 0 || aShapeLabel != SHAPESECTION_POS) {
268         myMsgDriver->Send (aMethStr + "error: Format failure", Message_Fail);
269         myReaderStatus = PCDM_RS_FormatFailure;
270         return;
271       }
272
273       // retrieve ShapeSection Position
274       Standard_Integer aShapeSectionPos; // go to ShapeSection
275       theIStream.read ((char*)&aShapeSectionPos, sizeof(Standard_Integer));
276
277 #if DO_INVERSE
278       aShapeSectionPos = InverseInt (aShapeSectionPos);
279 #endif
280 #ifdef OCCT_DEBUG
281       std::cout <<"aShapeSectionPos = " <<aShapeSectionPos <<std::endl;
282 #endif
283       if(aShapeSectionPos) { 
284         aDocumentPos = theIStream.tellg();
285         theIStream.seekg((std::streampos) aShapeSectionPos);
286
287         CheckShapeSection(aShapeSectionPos, theIStream);
288         // Read Shapes
289         BinLDrivers_DocumentSection aCurSection;
290         ReadShapeSection (aCurSection, theIStream, Standard_False);
291       }
292     }
293   } // end of reading Sections or shape section
294
295   // Return to read of the Document structure
296   theIStream.seekg(aDocumentPos);
297
298   // read the header (tag) of the root label
299   Standard_Integer aTag;
300   theIStream.read ((char*)&aTag, sizeof(Standard_Integer));
301
302   // read sub-tree of the root label
303   Standard_Integer nbRead = ReadSubTree (theIStream, aData->Root());
304   Clear();
305     
306   if (nbRead > 0) {
307     // attach data to the document
308     aDoc->SetData (aData);
309     TDocStd_Owner::SetDocument (aData, aDoc);
310     aDoc->SetComments(aHeaderData->Comments());
311     myReaderStatus = PCDM_RS_OK;
312   }
313
314   // Read Sections (post-reading type)
315   if (aFileVer >= 3) {
316     BinLDrivers_VectorOfDocumentSection::Iterator aSectIter (mySections);
317     for (; aSectIter.More(); aSectIter.Next()) {
318       BinLDrivers_DocumentSection& aCurSection = aSectIter.ChangeValue();
319       if (aCurSection.IsPostRead()) {
320         theIStream.seekg ((std::streampos) aCurSection.Offset());
321         ReadSection (aCurSection, theDoc, theIStream); 
322       }
323     }
324   }
325 }
326
327 //=======================================================================
328 //function : ReadSubTree
329 //purpose  :
330 //=======================================================================
331
332 Standard_Integer BinLDrivers_DocumentRetrievalDriver::ReadSubTree
333                          (Standard_IStream& theIS,
334                           const TDF_Label&  theLabel)
335 {
336   Standard_Integer nbRead = 0;
337   TCollection_ExtendedString aMethStr
338     ("BinLDrivers_DocumentRetrievalDriver: ");
339
340   // Read attributes:
341   theIS >> myPAtt;
342   while (theIS && myPAtt.TypeId() > 0 &&             // not an end marker ?
343          myPAtt.Id() > 0 &&                          // not a garbage ?
344          !theIS.eof()) {
345     // get a driver according to TypeId
346     Handle(BinMDF_ADriver) aDriver = myDrivers->GetDriver (myPAtt.TypeId());
347     if (!aDriver.IsNull()) {
348       // create transient attribute
349       nbRead++;
350       Standard_Integer anID = myPAtt.Id();
351       Handle(TDF_Attribute) tAtt;
352       Standard_Boolean isBound = myRelocTable.IsBound(anID);
353       if (isBound)
354         tAtt = Handle(TDF_Attribute)::DownCast(myRelocTable.Find(anID));
355       else
356         tAtt = aDriver->NewEmpty();
357
358       if (tAtt->Label().IsNull())
359       {
360         try
361         {
362           theLabel.AddAttribute (tAtt);
363         }
364         catch (const Standard_DomainError&)
365         {
366           // For attributes that can have arbitrary GUID (e.g. TDataStd_Integer), exception
367           // will be raised in valid case if attribute of that type with default GUID is already
368           // present  on the same label; the reason is that actual GUID will be read later.
369           // To avoid this, set invalid (null) GUID to the newly added attribute (see #29669)
370           static const Standard_GUID fbidGuid;
371           tAtt->SetID (fbidGuid);
372           theLabel.AddAttribute (tAtt);
373         }
374       }
375       else
376         myMsgDriver->Send (aMethStr +
377                      "warning: attempt to attach attribute " +
378                      aDriver->TypeName() + " to a second label", Message_Warning);
379
380       Standard_Boolean ok = aDriver->Paste (myPAtt, tAtt, myRelocTable);
381       if (!ok) {
382         // error converting persistent to transient
383         myMsgDriver->Send (aMethStr + "warning: failure reading attribute " +
384                       aDriver->TypeName(), Message_Warning);
385       }
386       else if (!isBound)
387         myRelocTable.Bind (anID, tAtt);
388     }
389     else if (!myMapUnsupported.Contains(myPAtt.TypeId()))
390       myMsgDriver->Send (aMethStr + "warning: type ID not registered in header: "
391                     + myPAtt.TypeId(), Message_Warning);
392
393     // read next attribute
394     theIS >> myPAtt;
395   }
396   if (!theIS || myPAtt.TypeId() != BinLDrivers_ENDATTRLIST) {
397     // unexpected EOF or garbage data
398     myMsgDriver->Send (aMethStr + "error: unexpected EOF or garbage data", Message_Fail);
399     myReaderStatus = PCDM_RS_UnrecognizedFileFormat;
400     return -1;
401   }
402
403   // Read children:
404   // read the tag of a child label
405   Standard_Integer aTag = BinLDrivers_ENDLABEL;
406   theIS.read ((char*) &aTag, sizeof(Standard_Integer));
407 #if DO_INVERSE
408   aTag = InverseInt (aTag);
409 #endif
410   while (theIS && aTag >= 0 && !theIS.eof()) { // not an end marker ?
411     // create sub-label
412     TDF_Label aLab = theLabel.FindChild (aTag, Standard_True);
413
414     // read sub-tree
415     Standard_Integer nbSubRead = ReadSubTree(theIS, aLab);
416     // check for error
417     if (nbSubRead == -1)
418       return -1;
419     nbRead += nbSubRead;
420
421     // read the tag of the next child
422     theIS.read ((char*) &aTag, sizeof(Standard_Integer));
423 #if DO_INVERSE
424     aTag = InverseInt (aTag);
425 #endif
426   }
427   if (aTag != BinLDrivers_ENDLABEL) {
428     // invalid end label marker
429     myMsgDriver->Send (aMethStr + "error: invalid end label marker", Message_Fail);
430     myReaderStatus = PCDM_RS_UnrecognizedFileFormat;
431     return -1;
432   }
433
434   return nbRead;
435 }
436
437 //=======================================================================
438 //function : AttributeDrivers
439 //purpose  :
440 //=======================================================================
441
442 Handle(BinMDF_ADriverTable) BinLDrivers_DocumentRetrievalDriver::AttributeDrivers
443        (const Handle(Message_Messenger)& theMessageDriver)
444 {
445   return BinLDrivers::AttributeDrivers (theMessageDriver);
446 }
447
448 //=======================================================================
449 //function : ReadSection
450 //purpose  : 
451 //=======================================================================
452
453 void BinLDrivers_DocumentRetrievalDriver::ReadSection
454                                 (BinLDrivers_DocumentSection& /*theSection*/,
455                                  const Handle(CDM_Document)&  /*theDocument*/,
456                                  Standard_IStream&            /*theIS*/)
457 {
458   // empty; should be redefined in subclasses
459 }
460
461 //=======================================================================
462 //function : ReadShapeSection
463 //purpose  : 
464 //=======================================================================
465
466 void BinLDrivers_DocumentRetrievalDriver::ReadShapeSection
467                               (BinLDrivers_DocumentSection& theSection,
468                               Standard_IStream&            /*theIS*/,
469                               const Standard_Boolean isMess)
470
471 {
472   if(isMess && theSection.Length()) {
473     const TCollection_ExtendedString aMethStr ("BinLDrivers_DocumentRetrievalDriver: ");
474     myMsgDriver->Send (aMethStr + "warning: Geometry is not supported by Lite schema. ", Message_Warning);
475   }
476 }
477
478 //=======================================================================
479 //function : CheckShapeSection
480 //purpose  : 
481 //=======================================================================
482 void BinLDrivers_DocumentRetrievalDriver::CheckShapeSection(
483                                           const Storage_Position& ShapeSectionPos, 
484                                           Standard_IStream& IS)
485 {
486   if (!IS.eof())
487   {
488     const std::streamoff endPos = IS.rdbuf()->pubseekoff(0L, std::ios_base::end, std::ios_base::in);
489 #ifdef OCCT_DEBUG
490     std::cout << "endPos = " << endPos <<std::endl;
491 #endif
492     if(ShapeSectionPos != endPos) {
493       const TCollection_ExtendedString aMethStr ("BinLDrivers_DocumentRetrievalDriver: ");
494       myMsgDriver->Send (aMethStr + "warning: Geometry is not supported by Lite schema. ", Message_Warning);
495     }
496   }
497 }
498
499 //=======================================================================
500 //function : Clear
501 //purpose  : 
502 //=======================================================================
503 void BinLDrivers_DocumentRetrievalDriver::Clear()
504 {
505   myPAtt.Destroy();    // free buffer
506   myRelocTable.Clear();
507   myMapUnsupported.Clear();
508 }
509
510 //=======================================================================
511 //function : CheckDocumentVersion
512 //purpose  : 
513 //=======================================================================
514 Standard_Boolean BinLDrivers_DocumentRetrievalDriver::CheckDocumentVersion(
515                                                           const Standard_Integer theFileVersion,
516                                                           const Standard_Integer theCurVersion)
517 {
518   if (theFileVersion < 2 || theFileVersion > theCurVersion) {
519     // file was written with another version
520     return Standard_False;
521   }
522   return Standard_True;
523 }