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