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