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