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