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