Salome HOME
bce32c7463d7ca937bf466dfc4599fb49fd8ceb2
[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 (_freeLabels.find(theDocID) != _freeLabels.end()) {
210     std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
211     if (!aFreeLabels.empty()) {
212       useExisting = true;
213       aChild = aFreeLabels.front();
214       aFreeLabels.pop_front();
215     }
216   }
217   if (!useExisting) {
218     // create new label
219     aChild = TDF_TagSource::NewChild(aDoc->Main());
220   }
221
222   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
223
224   //Put an object in the map of created objects
225   TCollection_AsciiString anID = BuildIDFromObject(anObject);
226   if(_objects.IsBound(anID)) _objects.UnBind(anID);
227   _objects.Bind(anID, anObject);
228
229   return anObject;
230 }
231
232 //=============================================================================
233 /*!
234  *  AddSubShape
235  */
236 //=============================================================================
237 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
238                                              Handle(TColStd_HArray1OfInteger) theIndices,
239                                              bool isStandaloneOperation)
240 {
241   if(theMainShape.IsNull() || theIndices.IsNull()) return NULL;
242
243   Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
244   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
245
246   // NPAL18604: use existing label to decrease memory usage,
247   //            if this label has been freed (object deleted)
248   bool useExisting = false;
249   TDF_Label aChild;
250   /*
251   if (!_lastCleared.IsNull()) {
252     if (_lastCleared.Root() == aDoc->Main().Root()) {
253       useExisting = true;
254       aChild = _lastCleared;
255       // 0020229: if next label exists and is empty, try to reuse it
256       Standard_Integer aNextTag = aChild.Tag() + 1;
257       TDF_Label aNextL = aDoc->Main().FindChild(aNextTag, Standard_False);
258       if (!aNextL.IsNull() && !aNextL.HasAttribute())
259         _lastCleared = aNextL;
260       else
261         _lastCleared.Nullify();
262     }
263   }
264   */
265   int aDocID = theMainShape->GetDocID();
266   if (_freeLabels.find(aDocID) != _freeLabels.end()) {
267     std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
268     if (!aFreeLabels.empty()) {
269       useExisting = true;
270       aChild = aFreeLabels.front();
271       aFreeLabels.pop_front();
272     }
273   }
274   if (!useExisting) {
275     // create new label
276     aChild = TDF_TagSource::NewChild(aDoc->Main());
277   }
278
279   Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
280   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type
281   Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
282
283   GEOM_ISubShape aSSI(aFunction);
284   aSSI.SetMainShape(aMainShape);
285   aSSI.SetIndices(theIndices);
286
287   try {
288 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
289     OCC_CATCH_SIGNALS;
290 #endif
291     GEOM_Solver aSolver (GEOM_Engine::GetEngine());
292     if (!aSolver.ComputeFunction(aFunction)) {
293       MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
294       return NULL;
295     }
296   }
297   catch (Standard_Failure) {
298     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
299     MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
300     return NULL;
301   }
302
303   //Put an object in the map of created objects
304   TCollection_AsciiString anID = BuildIDFromObject(anObject);
305   if(_objects.IsBound(anID)) _objects.UnBind(anID);
306   _objects.Bind(anID, anObject);
307
308   GEOM::TPythonDump pd (aFunction);
309
310   if (isStandaloneOperation) {
311     pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
312     Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
313     for (; i <= up - 1; i++) {
314       pd << theIndices->Value(i) << ", ";
315     }
316     pd << theIndices->Value(up) << "])";
317   }
318   else
319     pd << "None";
320
321   return anObject;
322 }
323
324 //=============================================================================
325 /*!
326  *  RemoveObject
327  */
328 //=============================================================================
329 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
330 {
331   if (!theObject) return false;
332
333   int aDocID = theObject->GetDocID();
334
335   //Remove an object from the map of available objects
336   TCollection_AsciiString anID = BuildIDFromObject(theObject);
337   if (_objects.IsBound(anID)) _objects.UnBind(anID);
338
339   int nb = theObject->GetNbFunctions();
340   Handle(TDataStd_TreeNode) aNode;
341   for (int i = 1; i<=nb; i++) {
342     Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
343     if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
344       aNode->Remove();
345   }
346
347   TDF_Label aLabel = theObject->GetEntry();
348   aLabel.ForgetAllAttributes(Standard_True);
349
350   // Remember the label to reuse it then
351   std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
352   aFreeLabels.push_back(aLabel);
353
354   theObject.Nullify();
355
356   return true;
357 }
358
359 //=============================================================================
360 /*!
361  *  Undo
362  */
363 //=============================================================================
364 void GEOM_Engine::Undo(int theDocID)
365 {
366   GetDocument(theDocID)->Undo();
367 }
368
369 //=============================================================================
370 /*!
371  *  Redo
372  */
373 //=============================================================================
374 void GEOM_Engine::Redo(int theDocID)
375 {
376   GetDocument(theDocID)->Redo();
377 }
378
379 //=============================================================================
380 /*!
381  *  Save
382  */
383 //=============================================================================
384 bool GEOM_Engine::Save(int theDocID, char* theFileName)
385 {
386   if(!_mapIDDocument.IsBound(theDocID)) return false;
387   Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
388
389   _OCAFApp->SaveAs(aDoc, theFileName);
390
391   return true;
392 }
393
394 //=============================================================================
395 /*!
396  *  Load
397  */
398 //=============================================================================
399 bool GEOM_Engine::Load(int theDocID, char* theFileName)
400 {
401   Handle(TDocStd_Document) aDoc;
402   if(_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
403     return false;
404   }
405
406   aDoc->SetUndoLimit(_UndoLimit);
407
408   if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
409   _mapIDDocument.Bind(theDocID, aDoc);
410
411   TDataStd_Integer::Set(aDoc->Main(), theDocID);
412
413   return true;
414 }
415
416 //=============================================================================
417 /*!
418  *  Close
419  */
420 //=============================================================================
421 void GEOM_Engine::Close(int theDocID)
422 {
423   if (_mapIDDocument.IsBound(theDocID)) {
424     Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
425
426     //Remove all GEOM Objects associated to the given document
427     TColStd_SequenceOfAsciiString aSeq;
428     GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
429     for (; It.More(); It.Next()) {
430       TCollection_AsciiString anObjID (It.Key());
431       Standard_Integer anID = ExtractDocID(anObjID);
432       if (theDocID == anID) aSeq.Append(It.Key());
433     }
434     for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
435
436     // Forget free labels for this document
437     TFreeLabelsList::iterator anIt = _freeLabels.find(theDocID);
438     if (anIt != _freeLabels.end()) {
439       _freeLabels.erase(anIt);
440     }
441
442     _mapIDDocument.UnBind(theDocID);
443     _OCAFApp->Close(aDoc);
444     aDoc.Nullify();
445   }
446 }
447
448 //=============================================================================
449 /*!
450  *  DumpPython
451  */
452 //=============================================================================
453 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
454                                                 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
455                                                 bool isPublished,
456                                                 bool& aValidScript)
457 {
458   TCollection_AsciiString aScript;
459   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
460
461   if (aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
462
463   aScript  = "import geompy\n";
464   aScript += "import math\n";
465   aScript += "import SALOMEDS\n\n";
466   aScript += "def RebuildData(theStudy):";
467   aScript += "\n\tgeompy.init_geom(theStudy)";
468
469   Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
470
471   Handle(TDataStd_TreeNode) aNode, aRoot;
472   Handle(GEOM_Function) aFunction;
473   TDF_LabelMap aCheckedFuncMap;
474   std::set<std::string> anIgnoreObjMap;
475
476   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
477     TDataStd_ChildNodeIterator Itr(aRoot);
478     for (; Itr.More(); Itr.Next()) {
479       aNode = Itr.Value();
480       aFunction = GEOM_Function::GetFunction(aNode->Label());
481       if (aFunction.IsNull()) {
482         MESSAGE ( "Null function !!!!" );
483         continue;
484       }
485       ProcessFunction(aFunction, aScript, aCheckedFuncMap, anIgnoreObjMap);
486     }
487   }
488
489   Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry;
490   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
491   // build maps entry <-> studyEntry
492   for (anEntryToNameIt.Initialize( theObjectNames );
493        anEntryToNameIt.More();
494        anEntryToNameIt.Next())
495   {
496     const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
497     // look for an object by entry
498     TDF_Label L;
499     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
500     if ( L.IsNull() ) continue;
501     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
502     // fill maps
503     if ( !obj.IsNull() ) {
504       TCollection_AsciiString aStudyEntry (obj->GetAuxData());
505       aEntry2StEntry.Bind( aEntry,  aStudyEntry);
506       aStEntry2Entry.Bind( aStudyEntry, aEntry );
507     }
508   }
509
510   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
511   Standard_Integer aLen = aSeq->Length(), objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
512   Resource_DataMapOfAsciiStringAsciiString aNameToEntry, anEntryToBadName;
513
514   //Replace entries by the names
515   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
516     allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
517   if (aLen == 0) anUpdatedScript = aScript;
518
519   for (Standard_Integer i = 1; i <= aLen; i+=2) {
520     anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i)-1);
521     anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
522     if (theObjectNames.IsBound(anEntry)) {
523       aName = theObjectNames.Find(anEntry);
524       // check validity of aName
525       bool isValidName = true;
526       if ( aName.IsIntegerValue() ) { // aName must not start with a digit
527         aName.Insert( 1, 'a' );
528         isValidName = false;
529       }
530       int p, p2=1; // replace not allowed chars
531       while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
532         aName.SetValue(p, '_');
533         p2=p;
534         isValidName = false;
535       }
536       if ( aNameToEntry.IsBound( aName ) && anEntry != aNameToEntry( aName ))
537       {  // diff objects have same name - make a new name by appending a digit
538         TCollection_AsciiString aName2;
539         Standard_Integer i = 0;
540         do {
541           aName2 = aName + "_" + ++i;
542         } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
543         aName = aName2;
544         isValidName = false;
545       }
546       if ( !isValidName ) {
547         if ( isPublished )
548           anEntryToBadName.Bind( anEntry, theObjectNames.Find(anEntry) );
549         theObjectNames( anEntry ) = aName;
550       }
551     }
552     else {
553       do {
554         aName = aBaseName + TCollection_AsciiString(++objectCounter);
555       } while(aNameToEntry.IsBound(aName));
556       theObjectNames.Bind(anEntry, aName);
557     }
558     aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
559
560     anUpdatedScript += aName;
561     aStart = aSeq->Value(i+1) + 1;
562   }
563
564   //Add final part of the script
565   if (aLen && aSeq->Value(aLen) < aScriptLength)
566     anUpdatedScript += aScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
567
568   // ouv : NPAL12872
569   for (anEntryToNameIt.Initialize( theObjectNames );
570        anEntryToNameIt.More();
571        anEntryToNameIt.Next())
572   {
573     const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
574     const TCollection_AsciiString& aName = anEntryToNameIt.Value();
575
576     TDF_Label L;
577     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
578     if ( L.IsNull() )
579       continue;
580
581     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
582     if ( obj.IsNull() )
583       continue;
584
585     bool anAutoColor = obj->GetAutoColor();
586     if ( anAutoColor )
587     {
588       TCollection_AsciiString aCommand( "\n\t" );
589       aCommand += aName + ".SetAutoColor(1)";
590       anUpdatedScript += aCommand.ToCString();
591     }
592
593     SALOMEDS::Color aColor = obj->GetColor();
594     if ( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 )
595     {
596       TCollection_AsciiString aCommand( "\n\t" );
597       aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
598       anUpdatedScript += aCommand.ToCString();
599     }
600   }
601
602   // Make script to publish in study
603   if ( isPublished )
604   {
605     std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
606     for (anEntryToNameIt.Initialize( theObjectNames );
607          anEntryToNameIt.More();
608          anEntryToNameIt.Next())
609     {
610       const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
611       const TCollection_AsciiString& aName = anEntryToNameIt.Value();
612       if (anIgnoreObjMap.count(aEntry.ToCString()))
613         continue; // should not be dumped
614       if ( !aEntry2StEntry.IsBound( aEntry ))
615         continue; // was not published
616       TCollection_AsciiString aCommand("\n\tgeompy."), aFatherEntry;
617
618       // find a father entry
619       const TCollection_AsciiString& aStudyEntry = aEntry2StEntry( aEntry );
620       TCollection_AsciiString aFatherStudyEntry =
621         aStudyEntry.SubString( 1, aStudyEntry.SearchFromEnd(":") - 1 );
622       if ( aStEntry2Entry.IsBound( aFatherStudyEntry ))
623         aFatherEntry = aStEntry2Entry( aFatherStudyEntry );
624
625       // make a command
626       if ( !aFatherEntry.IsEmpty() && theObjectNames.IsBound( aFatherEntry )) {
627         aCommand += "addToStudyInFather( ";
628         aCommand += theObjectNames( aFatherEntry ) + ", ";
629       }
630       else
631         aCommand += "addToStudy( ";
632       if ( anEntryToBadName.IsBound( aEntry ))
633         aCommand += aName + ", \"" + anEntryToBadName( aEntry ) + "\" )";
634       else
635         aCommand += aName + ", \"" + aName + "\" )";
636
637       // bind a command to the last digit of the entry
638       int tag =
639         aEntry.SubString( aEntry.SearchFromEnd(":")+1, aEntry.Length() ).IntegerValue();
640       anEntryToCommandMap.insert( std::make_pair( tag, aCommand.ToCString() ));
641     }
642
643     // add publishing commands to the script
644     std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
645     for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand ) {
646       anUpdatedScript += (char*)anEntryToCommand->second.c_str();
647     }
648   }
649
650   anUpdatedScript += "\n\tpass\n";
651   aValidScript = true;
652
653   // fill _studyEntry2NameMap and build globalVars
654   TCollection_AsciiString globalVars;
655   _studyEntry2NameMap.Clear();
656   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString aStEntryToEntryIt;
657   for (aStEntryToEntryIt.Initialize( aStEntry2Entry );
658        aStEntryToEntryIt.More();
659        aStEntryToEntryIt.Next() )
660   {
661     const TCollection_AsciiString & name = theObjectNames( aStEntryToEntryIt.Value() );
662     _studyEntry2NameMap.Bind (aStEntryToEntryIt.Key(), name );
663     if ( !globalVars.IsEmpty() )
664       globalVars += ", ";
665     globalVars += name;
666   }
667   if ( !globalVars.IsEmpty() ) {
668     globalVars.Insert( 1, "\n\tglobal " );
669     anUpdatedScript.Insert( posToInsertGlobalVars, globalVars );
670   }
671
672   return anUpdatedScript;
673 }
674
675 //=======================================================================
676 //function : GetDumpName
677 //purpose  :
678 //=======================================================================
679
680 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
681 {
682   if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
683     return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
684
685   return NULL;
686 }
687
688 //=======================================================================
689 //function : GetAllDumpNames
690 //purpose  :
691 //=======================================================================
692
693 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
694 {
695   Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
696
697   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
698   for (; it.More(); it.Next()) {
699     aRetSeq->Append(it.Value());
700   }
701
702   return aRetSeq;
703 }
704
705
706 //===========================================================================
707 //                     Internal functions
708 //===========================================================================
709 void ProcessFunction(Handle(GEOM_Function)&   theFunction,
710                      TCollection_AsciiString& theScript,
711                      TDF_LabelMap&            theProcessed,
712                      std::set<std::string>&   theIgnoreObjs)
713 {
714   if (theFunction.IsNull()) return;
715
716   if (theProcessed.Contains(theFunction->GetEntry())) return;
717
718   // pass functions, that depends on nonexisting ones
719   bool doNotProcess = false;
720   TDF_LabelSequence aSeq;
721   theFunction->GetDependency(aSeq);
722   Standard_Integer aLen = aSeq.Length();
723   for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
724     TDF_Label aRefLabel = aSeq.Value(i);
725     Handle(TDF_Reference) aRef;
726     if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
727       doNotProcess = true;
728     }
729     else {
730       if (aRef.IsNull() || aRef->Get().IsNull()) {
731         doNotProcess = true;
732       }
733       else {
734         Handle(TDataStd_TreeNode) aT;
735         if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
736           doNotProcess = true;
737         }
738         else {
739           TDF_Label aDepLabel = aT->Label();
740           Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
741
742           if (aFunction.IsNull()) doNotProcess = true;
743           else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
744         }
745       }
746     }
747   }
748
749   if (doNotProcess) {
750     TCollection_AsciiString anObjEntry;
751     TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
752     theIgnoreObjs.insert(anObjEntry.ToCString());
753     return;
754   }
755   theProcessed.Add(theFunction->GetEntry());
756
757   TCollection_AsciiString aDescr = theFunction->GetDescription();
758   if(aDescr.Length() == 0) return;
759
760   //Check if its internal function which doesn't requires dumping
761   if(aDescr == "None") return;
762
763   theScript += "\n\t";
764   theScript += aDescr;
765 }
766
767 //=============================================================================
768 /*!
769  *  FindEntries: Returns a sequence of start/end positions of entries in the string
770  */
771 //=============================================================================
772 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
773 {
774   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
775   Standard_Integer aLen = theString.Length();
776   Standard_Boolean isFound = Standard_False;
777
778   const char* arr = theString.ToCString();
779   Standard_Integer i = 0, j;
780
781   while(i < aLen) {
782     int c = (int)arr[i];
783     j = i+1;
784     if(c >= 48 && c <= 57) { //Is digit?
785
786       isFound = Standard_False;
787       while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
788         c = (int)arr[j++];
789         if(c == 58) isFound = Standard_True;
790       }
791
792       if(isFound && arr[j-2] != 58) { // last char should be a diggit
793         aSeq->Append(i+1); // +1 because AsciiString starts from 1
794         aSeq->Append(j-1);
795       }
796     }
797
798     i = j;
799   }
800
801   return aSeq;
802 }