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.hxx>
20 #include <Message_Messenger.hxx>
21 #include <Message_ProgressScope.hxx>
22 #include <LDOM_DocumentType.hxx>
23 #include <LDOM_LDOMImplementation.hxx>
24 #include <LDOM_XmlWriter.hxx>
25 #include <OSD_Environment.hxx>
26 #include <OSD_File.hxx>
27 #include <OSD_FileSystem.hxx>
28 #include <PCDM.hxx>
29 #include <PCDM_ReadWriter.hxx>
30 #include <Standard_ErrorHandler.hxx>
31 #include <Standard_Failure.hxx>
32 #include <Standard_Type.hxx>
33 #include <Storage_Data.hxx>
34 #include <TCollection_AsciiString.hxx>
35 #include <TCollection_ExtendedString.hxx>
36 #include <TColStd_SequenceOfAsciiString.hxx>
37 #include <TDocStd_Document.hxx>
38 #include <XmlLDrivers.hxx>
39 #include <XmlLDrivers_DocumentStorageDriver.hxx>
40 #include <XmlLDrivers_NamespaceDef.hxx>
41 #include <XmlMDF.hxx>
42 #include <XmlMDF_ADriverTable.hxx>
43 #include <XmlObjMgt.hxx>
44 #include <XmlObjMgt_Document.hxx>
45 #include <XmlObjMgt_SRelocationTable.hxx>
46 
47 #include <locale.h>
48 IMPLEMENT_STANDARD_RTTIEXT(XmlLDrivers_DocumentStorageDriver,PCDM_StorageDriver)
49 
50 #define STORAGE_VERSION      "STORAGE_VERSION: "
51 #define REFERENCE_COUNTER    "REFERENCE_COUNTER: "
52 #define MODIFICATION_COUNTER "MODIFICATION_COUNTER: "
53 #define START_REF            "START_REF"
54 #define END_REF              "END_REF"
55 
56 #define FAILSTR "Failed to write xsi:schemaLocation : "
57 
58 //#define TAKE_TIMES
59 static void take_time (const Standard_Integer, const char *,
60                        const Handle(Message_Messenger)&)
61 #ifdef TAKE_TIMES
62 ;
63 #else
64 {}
65 #endif
66 
67 //=======================================================================
68 //function : XmlLDrivers_DocumentStorageDriver
69 //purpose  : Constructor
70 //=======================================================================
XmlLDrivers_DocumentStorageDriver(const TCollection_ExtendedString & theCopyright)71 XmlLDrivers_DocumentStorageDriver::XmlLDrivers_DocumentStorageDriver
72                                 (const TCollection_ExtendedString& theCopyright)
73      : myCopyright (theCopyright)
74 {
75 }
76 
77 //=======================================================================
78 //function : AddNamespace
79 //purpose  :
80 //=======================================================================
81 
AddNamespace(const TCollection_AsciiString & thePrefix,const TCollection_AsciiString & theURI)82 void XmlLDrivers_DocumentStorageDriver::AddNamespace
83                                 (const TCollection_AsciiString& thePrefix,
84                                  const TCollection_AsciiString& theURI)
85 {
86   for (Standard_Integer i = 1; i <= mySeqOfNS.Length(); i++)
87     if (thePrefix == mySeqOfNS(i).Prefix()) return;
88   mySeqOfNS.Append (XmlLDrivers_NamespaceDef(thePrefix, theURI));
89 }
90 
91 //=======================================================================
92 //function : Write
93 //purpose  :
94 //=======================================================================
Write(const Handle (CDM_Document)& theDocument,const TCollection_ExtendedString & theFileName,const Message_ProgressRange & theRange)95 void XmlLDrivers_DocumentStorageDriver::Write (const Handle(CDM_Document)&       theDocument,
96                                                const TCollection_ExtendedString& theFileName,
97                                                const Message_ProgressRange&      theRange)
98 {
99   myFileName = theFileName;
100 
101   const Handle(OSD_FileSystem)& aFileSystem = OSD_FileSystem::DefaultFileSystem();
102   opencascade::std::shared_ptr<std::ostream> aFileStream = aFileSystem->OpenOStream (theFileName, std::ios::out);
103 
104   if (aFileStream.get() != NULL && aFileStream->good())
105   {
106     Write (theDocument, *aFileStream, theRange);
107   }
108   else
109   {
110     SetIsError (Standard_True);
111     SetStoreStatus(PCDM_SS_WriteFailure);
112 
113     TCollection_ExtendedString aMsg = TCollection_ExtendedString("Error: the file ") +
114                                       theFileName + " cannot be opened for writing";
115 
116     theDocument->Application()->MessageDriver()->Send (aMsg.ToExtString(), Message_Fail);
117     throw Standard_Failure("File cannot be opened for writing");
118   }
119 }
120 
121 //=======================================================================
122 //function : Write
123 //purpose  :
124 //=======================================================================
Write(const Handle (CDM_Document)& theDocument,Standard_OStream & theOStream,const Message_ProgressRange & theRange)125 void XmlLDrivers_DocumentStorageDriver::Write (const Handle(CDM_Document)&  theDocument,
126                                                Standard_OStream&            theOStream,
127                                                const Message_ProgressRange& theRange)
128 {
129   Handle(Message_Messenger) aMessageDriver = theDocument->Application()->MessageDriver();
130   ::take_time (~0, " +++++ Start STORAGE procedures ++++++", aMessageDriver);
131 
132   // Create new DOM_Document
133   XmlObjMgt_Document aDOMDoc = XmlObjMgt_Document::createDocument ("document");
134 
135   // Fill the document with data
136   XmlObjMgt_Element anElement = aDOMDoc.getDocumentElement();
137 
138   if (WriteToDomDocument (theDocument, anElement, theRange) == Standard_False) {
139 
140     LDOM_XmlWriter aWriter;
141     aWriter.SetIndentation(1);
142 
143     if (theOStream.good())
144     {
145       aWriter.Write (theOStream, aDOMDoc);
146     }
147     else
148     {
149       SetIsError (Standard_True);
150       SetStoreStatus(PCDM_SS_WriteFailure);
151 
152       TCollection_ExtendedString aMsg = TCollection_ExtendedString("Error: the stream is bad and") +
153                                         " cannot be used for writing";
154       theDocument->Application()->MessageDriver()->Send (aMsg.ToExtString(), Message_Fail);
155 
156       throw Standard_Failure("File cannot be opened for writing");
157     }
158 
159     ::take_time (0, " +++++ Fin formatting to XML : ", aMessageDriver);
160   }
161 }
162 
163 //=======================================================================
164 //function : WriteToDomDocument
165 //purpose  : management of the macro-structure of XML document data
166 //remark   : If the application needs to use myRelocTable to store additional
167 //           data to XML, this method should be reimplemented avoiding step 3
168 //=======================================================================
169 
WriteToDomDocument(const Handle (CDM_Document)& theDocument,XmlObjMgt_Element & theElement,const Message_ProgressRange & theRange)170 Standard_Boolean XmlLDrivers_DocumentStorageDriver::WriteToDomDocument
171                           (const Handle(CDM_Document)&  theDocument,
172                            XmlObjMgt_Element&           theElement,
173                            const Message_ProgressRange& theRange)
174 {
175   SetIsError(Standard_False);
176   Handle(Message_Messenger) aMessageDriver =
177     theDocument -> Application() -> MessageDriver();
178   // 1. Write header information
179   Standard_Integer i;
180   XmlObjMgt_Document aDOMDoc = theElement.getOwnerDocument();
181 
182   // 1.a File Format
183   TCollection_AsciiString aStorageFormat (theDocument->StorageFormat(), '?');
184   theElement.setAttribute ("format", aStorageFormat.ToCString());
185 //  theElement.setAttribute ("schema", "XSD");
186 
187   theElement.setAttribute ("xmlns" , "http://www.opencascade.org/OCAF/XML");
188   for (i = 1; i <= mySeqOfNS.Length(); i++) {
189     TCollection_AsciiString aPrefix =
190       TCollection_AsciiString("xmlns:") + mySeqOfNS(i).Prefix().ToCString();
191     theElement.setAttribute (aPrefix.ToCString(),
192                              mySeqOfNS(i).URI().ToCString());
193   }
194   theElement.setAttribute ("xmlns:xsi",
195                            "http://www.w3.org/2001/XMLSchema-instance");
196   //mkv 15.09.05 OCC10001
197   //theElement.setAttribute ("xsi:schemaLocation",
198   //                         "http://www.opencascade.org/OCAF/XML"
199   //                         " http://www.nnov.matra-dtv.fr/~agv/XmlOcaf.xsd");
200   //
201   // the order of search : by CSF_XmlOcafResource and then by CASROOT
202   TCollection_AsciiString anHTTP = "http://www.opencascade.org/OCAF/XML";
203   Standard_Boolean aToSetCSFVariable = Standard_False;
204   const char * aCSFVariable [2] = {
205     "CSF_XmlOcafResource",
206     "CASROOT"
207   };
208   OSD_Environment anEnv (aCSFVariable[0]);
209   TCollection_AsciiString aResourceDir = anEnv.Value();
210   if (aResourceDir.IsEmpty()) {
211     // now try by CASROOT
212     OSD_Environment anEnv2(aCSFVariable[1]);
213     aResourceDir = anEnv2.Value();
214     if ( !aResourceDir.IsEmpty() ) {
215       aResourceDir += "/src/XmlOcafResource" ;
216       aToSetCSFVariable = Standard_True; //CSF variable to be set later
217     }
218 #ifdef OCCT_DEBUGXML
219     else {
220       TCollection_ExtendedString aWarn = FAILSTR "Neither ";
221       aWarn = (aWarn + aCSFVariable[0] + ", nor " + aCSFVariable[1]
222                + " variables have been set");
223       aMessageDriver->Send (aWarn.ToExtString(), Message_Warning);
224     }
225 #endif
226   }
227   if (!aResourceDir.IsEmpty()) {
228     TCollection_AsciiString aResourceFileName =  aResourceDir + "/XmlOcaf.xsd";
229     // search directory name that has been constructed, now check whether
230     // it and the file exist
231     OSD_File aResourceFile ( aResourceFileName );
232     if ( aResourceFile.Exists() ) {
233       if (aToSetCSFVariable) {
234         OSD_Environment aCSFVarEnv ( aCSFVariable[0], aResourceDir );
235         aCSFVarEnv.Build();
236 #ifdef OCCT_DEBUGXML
237         TCollection_ExtendedString aWarn1 = "Variable ";
238         aWarn1 = (aWarn1 + aCSFVariable[0]
239                   + " has not been explicitly defined. Set to " + aResourceDir);
240         aMessageDriver->Send (aWarn1.ToExtString(), Message_Warning);
241 #endif
242         if ( aCSFVarEnv.Failed() ) {
243           TCollection_ExtendedString aWarn = FAILSTR "Failed to initialize ";
244           aWarn = aWarn + aCSFVariable[0] + " with " + aResourceDir;
245           aMessageDriver->Send (aWarn.ToExtString(), Message_Fail);
246         }
247       }
248     }
249 #ifdef OCCT_DEBUGXML
250     else {
251       TCollection_ExtendedString aWarn = FAILSTR "Schema definition file ";
252       aWarn += (aResourceFileName + " was not found");
253       aMessageDriver->Send (aWarn.ToExtString(), Message_Warning);
254     }
255 #endif
256     anHTTP = anHTTP + ' ' + aResourceFileName;
257   }
258   theElement.setAttribute ("xsi:schemaLocation", anHTTP.ToCString() );
259 
260   // 1.b Info section
261   XmlObjMgt_Element anInfoElem = aDOMDoc.createElement("info");
262   theElement.appendChild(anInfoElem);
263 
264   TCollection_AsciiString aCreationDate = XmlLDrivers::CreationDate();
265 
266 //  anInfoElem.setAttribute("dbv", 0);
267   anInfoElem.setAttribute("date", aCreationDate.ToCString());
268   anInfoElem.setAttribute("schemav", 0);
269 //  anInfoElem.setAttribute("appv", anAppVersion.ToCString());
270 
271   // Document version
272   Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast (theDocument);
273   TDocStd_FormatVersion aFormatVersion = TDocStd_Document::CurrentStorageFormatVersion(); // the last version of the format
274   if (TDocStd_Document::CurrentStorageFormatVersion() < aDoc->StorageFormatVersion())
275   {
276     TCollection_ExtendedString anErrorString("Unacceptable storage format version, the last version is used");
277     aMessageDriver->Send (anErrorString.ToExtString(), Message_Warning);
278   }
279   else
280   {
281     aFormatVersion = aDoc->StorageFormatVersion();
282   }
283   const TCollection_AsciiString aStringFormatVersion (aFormatVersion);
284   anInfoElem.setAttribute ("DocVersion", aStringFormatVersion.ToCString());
285 
286   // User info with Copyright
287   TColStd_SequenceOfAsciiString aUserInfo;
288   if (myCopyright.Length() > 0)
289     aUserInfo.Append (TCollection_AsciiString(myCopyright,'?'));
290 
291   Handle(Storage_Data) theData = new Storage_Data;
292   //PCDM_ReadWriter::WriteFileFormat( theData, theDocument );
293   PCDM_ReadWriter::Writer()->WriteReferenceCounter(theData,theDocument);
294   PCDM_ReadWriter::Writer()->WriteReferences(theData,theDocument, myFileName);
295   PCDM_ReadWriter::Writer()->WriteExtensions(theData,theDocument);
296   PCDM_ReadWriter::Writer()->WriteVersion(theData,theDocument);
297 
298   const TColStd_SequenceOfAsciiString& aRefs = theData->UserInfo();
299   for(i = 1; i <= aRefs.Length(); i++)
300     aUserInfo.Append(aRefs.Value(i));
301 
302   // Keep format version in Reloc. table
303   Handle(Storage_HeaderData) aHeaderData = theData->HeaderData();
304   aHeaderData->SetStorageVersion(aFormatVersion);
305   myRelocTable.Clear();
306   myRelocTable.SetHeaderData(aHeaderData);
307 
308   for (i = 1; i <= aUserInfo.Length(); i++)
309   {
310     XmlObjMgt_Element aUIItem = aDOMDoc.createElement ("iitem");
311     anInfoElem.appendChild (aUIItem);
312     LDOM_Text aUIText = aDOMDoc.createTextNode (aUserInfo(i).ToCString());
313     aUIItem.appendChild (aUIText);
314   }
315 
316   // 1.c Comments section
317   TColStd_SequenceOfExtendedString aComments;
318   theDocument->Comments(aComments);
319 
320   XmlObjMgt_Element aCommentsElem = aDOMDoc.createElement ("comments");
321   theElement.appendChild (aCommentsElem);
322 
323   for (i = 1; i <= aComments.Length(); i++)
324   {
325     XmlObjMgt_Element aCItem = aDOMDoc.createElement ("citem");
326     aCommentsElem.appendChild (aCItem);
327     XmlObjMgt::SetExtendedString (aCItem, aComments(i));
328   }
329   Message_ProgressScope aPS(theRange, "Writing", 2);
330   // 2a. Write document contents
331   Standard_Integer anObjNb = 0;
332   {
333     try
334     {
335       OCC_CATCH_SIGNALS
336       anObjNb = MakeDocument(theDocument, theElement, aPS.Next());
337       if (!aPS.More())
338       {
339         SetIsError(Standard_True);
340         SetStoreStatus(PCDM_SS_UserBreak);
341         return IsError();
342       }
343     }
344     catch (Standard_Failure const& anException)
345     {
346       SetIsError (Standard_True);
347       SetStoreStatus(PCDM_SS_Failure);
348       TCollection_ExtendedString anErrorString (anException.GetMessageString());
349       aMessageDriver ->Send (anErrorString.ToExtString(), Message_Fail);
350     }
351   }
352   if (anObjNb <= 0 && IsError() == Standard_False) {
353     SetIsError (Standard_True);
354     SetStoreStatus(PCDM_SS_No_Obj);
355     TCollection_ExtendedString anErrorString ("error occurred");
356     aMessageDriver ->Send (anErrorString.ToExtString(), Message_Fail);
357   }
358   // 2b. Write number of objects into the info section
359   anInfoElem.setAttribute("objnb", anObjNb);
360   ::take_time (0, " +++++ Fin DOM data for OCAF : ", aMessageDriver);
361 
362   // 3. Clear relocation table
363   //    If the application needs to use myRelocTable to store additional
364   //    data to XML, this method should be reimplemented avoiding this step
365   myRelocTable.Clear();
366 
367   // 4. Write Shapes section
368   if (WriteShapeSection(theElement, aFormatVersion, aPS.Next()))
369     ::take_time (0, " +++ Fin DOM data for Shapes : ", aMessageDriver);
370   if (!aPS.More())
371   {
372     SetIsError(Standard_True);
373     SetStoreStatus(PCDM_SS_UserBreak);
374     return IsError();
375   }
376   return IsError();
377 }
378 
379 //=======================================================================
380 //function : MakeDocument
381 //purpose  :
382 //=======================================================================
MakeDocument(const Handle (CDM_Document)& theTDoc,XmlObjMgt_Element & theElement,const Message_ProgressRange & theRange)383 Standard_Integer XmlLDrivers_DocumentStorageDriver::MakeDocument
384                                     (const Handle(CDM_Document)&  theTDoc,
385                                      XmlObjMgt_Element&           theElement,
386                                      const Message_ProgressRange& theRange)
387 {
388   TCollection_ExtendedString aMessage;
389   Handle(TDocStd_Document) TDOC = Handle(TDocStd_Document)::DownCast(theTDoc);
390   if (!TDOC.IsNull())
391   {
392 //    myRelocTable.SetDocument (theElement.getOwnerDocument());
393     Handle(TDF_Data) aTDF = TDOC->GetData();
394 
395 //      Find MessageDriver and pass it to AttributeDrivers()
396     Handle(CDM_Application) anApplication= theTDoc -> Application();
397     Handle(Message_Messenger) aMessageDriver;
398     if (anApplication.IsNull()) {
399       aMessageDriver = Message::DefaultMessenger();
400       aMessageDriver->ChangePrinters().Clear();
401     }
402     else
403       aMessageDriver = anApplication -> MessageDriver();
404     if (myDrivers.IsNull()) myDrivers = AttributeDrivers (aMessageDriver);
405 
406 //      Retrieve from DOM_Document
407     XmlMDF::FromTo (aTDF, theElement, myRelocTable, myDrivers, theRange);
408 #ifdef OCCT_DEBUGXML
409     aMessage = "First step successful";
410     aMessageDriver -> Send (aMessage.ToExtString(), Message_Warning);
411 #endif
412     return myRelocTable.Extent();
413   }
414 #ifdef OCCT_DEBUG
415   std::cout << "First step failed" << std::endl;  // No MessageDriver available
416 #endif
417   return -1; // error
418 }
419 
420 //=======================================================================
421 //function : AttributeDrivers
422 //purpose  :
423 //=======================================================================
Handle(XmlMDF_ADriverTable)424 Handle(XmlMDF_ADriverTable) XmlLDrivers_DocumentStorageDriver::AttributeDrivers
425        (const Handle(Message_Messenger)& theMessageDriver)
426 {
427   return XmlLDrivers::AttributeDrivers (theMessageDriver);
428 }
429 
430 //=======================================================================
431 //function : take_time
432 //class    : static
433 //purpose  : output astronomical time elapsed
434 //=======================================================================
435 #ifdef TAKE_TIMES
436 #include <time.h>
437 #include <sys/timeb.h>
438 #include <sys/types.h>
439 #include <stdio.h>
440 #ifndef _WIN32
441 extern "C" int ftime (struct timeb *tp);
442 #endif
443 struct timeb  tmbuf0;
444 
take_time(const Standard_Integer isReset,const char * aHeader,const Handle (Message_Messenger)& aMessageDriver)445 static void take_time (const Standard_Integer isReset, const char * aHeader,
446                        const Handle(Message_Messenger)& aMessageDriver)
447 {
448   struct timeb  tmbuf;
449   ftime (&tmbuf);
450   TCollection_ExtendedString aMessage ((Standard_CString)aHeader);
451   if (isReset) tmbuf0 = tmbuf;
452   else {
453     char take_tm_buf [64];
454     Sprintf (take_tm_buf, "%9.2f s ++++",
455              double(tmbuf.time - tmbuf0.time) +
456              double(tmbuf.millitm - tmbuf0.millitm)/1000.);
457     aMessage += take_tm_buf;
458   }
459   aMessageDriver ->Send (aMessage.ToExtString(), Message_Trace);
460 }
461 #endif
462 
463 //=======================================================================
464 //function : WriteShapeSection
465 //purpose  : defines WriteShapeSection
466 //=======================================================================
WriteShapeSection(XmlObjMgt_Element &,const TDocStd_FormatVersion,const Message_ProgressRange &)467 Standard_Boolean XmlLDrivers_DocumentStorageDriver::WriteShapeSection
468                                 (XmlObjMgt_Element&           /*theElement*/,
469                                  const TDocStd_FormatVersion /*theStorageFormatVersion*/,
470                                  const Message_ProgressRange&  /*theRange*/)
471 {
472   // empty; should be redefined in subclasses
473   return Standard_False;
474 }
475 
476