Salome HOME
Bug 0020065: EDF 876 GEOM : Deleting an object leads to unusable dump. Refix.
[modules/geom.git] / src / GEOM / GEOM_Engine.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 #ifdef WNT
23 #pragma warning( disable:4786 )
24 #endif
25
26 #include "GEOM_Engine.hxx"
27
28 #include "GEOM_Solver.hxx"
29 #include "GEOM_Function.hxx"
30 #include "GEOM_ISubShape.hxx"
31 #include "GEOM_SubShapeDriver.hxx"
32 #include "GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient.hxx"
33 #include "GEOM_PythonDump.hxx"
34
35 #include "utilities.h"
36
37 #include <TDF_Tool.hxx>
38 #include <TDF_Data.hxx>
39 #include <TDF_Reference.hxx>
40 #include <TDF_LabelSequence.hxx>
41 #include <TDataStd_Integer.hxx>
42 #include <TDataStd_ChildNodeIterator.hxx>
43 #include <TFunction_Driver.hxx>
44 #include <TFunction_DriverTable.hxx>
45
46 #include <TopExp.hxx>
47 #include <TopTools_IndexedMapOfShape.hxx>
48
49 #include <TCollection_AsciiString.hxx>
50 #include <TCollection_ExtendedString.hxx>
51 #include <TColStd_SequenceOfAsciiString.hxx>
52 #include <TColStd_MapOfTransient.hxx>
53 #include <TColStd_HSequenceOfInteger.hxx>
54
55 #include <Interface_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
56 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
57
58 #include <set>
59 #include <map>
60 #include <string>
61
62 #include <Standard_Failure.hxx>
63 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
64
65 static GEOM_Engine* TheEngine = NULL;
66
67 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
68 {
69   TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
70   TDF_Tool::Entry(theObject->GetEntry(), anEntry);
71   anID+=(TCollection_AsciiString("_")+anEntry);
72   return anID;
73 }
74
75 static TCollection_AsciiString BuildID(Standard_Integer theDocID, char* theEntry)
76 {
77   TCollection_AsciiString anID(theDocID);
78   anID+=(TCollection_AsciiString("_")+theEntry);
79   return anID;
80 }
81
82 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
83 {
84   TCollection_AsciiString aDocID = theID.Token("_");
85   if(aDocID.Length() < 1) return -1;
86   return aDocID.IntegerValue();
87 }
88
89 void ProcessFunction(Handle(GEOM_Function)&   theFunction,
90                      TCollection_AsciiString& theScript,
91                      TDF_LabelMap&            theProcessed,
92                      std::set<std::string>&   theDumpedObjs);
93
94 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
95
96 //=============================================================================
97 /*!
98  *  GetEngine
99  */
100 //=============================================================================
101 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
102
103 //=============================================================================
104 /*!
105  *  SetEngine
106  */
107 //=============================================================================
108 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
109
110 //=============================================================================
111 /*!
112  *  Constructor
113  */
114 //=============================================================================
115 GEOM_Engine::GEOM_Engine()
116 {
117   TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
118
119   _OCAFApp = new GEOM_Application();
120   _UndoLimit = 10;
121 }
122
123 /*!
124  *  Destructor
125  */
126 GEOM_Engine::~GEOM_Engine()
127 {
128   GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
129   for(; It.More(); It.Next())
130     {
131       RemoveObject(Handle(GEOM_Object)::DownCast(It.Value()));
132     }
133
134   //Close all documents not closed
135   for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
136     Close(anItr.Key());
137
138   _mapIDDocument.Clear();
139   _objects.Clear();
140 }
141
142 //=============================================================================
143 /*!
144  *  GetDocument
145  */
146 //=============================================================================
147 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID)
148 {
149   Handle(TDocStd_Document) aDoc;
150   if(!_mapIDDocument.IsBound(theDocID)) {
151     _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
152     aDoc->SetUndoLimit(_UndoLimit);
153     _mapIDDocument.Bind(theDocID, aDoc);
154     TDataStd_Integer::Set(aDoc->Main(), theDocID);
155   }
156
157   return Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
158 }
159
160 //=============================================================================
161 /*!
162  *  GetDocID
163  */
164 //=============================================================================
165 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
166 {
167   if(theDocument.IsNull()) return -1;
168   for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
169     if(anItr.Value() == theDocument) return anItr.Key();
170
171   return -1;
172
173 }
174
175 //=============================================================================
176 /*!
177  *  GetObject
178  */
179 //=============================================================================
180 Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry)
181 {
182   TCollection_AsciiString anID = BuildID(theDocID, theEntry);
183   if(_objects.IsBound(anID)) return Handle(GEOM_Object)::DownCast(_objects(anID));
184
185   TDF_Label aLabel;
186   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
187   TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
188   Handle(GEOM_Object) anObject = new GEOM_Object(aLabel);
189
190   _objects.Bind(anID, anObject);
191
192   return anObject;
193 }
194
195 //=============================================================================
196 /*!
197  *  AddObject
198  */
199 //=============================================================================
200 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
201 {
202   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
203   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
204
205   // NPAL18604: use existing label to decrease memory usage,
206   //            if this label has been freed (object deleted)
207   bool useExisting = false;
208   TDF_Label aChild;
209   if (!_lastCleared.IsNull()) {
210     if (_lastCleared.Root() == aDoc->Main().Root()) {
211       useExisting = true;
212       aChild = _lastCleared;
213       _lastCleared.Nullify();
214     }
215   }
216   if (!useExisting) {
217     // create new label
218     aChild = TDF_TagSource::NewChild(aDoc->Main());
219   }
220
221   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
222
223   //Put an object in the map of created objects
224   TCollection_AsciiString anID = BuildIDFromObject(anObject);
225   if(_objects.IsBound(anID)) _objects.UnBind(anID);
226   _objects.Bind(anID, anObject);
227
228   return anObject;
229 }
230
231 //=============================================================================
232 /*!
233  *  AddSubShape
234  */
235 //=============================================================================
236 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
237                                              Handle(TColStd_HArray1OfInteger) theIndices,
238                                              bool isStandaloneOperation)
239 {
240   if(theMainShape.IsNull() || theIndices.IsNull()) return NULL;
241
242   Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
243   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
244
245   // NPAL18604: use existing label to decrease memory usage,
246   //            if this label has been freed (object deleted)
247   bool useExisting = false;
248   TDF_Label aChild;
249   if (!_lastCleared.IsNull()) {
250     if (_lastCleared.Root() == aDoc->Main().Root()) {
251       useExisting = true;
252       aChild = _lastCleared;
253       _lastCleared.Nullify();
254     }
255   }
256   if (!useExisting) {
257     // create new label
258     aChild = TDF_TagSource::NewChild(aDoc->Main());
259   }
260
261   Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
262   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type
263   Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
264
265   GEOM_ISubShape aSSI(aFunction);
266   aSSI.SetMainShape(aMainShape);
267   aSSI.SetIndices(theIndices);
268
269   try {
270 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
271     OCC_CATCH_SIGNALS;
272 #endif
273     GEOM_Solver aSolver (GEOM_Engine::GetEngine());
274     if (!aSolver.ComputeFunction(aFunction)) {
275       MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
276       return NULL;
277     }
278   }
279   catch (Standard_Failure) {
280     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
281     MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
282     return NULL;
283   }
284
285   //Put an object in the map of created objects
286   TCollection_AsciiString anID = BuildIDFromObject(anObject);
287   if(_objects.IsBound(anID)) _objects.UnBind(anID);
288   _objects.Bind(anID, anObject);
289
290   GEOM::TPythonDump pd (aFunction);
291
292   if (isStandaloneOperation) {
293     pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
294     Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
295     for (; i <= up - 1; i++) {
296       pd << theIndices->Value(i) << ", ";
297     }
298     pd << theIndices->Value(up) << "])";
299   }
300   else
301     pd << "None";
302
303   return anObject;
304 }
305
306 //=============================================================================
307 /*!
308  *  RemoveObject
309  */
310 //=============================================================================
311 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
312 {
313   if (!theObject) return false;
314
315   //Remove an object from the map of available objects
316   TCollection_AsciiString anID = BuildIDFromObject(theObject);
317   if (_objects.IsBound(anID)) _objects.UnBind(anID);
318
319   int nb = theObject->GetNbFunctions();
320   Handle(TDataStd_TreeNode) aNode;
321   for (int i = 1; i<=nb; i++) {
322     Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
323     if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
324       aNode->Remove();
325   }
326
327   TDF_Label aLabel = theObject->GetEntry();
328   aLabel.ForgetAllAttributes(Standard_True);
329   _lastCleared = aLabel;
330
331   theObject.Nullify();
332
333   return true;
334 }
335
336 //=============================================================================
337 /*!
338  *  Undo
339  */
340 //=============================================================================
341 void GEOM_Engine::Undo(int theDocID)
342 {
343   GetDocument(theDocID)->Undo();
344 }
345
346 //=============================================================================
347 /*!
348  *  Redo
349  */
350 //=============================================================================
351 void GEOM_Engine::Redo(int theDocID)
352 {
353   GetDocument(theDocID)->Redo();
354 }
355
356 //=============================================================================
357 /*!
358  *  Save
359  */
360 //=============================================================================
361 bool GEOM_Engine::Save(int theDocID, char* theFileName)
362 {
363   if(!_mapIDDocument.IsBound(theDocID)) return false;
364   Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
365
366   _OCAFApp->SaveAs(aDoc, theFileName);
367
368   return true;
369 }
370
371 //=============================================================================
372 /*!
373  *  Load
374  */
375 //=============================================================================
376 bool GEOM_Engine::Load(int theDocID, char* theFileName)
377 {
378   Handle(TDocStd_Document) aDoc;
379   if(_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
380     return false;
381   }
382
383   aDoc->SetUndoLimit(_UndoLimit);
384
385   if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
386   _mapIDDocument.Bind(theDocID, aDoc);
387
388   TDataStd_Integer::Set(aDoc->Main(), theDocID);
389
390   return true;
391 }
392
393 //=============================================================================
394 /*!
395  *  Close
396  */
397 //=============================================================================
398 void GEOM_Engine::Close(int theDocID)
399 {
400   if (_mapIDDocument.IsBound(theDocID)) {
401     Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
402
403     //Remove all GEOM Objects associated to the given document
404     TColStd_SequenceOfAsciiString aSeq;
405     GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
406     for (; It.More(); It.Next()) {
407       TCollection_AsciiString anObjID (It.Key());
408       Standard_Integer anID = ExtractDocID(anObjID);
409       if (theDocID == anID) aSeq.Append(It.Key());
410     }
411     for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
412
413     _lastCleared.Nullify();
414
415     _mapIDDocument.UnBind(theDocID);
416     _OCAFApp->Close(aDoc);
417     aDoc.Nullify();
418   }
419 }
420
421 //=============================================================================
422 /*!
423  *  DumpPython
424  */
425 //=============================================================================
426 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
427                                                 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
428                                                 bool isPublished,
429                                                 bool& aValidScript)
430 {
431   TCollection_AsciiString aScript;
432   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
433
434   if (aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
435
436   aScript  = "import geompy\n";
437   aScript += "import math\n";
438   aScript += "import SALOMEDS\n\n";
439   aScript += "def RebuildData(theStudy):";
440   aScript += "\n\tgeompy.init_geom(theStudy)";
441
442   Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
443
444   Handle(TDataStd_TreeNode) aNode, aRoot;
445   Handle(GEOM_Function) aFunction;
446   TDF_LabelMap aFuncMap;
447   std::set<std::string> anObjMap;
448
449   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
450     TDataStd_ChildNodeIterator Itr(aRoot);
451     for (; Itr.More(); Itr.Next()) {
452       aNode = Itr.Value();
453       aFunction = GEOM_Function::GetFunction(aNode->Label());
454       if (aFunction.IsNull()) {
455         MESSAGE ( "Null function !!!!" );
456         continue;
457       }
458       ProcessFunction(aFunction, aScript, aFuncMap, anObjMap);
459     }
460   }
461
462   Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry;
463   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
464   // build maps entry <-> studyEntry
465   for (anEntryToNameIt.Initialize( theObjectNames );
466        anEntryToNameIt.More();
467        anEntryToNameIt.Next())
468   {
469     const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
470     // look for an object by entry
471     TDF_Label L;
472     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
473     if ( L.IsNull() ) continue;
474     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
475     // fill maps
476     if ( !obj.IsNull() ) {
477       TCollection_AsciiString aStudyEntry (obj->GetAuxData());
478       aEntry2StEntry.Bind( aEntry,  aStudyEntry);
479       aStEntry2Entry.Bind( aStudyEntry, aEntry );
480     }
481   }
482
483   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
484   Standard_Integer aLen = aSeq->Length(), objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
485   Resource_DataMapOfAsciiStringAsciiString aNameToEntry, anEntryToBadName;
486
487   //Replace entries by the names
488   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
489     allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
490   if (aLen == 0) anUpdatedScript = aScript;
491
492   for (Standard_Integer i = 1; i <= aLen; i+=2) {
493     anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i)-1);
494     anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
495     if (theObjectNames.IsBound(anEntry)) {
496       aName = theObjectNames.Find(anEntry);
497       // check validity of aName
498       bool isValidName = true;
499       if ( aName.IsIntegerValue() ) { // aName must not start with a digit
500         aName.Insert( 1, 'a' );
501         isValidName = false;
502       }
503       int p, p2=1; // replace not allowed chars
504       while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
505         aName.SetValue(p, '_');
506         p2=p;
507         isValidName = false;
508       }
509       if ( aNameToEntry.IsBound( aName ) && anEntry != aNameToEntry( aName ))
510       {  // diff objects have same name - make a new name by appending a digit
511         TCollection_AsciiString aName2;
512         Standard_Integer i = 0;
513         do {
514           aName2 = aName + "_" + ++i;
515         } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
516         aName = aName2;
517         isValidName = false;
518       }
519       if ( !isValidName ) {
520         if ( isPublished )
521           anEntryToBadName.Bind( anEntry, theObjectNames.Find(anEntry) );
522         theObjectNames( anEntry ) = aName;
523       }
524     }
525     else {
526       do {
527         aName = aBaseName + TCollection_AsciiString(++objectCounter);
528       } while(aNameToEntry.IsBound(aName));
529       theObjectNames.Bind(anEntry, aName);
530     }
531     aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
532
533     anUpdatedScript += aName;
534     aStart = aSeq->Value(i+1) + 1;
535   }
536
537   //Add final part of the script
538   if (aLen && aSeq->Value(aLen) < aScriptLength)
539     anUpdatedScript += aScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
540
541   // ouv : NPAL12872
542   for (anEntryToNameIt.Initialize( theObjectNames );
543        anEntryToNameIt.More();
544        anEntryToNameIt.Next())
545   {
546     const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
547     const TCollection_AsciiString& aName = anEntryToNameIt.Value();
548
549     TDF_Label L;
550     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
551     if ( L.IsNull() )
552       continue;
553
554     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
555     if ( obj.IsNull() )
556       continue;
557
558     bool anAutoColor = obj->GetAutoColor();
559     if ( anAutoColor )
560     {
561       TCollection_AsciiString aCommand( "\n\t" );
562       aCommand += aName + ".SetAutoColor(1)";
563       anUpdatedScript += aCommand.ToCString();
564     }
565
566     SALOMEDS::Color aColor = obj->GetColor();
567     if ( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 )
568     {
569       TCollection_AsciiString aCommand( "\n\t" );
570       aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
571       anUpdatedScript += aCommand.ToCString();
572     }
573   }
574
575   // Make script to publish in study
576   if ( isPublished )
577   {
578     std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
579     for (anEntryToNameIt.Initialize( theObjectNames );
580          anEntryToNameIt.More();
581          anEntryToNameIt.Next())
582     {
583       const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
584       const TCollection_AsciiString& aName = anEntryToNameIt.Value();
585       if (!anObjMap.count(aEntry.ToCString()))
586         continue; // was not dumped
587       if ( !aEntry2StEntry.IsBound( aEntry ))
588         continue; // was not published
589       TCollection_AsciiString aCommand("\n\tgeompy."), aFatherEntry;
590
591       // find a father entry
592       const TCollection_AsciiString& aStudyEntry = aEntry2StEntry( aEntry );
593       TCollection_AsciiString aFatherStudyEntry =
594         aStudyEntry.SubString( 1, aStudyEntry.SearchFromEnd(":") - 1 );
595       if ( aStEntry2Entry.IsBound( aFatherStudyEntry ))
596         aFatherEntry = aStEntry2Entry( aFatherStudyEntry );
597
598       // make a command
599       if ( !aFatherEntry.IsEmpty() && theObjectNames.IsBound( aFatherEntry )) {
600         aCommand += "addToStudyInFather( ";
601         aCommand += theObjectNames( aFatherEntry ) + ", ";
602       }
603       else
604         aCommand += "addToStudy( ";
605       if ( anEntryToBadName.IsBound( aEntry ))
606         aCommand += aName + ", \"" + anEntryToBadName( aEntry ) + "\" )";
607       else
608         aCommand += aName + ", \"" + aName + "\" )";
609
610       // bind a command to the last digit of the entry
611       int tag =
612         aEntry.SubString( aEntry.SearchFromEnd(":")+1, aEntry.Length() ).IntegerValue();
613       anEntryToCommandMap.insert( std::make_pair( tag, aCommand.ToCString() ));
614     }
615
616     // add publishing commands to the script
617     std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
618     for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand ) {
619       anUpdatedScript += (char*)anEntryToCommand->second.c_str();
620     }
621   }
622
623   anUpdatedScript += "\n\tpass\n";
624   aValidScript = true;
625
626   // fill _studyEntry2NameMap and build globalVars
627   TCollection_AsciiString globalVars;
628   _studyEntry2NameMap.Clear();
629   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString aStEntryToEntryIt;
630   for (aStEntryToEntryIt.Initialize( aStEntry2Entry );
631        aStEntryToEntryIt.More();
632        aStEntryToEntryIt.Next() )
633   {
634     const TCollection_AsciiString & name = theObjectNames( aStEntryToEntryIt.Value() );
635     _studyEntry2NameMap.Bind (aStEntryToEntryIt.Key(), name );
636     if ( !globalVars.IsEmpty() )
637       globalVars += ", ";
638     globalVars += name;
639   }
640   if ( !globalVars.IsEmpty() ) {
641     globalVars.Insert( 1, "\n\tglobal " );
642     anUpdatedScript.Insert( posToInsertGlobalVars, globalVars );
643   }
644
645   return anUpdatedScript;
646 }
647
648 //=======================================================================
649 //function : GetDumpName
650 //purpose  :
651 //=======================================================================
652
653 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
654 {
655   if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
656     return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
657
658   return NULL;
659 }
660
661 //=======================================================================
662 //function : GetAllDumpNames
663 //purpose  :
664 //=======================================================================
665
666 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
667 {
668   Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
669
670   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
671   for (; it.More(); it.Next()) {
672     aRetSeq->Append(it.Value());
673   }
674
675   return aRetSeq;
676 }
677
678
679 //===========================================================================
680 //                     Internal functions
681 //===========================================================================
682 void ProcessFunction(Handle(GEOM_Function)&   theFunction,
683                      TCollection_AsciiString& theScript,
684                      TDF_LabelMap&            theProcessed,
685                      std::set<std::string>&   theDumpedObjs)
686 {
687   if (theFunction.IsNull()) return;
688   if (theProcessed.Contains(theFunction->GetEntry())) return;
689
690 /*
691   TDF_LabelSequence aSeq;
692   theFunction->GetDependency(aSeq);
693   Standard_Integer aLen = aSeq.Length();
694   for(Standard_Integer i = 1; i <= aLen; i++) {
695     Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aSeq.Value(i));
696     if(aFunction.IsNull()) continue;
697     ProcessFunction(aFunction, theScript, theProcessed);
698   }
699 */
700
701   // pass functions, that depends on nonexisting ones
702   bool doNotProcess = false;
703   TDF_LabelSequence aSeq;
704   theFunction->GetDependency(aSeq);
705   Standard_Integer aLen = aSeq.Length();
706   for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
707     TDF_Label aRefLabel = aSeq.Value(i);
708     Handle(TDF_Reference) aRef;
709     if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
710       doNotProcess = true;
711     }
712     else {
713       if (aRef.IsNull() || aRef->Get().IsNull()) {
714         doNotProcess = true;
715       }
716       else {
717         Handle(TDataStd_TreeNode) aT;
718         if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
719           doNotProcess = true;
720         }
721         else {
722           TDF_Label aDepLabel = aT->Label();
723           Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
724
725           if (aFunction.IsNull()) doNotProcess = true;
726           else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
727         }
728       }
729     }
730   }
731
732   if (doNotProcess) return;
733
734   TCollection_AsciiString aDescr = theFunction->GetDescription();
735   if(aDescr.Length() == 0) {
736     //cout << "Warning: the function has no description" << endl;
737     return;
738   }
739
740   //Check if its internal function which doesn't requires dumping
741   if(aDescr == "None") return;
742
743   theScript += "\n\t";
744   theScript += aDescr;
745
746   theProcessed.Add(theFunction->GetEntry());
747
748   TCollection_AsciiString anObjEntry;
749   TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
750   theDumpedObjs.insert(anObjEntry.ToCString());
751 }
752
753 //=============================================================================
754 /*!
755  *  FindEntries: Returns a sequence of start/end positions of entries in the string
756  */
757 //=============================================================================
758 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
759 {
760   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
761   Standard_Integer aLen = theString.Length();
762   Standard_Boolean isFound = Standard_False;
763
764   const char* arr = theString.ToCString();
765   Standard_Integer i = 0, j;
766
767   while(i < aLen) {
768     int c = (int)arr[i];
769     j = i+1;
770     if(c >= 48 && c <= 57) { //Is digit?
771
772       isFound = Standard_False;
773       while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
774         c = (int)arr[j++];
775         if(c == 58) isFound = Standard_True;
776       }
777
778       if(isFound && arr[j-2] != 58) { // last char should be a diggit
779         aSeq->Append(i+1); // +1 because AsciiString starts from 1
780         aSeq->Append(j-1);
781       }
782     }
783
784     i = j;
785   }
786
787   return aSeq;
788 }