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