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