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