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