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