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