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