0031785: [REGRESSION] Application Framework - application crashes on reading XBF...
[occt.git] / src / XmlLDrivers / XmlLDrivers_DocumentRetrievalDriver.cxx
1 // Created on: 2001-07-09
2 // Created by: Julia DOROVSKIKH
3 // Copyright (c) 2001-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 <CDM_Application.hxx>
18 #include <CDM_Document.hxx>
19 #include <Message_Messenger.hxx>
20 #include <Message_ProgressScope.hxx>
21 #include <CDM_MetaData.hxx>
22 #include <LDOM_DocumentType.hxx>
23 #include <LDOM_LDOMImplementation.hxx>
24 #include <LDOMParser.hxx>
25 #include <OSD_Path.hxx>
26 #include <OSD_OpenFile.hxx>
27 #include <PCDM_Document.hxx>
28 #include <PCDM_DOMHeaderParser.hxx>
29 #include <Standard_Type.hxx>
30 #include <TCollection_AsciiString.hxx>
31 #include <TCollection_ExtendedString.hxx>
32 #include <TDF_Data.hxx>
33 #include <TDocStd_Document.hxx>
34 #include <TDocStd_Owner.hxx>
35 #include <UTL.hxx>
36 #include <XmlLDrivers.hxx>
37 #include <XmlLDrivers_DocumentRetrievalDriver.hxx>
38 #include <XmlMDF.hxx>
39 #include <XmlMDF_ADriver.hxx>
40 #include <XmlMDF_ADriverTable.hxx>
41 #include <XmlObjMgt.hxx>
42 #include <XmlObjMgt_Document.hxx>
43 #include <XmlObjMgt_RRelocationTable.hxx>
44
45 IMPLEMENT_STANDARD_RTTIEXT(XmlLDrivers_DocumentRetrievalDriver,PCDM_RetrievalDriver)
46
47 #ifdef _MSC_VER
48 # include <tchar.h>
49 #endif  // _MSC_VER
50
51 #include <locale.h>
52 #include <Standard_Failure.hxx>
53 #include <Standard_ErrorHandler.hxx>
54
55 #define START_REF         "START_REF"
56 #define END_REF           "END_REF"
57
58 #define MODIFICATION_COUNTER "MODIFICATION_COUNTER: "
59 #define REFERENCE_COUNTER    "REFERENCE_COUNTER: "
60
61 //#define TAKE_TIMES
62 static void take_time (const Standard_Integer, const char *,
63                        const Handle(Message_Messenger)&)
64 #ifdef TAKE_TIMES
65 ;
66 #else
67 {}
68 #endif
69
70 static Standard_Integer RemoveExtraSeparator(TCollection_AsciiString& aString) {
71
72   Standard_Integer i, j, len ;
73
74   len = aString.Length() ;
75 #ifdef _WIN32
76   // Case of network path, such as \\MACHINE\dir
77   for (i = j = 2 ; j <= len ; i++,j++) {
78 #else
79   for (i = j = 1 ; j <= len ; i++,j++) {
80 #endif
81       Standard_Character c = aString.Value(j) ;
82       aString.SetValue(i,c) ;
83       if (c == '/')
84           while(j < len && aString.Value(j+1) == '/') j++ ;
85   }
86   len = i-1 ;
87   if (aString.Value(len) == '/') len-- ;  
88   aString.Trunc(len) ;
89   return len ;
90 }
91 static TCollection_AsciiString GetDirFromFile(const TCollection_ExtendedString& aFileName) {
92   TCollection_AsciiString theCFile=UTL::CString(aFileName);
93   TCollection_AsciiString theDirectory;
94   Standard_Integer i=theCFile.SearchFromEnd("/");
95 #ifdef _WIN32    
96 //    if(i==-1) i=theCFile.SearchFromEnd("\\");
97   if(theCFile.SearchFromEnd("\\") > i)
98     i=theCFile.SearchFromEnd("\\");
99 #endif
100   if(i!=-1) theDirectory=theCFile.SubString(1,i);
101   return theDirectory;
102 }
103
104 static TCollection_AsciiString AbsolutePath(
105                             const TCollection_AsciiString& aDirPath,
106                             const TCollection_AsciiString& aRelFilePath)
107 {
108   TCollection_AsciiString EmptyString = "" ;
109 #ifdef _WIN32
110   if (aRelFilePath.Search(":") == 2 ||
111       (aRelFilePath.Search("\\") == 1 && aRelFilePath.Value(2) == '\\'))
112 #else
113   if(aRelFilePath.Search("/") == 1)
114 #endif
115     return aRelFilePath ;
116   
117   TCollection_AsciiString DirPath = aDirPath, RelFilePath = aRelFilePath  ;
118   Standard_Integer i,len ;
119   
120 #ifdef _WIN32
121   if(DirPath.Search(":") != 2 &&
122      (DirPath.Search("\\") != 1 || DirPath.Value(2) != '\\'))
123 #else
124   if (DirPath.Search("/") != 1 )
125 #endif
126     return EmptyString ;
127
128 #ifdef _WIN32
129   DirPath.ChangeAll('\\','/') ;
130   RelFilePath.ChangeAll('\\','/') ;      
131 #endif
132   
133   RemoveExtraSeparator(DirPath) ;
134   len = RemoveExtraSeparator(RelFilePath) ;
135   
136   while (RelFilePath.Search("../") == 1) {
137       if (len == 3)
138     return EmptyString ;
139       RelFilePath = RelFilePath.SubString(4,len) ;
140       len -= 3 ;
141       if (DirPath.IsEmpty())
142     return EmptyString ;
143       i = DirPath.SearchFromEnd("/") ;
144       if (i < 0)
145           return EmptyString ;
146       DirPath.Trunc(i-1) ;
147   }  
148   TCollection_AsciiString retx;
149   retx= DirPath;
150   retx+= "/";
151   retx+=RelFilePath ;
152   return retx;
153 }
154
155 //=======================================================================
156 //function : XmlLDrivers_DocumentRetrievalDriver
157 //purpose  : Constructor
158 //=======================================================================
159 XmlLDrivers_DocumentRetrievalDriver::XmlLDrivers_DocumentRetrievalDriver()
160 {
161   myReaderStatus = PCDM_RS_OK;
162 }
163
164 //=======================================================================
165 //function : CreateDocument
166 //purpose  : pure virtual method definition
167 //=======================================================================
168 Handle(CDM_Document) XmlLDrivers_DocumentRetrievalDriver::CreateDocument()
169 {
170   return new TDocStd_Document(PCDM_RetrievalDriver::GetFormat());
171 }
172
173 //=======================================================================
174 //function : Read
175 //purpose  : 
176 //=======================================================================
177 void XmlLDrivers_DocumentRetrievalDriver::Read
178                                           (const TCollection_ExtendedString& theFileName,
179                                            const Handle(CDM_Document)&       theNewDocument,
180                                            const Handle(CDM_Application)&    theApplication,
181                                            const Message_ProgressRange&      theRange)
182 {
183   myReaderStatus = PCDM_RS_DriverFailure;
184   myFileName = theFileName;
185
186   std::ifstream aFileStream;
187   OSD_OpenStream (aFileStream, myFileName, std::ios::in);
188
189   if (aFileStream.is_open() && aFileStream.good())
190   {
191     Read (aFileStream, NULL, theNewDocument, theApplication, theRange);
192   }
193   else
194   {
195     myReaderStatus = PCDM_RS_OpenError;
196    
197     TCollection_ExtendedString aMsg = TCollection_ExtendedString("Error: the file ") +
198                                       theFileName + " cannot be opened for reading";
199
200     theApplication->MessageDriver()->Send (aMsg.ToExtString(), Message_Fail);
201     throw Standard_Failure("File cannot be opened for reading");
202   }
203 }
204
205 //=======================================================================
206 //function : Read
207 //purpose  : 
208 //=======================================================================
209 void XmlLDrivers_DocumentRetrievalDriver::Read (Standard_IStream&              theIStream,
210                                                 const Handle(Storage_Data)&    /*theStorageData*/,
211                                                 const Handle(CDM_Document)&    theNewDocument,
212                                                 const Handle(CDM_Application)& theApplication,
213                                                 const Message_ProgressRange&   theRange)
214 {
215   Handle(Message_Messenger) aMessageDriver = theApplication -> MessageDriver();
216   ::take_time (~0, " +++++ Start RETRIEVE procedures ++++++", aMessageDriver);
217
218   // 1. Read DOM_Document from file
219   LDOMParser aParser;
220
221   // if myFileName is not empty, "document" tag is required to be read 
222   // from the received document
223   Standard_Boolean aWithoutRoot = myFileName.IsEmpty();
224
225   if (aParser.parse(theIStream, Standard_False, aWithoutRoot))
226   {
227     TCollection_AsciiString aData;
228     std::cout << aParser.GetError(aData) << ": " << aData << std::endl;
229     myReaderStatus = PCDM_RS_FormatFailure;
230     return;
231   }
232   const XmlObjMgt_Element anElement= aParser.getDocument().getDocumentElement();
233   ::take_time (0, " +++++ Fin parsing XML :       ", aMessageDriver);
234
235   ReadFromDomDocument (anElement, theNewDocument, theApplication, theRange);
236 }
237
238 //=======================================================================
239 //function : ReadFromDomDocument
240 //purpose  : management of the macro-structure of XML document data
241 //remark   : If the application needs to use myRelocTable to retrieve additional
242 //           data from LDOM, this method should be reimplemented
243 //=======================================================================
244
245 void XmlLDrivers_DocumentRetrievalDriver::ReadFromDomDocument
246                                 (const XmlObjMgt_Element&       theElement,
247                                  const Handle(CDM_Document)&    theNewDocument,
248                                  const Handle(CDM_Application)& theApplication,
249                                 const Message_ProgressRange&    theRange)
250 {
251   const Handle(Message_Messenger) aMsgDriver =
252     theApplication -> MessageDriver();
253   // 1. Read info // to be done
254   TCollection_AsciiString anAbsoluteDirectory = GetDirFromFile(myFileName);
255   Standard_Integer aCurDocVersion = 0;
256   TCollection_ExtendedString anInfo;
257   const XmlObjMgt_Element anInfoElem =
258     theElement.GetChildByTagName ("info");
259   if (anInfoElem != NULL) {
260     XmlObjMgt_DOMString aDocVerStr = anInfoElem.getAttribute("DocVersion");
261     if(aDocVerStr == NULL)
262       aCurDocVersion = 2;
263     else if (!aDocVerStr.GetInteger(aCurDocVersion)) {
264       TCollection_ExtendedString aMsg =
265         TCollection_ExtendedString ("Cannot retrieve the current Document version"
266                                     " attribute as \"") + aDocVerStr + "\"";
267       if(!aMsgDriver.IsNull()) 
268         aMsgDriver->Send(aMsg.ToExtString(), Message_Fail);
269     }
270     
271     // oan: OCC22305 - check a document verison and if it's greater than
272     // current version of storage driver set an error status and return
273     if( aCurDocVersion > XmlLDrivers::StorageVersion() )
274     {
275       TCollection_ExtendedString aMsg =
276         TCollection_ExtendedString ("error: wrong file version: ") +
277                                     aDocVerStr  + " while current is " +
278                                     XmlLDrivers::StorageVersion();
279       myReaderStatus = PCDM_RS_NoVersion;
280       if(!aMsgDriver.IsNull()) 
281         aMsgDriver->Send(aMsg.ToExtString(), Message_Fail);
282       return;
283     }
284
285     if( aCurDocVersion < 2) aCurDocVersion = 2;
286     Standard_Boolean isRef = Standard_False;
287     for (LDOM_Node aNode = anInfoElem.getFirstChild();
288          aNode != NULL; aNode = aNode.getNextSibling()) {
289       if (aNode.getNodeType() == LDOM_Node::ELEMENT_NODE) {
290         if (XmlObjMgt::GetExtendedString ((LDOM_Element&)aNode, anInfo)) {
291
292     // Read ref counter
293     if(anInfo.Search(REFERENCE_COUNTER) != -1) {
294       try {
295         OCC_CATCH_SIGNALS
296         TCollection_AsciiString anInf(anInfo,'?');
297         Standard_Integer aRefCounter = anInf.Token(" ",2).IntegerValue();
298         theNewDocument->SetReferenceCounter(aRefCounter);
299       }
300       catch (Standard_Failure const&) {
301         //    std::cout << "warning: could not read the reference counter in " << aFileName << std::endl;
302         TCollection_ExtendedString aMsg("Warning: ");
303         aMsg = aMsg.Cat("could not read the reference counter").Cat("\0");
304         if(!aMsgDriver.IsNull()) 
305           aMsgDriver->Send(aMsg.ToExtString(), Message_Warning);
306       }
307     }
308     else if (anInfo.Search(MODIFICATION_COUNTER) != -1) {
309       try {
310         OCC_CATCH_SIGNALS
311         
312         TCollection_AsciiString anInf(anInfo,'?');
313         Standard_Integer aModCounter = anInf.Token(" ",2).IntegerValue();
314         theNewDocument->SetModifications (aModCounter);
315       }
316       catch (Standard_Failure const&) {
317         TCollection_ExtendedString aMsg("Warning: could not read the modification counter\0");
318         if(!aMsgDriver.IsNull()) 
319           aMsgDriver->Send(aMsg.ToExtString(), Message_Warning);
320       }
321     }
322     
323     if(anInfo == END_REF)
324       isRef = Standard_False;
325     if(isRef) { // Process References
326       
327       Standard_Integer pos=anInfo.Search(" ");
328       if(pos != -1) {
329         // Parce RefId, DocumentVersion and FileName
330         Standard_Integer aRefId;
331         TCollection_ExtendedString aFileName;
332         Standard_Integer aDocumentVersion;
333
334
335         TCollection_ExtendedString aRest=anInfo.Split(pos);
336         aRefId = UTL::IntegerValue(anInfo);
337         
338         Standard_Integer pos2 = aRest.Search(" ");
339         
340         aFileName = aRest.Split(pos2);
341         aDocumentVersion = UTL::IntegerValue(aRest);
342         
343         TCollection_AsciiString aPath = UTL::CString(aFileName);
344         TCollection_AsciiString anAbsolutePath;
345         if(!anAbsoluteDirectory.IsEmpty()) {
346     anAbsolutePath = AbsolutePath(anAbsoluteDirectory,aPath);
347     if(!anAbsolutePath.IsEmpty()) aPath=anAbsolutePath;
348         }
349         if(!aMsgDriver.IsNull()) {
350     //      std::cout << "reference found; ReferenceIdentifier: " << theReferenceIdentifier << "; File:" << thePath << ", version:" << theDocumentVersion;
351           TCollection_ExtendedString aMsg("Warning: ");
352           aMsg = aMsg.Cat("reference found; ReferenceIdentifier:  ").Cat(aRefId).Cat("; File:").Cat(aPath).Cat(", version:").Cat(aDocumentVersion).Cat("\0");
353           aMsgDriver->Send(aMsg.ToExtString(), Message_Warning);
354         }
355         // Add new ref!
356         /////////////
357     TCollection_ExtendedString theFolder,theName;
358         //TCollection_ExtendedString theFile=myReferences(myIterator).FileName();
359         TCollection_ExtendedString f(aPath);
360 #ifndef _WIN32
361         
362         Standard_Integer i= f.SearchFromEnd("/");
363         TCollection_ExtendedString n = f.Split(i); 
364         f.Trunc(f.Length()-1);
365         theFolder = f;
366         theName = n;
367 #else
368         OSD_Path p = UTL::Path(f);
369         Standard_ExtCharacter      chr;
370         TCollection_ExtendedString dir, dirRet, name;
371         
372         dir = UTL::Disk(p);
373         dir += UTL::Trek(p);
374         
375         for ( int i = 1; i <= dir.Length (); ++i ) {
376     
377     chr = dir.Value ( i );
378     
379     switch ( chr ) {
380
381     case '|':
382       dirRet += "/";
383       break;
384
385     case '^':
386
387       dirRet += "..";
388       break;
389       
390     default:
391       dirRet += chr;
392       
393     }  
394         }
395         theFolder = dirRet;
396         theName   = UTL::Name(p); theName+= UTL::Extension(p);
397 #endif  // _WIN32
398         
399         Handle(CDM_MetaData) aMetaData =
400           CDM_MetaData::LookUp(theApplication->MetaDataLookUpTable(), theFolder, theName, aPath, aPath, UTL::IsReadOnly(aFileName));
401 ////////////
402         theNewDocument->CreateReference(aMetaData,aRefId,
403              theApplication,aDocumentVersion,Standard_False);
404
405         
406       }
407
408       
409     }
410     if(anInfo == START_REF)
411       isRef = Standard_True;
412         }
413       }
414     }
415   }
416
417   // 2. Read comments
418   TCollection_ExtendedString aComment;
419   const XmlObjMgt_Element aCommentsElem =
420     theElement.GetChildByTagName ("comments");
421   if (aCommentsElem != NULL)
422   {
423     for (LDOM_Node aNode = aCommentsElem.getFirstChild();
424          aNode != NULL; aNode = aNode.getNextSibling())
425     {
426       if (aNode.getNodeType() == LDOM_Node::ELEMENT_NODE)
427       {
428         if (XmlObjMgt::GetExtendedString ((LDOM_Element&)aNode, aComment))
429         {
430           theNewDocument->AddComment(aComment);
431         }
432       }
433     }
434   }
435   Message_ProgressScope aPS(theRange, "Reading document", 2);
436   // 2. Read Shapes section
437   if (myDrivers.IsNull()) myDrivers = AttributeDrivers (aMsgDriver);  
438   const Handle(XmlMDF_ADriver) aNSDriver = ReadShapeSection(theElement, aMsgDriver, aPS.Next());
439   if(!aNSDriver.IsNull())
440     ::take_time (0, " +++++ Fin reading Shapes :    ", aMsgDriver);
441
442   if (!aPS.More())
443   {
444     myReaderStatus = PCDM_RS_UserBreak;
445     return;
446   }
447
448   // 2.1. Keep document format version in RT
449   Handle(Storage_HeaderData) aHeaderData = new Storage_HeaderData();
450   aHeaderData->SetStorageVersion(aCurDocVersion);
451   myRelocTable.Clear();
452   myRelocTable.SetHeaderData(aHeaderData);
453
454   // 5. Read document contents
455   try
456   {
457     OCC_CATCH_SIGNALS
458 #ifdef OCCT_DEBUG
459     TCollection_ExtendedString aMessage ("PasteDocument");
460     aMsgDriver ->Send (aMessage.ToExtString(), Message_Trace);
461 #endif
462     if (!MakeDocument(theElement, theNewDocument, aPS.Next()))
463       myReaderStatus = PCDM_RS_MakeFailure;
464     else
465       myReaderStatus = PCDM_RS_OK;
466   }
467   catch (Standard_Failure const& anException)
468   {
469     TCollection_ExtendedString anErrorString (anException.GetMessageString());
470     aMsgDriver ->Send (anErrorString.ToExtString(), Message_Fail);
471   }
472   if (!aPS.More())
473   {
474     myReaderStatus = PCDM_RS_UserBreak;
475     return;
476   }
477
478   //    Wipe off the shapes written to the <shapes> section
479   ShapeSetCleaning(aNSDriver);
480
481   //    Clean the relocation table.
482   //    If the application needs to use myRelocTable to retrieve additional
483   //    data from LDOM, this method should be reimplemented avoiding this step
484   myRelocTable.Clear();
485   ::take_time (0, " +++++ Fin reading data OCAF : ", aMsgDriver);
486 }
487
488 //=======================================================================
489 //function : MakeDocument
490 //purpose  : 
491 //=======================================================================
492 Standard_Boolean XmlLDrivers_DocumentRetrievalDriver::MakeDocument
493                                     (const XmlObjMgt_Element&    theElement,
494                                      const Handle(CDM_Document)& theTDoc,
495                                      const Message_ProgressRange& theRange)
496 {
497   Standard_Boolean aResult = Standard_False;
498   Handle(TDocStd_Document) TDOC = Handle(TDocStd_Document)::DownCast(theTDoc);
499   if (!TDOC.IsNull()) 
500   {
501     Handle(TDF_Data) aTDF = new TDF_Data();
502     aResult = XmlMDF::FromTo (theElement, aTDF, myRelocTable, myDrivers, theRange);
503     if (aResult) {
504       TDOC->SetData (aTDF);
505       TDocStd_Owner::SetDocument (aTDF, TDOC);
506     }
507   }
508   return aResult;
509 }
510
511 //=======================================================================
512 //function : AttributeDrivers
513 //purpose  : 
514 //=======================================================================
515 Handle(XmlMDF_ADriverTable) XmlLDrivers_DocumentRetrievalDriver::AttributeDrivers
516        (const Handle(Message_Messenger)& theMessageDriver) 
517 {
518   return XmlLDrivers::AttributeDrivers (theMessageDriver);
519 }
520
521 //=======================================================================
522 //function : take_time
523 //class    : static
524 //purpose  : output astronomical time elapsed
525 //=======================================================================
526 #ifdef TAKE_TIMES
527 #include <time.h>
528 #include <sys/timeb.h>
529 #include <sys/types.h>
530 #include <stdio.h>
531 #ifndef _WIN32
532 extern "C" int ftime (struct timeb *tp);
533 #endif
534 extern struct timeb  tmbuf0;
535
536 static void take_time (const Standard_Integer isReset, const char * aHeader,
537                        const Handle(Message_Messenger)& aMessageDriver)
538 {
539   struct timeb  tmbuf;
540   ftime (&tmbuf);
541   TCollection_ExtendedString aMessage ((Standard_CString)aHeader);
542   if (isReset) tmbuf0 = tmbuf;
543   else {
544     char take_tm_buf [64];
545     Sprintf (take_tm_buf, "%9.2f s ++++",
546              double(tmbuf.time - tmbuf0.time) +
547              double(tmbuf.millitm - tmbuf0.millitm)/1000.);
548     aMessage += take_tm_buf;
549   }
550   aMessageDriver -> Write (aMessage.ToExtString());
551 }
552 #endif
553
554 //=======================================================================
555 //function : ReadShapeSection
556 //purpose  : definition of ReadShapeSection
557 //=======================================================================
558 Handle(XmlMDF_ADriver) XmlLDrivers_DocumentRetrievalDriver::ReadShapeSection(
559                                const XmlObjMgt_Element&       /*theElement*/,
560                                const Handle(Message_Messenger)& /*aMsgDriver*/,
561                                const Message_ProgressRange&    /*theRange*/)
562 {
563   Handle(XmlMDF_ADriver) aDriver;
564   //empty; to be redefined
565   return aDriver;
566 }
567
568 //=======================================================================
569 //function : ShapeSetCleaning
570 //purpose  : definition of ShapeSetCleaning
571 //=======================================================================
572 void XmlLDrivers_DocumentRetrievalDriver::ShapeSetCleaning(
573             const Handle(XmlMDF_ADriver)& /*theDriver*/) 
574 {}