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