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