Salome HOME
Implementation of 0021855: EDF 2321 GEOM : Add folders to group objects in the object...
[modules/geom.git] / src / GEOM / GEOM_Engine.cxx
1 // Copyright (C) 2007-2013  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.
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 WNT
24 #pragma warning( disable:4786 )
25 #endif
26
27 #include "GEOM_Engine.hxx"
28
29 #include "GEOM_Solver.hxx"
30 #include "GEOM_Function.hxx"
31 #include "GEOM_ISubShape.hxx"
32 #include "GEOM_SubShapeDriver.hxx"
33 #include "GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient.hxx"
34 #include "GEOM_PythonDump.hxx"
35 #include "Sketcher_Profile.hxx"
36
37 #include <Basics_OCCTVersion.hxx>
38
39 #include "utilities.h"
40
41 #include <Basics_Utils.hxx>
42
43 #include <TDF_Tool.hxx>
44 #include <TDF_Data.hxx>
45 #include <TDF_Reference.hxx>
46 #include <TDF_LabelSequence.hxx>
47 #include <TDataStd_Integer.hxx>
48 #include <TDataStd_ChildNodeIterator.hxx>
49 #include <TFunction_Driver.hxx>
50 #include <TFunction_DriverTable.hxx>
51 #include <TDataStd_ByteArray.hxx>
52 #include <TDataStd_UAttribute.hxx>
53 #include <TDF_ChildIterator.hxx>
54 #include <TDataStd_Comment.hxx>
55
56 #include <TopExp.hxx>
57 #include <TopTools_IndexedMapOfShape.hxx>
58
59 #include <TCollection_AsciiString.hxx>
60 #include <TCollection_ExtendedString.hxx>
61 #include <TColStd_SequenceOfAsciiString.hxx>
62 #include <TColStd_MapOfTransient.hxx>
63 #include <TColStd_HSequenceOfInteger.hxx>
64
65 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
66 #include <TColStd_HArray1OfByte.hxx>
67 #include <TColStd_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
68 #else
69 #include <TDataStd_HArray1OfByte.hxx>
70 #include <Interface_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
71 #endif
72
73 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
74
75 #include <set>
76
77 #include <Standard_Failure.hxx>
78 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
79
80 #define COMMA ','
81 #define O_BRACKET '('
82 #define C_BRACKET ')'
83 #define O_SQR_BRACKET '['
84 #define C_SQR_BRACKET ']'
85 #define PY_NULL "None"
86
87 #ifdef _DEBUG_
88 static int MYDEBUG = 0;
89 #else
90 static int MYDEBUG = 0;
91 #endif
92
93 typedef std::map< TCollection_AsciiString, TCollection_AsciiString > TSting2StringMap;
94 typedef std::map< TCollection_AsciiString, TObjectData >             TSting2ObjDataMap;
95 typedef std::map< TCollection_AsciiString, TObjectData* >            TSting2ObjDataPtrMap;
96
97 static GEOM_Engine* TheEngine = NULL;
98
99
100 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
101 {
102   TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
103   TDF_Tool::Entry(theObject->GetEntry(), anEntry);
104   anID+=(TCollection_AsciiString("_")+anEntry);
105   return anID;
106 }
107
108 static TCollection_AsciiString BuildID(Standard_Integer theDocID, char* theEntry)
109 {
110   TCollection_AsciiString anID(theDocID);
111   anID+=(TCollection_AsciiString("_")+theEntry);
112   return anID;
113 }
114
115 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
116 {
117   TCollection_AsciiString aDocID = theID.Token("_");
118   if(aDocID.Length() < 1) return -1;
119   return aDocID.IntegerValue();
120 }
121
122 bool ProcessFunction(Handle(GEOM_Function)&             theFunction,
123                      TCollection_AsciiString&           theScript,
124                      TCollection_AsciiString&           theAfterScript,
125                      const TVariablesList&              theVariables,
126                      const bool                         theIsPublished,
127                      TDF_LabelMap&                      theProcessed,
128                      std::set<TCollection_AsciiString>& theIgnoreObjs,
129                      bool&                              theIsDumpCollected);
130
131 void ReplaceVariables(TCollection_AsciiString& theCommand,
132                       const TVariablesList&    theVariables);
133
134 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
135
136 void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
137                             TSting2ObjDataMap&                        aEntry2ObjData,
138                             const bool                                theIsPublished,
139                             TColStd_SequenceOfAsciiString&            theObjListToPublish,
140                             Standard_Integer&                         objectCounter,
141                             Resource_DataMapOfAsciiStringAsciiString& aNameToEntry);
142
143 void AddObjectColors (int                      theDocID,
144                       TCollection_AsciiString& theScript,
145                       const TSting2ObjDataMap& theEntry2ObjData);
146
147 void AddTextures (int theDocID, TCollection_AsciiString& theScript);
148
149 void PublishObject (TObjectData&                              theObjectData,
150                     TSting2ObjDataMap&                        theEntry2ObjData,
151                     const TSting2ObjDataPtrMap&               theStEntry2ObjDataPtr,
152                     Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
153                     std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
154                     std::set<TCollection_AsciiString>&        theMapOfPublished);
155
156 //================================================================================
157 /*!
158  * \brief Fix up the name of python variable
159  */
160 //================================================================================
161
162 void GEOM_Engine::healPyName( TCollection_AsciiString&                  pyName,
163                               const TCollection_AsciiString&            anEntry,
164                               Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
165 {
166   const TCollection_AsciiString allowedChars
167     ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
168
169   if ( pyName.IsIntegerValue() ) { // pyName must not start with a digit
170     pyName.Insert( 1, 'a' );
171   }
172   int p, p2=1; // replace not allowed chars
173   while ((p = pyName.FirstLocationNotInSet(allowedChars, p2, pyName.Length()))) {
174     pyName.SetValue(p, '_');
175     p2=p;
176   }
177   if ( aNameToEntry.IsBound( pyName ) && anEntry != aNameToEntry( pyName ))
178     {  // diff objects have same name - make a new name by appending a digit
179       TCollection_AsciiString aName2;
180       Standard_Integer i = 0;
181       do {
182         aName2 = pyName + "_" + ++i;
183       } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
184       pyName = aName2;
185     }
186 }
187
188 //=======================================================================
189 //function : GetTextureGUID
190 //purpose  :
191 //=======================================================================
192 const Standard_GUID& GEOM_Engine::GetTextureGUID()
193 {
194   static Standard_GUID anID("FF1BBB01-5D14-4df2-980B-3A668264EA17");
195   return anID;
196 }
197
198 //=============================================================================
199 /*!
200  *  GetEngine
201  */
202 //=============================================================================
203 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
204
205 //=============================================================================
206 /*!
207  *  SetEngine
208  */
209 //=============================================================================
210 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
211
212 //=============================================================================
213 /*!
214  *  Constructor
215  */
216 //=============================================================================
217 GEOM_Engine::GEOM_Engine()
218 {
219   TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
220   
221   _OCAFApp = new GEOM_Application();
222   _UndoLimit = 10;
223 }
224
225 /*!
226  *  Destructor
227  */
228 GEOM_Engine::~GEOM_Engine()
229 {
230   GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
231   std::list< Handle(GEOM_Object) > objs;
232   for(; It.More(); It.Next())
233     objs.push_back( Handle(GEOM_Object)::DownCast(It.Value()) );
234   std::list< Handle(GEOM_Object) >::iterator objit;
235   for(objit = objs.begin(); objit != objs.end(); ++objit)
236     RemoveObject(*objit);
237
238   //Close all documents not closed
239 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
240   TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
241 #else
242   Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
243 #endif
244   for (; anItr.More(); anItr.Next())
245   {
246     Close(anItr.Key());
247     anItr.Initialize( _mapIDDocument ); // anItr becomes invalid at _mapIDDocument.UnBind(docId)
248   }
249   _mapIDDocument.Clear();
250   _objects.Clear();
251 }
252
253 //=============================================================================
254 /*!
255  *  GetDocument
256  */
257 //=============================================================================
258 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID, bool force)
259 {
260   Handle(TDocStd_Document) aDoc;
261   if(_mapIDDocument.IsBound(theDocID)) {
262     aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
263   }
264   else if (force) {
265     _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
266     aDoc->SetUndoLimit(_UndoLimit);
267     _mapIDDocument.Bind(theDocID, aDoc);
268     TDataStd_Integer::Set(aDoc->Main(), theDocID);
269   }
270   return aDoc;
271 }
272
273 //=============================================================================
274 /*!
275  *  GetDocID
276  */
277 //=============================================================================
278 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
279 {
280   if (theDocument.IsNull()) return -1;
281 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
282   TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
283 #else
284   Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
285 #endif
286   for (; anItr.More(); anItr.Next())
287     if (anItr.Value() == theDocument) return anItr.Key();
288
289   return -1;
290 }
291
292 //=============================================================================
293 /*!
294  *  GetObject
295  */
296 //=============================================================================
297 Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry, bool force)
298 {
299   Handle(GEOM_Object) anObject;
300
301   TCollection_AsciiString anID = BuildID(theDocID, theEntry);
302
303   if (_objects.IsBound(anID)) {
304     anObject = Handle(GEOM_Object)::DownCast(_objects(anID));
305   }
306   else if (force) {
307     Handle(TDocStd_Document) aDoc = GetDocument(theDocID, force);
308     if ( !aDoc.IsNull()) {
309       TDF_Label aLabel;
310       TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
311       anObject = new GEOM_Object(aLabel);
312       _objects.Bind(anID, anObject);
313     }
314   }
315
316   return anObject;
317 }
318
319 //=============================================================================
320 /*!
321  *  AddObject
322  */
323 //=============================================================================
324 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
325 {
326   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
327   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
328
329   // NPAL18604: use existing label to decrease memory usage,
330   //            if this label has been freed (object deleted)
331   bool useExisting = false;
332   TDF_Label aChild;
333   if (_freeLabels.find(theDocID) != _freeLabels.end()) {
334     std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
335     if (!aFreeLabels.empty()) {
336       useExisting = true;
337       aChild = aFreeLabels.front();
338       aFreeLabels.pop_front();
339     }
340   }
341   if (!useExisting) {
342     // create new label
343     aChild = TDF_TagSource::NewChild(aDoc->Main());
344   }
345
346   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
347
348   //Put an object in the map of created objects
349   TCollection_AsciiString anID = BuildIDFromObject(anObject);
350   if(_objects.IsBound(anID)) _objects.UnBind(anID);
351   _objects.Bind(anID, anObject);
352
353   return anObject;
354 }
355
356 //=============================================================================
357 /*!
358  *  AddSubShape
359  */
360 //=============================================================================
361 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
362                                              Handle(TColStd_HArray1OfInteger) theIndices,
363                                              bool isStandaloneOperation)
364 {
365   if (theMainShape.IsNull() || theIndices.IsNull()) return NULL;
366
367   Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
368   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
369
370   // NPAL18604: use existing label to decrease memory usage,
371   //            if this label has been freed (object deleted)
372   bool useExisting = false;
373   TDF_Label aChild;
374   int aDocID = theMainShape->GetDocID();
375   if (_freeLabels.find(aDocID) != _freeLabels.end()) {
376     std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
377     if (!aFreeLabels.empty()) {
378       useExisting = true;
379       aChild = aFreeLabels.front();
380       aFreeLabels.pop_front();
381     }
382   }
383   if (!useExisting) {
384     // create new label
385     aChild = TDF_TagSource::NewChild(aDoc->Main());
386   }
387
388   Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
389   Handle(GEOM_Object) anObject = new GEOM_Object (aChild, 28); //28 is SUBSHAPE type
390   Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
391
392   GEOM_ISubShape aSSI (aFunction);
393   aSSI.SetMainShape(aMainShape);
394   aSSI.SetIndices(theIndices);
395
396   try {
397 #if OCC_VERSION_LARGE > 0x06010000
398     OCC_CATCH_SIGNALS;
399 #endif
400     GEOM_Solver aSolver (GEOM_Engine::GetEngine());
401     if (!aSolver.ComputeFunction(aFunction)) {
402       MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
403       return NULL;
404     }
405   }
406   catch (Standard_Failure) {
407     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
408     MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
409     return NULL;
410   }
411
412   // Put an object in the map of created objects
413   TCollection_AsciiString anID = BuildIDFromObject(anObject);
414   if (_objects.IsBound(anID)) _objects.UnBind(anID);
415   _objects.Bind(anID, anObject);
416
417   // Put this sub-shape in the list of sub-shapes of theMainShape
418   aMainShape->AddSubShapeReference(aFunction);
419
420   GEOM::TPythonDump pd (aFunction);
421
422   if (isStandaloneOperation) {
423     pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
424     Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
425     for (; i <= up - 1; i++) {
426       pd << theIndices->Value(i) << ", ";
427     }
428     pd << theIndices->Value(up) << "])";
429   }
430   else
431     pd << "None";
432
433   return anObject;
434 }
435
436 //=============================================================================
437 /*!
438  *  RemoveObject
439  */
440 //=============================================================================
441 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
442 {
443   if (theObject.IsNull()) return false;
444
445   int aDocID = theObject->GetDocID();
446   if(!_mapIDDocument.IsBound(aDocID))
447     return false;  // document is closed...
448
449   //Remove an object from the map of available objects
450   TCollection_AsciiString anID = BuildIDFromObject(theObject);
451   if (_objects.IsBound(anID)) _objects.UnBind(anID);
452
453   // If sub-shape, remove it from the list of sub-shapes of its main shape
454   if (!theObject->IsMainShape()) {
455     Handle(GEOM_Function) aFunction = theObject->GetFunction(1);
456     GEOM_ISubShape aSSI (aFunction);
457     Handle(GEOM_Function) aMainShape = aSSI.GetMainShape();
458     //If main shape is not null, then remove
459     if(!aMainShape.IsNull())
460       aMainShape->RemoveSubShapeReference(aFunction);
461   }
462
463   int nb = theObject->GetNbFunctions();
464   Handle(TDataStd_TreeNode) aNode;
465   for (int i = 1; i <= nb; i++) {
466     Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
467     if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
468       aNode->Remove();
469   }
470
471   TDF_Label aLabel = theObject->GetEntry();
472   aLabel.ForgetAllAttributes(Standard_True);
473
474   // Remember the label to reuse it then
475   std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
476   aFreeLabels.push_back(aLabel);
477
478   theObject.Nullify();
479
480   return true;
481 }
482
483 //=============================================================================
484 /*!
485  *  Undo
486  */
487 //=============================================================================
488 void GEOM_Engine::Undo(int theDocID)
489 {
490   GetDocument(theDocID)->Undo();
491 }
492
493 //=============================================================================
494 /*!
495  *  Redo
496  */
497 //=============================================================================
498 void GEOM_Engine::Redo(int theDocID)
499 {
500   GetDocument(theDocID)->Redo();
501 }
502
503 //=============================================================================
504 /*!
505  *  Save
506  */
507 //=============================================================================
508 bool GEOM_Engine::Save(int theDocID, char* theFileName)
509 {
510   if(!_mapIDDocument.IsBound(theDocID)) return false;
511   Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
512
513   _OCAFApp->SaveAs(aDoc, theFileName);
514
515   return true;
516 }
517
518 //=============================================================================
519 /*!
520  *  Load
521  */
522 //=============================================================================
523 bool GEOM_Engine::Load(int theDocID, char* theFileName)
524 {
525   Handle(TDocStd_Document) aDoc;
526 #if OCC_VERSION_LARGE > 0x06050100 // For OCCT6.5.2 and higher
527   if (_OCAFApp->Open(theFileName, aDoc) != PCDM_RS_OK) {
528 #else
529   if (_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
530 #endif
531     return false;
532   }
533
534   aDoc->SetUndoLimit(_UndoLimit);
535
536   if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
537   _mapIDDocument.Bind(theDocID, aDoc);
538
539   TDataStd_Integer::Set(aDoc->Main(), theDocID);
540
541   return true;
542 }
543
544 //=============================================================================
545 /*!
546  *  Close
547  */
548 //=============================================================================
549 void GEOM_Engine::Close(int theDocID)
550 {
551   if (_mapIDDocument.IsBound(theDocID)) {
552     Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
553
554     //Remove all GEOM Objects associated to the given document
555     TColStd_SequenceOfAsciiString aSeq;
556     GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
557     for (; It.More(); It.Next()) {
558       TCollection_AsciiString anObjID (It.Key());
559       Standard_Integer anID = ExtractDocID(anObjID);
560       if (theDocID == anID) aSeq.Append(It.Key());
561     }
562     for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
563
564     // Forget free labels for this document
565     TFreeLabelsList::iterator anIt = _freeLabels.find(theDocID);
566     if (anIt != _freeLabels.end()) {
567       _freeLabels.erase(anIt);
568     }
569
570     _mapIDDocument.UnBind(theDocID);
571     _OCAFApp->Close(aDoc);
572     aDoc.Nullify();
573   }
574 }
575
576 //=============================================================================
577 /*!
578  *  DumpPython
579  */
580 //=============================================================================
581 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
582                                                 std::vector<TObjectData>& theObjectData,
583                                                 TVariablesList theVariables,
584                                                 bool isPublished,
585                                                 bool isMultiFile, 
586                                                 bool& aValidScript)
587 {
588   // Set "C" numeric locale to save numbers correctly
589   Kernel_Utils::Localizer loc;
590
591   TCollection_AsciiString aScript;
592   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
593
594   if (aDoc.IsNull())
595   {
596     TCollection_AsciiString anEmptyScript;
597     if( isMultiFile )
598       anEmptyScript = "def RebuildData(theStudy): pass\n";
599     return anEmptyScript;
600   }
601
602   aScript  = "import GEOM\n";
603   aScript += "from salome.geom import geomBuilder\n";
604   aScript += "import math\n";
605   aScript += "import SALOMEDS\n\n";
606   if( isMultiFile )
607     aScript += "def RebuildData(theStudy):";
608
609   aScript += "\n\tgeompy = geomBuilder.New(theStudy)\n";
610
611   AddTextures(theDocID, aScript);
612
613   Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
614
615   // a map containing copies of TObjectData from theObjectData
616   TSting2ObjDataMap    aEntry2ObjData;
617   // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
618   // occures when several StudyEntries correspond to one Entry
619   TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
620
621   //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
622   for (unsigned i = 0; i < theObjectData.size(); ++i )
623   {
624     TObjectData& data = theObjectData[i];
625     // look for an object by entry
626     TDF_Label L;
627     TDF_Tool::Label( aDoc->GetData(), data._entry, L );
628     if ( L.IsNull() ) continue;
629     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
630     // fill maps
631     if ( !obj.IsNull() ) {
632       TSting2ObjDataMap::iterator ent2Data =
633         aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
634
635       if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
636         aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
637       else
638         aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
639     }
640   }
641
642   // collect objects entries to be published
643   TColStd_SequenceOfAsciiString aObjListToPublish;
644
645   // iterates on functions till critical (that requiers publication of objects)
646   Handle(TDataStd_TreeNode) aNode, aRoot;
647   Handle(GEOM_Function) aFunction;
648   TDF_LabelMap aCheckedFuncMap;
649   std::set< TCollection_AsciiString > anIgnoreObjMap;
650
651   TCollection_AsciiString aFuncScript;
652
653   // Mantis issue 0020768
654   Standard_Integer objectCounter = 0;
655   Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
656
657   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
658     TDataStd_ChildNodeIterator Itr(aRoot);
659     for (; Itr.More(); Itr.Next()) {
660       aNode = Itr.Value();
661       aFunction = GEOM_Function::GetFunction(aNode->Label());
662       if (aFunction.IsNull()) {
663         MESSAGE ( "Null function !!!!" );
664         continue;
665       }
666       bool isDumpCollected = false;
667       TCollection_AsciiString aCurScript, anAfterScript;
668       if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
669                            isPublished, aCheckedFuncMap, anIgnoreObjMap,
670                            isDumpCollected ))
671         continue;
672       // add function description before dump
673       if (!aCurScript.IsEmpty())
674       {
675         if ( aFunction->GetDriverGUID() == GEOM_Object::GetSubShapeID() &&
676              aFuncScript.Length() > aCurScript.Length() )
677           // avoid repeated SubShape...() command at the end
678           if (aFuncScript.Location( aCurScript,
679                                     aFuncScript.Length() - aCurScript.Length(),
680                                     aFuncScript.Length()))
681             continue; // aCurScript is already at the end of aFuncScript
682         aFuncScript += aCurScript;
683       }
684       if (isDumpCollected ) {
685         // Replace entries by the names
686         ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
687                                aObjListToPublish, objectCounter, aNameToEntry );
688
689         // publish collected objects
690         std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry
691         int i = 1, n = aObjListToPublish.Length();
692         for ( ; i <= n; i++ )
693         {
694           const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
695           PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
696                          aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
697         }
698         // add publishing commands to the script
699         std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
700         for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
701           aFuncScript += anEntryToCmd->second;
702
703         // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
704         //  because they will be published during command execution
705         int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
706         if ( indx == -1 )
707           indx = anAfterScript.Search( "RestoreSubShapes" );
708         if ( indx != -1 ) {
709           TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
710           Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
711           i = 1, n = aSeq->Length();
712           for ( ; i <= n; i+=2) {
713             TCollection_AsciiString anEntry =
714               aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
715             anIgnoreObjMap.insert(anEntry.ToCString());
716           }
717         }
718
719         aObjListToPublish.Clear();
720         aScript += aFuncScript;
721         aFuncScript.Clear();
722       }
723       aFuncScript += anAfterScript;
724     }
725   }
726
727   // Replace entries by the names
728   aObjListToPublish.Clear();
729   ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
730                          objectCounter, aNameToEntry );
731
732   aScript += aFuncScript;
733
734   // ouv : NPAL12872
735   AddObjectColors( theDocID, aScript, aEntry2ObjData );
736
737   // Make script to publish in study
738   TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
739   if ( isPublished )
740   {
741     std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry
742
743     for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
744          aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
745          ++aStEntry2ObjDataPtrIt)
746     {
747       TObjectData* data = aStEntry2ObjDataPtrIt->second;
748       if ( anIgnoreObjMap.count( data->_entry ))
749         continue; // should not be dumped
750       PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
751                      aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
752     }
753     // add publishing commands to the script
754     std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
755     for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
756       aScript += anEntryToCmd->second;
757   }
758
759   //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function
760   //Add unpublish command if need
761   TCollection_AsciiString unpublishCmd("\n");
762   if(isMultiFile)
763     unpublishCmd += "\t";
764   unpublishCmd += "geompy.hideInStudy(";
765   
766   for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
767        aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
768        ++aStEntry2ObjDataPtrIt)
769     {
770       TObjectData* data = aStEntry2ObjDataPtrIt->second;      
771       if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
772         aScript +=  unpublishCmd + data->_pyName + ")";
773       }
774     }    
775   
776   // // add commands of folders creation and putting objects into it
777   // TCollection_AsciiString createFolderCmd("\n");
778   // createFolderCmd += "\t";
779   // createFolderCmd += "geompy.CreateFolder(";
780   // for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
781   //      aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
782   //      ++aStEntry2ObjDataPtrIt)
783   // {
784   //   const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
785   //   const TObjectData*                   data = aStEntry2ObjDataPtrIt->second;
786   //   if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
787   //     aScript +=  createFolderCmd + data->_pyName + ")";
788   //   }
789   // }
790
791   //aScript += "\n\tpass\n";
792   aScript += "\n";
793   aValidScript = true;
794
795   // fill _studyEntry2NameMap and build globalVars
796   TCollection_AsciiString globalVars;
797   _studyEntry2NameMap.Clear();
798   for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
799        aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
800        ++aStEntry2ObjDataPtrIt)
801   {
802     const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
803     const TObjectData*                   data = aStEntry2ObjDataPtrIt->second;
804     _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
805     if ( !globalVars.IsEmpty() )
806       globalVars += ", ";
807     globalVars += data->_pyName;
808   }
809   if ( isMultiFile && !globalVars.IsEmpty() ) {
810     globalVars.Insert( 1, "\n\tglobal " );
811     aScript.Insert( posToInsertGlobalVars, globalVars );
812   }
813
814   return aScript;
815 }
816
817 //=======================================================================
818 //function : GetDumpName
819 //purpose  :
820 //=======================================================================
821
822 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
823 {
824   if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
825     return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
826
827   return NULL;
828 }
829
830 //=======================================================================
831 //function : GetAllDumpNames
832 //purpose  :
833 //=======================================================================
834
835 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
836 {
837   Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
838
839   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
840   for (; it.More(); it.Next()) {
841     aRetSeq->Append(it.Value());
842   }
843
844   return aRetSeq;
845 }
846
847 #define TEXTURE_LABEL_ID       1
848 #define TEXTURE_LABEL_FILE     2
849 #define TEXTURE_LABEL_WIDTH    3
850 #define TEXTURE_LABEL_HEIGHT   4
851 #define TEXTURE_LABEL_DATA     5
852
853 int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight,
854 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
855                             const Handle(TColStd_HArray1OfByte)& theTexture,
856 #else
857                             const Handle(TDataStd_HArray1OfByte)& theTexture,
858 #endif
859                             const TCollection_AsciiString& theFileName)
860 {
861   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
862   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
863
864   // NPAL18604: use existing label to decrease memory usage,
865   //            if this label has been freed (object deleted)
866   bool useExisting = false;
867   TDF_Label aChild;
868   if (_freeLabels.find(theDocID) != _freeLabels.end()) {
869     std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
870     if (!aFreeLabels.empty()) {
871       useExisting = true;
872       aChild = aFreeLabels.front();
873       aFreeLabels.pop_front();
874     }
875   }
876   if (!useExisting) {
877     // create new label
878     aChild = TDF_TagSource::NewChild(aDoc->Main());
879   }
880
881   aChild.ForgetAllAttributes(Standard_True);
882   Handle(TDataStd_TreeNode) node;
883   if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) )
884     node = TDataStd_TreeNode::Set(aChild);
885   TDataStd_UAttribute::Set(aChild, GetTextureGUID());
886
887   static int aTextureID = 0;
888
889   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID),     ++aTextureID);
890   TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE),   theFileName);
891   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH),  theWidth);
892   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
893
894   Handle(TDataStd_ByteArray) anAttr =
895     TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
896                             theTexture.IsNull() ? 0 : theTexture->Lower(),
897                             theTexture.IsNull() ? 0 : theTexture->Upper());
898   anAttr->ChangeArray(theTexture);
899
900   return aTextureID;
901 }
902
903 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
904 Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
905 #else
906 Handle(TDataStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
907 #endif
908                                                       int& theWidth, int& theHeight,
909                                                       TCollection_AsciiString& theFileName)
910 {
911 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
912   Handle(TColStd_HArray1OfByte) anArray;
913 #else
914   Handle(TDataStd_HArray1OfByte) anArray;
915 #endif
916   theWidth = theHeight = 0;
917
918   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
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(int theDocID)
953 {
954   std::list<int> id_list;
955
956   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
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  *  FindEntries: Returns a sequence of start/end positions of entries in the string
1198  */
1199 //=============================================================================
1200 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
1201 {
1202   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1203   Standard_Integer aLen = theString.Length();
1204   Standard_Boolean isFound = Standard_False;
1205
1206   const char* arr = theString.ToCString();
1207   Standard_Integer i = 0, j;
1208
1209   while(i < aLen) {
1210     int c = (int)arr[i];
1211     j = i+1;
1212     if(c >= 48 && c <= 57) { //Is digit?
1213
1214       isFound = Standard_False;
1215       while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
1216         c = (int)arr[j++];
1217         if(c == 58) isFound = Standard_True;
1218       }
1219
1220       if(isFound && arr[j-2] != 58) { // last char should be a diggit
1221         aSeq->Append(i+1); // +1 because AsciiString starts from 1
1222         aSeq->Append(j-1);
1223       }
1224     }
1225
1226     i = j;
1227   }
1228
1229   return aSeq;
1230 }
1231
1232 //=============================================================================
1233 /*!
1234  *  ReplaceVariables: Replace parameters of the function by variales from
1235  *                    Notebook if need
1236  */
1237 //=============================================================================
1238 void ReplaceVariables(TCollection_AsciiString& theCommand,
1239                       const TVariablesList&    theVariables)
1240 {
1241   if (MYDEBUG)
1242     cout<<"Command : "<<theCommand<<endl;
1243
1244   if (MYDEBUG) {
1245     cout<<"All Entries:"<<endl;
1246     TVariablesList::const_iterator it = theVariables.begin();
1247     for(;it != theVariables.end();it++)
1248       cout<<"\t'"<<(*it).first<<"'"<<endl;
1249   }
1250
1251   //Additional case - multi-row commands
1252   int aCommandIndex = 1;
1253   while( aCommandIndex < 10 ) { // tmp check
1254     TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
1255     if( aCommand.Length() == 0 )
1256       break;
1257
1258     if (MYDEBUG)
1259       cout<<"Sub-command : "<<aCommand<<endl;
1260
1261     Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
1262     Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
1263
1264     //Get Entry of the result object
1265     TCollection_AsciiString anEntry;
1266     if( aCommand.Search("=") != -1 ) // command returns an object
1267       anEntry = aCommand.Token("=",1);
1268     else { // command modifies the object
1269       if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
1270         if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
1271           anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
1272     }
1273     //Remove white spaces
1274     anEntry.RightAdjust();
1275     anEntry.LeftAdjust();
1276     if(MYDEBUG)
1277       cout<<"Result entry : '" <<anEntry<<"'"<<endl;
1278
1279     if ( anEntry.IsEmpty() ) {
1280       aCommandIndex++;
1281       continue;
1282     }
1283
1284     //Check if result is list of entries - enough to get the first entry in this case
1285     int aNbEntries = 1;
1286     if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
1287       while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
1288         aNbEntries++;
1289       TCollection_AsciiString aSeparator(COMMA);
1290       anEntry = anEntry.Token(aSeparator.ToCString(),1);
1291       anEntry.Remove( 1, 1 );
1292       anEntry.RightAdjust();
1293       anEntry.LeftAdjust();
1294       if(MYDEBUG)
1295         cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
1296     }
1297
1298     //Find variables used for object construction
1299     ObjectStates* aStates = 0;
1300     TVariablesList::const_iterator it = theVariables.find(anEntry);
1301     if( it != theVariables.end() )
1302       aStates = (*it).second;
1303
1304     if(!aStates) {
1305       if(MYDEBUG)
1306         cout<<"Valiables list empty!!!"<<endl;
1307       aCommandIndex++;
1308       continue;
1309     }
1310
1311     TState aVariables = aStates->GetCurrectState();
1312
1313     if(MYDEBUG) {
1314       cout<<"Variables from SObject:"<<endl;
1315       for (int i = 0; i < aVariables.size();i++)
1316         cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
1317     }
1318
1319     //Calculate total number of parameters
1320     Standard_Integer aTotalNbParams = 1;
1321     while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
1322       aTotalNbParams++;
1323
1324     if(MYDEBUG)
1325       cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
1326
1327     Standard_Integer aFirstParam = aNbEntries;
1328
1329     //Replace parameters by variables
1330     Standard_Integer aStartPos = 0;
1331     Standard_Integer aEndPos = 0;
1332     int iVar = 0;
1333     TCollection_AsciiString aVar, aReplacedVar;
1334     for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
1335       //Replace first parameter (bettwen '(' character and first ',' character)
1336       if(i == aFirstParam)
1337       {
1338         aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
1339         if(aTotalNbParams - aNbEntries > 0 )
1340           aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
1341         else
1342           aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
1343       }
1344       //Replace last parameter (bettwen ',' character and ')' character)
1345       else if(i == aTotalNbParams)
1346       {
1347         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1348         aEndPos = aCommand.Location(C_BRACKET, aStartPos , aCommand.Length());
1349       }
1350       //Replace other parameters (bettwen two ',' characters)
1351       else if(i != aFirstParam && i != aTotalNbParams )
1352       {
1353         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1354         aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
1355       }
1356
1357       if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
1358         aStartPos++;
1359       if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
1360         aEndPos--;
1361       if ( aStartPos == aEndPos )
1362         continue; // PAL20889: for "[]"
1363
1364       if(MYDEBUG)
1365         cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
1366
1367       aVar = aCommand.SubString(aStartPos, aEndPos-1);
1368       aVar.RightAdjust();
1369       aVar.LeftAdjust();
1370
1371       if(MYDEBUG)
1372         cout<<"Variable: '"<< aVar <<"'"<<endl;
1373
1374       // specific case for sketcher
1375       if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
1376         Standard_Integer aNbSections = 1;
1377         while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
1378           aNbSections++;
1379         aNbSections--;
1380
1381         int aStartSectionPos = 0, aEndSectionPos = 0;
1382         TCollection_AsciiString aSection, aReplacedSection;
1383         for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
1384           aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
1385           if( aSectionIndex != aNbSections )
1386             aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
1387           else
1388             aEndSectionPos = aVar.Length();
1389
1390           aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
1391           if(MYDEBUG)
1392             cout<<"aSection: "<<aSection<<endl;
1393
1394           Standard_Integer aNbParams = 1;
1395           while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
1396             aNbParams++;
1397           aNbParams--;
1398
1399           int aStartParamPos = 0, aEndParamPos = 0;
1400           TCollection_AsciiString aParameter, aReplacedParameter;
1401           for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1402             aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1403             if( aParamIndex != aNbParams )
1404               aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1405             else
1406               aEndParamPos = aSection.Length() + 1;
1407
1408             if(MYDEBUG)
1409               cout<<"aParamIndex: "<<aParamIndex<<" aStartParamPos: " <<aStartParamPos<<" aEndParamPos: "<<aEndParamPos<<endl;
1410
1411             if ( aStartParamPos == aEndParamPos)
1412               continue;
1413
1414             aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1415             if(MYDEBUG)
1416               cout<<"aParameter: "<<aParameter<<endl;
1417
1418             if(iVar >= aVariables.size())
1419               continue;
1420
1421             aReplacedParameter = aVariables[iVar].myVariable;
1422             if(aReplacedParameter.IsEmpty()) {
1423               iVar++;
1424               continue;
1425             }
1426
1427             if(aVariables[iVar].isVariable) {
1428               aReplacedParameter.InsertBefore(1,"'");
1429               aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1430             }
1431
1432             if(MYDEBUG)
1433               cout<<"aSection before : "<<aSection<<endl;
1434             aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1435             aSection.Insert(aStartParamPos, aReplacedParameter);
1436             if(MYDEBUG)
1437               cout<<"aSection after  : "<<aSection<<endl<<endl;
1438             iVar++;
1439           }
1440           if(MYDEBUG)
1441             cout<<"aVar before : "<<aVar<<endl;
1442           aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1443           aVar.Insert(aStartSectionPos, aSection);
1444           if(MYDEBUG)
1445             cout<<"aVar after  : "<<aVar<<endl<<endl;
1446         }
1447
1448         if(MYDEBUG)
1449           cout<<"aCommand before : "<<aCommand<<endl;
1450         aCommand.Remove(aStartPos, aEndPos - aStartPos);
1451         aCommand.Insert(aStartPos, aVar);
1452         if(MYDEBUG)
1453           cout<<"aCommand after  : "<<aCommand<<endl;
1454
1455         break;
1456       } // end of specific case for sketcher
1457
1458       //If parameter is entry or 'None', skip it
1459       if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1460         continue;
1461
1462       if(iVar >= aVariables.size())
1463         continue;
1464
1465       aReplacedVar = aVariables[iVar].myVariable;
1466       if(aReplacedVar.IsEmpty()) {
1467         iVar++;
1468         continue;
1469       }
1470
1471       if(aVariables[iVar].isVariable) {
1472         aReplacedVar.InsertBefore(1,"\"");
1473         aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1474       }
1475
1476       aCommand.Remove(aStartPos, aEndPos - aStartPos);
1477       aCommand.Insert(aStartPos, aReplacedVar);
1478       iVar++;
1479     }
1480
1481     theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1482     theCommand.Insert(aStartCommandPos, aCommand);
1483
1484     aCommandIndex++;
1485
1486     aStates->IncrementState();
1487   }
1488
1489   if (MYDEBUG)
1490     cout<<"Command : "<<theCommand<<endl;
1491 }
1492
1493 //=============================================================================
1494 /*!
1495  *  ReplaceEntriesByNames: Replace object entries by their names
1496  */
1497 //=============================================================================
1498 void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
1499                             TSting2ObjDataMap&                        aEntry2ObjData,
1500                             const bool                                theIsPublished,
1501                             TColStd_SequenceOfAsciiString&            theObjListToPublish,
1502                             Standard_Integer&                         objectCounter,
1503                             Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
1504 {
1505   GEOM_Engine* engine = GEOM_Engine::GetEngine();
1506   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1507   Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
1508
1509   //Replace entries by the names
1510   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1511     allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1512   if (aLen == 0) anUpdatedScript = theScript;
1513
1514   for (Standard_Integer i = 1; i <= aLen; i+=2) {
1515     anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1516     anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1517     theObjListToPublish.Append( anEntry );
1518     
1519     TObjectData& data = aEntry2ObjData[ anEntry ];
1520     if ( data._pyName.IsEmpty() ) { // encounted for the 1st time
1521       if ( !data._name.IsEmpty() ) { // published object
1522         data._pyName = data._name;
1523         engine->healPyName( data._pyName, anEntry, aNameToEntry);
1524       }
1525       else {
1526         do {
1527           data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
1528         } while(aNameToEntry.IsBound(data._pyName));
1529       }
1530     }
1531     
1532     aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
1533     
1534     anUpdatedScript += data._pyName;
1535     aStart = aSeq->Value(i+1) + 1;
1536   }
1537   
1538   //Add final part of the script
1539   if (aLen && aSeq->Value(aLen) < aScriptLength)
1540     anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1541   
1542   theScript = anUpdatedScript;
1543 }
1544
1545 //=============================================================================
1546 /*!
1547  *  AddObjectColors: Add color to objects
1548  */
1549 //=============================================================================
1550 void AddObjectColors (int                      theDocID,
1551                       TCollection_AsciiString& theScript,
1552                       const TSting2ObjDataMap& theEntry2ObjData)
1553 {
1554   GEOM_Engine* engine = GEOM_Engine::GetEngine();
1555   Handle(TDocStd_Document) aDoc = engine->GetDocument(theDocID);
1556
1557   TSting2ObjDataMap::const_iterator anEntryToNameIt;
1558   for (anEntryToNameIt = theEntry2ObjData.begin();
1559        anEntryToNameIt!= theEntry2ObjData.end();
1560        ++anEntryToNameIt)
1561   {
1562     const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
1563     const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
1564
1565     TDF_Label L;
1566     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
1567     if ( L.IsNull() )
1568       continue;
1569
1570     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1571     if ( obj.IsNull() )
1572       continue;
1573
1574     bool anAutoColor = obj->GetAutoColor();
1575     if ( anAutoColor )
1576     {
1577       TCollection_AsciiString aCommand( "\n\t" );
1578       aCommand += aName + ".SetAutoColor(1)";
1579       theScript += aCommand.ToCString();
1580     }
1581
1582     GEOM_Object::Color aColor = obj->GetColor();
1583     if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
1584     {
1585       TCollection_AsciiString aCommand( "\n\t" );
1586       aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1587       theScript += aCommand.ToCString();
1588     }
1589
1590     Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
1591     if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
1592       TCollection_AsciiString aCommand( "\n\t" );
1593       aCommand += aName + ".SetMarkerStd(";
1594       switch (aMarkerType) {
1595       case Aspect_TOM_POINT:   aCommand += "GEOM.MT_POINT";   break;
1596       case Aspect_TOM_PLUS:    aCommand += "GEOM.MT_PLUS";    break;
1597       case Aspect_TOM_STAR:    aCommand += "GEOM.MT_STAR";    break;
1598       case Aspect_TOM_O:       aCommand += "GEOM.MT_O";       break;
1599       case Aspect_TOM_X:       aCommand += "GEOM.MT_X";       break;
1600       case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break;
1601       case Aspect_TOM_O_PLUS:  aCommand += "GEOM.MT_O_PLUS";  break;
1602       case Aspect_TOM_O_STAR:  aCommand += "GEOM.MT_O_STAR";  break;
1603       case Aspect_TOM_O_X:     aCommand += "GEOM.MT_O_X";     break;
1604       case Aspect_TOM_BALL:    aCommand += "GEOM.MT_BALL";    break;
1605       case Aspect_TOM_RING1:   aCommand += "GEOM.MT_RING1";   break;
1606       case Aspect_TOM_RING2:   aCommand += "GEOM.MT_RING2";   break;
1607       case Aspect_TOM_RING3:   aCommand += "GEOM.MT_RING3";   break;
1608       default:                 aCommand += "GEOM.MT_NONE";    break; // just for completeness, should not get here
1609       }
1610       aCommand += ", ";
1611       int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1;
1612       switch (aSize) {
1613       case  1: aCommand += "GEOM.MS_10";   break;
1614       case  2: aCommand += "GEOM.MS_15";   break;
1615       case  3: aCommand += "GEOM.MS_20";   break;
1616       case  4: aCommand += "GEOM.MS_25";   break;
1617       case  5: aCommand += "GEOM.MS_30";   break;
1618       case  6: aCommand += "GEOM.MS_35";   break;
1619       case  7: aCommand += "GEOM.MS_40";   break;
1620       case  8: aCommand += "GEOM.MS_45";   break;
1621       case  9: aCommand += "GEOM.MS_50";   break;
1622       case 10: aCommand += "GEOM.MS_55";   break;
1623       case 11: aCommand += "GEOM.MS_60";   break;
1624       case 12: aCommand += "GEOM.MS_65";   break;
1625       case 13: aCommand += "GEOM.MS_70";   break;
1626       default: aCommand += "GEOM.MS_NONE"; break;
1627       }
1628       aCommand += ")";
1629       theScript += aCommand.ToCString();
1630     }
1631     else if (aMarkerType == Aspect_TOM_USERDEFINED) {
1632       int aMarkerTextureID = obj->GetMarkerTexture();
1633       if (aMarkerTextureID >= 0) {
1634         TCollection_AsciiString aCommand( "\n\t" );
1635         aCommand += aName + ".SetMarkerTexture(texture_map[";
1636         aCommand += aMarkerTextureID;
1637         aCommand += "])";
1638         theScript += aCommand.ToCString();
1639       }
1640     }
1641   }
1642 }
1643
1644 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
1645 static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData)
1646 #else
1647 static TCollection_AsciiString pack_data (const Handle(TDataStd_HArray1OfByte)& aData)
1648 #endif
1649 {
1650   TCollection_AsciiString stream;
1651   if (!aData.IsNull()) {
1652     for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) {
1653       Standard_Byte byte = aData->Value(i);
1654       TCollection_AsciiString strByte = "";
1655       for (int j = 0; j < 8; j++)
1656         strByte.Prepend((byte & (1<<j)) ? "1" : "0");
1657       stream += strByte;
1658     }
1659   }
1660   return stream;
1661 }
1662
1663 void AddTextures (int theDocID, TCollection_AsciiString& theScript)
1664 {
1665   GEOM_Engine* engine = GEOM_Engine::GetEngine();
1666   std::list<int> allTextures = engine->getAllTextures(theDocID);
1667   std::list<int>::const_iterator it;
1668
1669   if (allTextures.size() > 0) {
1670     theScript += "\n\ttexture_map = {}\n";
1671
1672     for (it = allTextures.begin(); it != allTextures.end(); ++it) {
1673       if (*it <= 0) continue;
1674       Standard_Integer aWidth, aHeight;
1675       TCollection_AsciiString aFileName;
1676 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
1677       Handle(TColStd_HArray1OfByte) aTexture =
1678 #else
1679       Handle(TDataStd_HArray1OfByte) aTexture =
1680 #endif
1681         engine->getTexture(theDocID, *it, aWidth, aHeight, aFileName);
1682       if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
1683         TCollection_AsciiString aCommand = "\n\t";
1684         aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
1685         if (aFileName != "" ) {
1686           aCommand += "geompy.LoadTexture(\"";
1687           aCommand += aFileName.ToCString();
1688           aCommand += "\")";
1689         }
1690         else {
1691           aCommand += "geompy.AddTexture(";
1692           aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \"";
1693           aCommand += pack_data(aTexture);
1694           aCommand += "\")";
1695         }
1696         theScript += aCommand;
1697       }
1698     }
1699     theScript += "\n";
1700   }
1701 }
1702
1703 //=============================================================================
1704 /*!
1705  *  PublishObject: publish object in study script
1706  */
1707 //=============================================================================
1708 void PublishObject (TObjectData&                              theObjectData,
1709                     TSting2ObjDataMap&                        theEntry2ObjData,
1710                     const TSting2ObjDataPtrMap&               theStEntry2ObjDataPtr,
1711                     Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
1712                     std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
1713                     std::set< TCollection_AsciiString>&       theIgnoreMap)
1714 {
1715   GEOM_Engine* engine = GEOM_Engine::GetEngine();
1716   if ( theObjectData._studyEntry.IsEmpty() )
1717     return; // was not published
1718   if ( theIgnoreMap.count( theObjectData._entry ) )
1719     return; // not to publish
1720
1721   TCollection_AsciiString aCommand("\n\tgeompy.");
1722
1723   // find a father entry
1724   TObjectData* aFatherData = 0;
1725   TCollection_AsciiString aFatherStudyEntry =
1726     theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
1727   TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
1728     theStEntry2ObjDataPtr.find( aFatherStudyEntry );
1729   if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
1730     aFatherData = stEntry2DataPtr->second;
1731
1732   const int geomObjDepth = 3;
1733
1734   // treat multiply published object
1735   if ( theObjectData._pyName.IsEmpty() )
1736   {
1737     TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
1738     if ( data0._pyName.IsEmpty() ) return; // something wrong
1739
1740     theObjectData._pyName = theObjectData._name;
1741     engine->healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
1742
1743     TCollection_AsciiString aCreationCommand("\n\t");
1744     aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
1745
1746     // store aCreationCommand before publishing commands
1747     int tag = theObjectData._entry.Token( ":", geomObjDepth ).IntegerValue();
1748     theEntryToCmdMap.insert( std::make_pair( tag + 2*theEntry2ObjData.size(), aCreationCommand ));
1749   }
1750
1751   // make a command
1752   if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
1753     aCommand += "addToStudyInFather( ";
1754     aCommand += aFatherData->_pyName + ", ";
1755   }
1756   else {
1757     aCommand += "addToStudy( ";
1758   }
1759   aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
1760
1761   // bind a command to the study entry
1762   int tag = theObjectData._entry.Token( ":", geomObjDepth ).IntegerValue();
1763   theEntryToCmdMap.insert( std::make_pair( tag, aCommand ));
1764
1765   theObjectData._studyEntry.Clear(); // not to publish any more
1766 }
1767
1768 //================================================================================
1769 /*!
1770  * \brief Constructor
1771  */
1772 //================================================================================
1773 ObjectStates::ObjectStates()
1774 {
1775   _dumpstate = 0;
1776 }
1777
1778 //================================================================================
1779 /*!
1780  * \brief Destructor
1781  */
1782 //================================================================================
1783 ObjectStates::~ObjectStates()
1784 {
1785 }
1786
1787 //================================================================================
1788 /*!
1789  * \brief Return current object state
1790  * \retval state - Object state (vector of notebook variable)
1791  */
1792 //================================================================================
1793 TState ObjectStates::GetCurrectState() const
1794 {
1795   if(_states.size() > _dumpstate)
1796     return _states[_dumpstate];
1797   return TState();
1798 }
1799
1800 //================================================================================
1801 /*!
1802  * \brief Add new object state
1803  * \param theState - Object state (vector of notebook variable)
1804  */
1805 //================================================================================
1806 void ObjectStates::AddState(const TState &theState)
1807 {
1808   _states.push_back(theState);
1809 }
1810
1811 //================================================================================
1812 /*!
1813  * \brief Increment object state
1814  */
1815 //================================================================================
1816 void ObjectStates::IncrementState()
1817 {
1818   _dumpstate++;
1819 }