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