Salome HOME
untabify
[modules/geom.git] / src / GEOM / GEOM_Engine.cxx
1 // Copyright (C) 2007-2013  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
23 #ifdef WNT
24 #pragma warning( disable:4786 )
25 #endif
26
27 #include "GEOM_Engine.hxx"
28
29 #include "GEOM_Solver.hxx"
30 #include "GEOM_Function.hxx"
31 #include "GEOM_ISubShape.hxx"
32 #include "GEOM_SubShapeDriver.hxx"
33 #include "GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient.hxx"
34 #include "GEOM_PythonDump.hxx"
35 #include "Sketcher_Profile.hxx"
36
37 #include <Basics_OCCTVersion.hxx>
38
39 #include "utilities.h"
40
41 #include <Basics_Utils.hxx>
42
43 #include <TDF_Tool.hxx>
44 #include <TDF_Data.hxx>
45 #include <TDF_Reference.hxx>
46 #include <TDF_LabelSequence.hxx>
47 #include <TDataStd_Integer.hxx>
48 #include <TDataStd_ChildNodeIterator.hxx>
49 #include <TFunction_Driver.hxx>
50 #include <TFunction_DriverTable.hxx>
51 #include <TDataStd_ByteArray.hxx>
52 #include <TDataStd_UAttribute.hxx>
53 #include <TDF_ChildIterator.hxx>
54 #include <TDataStd_Comment.hxx>
55
56 #include <TopExp.hxx>
57 #include <TopTools_IndexedMapOfShape.hxx>
58
59 #include <TCollection_AsciiString.hxx>
60 #include <TCollection_ExtendedString.hxx>
61 #include <TColStd_SequenceOfAsciiString.hxx>
62 #include <TColStd_MapOfTransient.hxx>
63 #include <TColStd_HSequenceOfInteger.hxx>
64
65 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
66 #include <TColStd_HArray1OfByte.hxx>
67 #include <TColStd_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
68 #else
69 #include <TDataStd_HArray1OfByte.hxx>
70 #include <Interface_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
71 #endif
72
73 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
74
75 #include <set>
76
77 #include <Standard_Failure.hxx>
78 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
79
80 #define COMMA ','
81 #define O_BRACKET '('
82 #define C_BRACKET ')'
83 #define O_SQR_BRACKET '['
84 #define C_SQR_BRACKET ']'
85 #define PY_NULL "None"
86
87 #ifdef _DEBUG_
88 static int MYDEBUG = 0;
89 #else
90 static int MYDEBUG = 0;
91 #endif
92
93 typedef std::map< TCollection_AsciiString, TCollection_AsciiString > TSting2StringMap;
94 typedef std::map< TCollection_AsciiString, TObjectData >             TSting2ObjDataMap;
95 typedef std::map< TCollection_AsciiString, TObjectData* >            TSting2ObjDataPtrMap;
96
97 static GEOM_Engine* TheEngine = NULL;
98
99
100 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
101 {
102   TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
103   TDF_Tool::Entry(theObject->GetEntry(), anEntry);
104   anID+=(TCollection_AsciiString("_")+anEntry);
105   return anID;
106 }
107
108 static TCollection_AsciiString BuildID(Standard_Integer theDocID, char* theEntry)
109 {
110   TCollection_AsciiString anID(theDocID);
111   anID+=(TCollection_AsciiString("_")+theEntry);
112   return anID;
113 }
114
115 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
116 {
117   TCollection_AsciiString aDocID = theID.Token("_");
118   if(aDocID.Length() < 1) return -1;
119   return aDocID.IntegerValue();
120 }
121
122 bool ProcessFunction(Handle(GEOM_Function)&             theFunction,
123                      TCollection_AsciiString&           theScript,
124                      TCollection_AsciiString&           theAfterScript,
125                      const TVariablesList&              theVariables,
126                      const bool                         theIsPublished,
127                      TDF_LabelMap&                      theProcessed,
128                      std::set<TCollection_AsciiString>& theIgnoreObjs,
129                      bool&                              theIsDumpCollected);
130
131 void ReplaceVariables(TCollection_AsciiString& theCommand,
132                       const TVariablesList&    theVariables);
133
134 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
135
136 void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
137                             TSting2ObjDataMap&                        aEntry2ObjData,
138                             const bool                                theIsPublished,
139                             TColStd_SequenceOfAsciiString&            theObjListToPublish,
140                             Standard_Integer&                         objectCounter,
141                             Resource_DataMapOfAsciiStringAsciiString& aNameToEntry);
142
143 void AddObjectColors (int                      theDocID,
144                       TCollection_AsciiString& theScript,
145                       const TSting2ObjDataMap& theEntry2ObjData);
146
147 void AddTextures (int theDocID, TCollection_AsciiString& theScript);
148
149 void PublishObject (TObjectData&                              theObjectData,
150                     TSting2ObjDataMap&                        theEntry2ObjData,
151                     const TSting2ObjDataPtrMap&               theStEntry2ObjDataPtr,
152                     Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
153                     std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
154                     std::set<TCollection_AsciiString>&        theMapOfPublished);
155
156 namespace
157 {
158
159   //================================================================================
160   /*!
161    * \brief Fix up the name of python variable
162    */
163   //================================================================================
164
165   void healPyName( TCollection_AsciiString&                  pyName,
166                    const TCollection_AsciiString&            anEntry,
167                    Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
168   {
169     const TCollection_AsciiString allowedChars
170       ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
171
172     if ( pyName.IsIntegerValue() ) { // pyName must not start with a digit
173       pyName.Insert( 1, 'a' );
174     }
175     int p, p2=1; // replace not allowed chars
176     while ((p = pyName.FirstLocationNotInSet(allowedChars, p2, pyName.Length()))) {
177       pyName.SetValue(p, '_');
178       p2=p;
179     }
180     if ( aNameToEntry.IsBound( pyName ) && anEntry != aNameToEntry( pyName ))
181     {  // diff objects have same name - make a new name by appending a digit
182       TCollection_AsciiString aName2;
183       Standard_Integer i = 0;
184       do {
185         aName2 = pyName + "_" + ++i;
186       } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
187       pyName = aName2;
188     }
189   }
190 }
191
192 //=======================================================================
193 //function : GetTextureGUID
194 //purpose  :
195 //=======================================================================
196 const Standard_GUID& GEOM_Engine::GetTextureGUID()
197 {
198   static Standard_GUID anID("FF1BBB01-5D14-4df2-980B-3A668264EA17");
199   return anID;
200 }
201
202 //=============================================================================
203 /*!
204  *  GetEngine
205  */
206 //=============================================================================
207 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
208
209 //=============================================================================
210 /*!
211  *  SetEngine
212  */
213 //=============================================================================
214 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
215
216 //=============================================================================
217 /*!
218  *  Constructor
219  */
220 //=============================================================================
221 GEOM_Engine::GEOM_Engine()
222 {
223   TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
224   
225   _OCAFApp = new GEOM_Application();
226   _UndoLimit = 10;
227 }
228
229 /*!
230  *  Destructor
231  */
232 GEOM_Engine::~GEOM_Engine()
233 {
234   GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
235   std::list< Handle(GEOM_Object) > objs;
236   for(; It.More(); It.Next())
237     objs.push_back( Handle(GEOM_Object)::DownCast(It.Value()) );
238   std::list< Handle(GEOM_Object) >::iterator objit;
239   for(objit = objs.begin(); objit != objs.end(); ++objit)
240     RemoveObject(*objit);
241
242   //Close all documents not closed
243 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
244   TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
245 #else
246   Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
247 #endif
248   for (; anItr.More(); anItr.Next())
249   {
250     Close(anItr.Key());
251     anItr.Initialize( _mapIDDocument ); // anItr becomes invalid at _mapIDDocument.UnBind(docId)
252   }
253   _mapIDDocument.Clear();
254   _objects.Clear();
255 }
256
257 //=============================================================================
258 /*!
259  *  GetDocument
260  */
261 //=============================================================================
262 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID, bool force)
263 {
264   Handle(TDocStd_Document) aDoc;
265   if(_mapIDDocument.IsBound(theDocID)) {
266     aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
267   }
268   else if (force) {
269     _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
270     aDoc->SetUndoLimit(_UndoLimit);
271     _mapIDDocument.Bind(theDocID, aDoc);
272     TDataStd_Integer::Set(aDoc->Main(), theDocID);
273   }
274   return aDoc;
275 }
276
277 //=============================================================================
278 /*!
279  *  GetDocID
280  */
281 //=============================================================================
282 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
283 {
284   if (theDocument.IsNull()) return -1;
285 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
286   TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
287 #else
288   Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
289 #endif
290   for (; anItr.More(); anItr.Next())
291     if (anItr.Value() == theDocument) return anItr.Key();
292
293   return -1;
294 }
295
296 //=============================================================================
297 /*!
298  *  GetObject
299  */
300 //=============================================================================
301 Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry, bool force)
302 {
303   Handle(GEOM_Object) anObject;
304
305   TCollection_AsciiString anID = BuildID(theDocID, theEntry);
306
307   if (_objects.IsBound(anID)) {
308     anObject = Handle(GEOM_Object)::DownCast(_objects(anID));
309   }
310   else if (force) {
311     Handle(TDocStd_Document) aDoc = GetDocument(theDocID, force);
312     if ( !aDoc.IsNull()) {
313       TDF_Label aLabel;
314       TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
315       anObject = new GEOM_Object(aLabel);
316       _objects.Bind(anID, anObject);
317     }
318   }
319
320   return anObject;
321 }
322
323 //=============================================================================
324 /*!
325  *  AddObject
326  */
327 //=============================================================================
328 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
329 {
330   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
331   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
332
333   // NPAL18604: use existing label to decrease memory usage,
334   //            if this label has been freed (object deleted)
335   bool useExisting = false;
336   TDF_Label aChild;
337   if (_freeLabels.find(theDocID) != _freeLabels.end()) {
338     std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
339     if (!aFreeLabels.empty()) {
340       useExisting = true;
341       aChild = aFreeLabels.front();
342       aFreeLabels.pop_front();
343     }
344   }
345   if (!useExisting) {
346     // create new label
347     aChild = TDF_TagSource::NewChild(aDoc->Main());
348   }
349
350   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
351
352   //Put an object in the map of created objects
353   TCollection_AsciiString anID = BuildIDFromObject(anObject);
354   if(_objects.IsBound(anID)) _objects.UnBind(anID);
355   _objects.Bind(anID, anObject);
356
357   return anObject;
358 }
359
360 //=============================================================================
361 /*!
362  *  AddSubShape
363  */
364 //=============================================================================
365 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
366                                              Handle(TColStd_HArray1OfInteger) theIndices,
367                                              bool isStandaloneOperation)
368 {
369   if (theMainShape.IsNull() || theIndices.IsNull()) return NULL;
370
371   Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
372   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
373
374   // NPAL18604: use existing label to decrease memory usage,
375   //            if this label has been freed (object deleted)
376   bool useExisting = false;
377   TDF_Label aChild;
378   int aDocID = theMainShape->GetDocID();
379   if (_freeLabels.find(aDocID) != _freeLabels.end()) {
380     std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
381     if (!aFreeLabels.empty()) {
382       useExisting = true;
383       aChild = aFreeLabels.front();
384       aFreeLabels.pop_front();
385     }
386   }
387   if (!useExisting) {
388     // create new label
389     aChild = TDF_TagSource::NewChild(aDoc->Main());
390   }
391
392   Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
393   Handle(GEOM_Object) anObject = new GEOM_Object (aChild, 28); //28 is SUBSHAPE type
394   Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
395
396   GEOM_ISubShape aSSI (aFunction);
397   aSSI.SetMainShape(aMainShape);
398   aSSI.SetIndices(theIndices);
399
400   try {
401 #if OCC_VERSION_LARGE > 0x06010000
402     OCC_CATCH_SIGNALS;
403 #endif
404     GEOM_Solver aSolver (GEOM_Engine::GetEngine());
405     if (!aSolver.ComputeFunction(aFunction)) {
406       MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
407       return NULL;
408     }
409   }
410   catch (Standard_Failure) {
411     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
412     MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
413     return NULL;
414   }
415
416   // Put an object in the map of created objects
417   TCollection_AsciiString anID = BuildIDFromObject(anObject);
418   if (_objects.IsBound(anID)) _objects.UnBind(anID);
419   _objects.Bind(anID, anObject);
420
421   // Put this sub-shape in the list of sub-shapes of theMainShape
422   aMainShape->AddSubShapeReference(aFunction);
423
424   GEOM::TPythonDump pd (aFunction);
425
426   if (isStandaloneOperation) {
427     pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
428     Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
429     for (; i <= up - 1; i++) {
430       pd << theIndices->Value(i) << ", ";
431     }
432     pd << theIndices->Value(up) << "])";
433   }
434   else
435     pd << "None";
436
437   return anObject;
438 }
439
440 //=============================================================================
441 /*!
442  *  RemoveObject
443  */
444 //=============================================================================
445 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
446 {
447   if (theObject.IsNull()) return false;
448
449   int aDocID = theObject->GetDocID();
450   if(!_mapIDDocument.IsBound(aDocID))
451     return false;  // document is closed...
452
453   //Remove an object from the map of available objects
454   TCollection_AsciiString anID = BuildIDFromObject(theObject);
455   if (_objects.IsBound(anID)) _objects.UnBind(anID);
456
457   // If sub-shape, remove it from the list of sub-shapes of its main shape
458   if (!theObject->IsMainShape()) {
459     Handle(GEOM_Function) aFunction = theObject->GetFunction(1);
460     GEOM_ISubShape aSSI (aFunction);
461     Handle(GEOM_Function) aMainShape = aSSI.GetMainShape();
462     //If main shape is not null, then remove
463     if(!aMainShape.IsNull())
464       aMainShape->RemoveSubShapeReference(aFunction);
465   }
466
467   int nb = theObject->GetNbFunctions();
468   Handle(TDataStd_TreeNode) aNode;
469   for (int i = 1; i <= nb; i++) {
470     Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
471     if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
472       aNode->Remove();
473   }
474
475   TDF_Label aLabel = theObject->GetEntry();
476   aLabel.ForgetAllAttributes(Standard_True);
477
478   // Remember the label to reuse it then
479   std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
480   aFreeLabels.push_back(aLabel);
481
482   theObject.Nullify();
483
484   return true;
485 }
486
487 //=============================================================================
488 /*!
489  *  Undo
490  */
491 //=============================================================================
492 void GEOM_Engine::Undo(int theDocID)
493 {
494   GetDocument(theDocID)->Undo();
495 }
496
497 //=============================================================================
498 /*!
499  *  Redo
500  */
501 //=============================================================================
502 void GEOM_Engine::Redo(int theDocID)
503 {
504   GetDocument(theDocID)->Redo();
505 }
506
507 //=============================================================================
508 /*!
509  *  Save
510  */
511 //=============================================================================
512 bool GEOM_Engine::Save(int theDocID, char* theFileName)
513 {
514   if(!_mapIDDocument.IsBound(theDocID)) return false;
515   Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
516
517   _OCAFApp->SaveAs(aDoc, theFileName);
518
519   return true;
520 }
521
522 //=============================================================================
523 /*!
524  *  Load
525  */
526 //=============================================================================
527 bool GEOM_Engine::Load(int theDocID, char* theFileName)
528 {
529   Handle(TDocStd_Document) aDoc;
530 #if OCC_VERSION_LARGE > 0x06050100 // For OCCT6.5.2 and higher
531   if (_OCAFApp->Open(theFileName, aDoc) != PCDM_RS_OK) {
532 #else
533   if (_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
534 #endif
535     return false;
536   }
537
538   aDoc->SetUndoLimit(_UndoLimit);
539
540   if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
541   _mapIDDocument.Bind(theDocID, aDoc);
542
543   TDataStd_Integer::Set(aDoc->Main(), theDocID);
544
545   return true;
546 }
547
548 //=============================================================================
549 /*!
550  *  Close
551  */
552 //=============================================================================
553 void GEOM_Engine::Close(int theDocID)
554 {
555   if (_mapIDDocument.IsBound(theDocID)) {
556     Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
557
558     //Remove all GEOM Objects associated to the given document
559     TColStd_SequenceOfAsciiString aSeq;
560     GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
561     for (; It.More(); It.Next()) {
562       TCollection_AsciiString anObjID (It.Key());
563       Standard_Integer anID = ExtractDocID(anObjID);
564       if (theDocID == anID) aSeq.Append(It.Key());
565     }
566     for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
567
568     // Forget free labels for this document
569     TFreeLabelsList::iterator anIt = _freeLabels.find(theDocID);
570     if (anIt != _freeLabels.end()) {
571       _freeLabels.erase(anIt);
572     }
573
574     _mapIDDocument.UnBind(theDocID);
575     _OCAFApp->Close(aDoc);
576     aDoc.Nullify();
577   }
578 }
579
580 //=============================================================================
581 /*!
582  *  DumpPython
583  */
584 //=============================================================================
585 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
586                                                 std::vector<TObjectData>& theObjectData,
587                                                 TVariablesList theVariables,
588                                                 bool isPublished,
589                                                 bool isMultiFile, 
590                                                 bool& aValidScript)
591 {
592   // Set "C" numeric locale to save numbers correctly
593   Kernel_Utils::Localizer loc;
594
595   TCollection_AsciiString aScript;
596   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
597
598   if (aDoc.IsNull())
599   {
600     TCollection_AsciiString anEmptyScript;
601     if( isMultiFile )
602       anEmptyScript = "def RebuildData(theStudy): pass\n";
603     return anEmptyScript;
604   }
605
606   aScript  = "import GEOM\n";
607   aScript += "from salome.geom import geomBuilder\n";
608   aScript += "import math\n";
609   aScript += "import SALOMEDS\n\n";
610   if( isMultiFile )
611     aScript += "def RebuildData(theStudy):";
612
613   aScript += "\n\tgeompy = geomBuilder.New(theStudy)\n";
614
615   AddTextures(theDocID, aScript);
616
617   Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
618
619   // a map containing copies of TObjectData from theObjectData
620   TSting2ObjDataMap    aEntry2ObjData;
621   // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
622   // occures when several StudyEntries correspond to one Entry
623   TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
624
625   //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
626   for (unsigned i = 0; i < theObjectData.size(); ++i )
627   {
628     TObjectData& data = theObjectData[i];
629     // look for an object by entry
630     TDF_Label L;
631     TDF_Tool::Label( aDoc->GetData(), data._entry, L );
632     if ( L.IsNull() ) continue;
633     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
634     // fill maps
635     if ( !obj.IsNull() ) {
636       TSting2ObjDataMap::iterator ent2Data =
637         aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
638
639       if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
640         aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
641       else
642         aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
643     }
644   }
645
646   // collect objects entries to be published
647   TColStd_SequenceOfAsciiString aObjListToPublish;
648
649   // iterates on functions till critical (that requiers publication of objects)
650   Handle(TDataStd_TreeNode) aNode, aRoot;
651   Handle(GEOM_Function) aFunction;
652   TDF_LabelMap aCheckedFuncMap;
653   std::set< TCollection_AsciiString > anIgnoreObjMap;
654
655   TCollection_AsciiString aFuncScript;
656
657   // Mantis issue 0020768
658   Standard_Integer objectCounter = 0;
659   Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
660
661   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
662     TDataStd_ChildNodeIterator Itr(aRoot);
663     for (; Itr.More(); Itr.Next()) {
664       aNode = Itr.Value();
665       aFunction = GEOM_Function::GetFunction(aNode->Label());
666       if (aFunction.IsNull()) {
667         MESSAGE ( "Null function !!!!" );
668         continue;
669       }
670       bool isDumpCollected = false;
671       TCollection_AsciiString aCurScript, anAfterScript;
672       if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
673                            isPublished, aCheckedFuncMap, anIgnoreObjMap,
674                            isDumpCollected ))
675         continue;
676       // add function description before dump
677       if (!aCurScript.IsEmpty())
678       {
679         if ( aFunction->GetDriverGUID() == GEOM_Object::GetSubShapeID() &&
680              aFuncScript.Length() > aCurScript.Length() )
681           // avoid repeated SubShape...() command at the end
682           if (aFuncScript.Location( aCurScript,
683                                     aFuncScript.Length() - aCurScript.Length(),
684                                     aFuncScript.Length()))
685             continue; // aCurScript is already at the end of aFuncScript
686         aFuncScript += aCurScript;
687       }
688       if (isDumpCollected ) {
689         // Replace entries by the names
690         ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
691                                aObjListToPublish, objectCounter, aNameToEntry );
692
693         // publish collected objects
694         std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry
695         int i = 1, n = aObjListToPublish.Length();
696         for ( ; i <= n; i++ )
697         {
698           const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
699           PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
700                          aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
701         }
702         // add publishing commands to the script
703         std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
704         for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
705           aFuncScript += anEntryToCmd->second;
706
707         // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
708         //  because they will be published during command execution
709         int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
710         if ( indx == -1 )
711           indx = anAfterScript.Search( "RestoreSubShapes" );
712         if ( indx != -1 ) {
713           TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
714           Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
715           i = 1, n = aSeq->Length();
716           for ( ; i <= n; i+=2) {
717             TCollection_AsciiString anEntry =
718               aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
719             anIgnoreObjMap.insert(anEntry.ToCString());
720           }
721         }
722
723         aObjListToPublish.Clear();
724         aScript += aFuncScript;
725         aFuncScript.Clear();
726       }
727       aFuncScript += anAfterScript;
728     }
729   }
730
731   // Replace entries by the names
732   aObjListToPublish.Clear();
733   ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
734                          objectCounter, aNameToEntry );
735
736   aScript += aFuncScript;
737
738   // ouv : NPAL12872
739   AddObjectColors( theDocID, aScript, aEntry2ObjData );
740
741   // Make script to publish in study
742   TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
743   if ( isPublished )
744   {
745     std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry
746
747     for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
748          aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
749          ++aStEntry2ObjDataPtrIt)
750     {
751       TObjectData* data = aStEntry2ObjDataPtrIt->second;
752       if ( anIgnoreObjMap.count( data->_entry ))
753         continue; // should not be dumped
754       PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
755                      aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
756     }
757     // add publishing commands to the script
758     std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
759     for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
760       aScript += anEntryToCmd->second;
761   }
762
763   //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function
764   //Add unpublish command if need
765   TCollection_AsciiString unpublishCmd("\n");
766   if(isMultiFile)
767     unpublishCmd += "\t";
768   unpublishCmd += "geompy.hideInStudy(";
769   
770   for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
771        aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
772        ++aStEntry2ObjDataPtrIt)
773     {
774       TObjectData* data = aStEntry2ObjDataPtrIt->second;      
775       if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
776         aScript +=  unpublishCmd + data->_pyName + ")";
777       }
778     }    
779   
780   //aScript += "\n\tpass\n";
781   aScript += "\n";
782   aValidScript = true;
783
784   // fill _studyEntry2NameMap and build globalVars
785   TCollection_AsciiString globalVars;
786   _studyEntry2NameMap.Clear();
787   for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
788        aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
789        ++aStEntry2ObjDataPtrIt)
790   {
791     const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
792     const TObjectData*                   data = aStEntry2ObjDataPtrIt->second;
793     _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
794     if ( !globalVars.IsEmpty() )
795       globalVars += ", ";
796     globalVars += data->_pyName;
797   }
798   if ( isMultiFile && !globalVars.IsEmpty() ) {
799     globalVars.Insert( 1, "\n\tglobal " );
800     aScript.Insert( posToInsertGlobalVars, globalVars );
801   }
802
803   return aScript;
804 }
805
806 //=======================================================================
807 //function : GetDumpName
808 //purpose  :
809 //=======================================================================
810
811 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
812 {
813   if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
814     return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
815
816   return NULL;
817 }
818
819 //=======================================================================
820 //function : GetAllDumpNames
821 //purpose  :
822 //=======================================================================
823
824 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
825 {
826   Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
827
828   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
829   for (; it.More(); it.Next()) {
830     aRetSeq->Append(it.Value());
831   }
832
833   return aRetSeq;
834 }
835
836 #define TEXTURE_LABEL_ID       1
837 #define TEXTURE_LABEL_FILE     2
838 #define TEXTURE_LABEL_WIDTH    3
839 #define TEXTURE_LABEL_HEIGHT   4
840 #define TEXTURE_LABEL_DATA     5
841
842 int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight,
843 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
844                             const Handle(TColStd_HArray1OfByte)& theTexture,
845 #else
846                             const Handle(TDataStd_HArray1OfByte)& theTexture,
847 #endif
848                             const TCollection_AsciiString& theFileName)
849 {
850   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
851   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
852
853   // NPAL18604: use existing label to decrease memory usage,
854   //            if this label has been freed (object deleted)
855   bool useExisting = false;
856   TDF_Label aChild;
857   if (_freeLabels.find(theDocID) != _freeLabels.end()) {
858     std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
859     if (!aFreeLabels.empty()) {
860       useExisting = true;
861       aChild = aFreeLabels.front();
862       aFreeLabels.pop_front();
863     }
864   }
865   if (!useExisting) {
866     // create new label
867     aChild = TDF_TagSource::NewChild(aDoc->Main());
868   }
869
870   aChild.ForgetAllAttributes(Standard_True);
871   Handle(TDataStd_TreeNode) node;
872   if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) )
873     node = TDataStd_TreeNode::Set(aChild);
874   TDataStd_UAttribute::Set(aChild, GetTextureGUID());
875
876   static int aTextureID = 0;
877
878   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID),     ++aTextureID);
879   TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE),   theFileName);
880   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH),  theWidth);
881   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
882
883   Handle(TDataStd_ByteArray) anAttr =
884     TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
885                             theTexture.IsNull() ? 0 : theTexture->Lower(),
886                             theTexture.IsNull() ? 0 : theTexture->Upper());
887   anAttr->ChangeArray(theTexture);
888
889   return aTextureID;
890 }
891
892 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
893 Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
894 #else
895 Handle(TDataStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
896 #endif
897                                                       int& theWidth, int& theHeight,
898                                                       TCollection_AsciiString& theFileName)
899 {
900 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
901   Handle(TColStd_HArray1OfByte) anArray;
902 #else
903   Handle(TDataStd_HArray1OfByte) anArray;
904 #endif
905   theWidth = theHeight = 0;
906
907   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
908
909   TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
910   bool found = false;
911   for (; anIterator.More() && !found; anIterator.Next()) {
912     TDF_Label aTextureLabel = anIterator.Value();
913     if (aTextureLabel.IsAttribute( GetTextureGUID())) {
914       TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
915       Handle(TDataStd_Integer) anIdAttr;
916       if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) &&
917          anIdAttr->Get() == theTextureID) {
918         TDF_Label aFileLabel   = aTextureLabel.FindChild(TEXTURE_LABEL_FILE,    Standard_False);
919         TDF_Label aWidthLabel  = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH,   Standard_False);
920         TDF_Label aHeightLabel = aTextureLabel.FindChild(TEXTURE_LABEL_HEIGHT,  Standard_False);
921         TDF_Label aDataLabel   = aTextureLabel.FindChild(TEXTURE_LABEL_DATA,    Standard_False);
922         Handle(TDataStd_Integer) aWidthAttr, aHeightAttr;
923         Handle(TDataStd_ByteArray) aTextureAttr;
924         Handle(TDataStd_Comment) aFileAttr;
925         if (!aWidthLabel.IsNull()  && aWidthLabel.FindAttribute(TDataStd_Integer::GetID(),  aWidthAttr) &&
926             !aHeightLabel.IsNull() && aHeightLabel.FindAttribute(TDataStd_Integer::GetID(), aHeightAttr) &&
927             !aDataLabel.IsNull()   && aDataLabel.FindAttribute(TDataStd_ByteArray::GetID(), aTextureAttr)) {
928           theWidth = aWidthAttr->Get();
929           theHeight = aHeightAttr->Get();
930           anArray = aTextureAttr->InternalArray();
931         }
932         if (!aFileLabel.IsNull() && aFileLabel.FindAttribute(TDataStd_Comment::GetID(), aFileAttr))
933           theFileName = aFileAttr->Get();
934         found = true;
935       }
936     }
937   }
938   return anArray;
939 }
940
941 std::list<int> GEOM_Engine::getAllTextures(int theDocID)
942 {
943   std::list<int> id_list;
944
945   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
946
947   TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
948   for (; anIterator.More(); anIterator.Next()) {
949     TDF_Label aTextureLabel = anIterator.Value();
950     if (aTextureLabel.IsAttribute( GetTextureGUID())) {
951       TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
952       Handle(TDataStd_Integer) anIdAttr;
953       if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr))
954         id_list.push_back((int)anIdAttr->Get());
955     }
956   }
957   return id_list;
958 }
959
960 //===========================================================================
961 //                     Internal functions
962 //===========================================================================
963
964 //=============================================================================
965 /*!
966  *  MakeCommandfor3DSketcher: Make new command for 3DSketcher
967  */
968 //=============================================================================
969 TCollection_AsciiString MakeCommandfor3DSketcher (const TCollection_AsciiString& theDescr )
970 {
971     TCollection_AsciiString aNewDescr;
972     int i = 1;
973     TCollection_AsciiString aSubStr = theDescr.Token("\n\t", i);
974     for (; !aSubStr.IsEmpty(); aSubStr = theDescr.Token("\n\t", i)) {
975       if (aSubStr.Search( "Make3DSketcherCommand" ) != -1) {
976         TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
977         // "3DSketcher:CMD[:CMD[:CMD...]]"
978         TCollection_AsciiString aCommand = aSubStr.Token("\"", 2);
979
980         // Split the command string to separate CMDs
981         int icmd = 2;
982         TColStd_SequenceOfAsciiString aSequence;
983         if (aCommand.Length()) {
984           TCollection_AsciiString aToken = aCommand.Token(":", icmd);
985           while (aToken.Length() > 0) {
986             aSequence.Append(aToken);
987             aToken = aCommand.Token(":", ++icmd);
988           }
989         }
990
991         if (aSequence.Length() > 0) {
992           if (i > 1)
993             aNewDescr += "\n\t";
994
995           aNewDescr += "\nsk = geompy.Sketcher3D()";
996           int nbCMDs = aSequence.Length();
997           for (icmd = 1; icmd <= nbCMDs; icmd++) {
998             aNewDescr += "\n\t";
999
1000             TCollection_AsciiString aCMD = aSequence.Value(icmd);
1001
1002             // Split the CMD into string values
1003             TColStd_SequenceOfAsciiString aStrVals;
1004             int ival = 1;
1005             TCollection_AsciiString aToken = aCMD.Token(" ", ival);
1006             while (aToken.Length() > 0) {
1007               aStrVals.Append(aToken);
1008               aToken = aCMD.Token(" ", ++ival);
1009             }
1010
1011             TCollection_AsciiString aCMDpref = aStrVals.Value(1);
1012             if (aCMDpref == "TT") {
1013               aNewDescr += "sk.addPointsAbsolute(";
1014               aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1015             }
1016             else if (aCMDpref == "T") {
1017               aNewDescr += "sk.addPointsRelative(";
1018               aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1019             }
1020             else if (aCMDpref == "WW") {
1021               aNewDescr += "sk.close()";
1022             }
1023             else if (aCMDpref.Value(1) == 'O'){
1024               TCollection_AsciiString aCMDtrunc = aStrVals.Value(1);
1025               aCMDtrunc.Trunc(3);
1026               if (aCMDpref.Value(4) == 'C')
1027                 aNewDescr += "sk.addPointRadiusAngleH";
1028               else
1029                 aNewDescr += "sk.addPointRadiusAngles";
1030               if (aCMDpref.Value(5) == 'A')
1031                 aNewDescr += "Absolute(";
1032               else
1033                 aNewDescr += "Relative(";
1034               aNewDescr +=  aStrVals.Value(4) + ", " +
1035                 aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + "\""+aCMDtrunc+"\"" + ")";
1036             }
1037           }
1038           aNewDescr += "\n\t";
1039           aNewDescr += aResult + " = sk.wire()";
1040         }
1041       } // Make3DSketcherCommand
1042       else if (aSubStr.Search( "Make3DSketcher" ) != -1) {
1043         TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
1044         TCollection_AsciiString aCommand = aSubStr.Token("[", 2);
1045         aCommand = aCommand.Token("]", 1);
1046         if (i > 1)
1047           aNewDescr += "\n\t";
1048         aNewDescr += "\nsk = geompy.Sketcher3D()";
1049         aNewDescr += "\n\t";
1050         aNewDescr += "sk.addPointsAbsolute(";
1051         aNewDescr += aCommand + ")";
1052         aNewDescr += "\n\t";
1053         aNewDescr += aResult + " = sk.wire()";
1054       }
1055       else {
1056         if (i > 1)
1057           aNewDescr += "\n\t";
1058         aNewDescr += aSubStr;
1059       }
1060       i++;
1061     }
1062     return aNewDescr;
1063 }
1064
1065 //=============================================================================
1066 /*!
1067  *  ProcessFunction: Dump function description into script
1068  */
1069 //=============================================================================
1070 bool ProcessFunction(Handle(GEOM_Function)&             theFunction,
1071                      TCollection_AsciiString&           theScript,
1072                      TCollection_AsciiString&           theAfterScript,
1073                      const TVariablesList&              theVariables,
1074                      const bool                         theIsPublished,
1075                      TDF_LabelMap&                      theProcessed,
1076                      std::set<TCollection_AsciiString>& theIgnoreObjs,
1077                      bool&                              theIsDumpCollected)
1078 {
1079   theIsDumpCollected = false;
1080   if (theFunction.IsNull()) return false;
1081
1082   if (theProcessed.Contains(theFunction->GetEntry())) return false;
1083
1084   // pass functions, that depends on nonexisting ones
1085   bool doNotProcess = false;
1086   TDF_LabelSequence aSeq;
1087   theFunction->GetDependency(aSeq);
1088   Standard_Integer aLen = aSeq.Length();
1089   for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
1090     TDF_Label aRefLabel = aSeq.Value(i);
1091     Handle(TDF_Reference) aRef;
1092     if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1093       doNotProcess = true;
1094     }
1095     else {
1096       if (aRef.IsNull() || aRef->Get().IsNull()) {
1097         doNotProcess = true;
1098       }
1099       else {
1100         Handle(TDataStd_TreeNode) aT;
1101         if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1102           doNotProcess = true;
1103         }
1104         else {
1105           TDF_Label aDepLabel = aT->Label();
1106           Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
1107
1108           if (aFunction.IsNull()) doNotProcess = true;
1109           else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
1110         }
1111       }
1112     }
1113   }
1114
1115   if (doNotProcess) {
1116     TCollection_AsciiString anObjEntry;
1117     TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1118     theIgnoreObjs.insert(anObjEntry);
1119     return false;
1120   }
1121   theProcessed.Add(theFunction->GetEntry());
1122
1123   TCollection_AsciiString aDescr = theFunction->GetDescription();
1124   if(aDescr.Length() == 0) return false;
1125
1126   //Check if its internal function which doesn't requires dumping
1127   if(aDescr == "None") return false;
1128
1129   //Check the very specific case of RestoreShape function,
1130   //which is not dumped, but the result can be published by the user.
1131   //We do not publish such objects to decrease danger of dumped script failure.
1132   if(aDescr.Value(1) == '#') {
1133     TCollection_AsciiString anObjEntry;
1134     TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1135     theIgnoreObjs.insert(anObjEntry);
1136     return false;
1137   }
1138
1139   // 0020001 PTv, check for critical functions, which require dump of objects
1140   if (theIsPublished)
1141   {
1142     // currently, there is only one function "RestoreGivenSubShapes",
1143     // later this check could be replaced by iterations on list of such functions
1144     if (aDescr.Search( "RestoreGivenSubShapes" ) != -1)
1145       theIsDumpCollected = true;
1146     else if (aDescr.Search( "RestoreSubShapes" ) != -1)
1147       theIsDumpCollected = true;
1148   }
1149
1150   //Replace parameter by notebook variables
1151   ReplaceVariables(aDescr,theVariables);
1152
1153   //Process sketcher functions, replacing string command by calls to Sketcher interface
1154   if ( ( aDescr.Search( "MakeSketcherOnPlane" ) != -1 ) || ( aDescr.Search( "MakeSketcher" ) != -1 ) ) {
1155     Sketcher_Profile aProfile( aDescr.ToCString());
1156     // Make new command for SketcherOnPlane and for Sketcher
1157     aDescr = aProfile.GetDump();
1158   }
1159   if (aDescr.Search( "Make3DSketcher" ) != -1) {
1160     aDescr = MakeCommandfor3DSketcher ( aDescr );
1161   }
1162
1163   if ( theIsDumpCollected ) {
1164     int i = 1;
1165     bool isBefore = true;
1166     TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
1167     while (!aSubStr.IsEmpty()) {
1168       if (isBefore &&
1169           aSubStr.Search( "RestoreGivenSubShapes" ) == -1 &&
1170           aSubStr.Search( "RestoreSubShapes" ) == -1)
1171         theScript += TCollection_AsciiString("\n\t") + aSubStr;
1172       else
1173         theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
1174       aSubStr = aDescr.Token("\n\t", i++);
1175     }
1176   }
1177   else {
1178     theScript += "\n\t";
1179     theScript += aDescr;
1180   }
1181   return true;
1182 }
1183
1184 //=============================================================================
1185 /*!
1186  *  FindEntries: Returns a sequence of start/end positions of entries in the string
1187  */
1188 //=============================================================================
1189 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
1190 {
1191   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1192   Standard_Integer aLen = theString.Length();
1193   Standard_Boolean isFound = Standard_False;
1194
1195   const char* arr = theString.ToCString();
1196   Standard_Integer i = 0, j;
1197
1198   while(i < aLen) {
1199     int c = (int)arr[i];
1200     j = i+1;
1201     if(c >= 48 && c <= 57) { //Is digit?
1202
1203       isFound = Standard_False;
1204       while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
1205         c = (int)arr[j++];
1206         if(c == 58) isFound = Standard_True;
1207       }
1208
1209       if(isFound && arr[j-2] != 58) { // last char should be a diggit
1210         aSeq->Append(i+1); // +1 because AsciiString starts from 1
1211         aSeq->Append(j-1);
1212       }
1213     }
1214
1215     i = j;
1216   }
1217
1218   return aSeq;
1219 }
1220
1221 //=============================================================================
1222 /*!
1223  *  ReplaceVariables: Replace parameters of the function by variales from
1224  *                    Notebook if need
1225  */
1226 //=============================================================================
1227 void ReplaceVariables(TCollection_AsciiString& theCommand,
1228                       const TVariablesList&    theVariables)
1229 {
1230   if (MYDEBUG)
1231     cout<<"Command : "<<theCommand<<endl;
1232
1233   if (MYDEBUG) {
1234     cout<<"All Entries:"<<endl;
1235     TVariablesList::const_iterator it = theVariables.begin();
1236     for(;it != theVariables.end();it++)
1237       cout<<"\t'"<<(*it).first<<"'"<<endl;
1238   }
1239
1240   //Additional case - multi-row commands
1241   int aCommandIndex = 1;
1242   while( aCommandIndex < 10 ) { // tmp check
1243     TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
1244     if( aCommand.Length() == 0 )
1245       break;
1246
1247     if (MYDEBUG)
1248       cout<<"Sub-command : "<<aCommand<<endl;
1249
1250     Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
1251     Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
1252
1253     //Get Entry of the result object
1254     TCollection_AsciiString anEntry;
1255     if( aCommand.Search("=") != -1 ) // command returns an object
1256       anEntry = aCommand.Token("=",1);
1257     else { // command modifies the object
1258       if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
1259         if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
1260           anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
1261     }
1262     //Remove white spaces
1263     anEntry.RightAdjust();
1264     anEntry.LeftAdjust();
1265     if(MYDEBUG)
1266       cout<<"Result entry : '" <<anEntry<<"'"<<endl;
1267
1268     if ( anEntry.IsEmpty() ) {
1269       aCommandIndex++;
1270       continue;
1271     }
1272
1273     //Check if result is list of entries - enough to get the first entry in this case
1274     int aNbEntries = 1;
1275     if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
1276       while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
1277         aNbEntries++;
1278       TCollection_AsciiString aSeparator(COMMA);
1279       anEntry = anEntry.Token(aSeparator.ToCString(),1);
1280       anEntry.Remove( 1, 1 );
1281       anEntry.RightAdjust();
1282       anEntry.LeftAdjust();
1283       if(MYDEBUG)
1284         cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
1285     }
1286
1287     //Find variables used for object construction
1288     ObjectStates* aStates = 0;
1289     TVariablesList::const_iterator it = theVariables.find(anEntry);
1290     if( it != theVariables.end() )
1291       aStates = (*it).second;
1292
1293     if(!aStates) {
1294       if(MYDEBUG)
1295         cout<<"Valiables list empty!!!"<<endl;
1296       aCommandIndex++;
1297       continue;
1298     }
1299
1300     TState aVariables = aStates->GetCurrectState();
1301
1302     if(MYDEBUG) {
1303       cout<<"Variables from SObject:"<<endl;
1304       for (int i = 0; i < aVariables.size();i++)
1305         cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
1306     }
1307
1308     //Calculate total number of parameters
1309     Standard_Integer aTotalNbParams = 1;
1310     while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
1311       aTotalNbParams++;
1312
1313     if(MYDEBUG)
1314       cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
1315
1316     Standard_Integer aFirstParam = aNbEntries;
1317
1318     //Replace parameters by variables
1319     Standard_Integer aStartPos = 0;
1320     Standard_Integer aEndPos = 0;
1321     int iVar = 0;
1322     TCollection_AsciiString aVar, aReplacedVar;
1323     for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
1324       //Replace first parameter (bettwen '(' character and first ',' character)
1325       if(i == aFirstParam)
1326       {
1327         aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
1328         if(aTotalNbParams - aNbEntries > 0 )
1329           aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
1330         else
1331           aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
1332       }
1333       //Replace last parameter (bettwen ',' character and ')' character)
1334       else if(i == aTotalNbParams)
1335       {
1336         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1337         aEndPos = aCommand.Location(C_BRACKET, aStartPos , aCommand.Length());
1338       }
1339       //Replace other parameters (bettwen two ',' characters)
1340       else if(i != aFirstParam && i != aTotalNbParams )
1341       {
1342         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1343         aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
1344       }
1345
1346       if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
1347         aStartPos++;
1348       if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
1349         aEndPos--;
1350       if ( aStartPos == aEndPos )
1351         continue; // PAL20889: for "[]"
1352
1353       if(MYDEBUG)
1354         cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
1355
1356       aVar = aCommand.SubString(aStartPos, aEndPos-1);
1357       aVar.RightAdjust();
1358       aVar.LeftAdjust();
1359
1360       if(MYDEBUG)
1361         cout<<"Variable: '"<< aVar <<"'"<<endl;
1362
1363       // specific case for sketcher
1364       if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
1365         Standard_Integer aNbSections = 1;
1366         while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
1367           aNbSections++;
1368         aNbSections--;
1369
1370         int aStartSectionPos = 0, aEndSectionPos = 0;
1371         TCollection_AsciiString aSection, aReplacedSection;
1372         for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
1373           aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
1374           if( aSectionIndex != aNbSections )
1375             aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
1376           else
1377             aEndSectionPos = aVar.Length();
1378
1379           aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
1380           if(MYDEBUG)
1381             cout<<"aSection: "<<aSection<<endl;
1382
1383           Standard_Integer aNbParams = 1;
1384           while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
1385             aNbParams++;
1386           aNbParams--;
1387
1388           int aStartParamPos = 0, aEndParamPos = 0;
1389           TCollection_AsciiString aParameter, aReplacedParameter;
1390           for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1391             aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1392             if( aParamIndex != aNbParams )
1393               aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1394             else
1395               aEndParamPos = aSection.Length() + 1;
1396
1397             if(MYDEBUG)
1398               cout<<"aParamIndex: "<<aParamIndex<<" aStartParamPos: " <<aStartParamPos<<" aEndParamPos: "<<aEndParamPos<<endl;
1399
1400             if ( aStartParamPos == aEndParamPos)
1401               continue;
1402
1403             aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1404             if(MYDEBUG)
1405               cout<<"aParameter: "<<aParameter<<endl;
1406
1407             if(iVar >= aVariables.size())
1408               continue;
1409
1410             aReplacedParameter = aVariables[iVar].myVariable;
1411             if(aReplacedParameter.IsEmpty()) {
1412               iVar++;
1413               continue;
1414             }
1415
1416             if(aVariables[iVar].isVariable) {
1417               aReplacedParameter.InsertBefore(1,"'");
1418               aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1419             }
1420
1421             if(MYDEBUG)
1422               cout<<"aSection before : "<<aSection<<endl;
1423             aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1424             aSection.Insert(aStartParamPos, aReplacedParameter);
1425             if(MYDEBUG)
1426               cout<<"aSection after  : "<<aSection<<endl<<endl;
1427             iVar++;
1428           }
1429           if(MYDEBUG)
1430             cout<<"aVar before : "<<aVar<<endl;
1431           aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1432           aVar.Insert(aStartSectionPos, aSection);
1433           if(MYDEBUG)
1434             cout<<"aVar after  : "<<aVar<<endl<<endl;
1435         }
1436
1437         if(MYDEBUG)
1438           cout<<"aCommand before : "<<aCommand<<endl;
1439         aCommand.Remove(aStartPos, aEndPos - aStartPos);
1440         aCommand.Insert(aStartPos, aVar);
1441         if(MYDEBUG)
1442           cout<<"aCommand after  : "<<aCommand<<endl;
1443
1444         break;
1445       } // end of specific case for sketcher
1446
1447       //If parameter is entry or 'None', skip it
1448       if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1449         continue;
1450
1451       if(iVar >= aVariables.size())
1452         continue;
1453
1454       aReplacedVar = aVariables[iVar].myVariable;
1455       if(aReplacedVar.IsEmpty()) {
1456         iVar++;
1457         continue;
1458       }
1459
1460       if(aVariables[iVar].isVariable) {
1461         aReplacedVar.InsertBefore(1,"\"");
1462         aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1463       }
1464
1465       aCommand.Remove(aStartPos, aEndPos - aStartPos);
1466       aCommand.Insert(aStartPos, aReplacedVar);
1467       iVar++;
1468     }
1469
1470     theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1471     theCommand.Insert(aStartCommandPos, aCommand);
1472
1473     aCommandIndex++;
1474
1475     aStates->IncrementState();
1476   }
1477
1478   if (MYDEBUG)
1479     cout<<"Command : "<<theCommand<<endl;
1480 }
1481
1482 //=============================================================================
1483 /*!
1484  *  ReplaceEntriesByNames: Replace object entries by their names
1485  */
1486 //=============================================================================
1487 void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
1488                             TSting2ObjDataMap&                        aEntry2ObjData,
1489                             const bool                                theIsPublished,
1490                             TColStd_SequenceOfAsciiString&            theObjListToPublish,
1491                             Standard_Integer&                         objectCounter,
1492                             Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
1493 {
1494   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1495   Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
1496
1497   //Replace entries by the names
1498   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1499     allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1500   if (aLen == 0) anUpdatedScript = theScript;
1501
1502   for (Standard_Integer i = 1; i <= aLen; i+=2) {
1503     anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1504     anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1505     theObjListToPublish.Append( anEntry );
1506     
1507     TObjectData& data = aEntry2ObjData[ anEntry ];
1508     if ( data._pyName.IsEmpty() ) { // encounted for the 1st time
1509       if ( !data._name.IsEmpty() ) { // published object
1510         data._pyName = data._name;
1511         healPyName( data._pyName, anEntry, aNameToEntry);
1512       }
1513       else {
1514         do {
1515           data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
1516         } while(aNameToEntry.IsBound(data._pyName));
1517       }
1518     }
1519     
1520     aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
1521     
1522     anUpdatedScript += data._pyName;
1523     aStart = aSeq->Value(i+1) + 1;
1524   }
1525   
1526   //Add final part of the script
1527   if (aLen && aSeq->Value(aLen) < aScriptLength)
1528     anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1529   
1530   theScript = anUpdatedScript;
1531 }
1532
1533 //=============================================================================
1534 /*!
1535  *  AddObjectColors: Add color to objects
1536  */
1537 //=============================================================================
1538 void AddObjectColors (int                      theDocID,
1539                       TCollection_AsciiString& theScript,
1540                       const TSting2ObjDataMap& theEntry2ObjData)
1541 {
1542   GEOM_Engine* engine = GEOM_Engine::GetEngine();
1543   Handle(TDocStd_Document) aDoc = engine->GetDocument(theDocID);
1544
1545   TSting2ObjDataMap::const_iterator anEntryToNameIt;
1546   for (anEntryToNameIt = theEntry2ObjData.begin();
1547        anEntryToNameIt!= theEntry2ObjData.end();
1548        ++anEntryToNameIt)
1549   {
1550     const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
1551     const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
1552
1553     TDF_Label L;
1554     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
1555     if ( L.IsNull() )
1556       continue;
1557
1558     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1559     if ( obj.IsNull() )
1560       continue;
1561
1562     bool anAutoColor = obj->GetAutoColor();
1563     if ( anAutoColor )
1564     {
1565       TCollection_AsciiString aCommand( "\n\t" );
1566       aCommand += aName + ".SetAutoColor(1)";
1567       theScript += aCommand.ToCString();
1568     }
1569
1570     GEOM_Object::Color aColor = obj->GetColor();
1571     if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
1572     {
1573       TCollection_AsciiString aCommand( "\n\t" );
1574       aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1575       theScript += aCommand.ToCString();
1576     }
1577
1578     Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
1579     if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
1580       TCollection_AsciiString aCommand( "\n\t" );
1581       aCommand += aName + ".SetMarkerStd(";
1582       switch (aMarkerType) {
1583       case Aspect_TOM_POINT:   aCommand += "GEOM.MT_POINT";   break;
1584       case Aspect_TOM_PLUS:    aCommand += "GEOM.MT_PLUS";    break;
1585       case Aspect_TOM_STAR:    aCommand += "GEOM.MT_STAR";    break;
1586       case Aspect_TOM_O:       aCommand += "GEOM.MT_O";       break;
1587       case Aspect_TOM_X:       aCommand += "GEOM.MT_X";       break;
1588       case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break;
1589       case Aspect_TOM_O_PLUS:  aCommand += "GEOM.MT_O_PLUS";  break;
1590       case Aspect_TOM_O_STAR:  aCommand += "GEOM.MT_O_STAR";  break;
1591       case Aspect_TOM_O_X:     aCommand += "GEOM.MT_O_X";     break;
1592       case Aspect_TOM_BALL:    aCommand += "GEOM.MT_BALL";    break;
1593       case Aspect_TOM_RING1:   aCommand += "GEOM.MT_RING1";   break;
1594       case Aspect_TOM_RING2:   aCommand += "GEOM.MT_RING2";   break;
1595       case Aspect_TOM_RING3:   aCommand += "GEOM.MT_RING3";   break;
1596       default:                 aCommand += "GEOM.MT_NONE";    break; // just for completeness, should not get here
1597       }
1598       aCommand += ", ";
1599       int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1;
1600       switch (aSize) {
1601       case  1: aCommand += "GEOM.MS_10";   break;
1602       case  2: aCommand += "GEOM.MS_15";   break;
1603       case  3: aCommand += "GEOM.MS_20";   break;
1604       case  4: aCommand += "GEOM.MS_25";   break;
1605       case  5: aCommand += "GEOM.MS_30";   break;
1606       case  6: aCommand += "GEOM.MS_35";   break;
1607       case  7: aCommand += "GEOM.MS_40";   break;
1608       case  8: aCommand += "GEOM.MS_45";   break;
1609       case  9: aCommand += "GEOM.MS_50";   break;
1610       case 10: aCommand += "GEOM.MS_55";   break;
1611       case 11: aCommand += "GEOM.MS_60";   break;
1612       case 12: aCommand += "GEOM.MS_65";   break;
1613       case 13: aCommand += "GEOM.MS_70";   break;
1614       default: aCommand += "GEOM.MS_NONE"; break;
1615       }
1616       aCommand += ")";
1617       theScript += aCommand.ToCString();
1618     }
1619     else if (aMarkerType == Aspect_TOM_USERDEFINED) {
1620       int aMarkerTextureID = obj->GetMarkerTexture();
1621       if (aMarkerTextureID >= 0) {
1622         TCollection_AsciiString aCommand( "\n\t" );
1623         aCommand += aName + ".SetMarkerTexture(texture_map[";
1624         aCommand += aMarkerTextureID;
1625         aCommand += "])";
1626         theScript += aCommand.ToCString();
1627       }
1628     }
1629   }
1630 }
1631
1632 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
1633 static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData)
1634 #else
1635 static TCollection_AsciiString pack_data (const Handle(TDataStd_HArray1OfByte)& aData)
1636 #endif
1637 {
1638   TCollection_AsciiString stream;
1639   if (!aData.IsNull()) {
1640     for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) {
1641       Standard_Byte byte = aData->Value(i);
1642       TCollection_AsciiString strByte = "";
1643       for (int j = 0; j < 8; j++)
1644         strByte.Prepend((byte & (1<<j)) ? "1" : "0");
1645       stream += strByte;
1646     }
1647   }
1648   return stream;
1649 }
1650
1651 void AddTextures (int theDocID, TCollection_AsciiString& theScript)
1652 {
1653   GEOM_Engine* engine = GEOM_Engine::GetEngine();
1654   std::list<int> allTextures = engine->getAllTextures(theDocID);
1655   std::list<int>::const_iterator it;
1656
1657   if (allTextures.size() > 0) {
1658     theScript += "\n\ttexture_map = {}\n";
1659
1660     for (it = allTextures.begin(); it != allTextures.end(); ++it) {
1661       if (*it <= 0) continue;
1662       Standard_Integer aWidth, aHeight;
1663       TCollection_AsciiString aFileName;
1664 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
1665       Handle(TColStd_HArray1OfByte) aTexture =
1666 #else
1667       Handle(TDataStd_HArray1OfByte) aTexture =
1668 #endif
1669         engine->getTexture(theDocID, *it, aWidth, aHeight, aFileName);
1670       if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
1671         TCollection_AsciiString aCommand = "\n\t";
1672         aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
1673         if (aFileName != "" ) {
1674           aCommand += "geompy.LoadTexture(\"";
1675           aCommand += aFileName.ToCString();
1676           aCommand += "\")";
1677         }
1678         else {
1679           aCommand += "geompy.AddTexture(";
1680           aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \"";
1681           aCommand += pack_data(aTexture);
1682           aCommand += "\")";
1683         }
1684         theScript += aCommand;
1685       }
1686     }
1687     theScript += "\n";
1688   }
1689 }
1690
1691 //=============================================================================
1692 /*!
1693  *  PublishObject: publish object in study script
1694  */
1695 //=============================================================================
1696 void PublishObject (TObjectData&                              theObjectData,
1697                     TSting2ObjDataMap&                        theEntry2ObjData,
1698                     const TSting2ObjDataPtrMap&               theStEntry2ObjDataPtr,
1699                     Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
1700                     std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
1701                     std::set< TCollection_AsciiString>&       theIgnoreMap)
1702 {
1703   if ( theObjectData._studyEntry.IsEmpty() )
1704     return; // was not published
1705   if ( theIgnoreMap.count( theObjectData._entry ) )
1706     return; // not to publish
1707
1708   TCollection_AsciiString aCommand("\n\tgeompy.");
1709
1710   // find a father entry
1711   TObjectData* aFatherData = 0;
1712   TCollection_AsciiString aFatherStudyEntry =
1713     theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
1714   TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
1715     theStEntry2ObjDataPtr.find( aFatherStudyEntry );
1716   if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
1717     aFatherData = stEntry2DataPtr->second;
1718
1719   const int geomObjDepth = 3;
1720
1721   // treat multiply published object
1722   if ( theObjectData._pyName.IsEmpty() )
1723   {
1724     TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
1725     if ( data0._pyName.IsEmpty() ) return; // something wrong
1726
1727     theObjectData._pyName = theObjectData._name;
1728     healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
1729
1730     TCollection_AsciiString aCreationCommand("\n\t");
1731     aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
1732
1733     // store aCreationCommand before publishing commands
1734     int tag = theObjectData._entry.Token( ":", geomObjDepth ).IntegerValue();
1735     theEntryToCmdMap.insert( std::make_pair( tag + 2*theEntry2ObjData.size(), aCreationCommand ));
1736   }
1737
1738   // make a command
1739   if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
1740     aCommand += "addToStudyInFather( ";
1741     aCommand += aFatherData->_pyName + ", ";
1742   }
1743   else {
1744     aCommand += "addToStudy( ";
1745   }
1746   aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
1747
1748   // bind a command to the study entry
1749   int tag = theObjectData._entry.Token( ":", geomObjDepth ).IntegerValue();
1750   theEntryToCmdMap.insert( std::make_pair( tag, aCommand ));
1751
1752   theObjectData._studyEntry.Clear(); // not to publish any more
1753 }
1754
1755 //================================================================================
1756 /*!
1757  * \brief Constructor
1758  */
1759 //================================================================================
1760 ObjectStates::ObjectStates()
1761 {
1762   _dumpstate = 0;
1763 }
1764
1765 //================================================================================
1766 /*!
1767  * \brief Destructor
1768  */
1769 //================================================================================
1770 ObjectStates::~ObjectStates()
1771 {
1772 }
1773
1774 //================================================================================
1775 /*!
1776  * \brief Return current object state
1777  * \retval state - Object state (vector of notebook variable)
1778  */
1779 //================================================================================
1780 TState ObjectStates::GetCurrectState() const
1781 {
1782   if(_states.size() > _dumpstate)
1783     return _states[_dumpstate];
1784   return TState();
1785 }
1786
1787 //================================================================================
1788 /*!
1789  * \brief Add new object state
1790  * \param theState - Object state (vector of notebook variable)
1791  */
1792 //================================================================================
1793 void ObjectStates::AddState(const TState &theState)
1794 {
1795   _states.push_back(theState);
1796 }
1797
1798 //================================================================================
1799 /*!
1800  * \brief Increment object state
1801  */
1802 //================================================================================
1803 void ObjectStates::IncrementState()
1804 {
1805   _dumpstate++;
1806 }