]> SALOME platform Git repositories - modules/geom.git/blob - src/GEOM/GEOM_Engine.cxx
Salome HOME
7a572ba1fca7ce2de164d043bb8f22452041c04f
[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 #include <vector>
62
63 #include <Standard_Failure.hxx>
64 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
65
66 #define COMMA ','
67 #define O_BRACKET '('
68 #define C_BRACKET ')'
69 #define O_SQR_BRACKET '['
70 #define C_SQR_BRACKET ']'
71 #define PY_NULL "None"
72
73 #ifdef _DEBUG_
74 static int MYDEBUG = 0;
75 #else
76 static int MYDEBUG = 0;
77 #endif
78
79 static GEOM_Engine* TheEngine = NULL;
80
81 using namespace std;
82
83 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
84 {
85   TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
86   TDF_Tool::Entry(theObject->GetEntry(), anEntry);
87   anID+=(TCollection_AsciiString("_")+anEntry);
88   return anID;
89 }
90
91 static TCollection_AsciiString BuildID(Standard_Integer theDocID, char* theEntry)
92 {
93   TCollection_AsciiString anID(theDocID);
94   anID+=(TCollection_AsciiString("_")+theEntry);
95   return anID;
96 }
97
98 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
99 {
100   TCollection_AsciiString aDocID = theID.Token("_");
101   if(aDocID.Length() < 1) return -1;
102   return aDocID.IntegerValue();
103 }
104
105 bool ProcessFunction(Handle(GEOM_Function)&   theFunction,
106                      TCollection_AsciiString& theScript,
107                      TCollection_AsciiString& theAfterScript,
108                      const TVariablesList&    theVariables,
109                      const bool               theIsPublished,
110                      TDF_LabelMap&            theProcessed,
111                      std::set<std::string>&   theIgnoreObjs,
112                      bool&                    theIsDumpCollected);
113
114 void ReplaceVariables(TCollection_AsciiString& theCommand, 
115                       const TVariablesList&    theVariables);
116
117 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
118
119 void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
120                             Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
121                             const bool                                theIsPublished,
122                             Resource_DataMapOfAsciiStringAsciiString& theEntryToBadName,
123                             TColStd_SequenceOfAsciiString&            theObjListToPublish);
124
125 void AddObjectColors (const Handle(TDocStd_Document)&                 theDoc,
126                       TCollection_AsciiString&                        theScript,
127                       const Resource_DataMapOfAsciiStringAsciiString& theObjectNames);
128
129 void PublishObject (const TCollection_AsciiString&                  theEntry,
130                     const TCollection_AsciiString&                  theName,
131                     const Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
132                     const Resource_DataMapOfAsciiStringAsciiString& theEntry2StEntry,
133                     const Resource_DataMapOfAsciiStringAsciiString& theStEntry2Entry,
134                     const Resource_DataMapOfAsciiStringAsciiString& theEntryToBadName,
135                     std::map< int, std::string >&                   theEntryToCommandMap,
136                     std::set<std::string>&                          theMapOfPublished);
137
138 //=============================================================================
139 /*!
140  *  GetEngine
141  */
142 //=============================================================================
143 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
144
145 //=============================================================================
146 /*!
147  *  SetEngine
148  */
149 //=============================================================================
150 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
151
152 //=============================================================================
153 /*!
154  *  Constructor
155  */
156 //=============================================================================
157 GEOM_Engine::GEOM_Engine()
158 {
159   TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
160
161   _OCAFApp = new GEOM_Application();
162   _UndoLimit = 10;
163 }
164
165 /*!
166  *  Destructor
167  */
168 GEOM_Engine::~GEOM_Engine()
169 {
170   GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
171   for(; It.More(); It.Next())
172     {
173       RemoveObject(Handle(GEOM_Object)::DownCast(It.Value()));
174     }
175
176   //Close all documents not closed
177   for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
178     Close(anItr.Key());
179
180   _mapIDDocument.Clear();
181   _objects.Clear();
182 }
183
184 //=============================================================================
185 /*!
186  *  GetDocument
187  */
188 //=============================================================================
189 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID)
190 {
191   Handle(TDocStd_Document) aDoc;
192   if(!_mapIDDocument.IsBound(theDocID)) {
193     _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
194     aDoc->SetUndoLimit(_UndoLimit);
195     _mapIDDocument.Bind(theDocID, aDoc);
196     TDataStd_Integer::Set(aDoc->Main(), theDocID);
197   }
198
199   return Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
200 }
201
202 //=============================================================================
203 /*!
204  *  GetDocID
205  */
206 //=============================================================================
207 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
208 {
209   if(theDocument.IsNull()) return -1;
210   for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
211     if(anItr.Value() == theDocument) return anItr.Key();
212
213   return -1;
214
215 }
216
217 //=============================================================================
218 /*!
219  *  GetObject
220  */
221 //=============================================================================
222 Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry)
223 {
224   TCollection_AsciiString anID = BuildID(theDocID, theEntry);
225   if(_objects.IsBound(anID)) return Handle(GEOM_Object)::DownCast(_objects(anID));
226
227   TDF_Label aLabel;
228   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
229   TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
230   Handle(GEOM_Object) anObject = new GEOM_Object(aLabel);
231
232   _objects.Bind(anID, anObject);
233
234   return anObject;
235 }
236
237 //=============================================================================
238 /*!
239  *  AddObject
240  */
241 //=============================================================================
242 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
243 {
244   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
245   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
246
247   // NPAL18604: use existing label to decrease memory usage,
248   //            if this label has been freed (object deleted)
249   bool useExisting = false;
250   TDF_Label aChild;
251   if (_freeLabels.find(theDocID) != _freeLabels.end()) {
252     std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
253     if (!aFreeLabels.empty()) {
254       useExisting = true;
255       aChild = aFreeLabels.front();
256       aFreeLabels.pop_front();
257     }
258   }
259   if (!useExisting) {
260     // create new label
261     aChild = TDF_TagSource::NewChild(aDoc->Main());
262   }
263
264   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
265
266   //Put an object in the map of created objects
267   TCollection_AsciiString anID = BuildIDFromObject(anObject);
268   if(_objects.IsBound(anID)) _objects.UnBind(anID);
269   _objects.Bind(anID, anObject);
270
271   return anObject;
272 }
273
274 //=============================================================================
275 /*!
276  *  AddSubShape
277  */
278 //=============================================================================
279 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
280                                              Handle(TColStd_HArray1OfInteger) theIndices,
281                                              bool isStandaloneOperation)
282 {
283   if(theMainShape.IsNull() || theIndices.IsNull()) return NULL;
284
285   Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
286   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
287
288   // NPAL18604: use existing label to decrease memory usage,
289   //            if this label has been freed (object deleted)
290   bool useExisting = false;
291   TDF_Label aChild;
292   /*
293   if (!_lastCleared.IsNull()) {
294     if (_lastCleared.Root() == aDoc->Main().Root()) {
295       useExisting = true;
296       aChild = _lastCleared;
297       // 0020229: if next label exists and is empty, try to reuse it
298       Standard_Integer aNextTag = aChild.Tag() + 1;
299       TDF_Label aNextL = aDoc->Main().FindChild(aNextTag, Standard_False);
300       if (!aNextL.IsNull() && !aNextL.HasAttribute())
301         _lastCleared = aNextL;
302       else
303         _lastCleared.Nullify();
304     }
305   }
306   */
307   int aDocID = theMainShape->GetDocID();
308   if (_freeLabels.find(aDocID) != _freeLabels.end()) {
309     std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
310     if (!aFreeLabels.empty()) {
311       useExisting = true;
312       aChild = aFreeLabels.front();
313       aFreeLabels.pop_front();
314     }
315   }
316   if (!useExisting) {
317     // create new label
318     aChild = TDF_TagSource::NewChild(aDoc->Main());
319   }
320
321   Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
322   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type
323   Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
324
325   GEOM_ISubShape aSSI(aFunction);
326   aSSI.SetMainShape(aMainShape);
327   aSSI.SetIndices(theIndices);
328
329   try {
330 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
331     OCC_CATCH_SIGNALS;
332 #endif
333     GEOM_Solver aSolver (GEOM_Engine::GetEngine());
334     if (!aSolver.ComputeFunction(aFunction)) {
335       MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
336       return NULL;
337     }
338   }
339   catch (Standard_Failure) {
340     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
341     MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
342     return NULL;
343   }
344
345   //Put an object in the map of created objects
346   TCollection_AsciiString anID = BuildIDFromObject(anObject);
347   if(_objects.IsBound(anID)) _objects.UnBind(anID);
348   _objects.Bind(anID, anObject);
349
350   GEOM::TPythonDump pd (aFunction);
351
352   if (isStandaloneOperation) {
353     pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
354     Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
355     for (; i <= up - 1; i++) {
356       pd << theIndices->Value(i) << ", ";
357     }
358     pd << theIndices->Value(up) << "])";
359   }
360   else
361     pd << "None";
362
363   return anObject;
364 }
365
366 //=============================================================================
367 /*!
368  *  RemoveObject
369  */
370 //=============================================================================
371 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
372 {
373   if (!theObject) return false;
374
375   int aDocID = theObject->GetDocID();
376
377   //Remove an object from the map of available objects
378   TCollection_AsciiString anID = BuildIDFromObject(theObject);
379   if (_objects.IsBound(anID)) _objects.UnBind(anID);
380
381   int nb = theObject->GetNbFunctions();
382   Handle(TDataStd_TreeNode) aNode;
383   for (int i = 1; i<=nb; i++) {
384     Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
385     if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
386       aNode->Remove();
387   }
388
389   TDF_Label aLabel = theObject->GetEntry();
390   aLabel.ForgetAllAttributes(Standard_True);
391
392   // Remember the label to reuse it then
393   std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
394   aFreeLabels.push_back(aLabel);
395
396   theObject.Nullify();
397
398   return true;
399 }
400
401 //=============================================================================
402 /*!
403  *  Undo
404  */
405 //=============================================================================
406 void GEOM_Engine::Undo(int theDocID)
407 {
408   GetDocument(theDocID)->Undo();
409 }
410
411 //=============================================================================
412 /*!
413  *  Redo
414  */
415 //=============================================================================
416 void GEOM_Engine::Redo(int theDocID)
417 {
418   GetDocument(theDocID)->Redo();
419 }
420
421 //=============================================================================
422 /*!
423  *  Save
424  */
425 //=============================================================================
426 bool GEOM_Engine::Save(int theDocID, char* theFileName)
427 {
428   if(!_mapIDDocument.IsBound(theDocID)) return false;
429   Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
430
431   _OCAFApp->SaveAs(aDoc, theFileName);
432
433   return true;
434 }
435
436 //=============================================================================
437 /*!
438  *  Load
439  */
440 //=============================================================================
441 bool GEOM_Engine::Load(int theDocID, char* theFileName)
442 {
443   Handle(TDocStd_Document) aDoc;
444   if(_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
445     return false;
446   }
447
448   aDoc->SetUndoLimit(_UndoLimit);
449
450   if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
451   _mapIDDocument.Bind(theDocID, aDoc);
452
453   TDataStd_Integer::Set(aDoc->Main(), theDocID);
454
455   return true;
456 }
457
458 //=============================================================================
459 /*!
460  *  Close
461  */
462 //=============================================================================
463 void GEOM_Engine::Close(int theDocID)
464 {
465   if (_mapIDDocument.IsBound(theDocID)) {
466     Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
467
468     //Remove all GEOM Objects associated to the given document
469     TColStd_SequenceOfAsciiString aSeq;
470     GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
471     for (; It.More(); It.Next()) {
472       TCollection_AsciiString anObjID (It.Key());
473       Standard_Integer anID = ExtractDocID(anObjID);
474       if (theDocID == anID) aSeq.Append(It.Key());
475     }
476     for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
477
478     // Forget free labels for this document
479     TFreeLabelsList::iterator anIt = _freeLabels.find(theDocID);
480     if (anIt != _freeLabels.end()) {
481       _freeLabels.erase(anIt);
482     }
483
484     _mapIDDocument.UnBind(theDocID);
485     _OCAFApp->Close(aDoc);
486     aDoc.Nullify();
487   }
488 }
489
490 //=============================================================================
491 /*!
492  *  DumpPython
493  */
494 //=============================================================================
495 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
496                                                 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
497                                                 TVariablesList theVariables,
498                                                 bool isPublished,
499                                                 bool& aValidScript)
500 {
501   TCollection_AsciiString aScript;
502   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
503
504   if (aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
505
506   aScript  = "import geompy\n";
507   aScript += "import math\n";
508   aScript += "import SALOMEDS\n\n";
509   aScript += "def RebuildData(theStudy):";
510   aScript += "\n\tgeompy.init_geom(theStudy)";
511
512   Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
513
514   Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry;
515   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
516   // build maps entry <-> studyEntry
517   for (anEntryToNameIt.Initialize( theObjectNames );
518        anEntryToNameIt.More();
519        anEntryToNameIt.Next())
520   {
521     const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
522     // look for an object by entry
523     TDF_Label L;
524     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
525     if ( L.IsNull() ) continue;
526     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
527     // fill maps
528     if ( !obj.IsNull() ) {
529       TCollection_AsciiString aStudyEntry (obj->GetAuxData());
530       aEntry2StEntry.Bind( aEntry,  aStudyEntry);
531       aStEntry2Entry.Bind( aStudyEntry, aEntry );
532     }
533   }
534
535   // collect objects entries to be published
536   TColStd_SequenceOfAsciiString aObjListToPublish;
537   
538   // iterates on functions till critical (that requiers publication of objects)
539   Handle(TDataStd_TreeNode) aNode, aRoot;
540   Handle(GEOM_Function) aFunction;
541   TDF_LabelMap aCheckedFuncMap;
542   std::set<std::string> anIgnoreObjMap;
543
544   TCollection_AsciiString aFuncScript;
545   Resource_DataMapOfAsciiStringAsciiString anEntryToBadName;
546
547   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
548     TDataStd_ChildNodeIterator Itr(aRoot);
549     for (; Itr.More(); Itr.Next()) {
550       aNode = Itr.Value();
551       aFunction = GEOM_Function::GetFunction(aNode->Label());
552       if (aFunction.IsNull()) {
553         MESSAGE ( "Null function !!!!" );
554         continue;
555       }
556       bool isDumpCollected = false;
557       TCollection_AsciiString aCurScript, anAfterScript;
558       if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
559                            isPublished, aCheckedFuncMap, anIgnoreObjMap,
560                            isDumpCollected ))
561         continue;
562       // add function description before dump
563       if (!aCurScript.IsEmpty())
564         aFuncScript += aCurScript;
565       if (isDumpCollected ) {
566         // Replace entries by the names
567         ReplaceEntriesByNames( aFuncScript, theObjectNames,
568                                isPublished, anEntryToBadName, aObjListToPublish );
569         
570         // publish collected objects
571         std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
572         int i = 1, n = aObjListToPublish.Length();
573         for ( ; i <= n; i++ )
574         {
575           const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
576           if (!theObjectNames.IsBound( aEntry ))
577             continue;
578           PublishObject( aEntry, theObjectNames.Find(aEntry),
579                         theObjectNames, aEntry2StEntry, aStEntry2Entry,
580                         anEntryToBadName, anEntryToCommandMap, anIgnoreObjMap );
581         }
582         // add publishing commands to the script
583         std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
584         for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand )
585           aFuncScript += (char*)anEntryToCommand->second.c_str();
586         
587         // PTv, 0020001 add result objects from RestoreSubShapes into ignore list,
588         //  because they will be published during command execution
589         int indx = anAfterScript.Search( "RestoreSubShapes" );
590         if ( indx != -1 ) {
591           TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
592           Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
593           i = 1, n = aSeq->Length();
594           for ( ; i <= n; i+=2) {
595             TCollection_AsciiString anEntry =
596               aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
597             if (!anIgnoreObjMap.count(anEntry.ToCString()))
598               anIgnoreObjMap.insert(anEntry.ToCString());
599           }
600         }
601
602         aObjListToPublish.Clear();
603         aScript += aFuncScript;
604         aFuncScript.Clear();
605       }
606       aFuncScript += anAfterScript;
607     }
608   }
609
610   // Replace entries by the names
611   aObjListToPublish.Clear();
612   ReplaceEntriesByNames( aFuncScript, theObjectNames,
613                          isPublished, anEntryToBadName, aObjListToPublish );
614   
615   aScript += aFuncScript;
616
617   // ouv : NPAL12872
618   AddObjectColors( aDoc, aScript, theObjectNames );
619
620   // Make script to publish in study
621   if ( isPublished )
622   {
623     std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
624     for (anEntryToNameIt.Initialize( theObjectNames );
625          anEntryToNameIt.More();
626          anEntryToNameIt.Next())
627     {
628       const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
629       if (anIgnoreObjMap.count(aEntry.ToCString()))
630         continue; // should not be dumped
631       const TCollection_AsciiString& aName = anEntryToNameIt.Value();
632       PublishObject( aEntry, aName, theObjectNames,
633                     aEntry2StEntry, aStEntry2Entry,
634                     anEntryToBadName, anEntryToCommandMap, anIgnoreObjMap );
635     }
636     // add publishing commands to the script
637     std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
638     for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand )
639       aScript += (char*)anEntryToCommand->second.c_str();
640   }
641
642   //aScript += "\n\tpass\n";
643   aScript += "\n";
644   aValidScript = true;
645
646   // fill _studyEntry2NameMap and build globalVars
647   TCollection_AsciiString globalVars;
648   _studyEntry2NameMap.Clear();
649   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString aStEntryToEntryIt;
650   for (aStEntryToEntryIt.Initialize( aStEntry2Entry );
651        aStEntryToEntryIt.More();
652        aStEntryToEntryIt.Next() )
653   {
654     const TCollection_AsciiString & name = theObjectNames( aStEntryToEntryIt.Value() );
655     _studyEntry2NameMap.Bind (aStEntryToEntryIt.Key(), name );
656     if ( !globalVars.IsEmpty() )
657       globalVars += ", ";
658     globalVars += name;
659   }
660   if ( !globalVars.IsEmpty() ) {
661     globalVars.Insert( 1, "\n\tglobal " );
662     aScript.Insert( posToInsertGlobalVars, globalVars );
663   }
664
665   return aScript;
666 }
667
668 //=======================================================================
669 //function : GetDumpName
670 //purpose  :
671 //=======================================================================
672
673 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
674 {
675   if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
676     return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
677
678   return NULL;
679 }
680
681 //=======================================================================
682 //function : GetAllDumpNames
683 //purpose  :
684 //=======================================================================
685
686 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
687 {
688   Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
689
690   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
691   for (; it.More(); it.Next()) {
692     aRetSeq->Append(it.Value());
693   }
694
695   return aRetSeq;
696 }
697
698
699 //===========================================================================
700 //                     Internal functions
701 //===========================================================================
702
703 //=============================================================================
704 /*!
705  *  ProcessFunction: Dump fucntion description into script
706  */
707 //=============================================================================
708 bool ProcessFunction(Handle(GEOM_Function)&     theFunction,
709                      TCollection_AsciiString&   theScript,
710                      TCollection_AsciiString&   theAfterScript,
711                      const TVariablesList&      theVariables,
712                      const bool                 theIsPublished,
713                      TDF_LabelMap&              theProcessed,
714                      std::set<std::string>&     theIgnoreObjs,
715                      bool&                      theIsDumpCollected)
716 {
717   theIsDumpCollected = false;
718   if (theFunction.IsNull()) return false;
719
720   if (theProcessed.Contains(theFunction->GetEntry())) return false;
721
722   // pass functions, that depends on nonexisting ones
723   bool doNotProcess = false;
724   TDF_LabelSequence aSeq;
725   theFunction->GetDependency(aSeq);
726   Standard_Integer aLen = aSeq.Length();
727   for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
728     TDF_Label aRefLabel = aSeq.Value(i);
729     Handle(TDF_Reference) aRef;
730     if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
731       doNotProcess = true;
732     }
733     else {
734       if (aRef.IsNull() || aRef->Get().IsNull()) {
735         doNotProcess = true;
736       }
737       else {
738         Handle(TDataStd_TreeNode) aT;
739         if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
740           doNotProcess = true;
741         }
742         else {
743           TDF_Label aDepLabel = aT->Label();
744           Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
745
746           if (aFunction.IsNull()) doNotProcess = true;
747           else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
748         }
749       }
750     }
751   }
752
753   if (doNotProcess) {
754     TCollection_AsciiString anObjEntry;
755     TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
756     theIgnoreObjs.insert(anObjEntry.ToCString());
757     return false;
758   }
759   theProcessed.Add(theFunction->GetEntry());
760
761   TCollection_AsciiString aDescr = theFunction->GetDescription();
762   if(aDescr.Length() == 0) return false;
763
764   //Check if its internal function which doesn't requires dumping
765   if(aDescr == "None") return false;
766
767   // 0020001 PTv, check for critical functions, which requier dump of objects
768   if (theIsPublished)
769   {
770     // currently, there is only one function "RestoreSubShapes",
771     // later this check could be replaced by iterations on list of such functions
772     if (aDescr.Search( "RestoreSubShapes" ) != -1)
773       theIsDumpCollected = true;
774   }
775
776   //Replace parameter by notebook variables
777   ReplaceVariables(aDescr,theVariables);
778   if ( theIsDumpCollected ) {
779     int i = 1;
780     bool isBefore = true;
781     TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
782     while (!aSubStr.IsEmpty()) {
783       if (isBefore && aSubStr.Search( "RestoreSubShapes" ) == -1)
784         theScript += TCollection_AsciiString("\n\t") + aSubStr;
785       else
786         theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
787       aSubStr = aDescr.Token("\n\t", i++);
788     }
789   }
790   else {
791     theScript += "\n\t";
792     theScript += aDescr;
793   }
794   return true;
795 }
796
797 //=============================================================================
798 /*!
799  *  FindEntries: Returns a sequence of start/end positions of entries in the string
800  */
801 //=============================================================================
802 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
803 {
804   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
805   Standard_Integer aLen = theString.Length();
806   Standard_Boolean isFound = Standard_False;
807
808   const char* arr = theString.ToCString();
809   Standard_Integer i = 0, j;
810
811   while(i < aLen) {
812     int c = (int)arr[i];
813     j = i+1;
814     if(c >= 48 && c <= 57) { //Is digit?
815
816       isFound = Standard_False;
817       while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
818         c = (int)arr[j++];
819         if(c == 58) isFound = Standard_True;
820       }
821
822       if(isFound && arr[j-2] != 58) { // last char should be a diggit
823         aSeq->Append(i+1); // +1 because AsciiString starts from 1
824         aSeq->Append(j-1);
825       }
826     }
827
828     i = j;
829   }
830
831   return aSeq;
832 }
833
834 //=============================================================================
835 /*!
836  *  ReplaceVariables: Replace parameters of the function by variales from 
837  *                    Notebook if need
838  */
839 //=============================================================================
840 void ReplaceVariables(TCollection_AsciiString& theCommand, 
841                       const TVariablesList&    theVariables)
842 {
843   if (MYDEBUG)
844     cout<<"Command : "<<theCommand<<endl;
845
846   if (MYDEBUG) {
847     cout<<"All Entries:"<<endl;
848     TVariablesList::const_iterator it = theVariables.begin();
849     for(;it != theVariables.end();it++)
850       cout<<"\t'"<<(*it).first<<"'"<<endl;
851   }
852
853   //Additional case - multi-row commands
854   int aCommandIndex = 1;
855   while( aCommandIndex < 10 ) { // tmp check
856     TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
857     if( aCommand.Length() == 0 )
858       break;
859
860     if (MYDEBUG)
861       cout<<"Sub-command : "<<aCommand<<endl;
862
863     Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
864     Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
865
866     //Get Entry of the result object
867     TCollection_AsciiString anEntry;
868     if( aCommand.Search("=") != -1 ) // command returns an object
869       anEntry = aCommand.Token("=",1);
870     else { // command modifies the object
871       if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
872         if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
873           anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
874     }
875     //Remove white spaces
876     anEntry.RightAdjust();
877     anEntry.LeftAdjust();
878     if(MYDEBUG)
879       cout<<"Result entry : '" <<anEntry<<"'"<<endl;
880
881     if ( anEntry.IsEmpty() ) {
882       aCommandIndex++;
883       continue;
884     }
885
886     //Check if result is list of entries - enough to get the first entry in this case
887     int aNbEntries = 1;
888     if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
889       while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
890         aNbEntries++;
891       TCollection_AsciiString aSeparator(COMMA);
892       anEntry = anEntry.Token(aSeparator.ToCString(),1);
893       anEntry.Remove( 1, 1 );
894       anEntry.RightAdjust();
895       anEntry.LeftAdjust();
896       if(MYDEBUG)
897         cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
898     }
899     
900     //Find variables used for object construction
901     ObjectStates* aStates = 0;
902     TVariablesList::const_iterator it = theVariables.find(anEntry);
903     if( it != theVariables.end() )
904       aStates = (*it).second;
905
906     if(!aStates) {
907       if(MYDEBUG)
908         cout<<"Valiables list empty!!!"<<endl;
909       aCommandIndex++;
910       continue;
911     }
912
913     TState aVariables = aStates->GetCurrectState();
914
915     if(MYDEBUG) {
916       cout<<"Variables from SObject:"<<endl;
917       for (int i = 0; i < aVariables.size();i++)
918         cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
919     }
920
921     //Calculate total number of parameters
922     Standard_Integer aTotalNbParams = 1;
923     while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
924       aTotalNbParams++;
925
926     if(MYDEBUG)
927       cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
928
929     Standard_Integer aFirstParam = aNbEntries;
930
931     //Replace parameters by variables
932     Standard_Integer aStartPos = 0;
933     Standard_Integer aEndPos = 0;
934     int iVar = 0;
935     TCollection_AsciiString aVar, aReplacedVar;
936     for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
937       //Replace first parameter (bettwen '(' character and first ',' character)
938       if(i == aFirstParam)
939       {
940         aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
941         if(aTotalNbParams - aNbEntries > 0 )
942           aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
943         else
944           aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length()); 
945       }
946       //Replace last parameter (bettwen ',' character and ')' character)
947       else if(i == aTotalNbParams)
948       {
949         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
950         aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
951       }
952       //Replace other parameters (bettwen two ',' characters)
953       else if(i != aFirstParam && i != aTotalNbParams )
954       {
955         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
956         aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
957       }
958
959       if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
960         aStartPos++;
961       if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
962         aEndPos--;
963       if ( aStartPos == aEndPos )
964         continue; // PAL20889: for "[]"
965
966       if(MYDEBUG) 
967         cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
968
969       aVar = aCommand.SubString(aStartPos, aEndPos-1);
970       aVar.RightAdjust();
971       aVar.LeftAdjust();
972     
973       if(MYDEBUG) 
974         cout<<"Variable: '"<< aVar <<"'"<<endl;
975
976       // specific case for sketcher
977       if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
978         Standard_Integer aNbSections = 1;
979         while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
980           aNbSections++;
981         aNbSections--;
982
983         int aStartSectionPos = 0, aEndSectionPos = 0;
984         TCollection_AsciiString aSection, aReplacedSection;
985         for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
986           aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
987           if( aSectionIndex != aNbSections )
988             aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
989           else
990             aEndSectionPos = aVar.Length();
991
992           aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
993           if(MYDEBUG) 
994             cout<<"aSection: "<<aSection<<endl;
995
996           Standard_Integer aNbParams = 1;
997           while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
998             aNbParams++;
999           aNbParams--;
1000
1001           int aStartParamPos = 0, aEndParamPos = 0;
1002           TCollection_AsciiString aParameter, aReplacedParameter;
1003           for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1004             aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1005             if( aParamIndex != aNbParams )
1006               aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1007             else
1008               aEndParamPos = aSection.Length() + 1;
1009
1010             aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1011             if(MYDEBUG) 
1012               cout<<"aParameter: "<<aParameter<<endl;
1013
1014             if(iVar >= aVariables.size())
1015               continue;
1016
1017             aReplacedParameter = aVariables[iVar].myVariable;
1018             if(aReplacedParameter.IsEmpty()) {
1019               iVar++;
1020               continue;
1021             }
1022
1023             if(aVariables[iVar].isVariable) {
1024               aReplacedParameter.InsertBefore(1,"'");
1025               aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1026             }
1027
1028             if(MYDEBUG) 
1029               cout<<"aSection before : "<<aSection<<endl;
1030             aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1031             aSection.Insert(aStartParamPos, aReplacedParameter);
1032             if(MYDEBUG) 
1033               cout<<"aSection after  : "<<aSection<<endl<<endl;
1034             iVar++;
1035           }
1036           if(MYDEBUG) 
1037             cout<<"aVar before : "<<aVar<<endl;
1038           aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1039           aVar.Insert(aStartSectionPos, aSection);
1040           if(MYDEBUG) 
1041             cout<<"aVar after  : "<<aVar<<endl<<endl;
1042         }
1043
1044         if(MYDEBUG) 
1045           cout<<"aCommand before : "<<aCommand<<endl;
1046         aCommand.Remove(aStartPos, aEndPos - aStartPos);
1047         aCommand.Insert(aStartPos, aVar);
1048         if(MYDEBUG) 
1049           cout<<"aCommand after  : "<<aCommand<<endl;
1050
1051         break;
1052       } // end of specific case for sketcher
1053
1054       //If parameter is entry or 'None', skip it
1055       if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1056         continue;
1057
1058       if(iVar >= aVariables.size())
1059         continue;
1060
1061       aReplacedVar = aVariables[iVar].myVariable;
1062       if(aReplacedVar.IsEmpty()) {
1063         iVar++;
1064         continue;
1065       }
1066
1067       if(aVariables[iVar].isVariable) {
1068         aReplacedVar.InsertBefore(1,"\"");
1069         aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1070       }
1071
1072       aCommand.Remove(aStartPos, aEndPos - aStartPos);
1073       aCommand.Insert(aStartPos, aReplacedVar);
1074       iVar++;
1075     }
1076
1077     theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1078     theCommand.Insert(aStartCommandPos, aCommand);
1079
1080     aCommandIndex++;
1081
1082     aStates->IncrementState();
1083   }
1084
1085   if (MYDEBUG)
1086     cout<<"Command : "<<theCommand<<endl;
1087 }
1088
1089 //=============================================================================
1090 /*!
1091  *  ReplaceEntriesByNames: Replace object entries by their names
1092  */
1093 //=============================================================================
1094 void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
1095                             Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
1096                             const bool                                theIsPublished,
1097                             Resource_DataMapOfAsciiStringAsciiString& theEntryToBadName,
1098                             TColStd_SequenceOfAsciiString&            theObjListToPublish)
1099 {
1100   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1101   Standard_Integer aLen = aSeq->Length(), objectCounter = 0, aStart = 1, aScriptLength = theScript.Length();
1102   Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
1103
1104   //Replace entries by the names
1105   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1106     allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1107   if (aLen == 0) anUpdatedScript = theScript;
1108
1109   for (Standard_Integer i = 1; i <= aLen; i+=2) {
1110     anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1111     anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1112     theObjListToPublish.Append( anEntry );
1113     if (theObjectNames.IsBound(anEntry)) {
1114       aName = theObjectNames.Find(anEntry);
1115       // check validity of aName
1116       bool isValidName = true;
1117       if ( aName.IsIntegerValue() ) { // aName must not start with a digit
1118         aName.Insert( 1, 'a' );
1119         isValidName = false;
1120       }
1121       int p, p2=1; // replace not allowed chars
1122       while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
1123         aName.SetValue(p, '_');
1124         p2=p;
1125         isValidName = false;
1126       }
1127       if ( aNameToEntry.IsBound( aName ) && anEntry != aNameToEntry( aName ))
1128       {  // diff objects have same name - make a new name by appending a digit
1129         TCollection_AsciiString aName2;
1130         Standard_Integer i = 0;
1131         do {
1132           aName2 = aName + "_" + ++i;
1133         } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
1134         aName = aName2;
1135         isValidName = false;
1136       }
1137       if ( !isValidName ) {
1138         if ( theIsPublished )
1139           theEntryToBadName.Bind( anEntry, theObjectNames.Find(anEntry) );
1140         theObjectNames( anEntry ) = aName;
1141       }
1142     }
1143     else {
1144       do {
1145         aName = aBaseName + TCollection_AsciiString(++objectCounter);
1146       } while(aNameToEntry.IsBound(aName));
1147       theObjectNames.Bind(anEntry, aName);
1148     }
1149     aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
1150
1151     anUpdatedScript += aName;
1152     aStart = aSeq->Value(i+1) + 1;
1153   }
1154
1155   //Add final part of the script
1156   if (aLen && aSeq->Value(aLen) < aScriptLength)
1157     anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1158
1159   theScript = anUpdatedScript;
1160 }
1161
1162 //=============================================================================
1163 /*!
1164  *  AddObjectColors: Add color to objects
1165  */
1166 //=============================================================================
1167 void AddObjectColors (const Handle(TDocStd_Document)&                 theDoc,
1168                       TCollection_AsciiString&                        theScript,
1169                       const Resource_DataMapOfAsciiStringAsciiString& theObjectNames)
1170 {
1171   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
1172   for (anEntryToNameIt.Initialize( theObjectNames );
1173        anEntryToNameIt.More();
1174        anEntryToNameIt.Next())
1175   {
1176     const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
1177     const TCollection_AsciiString& aName = anEntryToNameIt.Value();
1178
1179     TDF_Label L;
1180     TDF_Tool::Label( theDoc->GetData(), aEntry, L );
1181     if ( L.IsNull() )
1182       continue;
1183
1184     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1185     if ( obj.IsNull() )
1186       continue;
1187
1188     bool anAutoColor = obj->GetAutoColor();
1189     if ( anAutoColor )
1190     {
1191       TCollection_AsciiString aCommand( "\n\t" );
1192       aCommand += aName + ".SetAutoColor(1)";
1193       theScript += aCommand.ToCString();
1194     }
1195
1196     SALOMEDS::Color aColor = obj->GetColor();
1197     if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
1198     {
1199       TCollection_AsciiString aCommand( "\n\t" );
1200       aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1201       theScript += aCommand.ToCString();
1202     }
1203   }
1204 }
1205
1206 //=============================================================================
1207 /*!
1208  *  PublishObject: publish object in study script
1209  */
1210 //=============================================================================
1211 void PublishObject (const TCollection_AsciiString&                  theEntry,
1212                     const TCollection_AsciiString&                  theName,
1213                     const Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
1214                     const Resource_DataMapOfAsciiStringAsciiString& theEntry2StEntry,
1215                     const Resource_DataMapOfAsciiStringAsciiString& theStEntry2Entry,
1216                     const Resource_DataMapOfAsciiStringAsciiString& theEntryToBadName,
1217                     std::map< int, std::string >&                   theEntryToCommandMap,
1218                     std::set<std::string>&                          theMapOfPublished)
1219 {
1220   if ( !theEntry2StEntry.IsBound( theEntry ))
1221     return; // was not published
1222   if ( theMapOfPublished.count(theEntry.ToCString()) )
1223     return; // aready published
1224   theMapOfPublished.insert( theEntry.ToCString() );
1225
1226   TCollection_AsciiString aCommand("\n\tgeompy."), aFatherEntry;
1227
1228   // find a father entry
1229   const TCollection_AsciiString& aStudyEntry = theEntry2StEntry( theEntry );
1230   TCollection_AsciiString aFatherStudyEntry =
1231     aStudyEntry.SubString( 1, aStudyEntry.SearchFromEnd(":") - 1 );
1232   if ( theStEntry2Entry.IsBound( aFatherStudyEntry ))
1233     aFatherEntry = theStEntry2Entry( aFatherStudyEntry );
1234
1235   // make a command
1236   if ( !aFatherEntry.IsEmpty() && theObjectNames.IsBound( aFatherEntry )) {
1237         aCommand += "addToStudyInFather( ";
1238         aCommand += theObjectNames( aFatherEntry ) + ", ";
1239   }
1240   else
1241     aCommand += "addToStudy( ";
1242   if ( theEntryToBadName.IsBound( theEntry ))
1243     aCommand += theName + ", \"" + theEntryToBadName( theEntry ) + "\" )";
1244   else
1245     aCommand += theName + ", \"" + theName + "\" )";
1246
1247   // bind a command to the last digit of the entry
1248   int tag =
1249     theEntry.SubString( theEntry.SearchFromEnd(":")+1, theEntry.Length() ).IntegerValue();
1250   theEntryToCommandMap.insert( std::make_pair( tag, aCommand.ToCString() ));
1251 }
1252
1253 //================================================================================
1254 /*!
1255  * \brief Constructor
1256  */
1257 //================================================================================
1258 ObjectStates::ObjectStates()
1259 {
1260   _dumpstate = 0;
1261 }
1262
1263 //================================================================================
1264 /*!
1265  * \brief Destructor
1266  */
1267 //================================================================================
1268 ObjectStates::~ObjectStates()
1269 {
1270 }
1271
1272 //================================================================================
1273 /*!
1274  * \brief Return current object state
1275  * \retval state - Object state (vector of notebook variable)
1276  */
1277 //================================================================================
1278 TState ObjectStates::GetCurrectState() const
1279 {
1280   if(_states.size() > _dumpstate)
1281     return _states[_dumpstate];
1282   return TState();
1283 }
1284
1285 //================================================================================
1286 /*!
1287  * \brief Add new object state 
1288  * \param theState - Object state (vector of notebook variable)
1289  */
1290 //================================================================================
1291 void ObjectStates::AddState(const TState &theState)
1292 {
1293   _states.push_back(theState);
1294 }
1295
1296 //================================================================================
1297 /*!
1298  * \brief Increment object state
1299  */
1300 //================================================================================
1301 void ObjectStates::IncrementState()
1302 {
1303   _dumpstate++;
1304 }