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