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