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