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