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