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