summaryrefslogtreecommitdiff
path: root/src/BinLDrivers/BinLDrivers_DocumentRetrievalDriver.cxx
blob: 26f02bdf12c49f2085fcac4a45b765abc55a68a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
// File:      BinLDrivers_DocumentRetrievalDriver.cxx
// Created:   31.10.02 11:12:22
// Author:    Michael SAZONOV
// Copyright: Open CASCADE 2002

#include <BinLDrivers_DocumentRetrievalDriver.ixx>
#include <BinLDrivers.hxx>
#include <BinLDrivers_Marker.hxx>
#include <BinMDF_ADriver.hxx>
#include <BinMDataStd.hxx>
#include <BinObjMgt_Persistent.hxx>
#include <FSD_BinaryFile.hxx>
#include <FSD_FileHeader.hxx>
#include <Standard_ErrorHandler.hxx>
#include <Standard_Stream.hxx>
#include <Storage_Schema.hxx>
#include <TDF_Data.hxx>
#include <TDocStd_Document.hxx>
#include <TDocStd_Owner.hxx>

#define SHAPESECTION_POS "SHAPE_SECTION_POS:"
#define SIZEOFSHAPELABEL  18

#define DATATYPE_MIGRATION
//#define DATATYPE_MIGRATION_DEB
//=======================================================================
//function : BinLDrivers_DocumentRetrievalDriver
//purpose  : Constructor
//=======================================================================

BinLDrivers_DocumentRetrievalDriver::BinLDrivers_DocumentRetrievalDriver ()
{
  myReaderStatus = PCDM_RS_OK;
}

//=======================================================================
//function : CreateDocument
//purpose  : pure virtual method definition
//=======================================================================

Handle(CDM_Document) BinLDrivers_DocumentRetrievalDriver::CreateDocument()
{
  return new TDocStd_Document(PCDM_RetrievalDriver::GetFormat());
}

//=======================================================================
//function : SchemaName
//purpose  : pure virtual method definition
//=======================================================================

TCollection_ExtendedString BinLDrivers_DocumentRetrievalDriver::SchemaName() const
{
  TCollection_ExtendedString schemaname;
  return schemaname;
}

//=======================================================================
//function : Make
//purpose  : pure virtual method definition
//=======================================================================

void BinLDrivers_DocumentRetrievalDriver::Make (const Handle(PCDM_Document)&,
                                               const Handle(CDM_Document)&)
{
}

//=======================================================================
//function : Read
//purpose  :
//=======================================================================

#define START_TYPES "START_TYPES"
#define END_TYPES "END_TYPES"

void BinLDrivers_DocumentRetrievalDriver::Read
                         (const TCollection_ExtendedString& theFileName,
                          const Handle(CDM_Document)&       theNewDocument,
                          const Handle(CDM_Application)&    theApplication)
{
  myReaderStatus = PCDM_RS_DriverFailure;
  myMsgDriver = theApplication -> MessageDriver();

  const TCollection_ExtendedString aMethStr
    ("BinLDrivers_DocumentRetrievalDriver: ");

  Handle(TDocStd_Document) aDoc =
    Handle(TDocStd_Document)::DownCast(theNewDocument);
  if (aDoc.IsNull()) {
#ifdef DEB
    WriteMessage (aMethStr + "error: null document");
#endif
    myReaderStatus = PCDM_RS_NoDocument;
    return;
  }

  TCollection_AsciiString aFileName (theFileName,'?');

  // 1. Read the information section
  Handle(Storage_HeaderData) aHeaderData;
  Storage_Position anInfoSectionEnd = ReadInfoSection( aFileName, aHeaderData );
  if (!anInfoSectionEnd) {
    WriteMessage (aMethStr + "error: file has invalid header");
    myReaderStatus = PCDM_RS_UnrecognizedFileFormat;
    return;
  }

  // 1.a Version of writer
  if (!aHeaderData->StorageVersion().IsIntegerValue()) {
    // file has no format version
    WriteMessage (aMethStr + "error: file has no format version");
    myReaderStatus = PCDM_RS_FormatFailure;
    return;
  }
  Standard_Integer aFileVer = aHeaderData->StorageVersion().IntegerValue();
  Standard_Integer aCurrVer = BinLDrivers::StorageVersion().IntegerValue();
  // maintain one-way compatibility starting from version 2+
  if (aFileVer < 2 || aFileVer > aCurrVer) {
    // file was written with another version
    WriteMessage (aMethStr + "error: wrong file version: " +
		  aHeaderData->StorageVersion() + " while current is " +
		  BinLDrivers::StorageVersion());
    myReaderStatus = PCDM_RS_NoVersion;
    return;
  }

  // 1.b Retrieve the Types table
  TColStd_SequenceOfAsciiString aTypeNames; //Sequence of types in file
  const TColStd_SequenceOfAsciiString& aUserInfo = aHeaderData->UserInfo();
  Standard_Boolean begin = Standard_False;
  Standard_Integer i;
  for (i=1; i <= aUserInfo.Length(); i++) {
    //const TCollection_AsciiString& aStr = aUserInfo(i);
    TCollection_AsciiString aStr = aUserInfo(i);
    if (aStr == START_TYPES)
      begin = Standard_True;
    else if (aStr == END_TYPES)
      break;
    else if (begin) {
      if(aFileVer < 5) {
#ifdef DATATYPE_MIGRATION
	TCollection_AsciiString  newName;	
	if(Storage_Schema::CheckTypeMigration(aStr, newName)) {
#ifdef DATATYPE_MIGRATION_DEB
	  cout << "CheckTypeMigration:OldType = " <<aStr << " Len = "<<aStr.Length()<<endl;
	  cout << "CheckTypeMigration:NewType = " <<newName  << " Len = "<< newName.Length()<<endl;
#endif
	  aStr = newName;
	}
#endif  
      } 
      aTypeNames.Append (aStr);    
    }
  }
  if (myDrivers.IsNull())
    myDrivers = AttributeDrivers (myMsgDriver);
  myDrivers->AssignIds (aTypeNames); 

  // recognize types not supported by drivers
  myMapUnsupported.Clear();
  for (i=1; i <= aTypeNames.Length(); i++)
    if (myDrivers->GetDriver(i).IsNull()) 
      myMapUnsupported.Add(i);
  if (!myMapUnsupported.IsEmpty()) {
    WriteMessage (aMethStr + "warning: "
                  "the following attributes have no driver:");
    for (i=1; i <= aTypeNames.Length(); i++)
      if (myMapUnsupported.Contains(i))
	WriteMessage (aTypeNames(i));
  }

  // Open the file stream
#ifdef WNT
  ifstream anIS (aFileName.ToCString(), ios::in | ios::binary);
#else
  ifstream anIS (aFileName.ToCString());
#endif

  if (!anIS) {
    // Can not open file
    WriteMessage (aMethStr + "error: can't open file " + theFileName);
    myReaderStatus = PCDM_RS_OpenError;
    return;
  }

  // skip info section
  anIS.seekg( (streampos) anInfoSectionEnd );

  // propagate the opened document version to data drivers
  PropagateDocumentVersion(aFileVer);

  // 2. Read document contents

  // 2a. Retrieve data from the stream:
  myRelocTable.Clear();
  mySections.Clear();
  myPAtt.Init();
  Handle(TDF_Data) aData = new TDF_Data();
  std::streamoff aDocumentPos = -1;

  // 2b. Read the TOC of Sections
  if (aFileVer >= 3) {
    BinLDrivers_DocumentSection aSection;
    do {
      BinLDrivers_DocumentSection::ReadTOC (aSection, anIS);
      mySections.Append(aSection);
    } while
      (!aSection.Name().IsEqual((Standard_CString)SHAPESECTION_POS));
    aDocumentPos = anIS.tellg(); // position of root label

    BinLDrivers_VectorOfDocumentSection::Iterator anIterS (mySections);
    for (; anIterS.More(); anIterS.Next()) {
      BinLDrivers_DocumentSection& aCurSection = anIterS.ChangeValue();
      if (aCurSection.IsPostRead() == Standard_False) {
        anIS.seekg ((streampos) aCurSection.Offset());
        if (aCurSection.Name().IsEqual ((Standard_CString)SHAPESECTION_POS)) 
          ReadShapeSection (aCurSection, anIS);
        else
          ReadSection (aCurSection, theNewDocument, anIS); 
      }
    }
  } else { //aFileVer < 3
    aDocumentPos = anIS.tellg(); // position of root label

    // retrieve SHAPESECTION_POS string
    char aShapeSecLabel[SIZEOFSHAPELABEL + 1];
    aShapeSecLabel[SIZEOFSHAPELABEL] = 0x00;
    anIS.read ((char*)&aShapeSecLabel, SIZEOFSHAPELABEL);// SHAPESECTION_POS
    TCollection_AsciiString aShapeLabel(aShapeSecLabel);
    // detect if a file was written in old fashion (version 2 without shapes)
    // and if so then skip reading ShapeSection
    if (aShapeLabel.Length() > 0) {
      // version 2+(with shapes) and higher goes here
      if(aShapeLabel.Length() <= 0 || aShapeLabel != SHAPESECTION_POS) {
        WriteMessage (aMethStr + "error: Format failure");
        myReaderStatus = PCDM_RS_FormatFailure;
        return;
      }

      // retrieve ShapeSection Position
      Standard_Integer aShapeSectionPos; // go to ShapeSection
      anIS.read ((char*)&aShapeSectionPos, sizeof(Standard_Integer));

#if DO_INVERSE
      aShapeSectionPos = InverseInt (aShapeSectionPos);
#endif
#ifdef DATATYPE_MIGRATION_DEB      
      cout <<"aShapeSectionPos = " <<aShapeSectionPos <<endl;
#endif
      if(aShapeSectionPos) { 
	aDocumentPos = anIS.tellg();
	anIS.seekg((streampos) aShapeSectionPos);

	CheckShapeSection((streampos)aShapeSectionPos, anIS);
	// Read Shapes
	BinLDrivers_DocumentSection aCurSection;
	ReadShapeSection (aCurSection, anIS, Standard_False);
      }
    }
  } // end of reading Sections or shape section

  // Return to read of the Document structure
  anIS.seekg((streampos) aDocumentPos);

  // read the header (tag) of the root label
  Standard_Integer aTag;
  anIS.read ((char*)&aTag, sizeof(Standard_Integer));

  // read sub-tree of the root label
  Standard_Integer nbRead = ReadSubTree (anIS, aData->Root());
  myPAtt.Destroy();    // free buffer
  myRelocTable.Clear();
  myMapUnsupported.Clear();
    
  if (nbRead > 0) {
    // attach data to the document
    aDoc->SetData (aData);
    TDocStd_Owner::SetDocument (aData, aDoc);
    aDoc->SetComments(aHeaderData->Comments());
    myReaderStatus = PCDM_RS_OK;
  }

  // Read Sections (post-reading type)
  if (aFileVer >= 3) {
    BinLDrivers_VectorOfDocumentSection::Iterator anIterS (mySections);
    for (; anIterS.More(); anIterS.Next()) {
      BinLDrivers_DocumentSection& aCurSection = anIterS.ChangeValue();
      if (aCurSection.IsPostRead()) {
	anIS.seekg ((streampos) aCurSection.Offset());
	ReadSection (aCurSection, theNewDocument, anIS); 
      }
    }
  }
}

//=======================================================================
//function : ReadSubTree
//purpose  :
//=======================================================================

Standard_Integer BinLDrivers_DocumentRetrievalDriver::ReadSubTree
                         (Standard_IStream& theIS,
                          const TDF_Label&  theLabel)
{
  Standard_Integer nbRead = 0;
  static TCollection_ExtendedString aMethStr
    ("BinLDrivers_DocumentRetrievalDriver: ");

  // Read attributes:
  theIS >> myPAtt;
  while (theIS && myPAtt.TypeId() > 0 &&             // not an end marker ?
         myPAtt.Id() > 0) {                          // not a garbage ?
    // get a driver according to TypeId
    Handle(BinMDF_ADriver) aDriver = myDrivers->GetDriver (myPAtt.TypeId());
    if (!aDriver.IsNull()) {
      // create transient attribute
      nbRead++;
      Standard_Integer anID = myPAtt.Id();
      Handle(TDF_Attribute) tAtt;
      Standard_Boolean isBound = myRelocTable.IsBound(anID);
      if (isBound)
        tAtt = Handle(TDF_Attribute)::DownCast(myRelocTable.Find(anID));
      else
        tAtt = aDriver->NewEmpty();
      if (tAtt->Label().IsNull())
	theLabel.AddAttribute (tAtt);
      else
	WriteMessage (aMethStr +
		      "warning: attempt to attach attribute " +
		      aDriver->TypeName() + " to a second label");

      Standard_Boolean ok = aDriver->Paste (myPAtt, tAtt, myRelocTable);
      if (!ok) {
        // error converting persistent to transient
        WriteMessage (aMethStr + "warning: failure reading attribute " +
                      aDriver->TypeName());
      }
      else if (!isBound)
        myRelocTable.Bind (anID, tAtt);
    }
    else if (!myMapUnsupported.Contains(myPAtt.TypeId()))
      WriteMessage (aMethStr + "warning: type ID not registered in header: "
                    + myPAtt.TypeId());

    // read next attribute
    theIS >> myPAtt;
  }
  if (!theIS || myPAtt.TypeId() != BinLDrivers_ENDATTRLIST) {
    // unexpected EOF or garbage data
    WriteMessage (aMethStr + "error: unexpected EOF or garbage data");
    myReaderStatus = PCDM_RS_UnrecognizedFileFormat;
    return -1;
  }

  // Read children:
  // read the tag of a child label
  Standard_Integer aTag = BinLDrivers_ENDLABEL;
  theIS.read ((char*) &aTag, sizeof(Standard_Integer));
#if DO_INVERSE
  aTag = InverseInt (aTag);
#endif
  while (theIS && aTag >= 0) { // not an end marker ?
    // create sub-label
    TDF_Label aLab = theLabel.FindChild (aTag, Standard_True);

    // read sub-tree
    Standard_Integer nbSubRead = ReadSubTree(theIS, aLab);
    // check for error
    if (nbSubRead == -1)
      return -1;
    nbRead += nbSubRead;

    // read the tag of the next child
    theIS.read ((char*) &aTag, sizeof(Standard_Integer));
#if DO_INVERSE
    aTag = InverseInt (aTag);
#endif
  }
  if (aTag != BinLDrivers_ENDLABEL) {
    // invalid end label marker
    WriteMessage (aMethStr + "error: invalid end label marker");
    myReaderStatus = PCDM_RS_UnrecognizedFileFormat;
    return -1;
  }

  return nbRead;
}

//=======================================================================
//function : AttributeDrivers
//purpose  :
//=======================================================================

Handle(BinMDF_ADriverTable) BinLDrivers_DocumentRetrievalDriver::AttributeDrivers
       (const Handle(CDM_MessageDriver)& theMessageDriver)
{
  return BinLDrivers::AttributeDrivers (theMessageDriver);
}

//=======================================================================
//function : ReadInfoSection
//purpose  : Read the info  section  of  theFile, return a file
//           position corresponding to the info section end
//=======================================================================

Storage_Position BinLDrivers_DocumentRetrievalDriver::ReadInfoSection
                         (const TCollection_AsciiString& theFileName,
                          Handle(Storage_HeaderData)&    theData)
{
  TCollection_ExtendedString aMsg
    ( "BinLDrivers_DocumentRetrievalDriver: error: ");

  FSD_BinaryFile aFileDriver;
  Storage_Position aPos = 0;
  if (aFileDriver.Open( theFileName, Storage_VSRead ) == Storage_VSOk)
  {
    Storage_Schema aSchema;
    theData = aSchema.ReadHeaderSection( aFileDriver );

    if (theData->ErrorStatus() == Storage_VSOk)
      aPos = aFileDriver.Tell();
    else
      WriteMessage( aMsg + theData->ErrorStatusExtension() );
  }
  else
    WriteMessage( aMsg + "can not open file " + theFileName);

  aFileDriver.Close();

  return aPos;
}

//=======================================================================
//function : WriteMessage
//purpose  : write   theMessage   to   the   MessageDriver   of
//           theApplication
//=======================================================================

void BinLDrivers_DocumentRetrievalDriver::WriteMessage
                         (const TCollection_ExtendedString& theMsg)
{
  if (!myMsgDriver.IsNull())
    myMsgDriver->Write (theMsg.ToExtString());
}

//=======================================================================
//function : ReadSection
//purpose  : 
//=======================================================================

void BinLDrivers_DocumentRetrievalDriver::ReadSection
                                (BinLDrivers_DocumentSection& /*theSection*/,
                                 const Handle(CDM_Document)&  /*theDocument*/,
                                 Standard_IStream&            /*theIS*/)
{
  // empty; should be redefined in subclasses
}

//=======================================================================
//function : ReadShapeSection
//purpose  : 
//=======================================================================

void BinLDrivers_DocumentRetrievalDriver::ReadShapeSection
                              (BinLDrivers_DocumentSection& theSection,
                               Standard_IStream&            /*theIS*/,
			       const Standard_Boolean isMess)

{
  if(isMess && theSection.Length()) {
    const TCollection_ExtendedString aMethStr ("BinLDrivers_DocumentRetrievalDriver: ");
    WriteMessage (aMethStr + "warning: Geometry is not supported by Lite schema. ");
  }
}

//=======================================================================
//function : CheckShapeSection
//purpose  : 
//=======================================================================
void BinLDrivers_DocumentRetrievalDriver::CheckShapeSection(
				  const Storage_Position& ShapeSectionPos, 
						    Standard_IStream& IS)
{
  if(!IS.eof()) {
#if defined(WNT) || defined(OCE_HAVE_IOSTREAM)
    const Storage_Position endPos = IS.rdbuf()->pubseekoff(0L, std::ios_base::end, std::ios_base::in);
#else
    const Storage_Position endPos = IS.rdbuf()->seekoff(0L, unsafe_ios::end, unsafe_ios::in);
#endif
#ifdef DATATYPE_MIGRATION_DEB
    cout << "endPos = " << endPos <<endl;
#endif
    if(ShapeSectionPos != endPos) {
      const TCollection_ExtendedString aMethStr ("BinLDrivers_DocumentRetrievalDriver: ");
      WriteMessage (aMethStr + "warning: Geometry is not supported by Lite schema. ");
    }
  }
}

//=======================================================================
//function : PropagateDocumentVersion
//purpose  : 
//=======================================================================
void BinLDrivers_DocumentRetrievalDriver::PropagateDocumentVersion(const Standard_Integer theDocVersion )
{
  BinMDataStd::SetDocumentVersion(theDocVersion);
}