]> SALOME platform Git repositories - modules/geom.git/blob - src/GEOM/GEOM_Engine.cxx
Salome HOME
in python dump, publish objects in the same order as in the internal CAF document
[modules/geom.git] / src / GEOM / GEOM_Engine.cxx
1 //  Copyright (C) 2007-2010  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   else
588     aScript += "theStudy = salome.myStudy";
589   aScript += "\n\tgeompy.init_geom(theStudy)\n";
590
591   AddTextures(theDocID, aScript);
592
593   Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
594
595   // a map containing copies of TObjectData from theObjectData
596   TSting2ObjDataMap    aEntry2ObjData;
597   // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
598   // occures when several StudyEntries correspond to one Entry
599   TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
600
601   //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
602   for (unsigned i = 0; i < theObjectData.size(); ++i )
603   {
604     TObjectData& data = theObjectData[i];
605     // look for an object by entry
606     TDF_Label L;
607     TDF_Tool::Label( aDoc->GetData(), data._entry, L );
608     if ( L.IsNull() ) continue;
609     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
610     // fill maps
611     if ( !obj.IsNull() ) {
612       TSting2ObjDataMap::iterator ent2Data =
613         aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
614
615       if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
616         aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
617       else
618         aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
619     }
620   }
621
622   // collect objects entries to be published
623   TColStd_SequenceOfAsciiString aObjListToPublish;
624
625   // iterates on functions till critical (that requiers publication of objects)
626   Handle(TDataStd_TreeNode) aNode, aRoot;
627   Handle(GEOM_Function) aFunction;
628   TDF_LabelMap aCheckedFuncMap;
629   std::set< TCollection_AsciiString > anIgnoreObjMap;
630
631   TCollection_AsciiString aFuncScript;
632
633   // Mantis issue 0020768
634   Standard_Integer objectCounter = 0;
635   Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
636
637   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
638     TDataStd_ChildNodeIterator Itr(aRoot);
639     for (; Itr.More(); Itr.Next()) {
640       aNode = Itr.Value();
641       aFunction = GEOM_Function::GetFunction(aNode->Label());
642       if (aFunction.IsNull()) {
643         MESSAGE ( "Null function !!!!" );
644         continue;
645       }
646       bool isDumpCollected = false;
647       TCollection_AsciiString aCurScript, anAfterScript;
648       if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
649                            isPublished, aCheckedFuncMap, anIgnoreObjMap,
650                            isDumpCollected ))
651         continue;
652       // add function description before dump
653       if (!aCurScript.IsEmpty())
654         aFuncScript += aCurScript;
655       if (isDumpCollected ) {
656         // Replace entries by the names
657         ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
658                                aObjListToPublish, objectCounter, aNameToEntry );
659
660         // publish collected objects
661         std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry
662         int i = 1, n = aObjListToPublish.Length();
663         for ( ; i <= n; i++ )
664         {
665           const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
666           PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
667                          aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
668         }
669         // add publishing commands to the script
670         std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
671         for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
672           aFuncScript += anEntryToCmd->second;
673
674         // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
675         //  because they will be published during command execution
676         int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
677         if ( indx == -1 )
678           indx = anAfterScript.Search( "RestoreSubShapes" );
679         if ( indx != -1 ) {
680           TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
681           Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
682           i = 1, n = aSeq->Length();
683           for ( ; i <= n; i+=2) {
684             TCollection_AsciiString anEntry =
685               aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
686             anIgnoreObjMap.insert(anEntry.ToCString());
687           }
688         }
689
690         aObjListToPublish.Clear();
691         aScript += aFuncScript;
692         aFuncScript.Clear();
693       }
694       aFuncScript += anAfterScript;
695     }
696   }
697
698   // Replace entries by the names
699   aObjListToPublish.Clear();
700   ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
701                          objectCounter, aNameToEntry );
702
703   aScript += aFuncScript;
704
705   // ouv : NPAL12872
706   AddObjectColors( theDocID, aScript, aEntry2ObjData );
707
708   // Make script to publish in study
709   TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
710   if ( isPublished )
711   {
712     std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry
713
714     for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
715          aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
716          ++aStEntry2ObjDataPtrIt)
717     {
718       TObjectData* data = aStEntry2ObjDataPtrIt->second;
719       if ( anIgnoreObjMap.count( data->_entry ))
720         continue; // should not be dumped
721       PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
722                      aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
723     }
724     // add publishing commands to the script
725     std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
726     for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
727       aScript += anEntryToCmd->second;
728   }
729
730   //aScript += "\n\tpass\n";
731   aScript += "\n";
732   aValidScript = true;
733
734   // fill _studyEntry2NameMap and build globalVars
735   TCollection_AsciiString globalVars;
736   _studyEntry2NameMap.Clear();
737   for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
738        aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
739        ++aStEntry2ObjDataPtrIt)
740   {
741     const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
742     const TObjectData*                   data = aStEntry2ObjDataPtrIt->second;
743     _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
744     if ( !globalVars.IsEmpty() )
745       globalVars += ", ";
746     globalVars += data->_pyName;
747   }
748   if ( isMultiFile && !globalVars.IsEmpty() ) {
749     globalVars.Insert( 1, "\n\tglobal " );
750     aScript.Insert( posToInsertGlobalVars, globalVars );
751   }
752
753   return aScript;
754 }
755
756 //=======================================================================
757 //function : GetDumpName
758 //purpose  :
759 //=======================================================================
760
761 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
762 {
763   if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
764     return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
765
766   return NULL;
767 }
768
769 //=======================================================================
770 //function : GetAllDumpNames
771 //purpose  :
772 //=======================================================================
773
774 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
775 {
776   Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
777
778   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
779   for (; it.More(); it.Next()) {
780     aRetSeq->Append(it.Value());
781   }
782
783   return aRetSeq;
784 }
785
786 #define TEXTURE_LABEL_ID       1
787 #define TEXTURE_LABEL_FILE     2
788 #define TEXTURE_LABEL_WIDTH    3
789 #define TEXTURE_LABEL_HEIGHT   4
790 #define TEXTURE_LABEL_DATA     5
791
792 int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight,
793                             const Handle(TDataStd_HArray1OfByte)& theTexture,
794                             const TCollection_AsciiString& theFileName)
795 {
796   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
797   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
798
799   // NPAL18604: use existing label to decrease memory usage,
800   //            if this label has been freed (object deleted)
801   bool useExisting = false;
802   TDF_Label aChild;
803   if (_freeLabels.find(theDocID) != _freeLabels.end()) {
804     std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
805     if (!aFreeLabels.empty()) {
806       useExisting = true;
807       aChild = aFreeLabels.front();
808       aFreeLabels.pop_front();
809     }
810   }
811   if (!useExisting) {
812     // create new label
813     aChild = TDF_TagSource::NewChild(aDoc->Main());
814   }
815
816   aChild.ForgetAllAttributes(Standard_True);
817   Handle(TDataStd_TreeNode) node;
818   if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) )
819     node = TDataStd_TreeNode::Set(aChild);
820   TDataStd_UAttribute::Set(aChild, GetTextureGUID());
821
822   static int aTextureID = 0;
823
824   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID),     ++aTextureID);
825   TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE),   theFileName);
826   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH),  theWidth);
827   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
828
829   Handle(TDataStd_ByteArray) anAttr =
830     TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
831                             theTexture.IsNull() ? 0 : theTexture->Lower(),
832                             theTexture.IsNull() ? 0 : theTexture->Upper());
833   anAttr->ChangeArray(theTexture);
834
835   return aTextureID;
836 }
837
838 Handle(TDataStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
839                                                        int& theWidth, int& theHeight,
840                                                        TCollection_AsciiString& theFileName)
841 {
842   Handle(TDataStd_HArray1OfByte) anArray;
843   theWidth = theHeight = 0;
844
845   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
846
847   TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
848   bool found = false;
849   for (; anIterator.More() && !found; anIterator.Next()) {
850     TDF_Label aTextureLabel = anIterator.Value();
851     if (aTextureLabel.IsAttribute( GetTextureGUID())) {
852       TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
853       Handle(TDataStd_Integer) anIdAttr;
854       if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) &&
855          anIdAttr->Get() == theTextureID) {
856         TDF_Label aFileLabel   = aTextureLabel.FindChild(TEXTURE_LABEL_FILE,    Standard_False);
857         TDF_Label aWidthLabel  = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH,   Standard_False);
858         TDF_Label aHeightLabel = aTextureLabel.FindChild(TEXTURE_LABEL_HEIGHT,  Standard_False);
859         TDF_Label aDataLabel   = aTextureLabel.FindChild(TEXTURE_LABEL_DATA,    Standard_False);
860         Handle(TDataStd_Integer) aWidthAttr, aHeightAttr;
861         Handle(TDataStd_ByteArray) aTextureAttr;
862         Handle(TDataStd_Comment) aFileAttr;
863         if (!aWidthLabel.IsNull()  && aWidthLabel.FindAttribute(TDataStd_Integer::GetID(),  aWidthAttr) &&
864             !aHeightLabel.IsNull() && aHeightLabel.FindAttribute(TDataStd_Integer::GetID(), aHeightAttr) &&
865             !aDataLabel.IsNull()   && aDataLabel.FindAttribute(TDataStd_ByteArray::GetID(), aTextureAttr)) {
866           theWidth = aWidthAttr->Get();
867           theHeight = aHeightAttr->Get();
868           anArray = aTextureAttr->InternalArray();
869         }
870         if (!aFileLabel.IsNull() && aFileLabel.FindAttribute(TDataStd_Comment::GetID(), aFileAttr))
871           theFileName = aFileAttr->Get();
872         found = true;
873       }
874     }
875   }
876   return anArray;
877 }
878
879 std::list<int> GEOM_Engine::getAllTextures(int theDocID)
880 {
881   std::list<int> id_list;
882
883   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
884
885   TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
886   for (; anIterator.More(); anIterator.Next()) {
887     TDF_Label aTextureLabel = anIterator.Value();
888     if (aTextureLabel.IsAttribute( GetTextureGUID())) {
889       TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
890       Handle(TDataStd_Integer) anIdAttr;
891       if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr))
892         id_list.push_back((int)anIdAttr->Get());
893     }
894   }
895   return id_list;
896 }
897
898 //===========================================================================
899 //                     Internal functions
900 //===========================================================================
901
902 //=============================================================================
903 /*!
904  *  ProcessFunction: Dump fucntion description into script
905  */
906 //=============================================================================
907 bool ProcessFunction(Handle(GEOM_Function)&             theFunction,
908                      TCollection_AsciiString&           theScript,
909                      TCollection_AsciiString&           theAfterScript,
910                      const TVariablesList&              theVariables,
911                      const bool                         theIsPublished,
912                      TDF_LabelMap&                      theProcessed,
913                      std::set<TCollection_AsciiString>& theIgnoreObjs,
914                      bool&                              theIsDumpCollected)
915 {
916   theIsDumpCollected = false;
917   if (theFunction.IsNull()) return false;
918
919   if (theProcessed.Contains(theFunction->GetEntry())) return false;
920
921   // pass functions, that depends on nonexisting ones
922   bool doNotProcess = false;
923   TDF_LabelSequence aSeq;
924   theFunction->GetDependency(aSeq);
925   Standard_Integer aLen = aSeq.Length();
926   for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
927     TDF_Label aRefLabel = aSeq.Value(i);
928     Handle(TDF_Reference) aRef;
929     if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
930       doNotProcess = true;
931     }
932     else {
933       if (aRef.IsNull() || aRef->Get().IsNull()) {
934         doNotProcess = true;
935       }
936       else {
937         Handle(TDataStd_TreeNode) aT;
938         if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
939           doNotProcess = true;
940         }
941         else {
942           TDF_Label aDepLabel = aT->Label();
943           Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
944
945           if (aFunction.IsNull()) doNotProcess = true;
946           else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
947         }
948       }
949     }
950   }
951
952   if (doNotProcess) {
953     TCollection_AsciiString anObjEntry;
954     TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
955     theIgnoreObjs.insert(anObjEntry);
956     return false;
957   }
958   theProcessed.Add(theFunction->GetEntry());
959
960   TCollection_AsciiString aDescr = theFunction->GetDescription();
961   if(aDescr.Length() == 0) return false;
962
963   //Check if its internal function which doesn't requires dumping
964   if(aDescr == "None") return false;
965
966   // 0020001 PTv, check for critical functions, which require dump of objects
967   if (theIsPublished)
968   {
969     // currently, there is only one function "RestoreGivenSubShapes",
970     // later this check could be replaced by iterations on list of such functions
971     if (aDescr.Search( "RestoreGivenSubShapes" ) != -1)
972       theIsDumpCollected = true;
973     else if (aDescr.Search( "RestoreSubShapes" ) != -1)
974       theIsDumpCollected = true;
975   }
976
977   //Replace parameter by notebook variables
978   ReplaceVariables(aDescr,theVariables);
979   if ( theIsDumpCollected ) {
980     int i = 1;
981     bool isBefore = true;
982     TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
983     while (!aSubStr.IsEmpty()) {
984       if (isBefore &&
985           aSubStr.Search( "RestoreGivenSubShapes" ) == -1 &&
986           aSubStr.Search( "RestoreSubShapes" ) == -1)
987         theScript += TCollection_AsciiString("\n\t") + aSubStr;
988       else
989         theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
990       aSubStr = aDescr.Token("\n\t", i++);
991     }
992   }
993   else {
994     theScript += "\n\t";
995     theScript += aDescr;
996   }
997   return true;
998 }
999
1000 //=============================================================================
1001 /*!
1002  *  FindEntries: Returns a sequence of start/end positions of entries in the string
1003  */
1004 //=============================================================================
1005 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
1006 {
1007   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1008   Standard_Integer aLen = theString.Length();
1009   Standard_Boolean isFound = Standard_False;
1010
1011   const char* arr = theString.ToCString();
1012   Standard_Integer i = 0, j;
1013
1014   while(i < aLen) {
1015     int c = (int)arr[i];
1016     j = i+1;
1017     if(c >= 48 && c <= 57) { //Is digit?
1018
1019       isFound = Standard_False;
1020       while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
1021         c = (int)arr[j++];
1022         if(c == 58) isFound = Standard_True;
1023       }
1024
1025       if(isFound && arr[j-2] != 58) { // last char should be a diggit
1026         aSeq->Append(i+1); // +1 because AsciiString starts from 1
1027         aSeq->Append(j-1);
1028       }
1029     }
1030
1031     i = j;
1032   }
1033
1034   return aSeq;
1035 }
1036
1037 //=============================================================================
1038 /*!
1039  *  ReplaceVariables: Replace parameters of the function by variales from
1040  *                    Notebook if need
1041  */
1042 //=============================================================================
1043 void ReplaceVariables(TCollection_AsciiString& theCommand,
1044                       const TVariablesList&    theVariables)
1045 {
1046   if (MYDEBUG)
1047     cout<<"Command : "<<theCommand<<endl;
1048
1049   if (MYDEBUG) {
1050     cout<<"All Entries:"<<endl;
1051     TVariablesList::const_iterator it = theVariables.begin();
1052     for(;it != theVariables.end();it++)
1053       cout<<"\t'"<<(*it).first<<"'"<<endl;
1054   }
1055
1056   //Additional case - multi-row commands
1057   int aCommandIndex = 1;
1058   while( aCommandIndex < 10 ) { // tmp check
1059     TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
1060     if( aCommand.Length() == 0 )
1061       break;
1062
1063     if (MYDEBUG)
1064       cout<<"Sub-command : "<<aCommand<<endl;
1065
1066     Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
1067     Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
1068
1069     //Get Entry of the result object
1070     TCollection_AsciiString anEntry;
1071     if( aCommand.Search("=") != -1 ) // command returns an object
1072       anEntry = aCommand.Token("=",1);
1073     else { // command modifies the object
1074       if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
1075         if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
1076           anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
1077     }
1078     //Remove white spaces
1079     anEntry.RightAdjust();
1080     anEntry.LeftAdjust();
1081     if(MYDEBUG)
1082       cout<<"Result entry : '" <<anEntry<<"'"<<endl;
1083
1084     if ( anEntry.IsEmpty() ) {
1085       aCommandIndex++;
1086       continue;
1087     }
1088
1089     //Check if result is list of entries - enough to get the first entry in this case
1090     int aNbEntries = 1;
1091     if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
1092       while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
1093         aNbEntries++;
1094       TCollection_AsciiString aSeparator(COMMA);
1095       anEntry = anEntry.Token(aSeparator.ToCString(),1);
1096       anEntry.Remove( 1, 1 );
1097       anEntry.RightAdjust();
1098       anEntry.LeftAdjust();
1099       if(MYDEBUG)
1100         cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
1101     }
1102
1103     //Find variables used for object construction
1104     ObjectStates* aStates = 0;
1105     TVariablesList::const_iterator it = theVariables.find(anEntry);
1106     if( it != theVariables.end() )
1107       aStates = (*it).second;
1108
1109     if(!aStates) {
1110       if(MYDEBUG)
1111         cout<<"Valiables list empty!!!"<<endl;
1112       aCommandIndex++;
1113       continue;
1114     }
1115
1116     TState aVariables = aStates->GetCurrectState();
1117
1118     if(MYDEBUG) {
1119       cout<<"Variables from SObject:"<<endl;
1120       for (int i = 0; i < aVariables.size();i++)
1121         cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
1122     }
1123
1124     //Calculate total number of parameters
1125     Standard_Integer aTotalNbParams = 1;
1126     while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
1127       aTotalNbParams++;
1128
1129     if(MYDEBUG)
1130       cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
1131
1132     Standard_Integer aFirstParam = aNbEntries;
1133
1134     //Replace parameters by variables
1135     Standard_Integer aStartPos = 0;
1136     Standard_Integer aEndPos = 0;
1137     int iVar = 0;
1138     TCollection_AsciiString aVar, aReplacedVar;
1139     for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
1140       //Replace first parameter (bettwen '(' character and first ',' character)
1141       if(i == aFirstParam)
1142       {
1143         aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
1144         if(aTotalNbParams - aNbEntries > 0 )
1145           aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
1146         else
1147           aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
1148       }
1149       //Replace last parameter (bettwen ',' character and ')' character)
1150       else if(i == aTotalNbParams)
1151       {
1152         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1153         aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
1154       }
1155       //Replace other parameters (bettwen two ',' characters)
1156       else if(i != aFirstParam && i != aTotalNbParams )
1157       {
1158         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1159         aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
1160       }
1161
1162       if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
1163         aStartPos++;
1164       if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
1165         aEndPos--;
1166       if ( aStartPos == aEndPos )
1167         continue; // PAL20889: for "[]"
1168
1169       if(MYDEBUG)
1170         cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
1171
1172       aVar = aCommand.SubString(aStartPos, aEndPos-1);
1173       aVar.RightAdjust();
1174       aVar.LeftAdjust();
1175
1176       if(MYDEBUG)
1177         cout<<"Variable: '"<< aVar <<"'"<<endl;
1178
1179       // specific case for sketcher
1180       if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
1181         Standard_Integer aNbSections = 1;
1182         while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
1183           aNbSections++;
1184         aNbSections--;
1185
1186         int aStartSectionPos = 0, aEndSectionPos = 0;
1187         TCollection_AsciiString aSection, aReplacedSection;
1188         for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
1189           aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
1190           if( aSectionIndex != aNbSections )
1191             aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
1192           else
1193             aEndSectionPos = aVar.Length();
1194
1195           aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
1196           if(MYDEBUG)
1197             cout<<"aSection: "<<aSection<<endl;
1198
1199           Standard_Integer aNbParams = 1;
1200           while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
1201             aNbParams++;
1202           aNbParams--;
1203
1204           int aStartParamPos = 0, aEndParamPos = 0;
1205           TCollection_AsciiString aParameter, aReplacedParameter;
1206           for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1207             aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1208             if( aParamIndex != aNbParams )
1209               aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1210             else
1211               aEndParamPos = aSection.Length() + 1;
1212
1213             aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1214             if(MYDEBUG)
1215               cout<<"aParameter: "<<aParameter<<endl;
1216
1217             if(iVar >= aVariables.size())
1218               continue;
1219
1220             aReplacedParameter = aVariables[iVar].myVariable;
1221             if(aReplacedParameter.IsEmpty()) {
1222               iVar++;
1223               continue;
1224             }
1225
1226             if(aVariables[iVar].isVariable) {
1227               aReplacedParameter.InsertBefore(1,"'");
1228               aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1229             }
1230
1231             if(MYDEBUG)
1232               cout<<"aSection before : "<<aSection<<endl;
1233             aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1234             aSection.Insert(aStartParamPos, aReplacedParameter);
1235             if(MYDEBUG)
1236               cout<<"aSection after  : "<<aSection<<endl<<endl;
1237             iVar++;
1238           }
1239           if(MYDEBUG)
1240             cout<<"aVar before : "<<aVar<<endl;
1241           aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1242           aVar.Insert(aStartSectionPos, aSection);
1243           if(MYDEBUG)
1244             cout<<"aVar after  : "<<aVar<<endl<<endl;
1245         }
1246
1247         if(MYDEBUG)
1248           cout<<"aCommand before : "<<aCommand<<endl;
1249         aCommand.Remove(aStartPos, aEndPos - aStartPos);
1250         aCommand.Insert(aStartPos, aVar);
1251         if(MYDEBUG)
1252           cout<<"aCommand after  : "<<aCommand<<endl;
1253
1254         break;
1255       } // end of specific case for sketcher
1256
1257       //If parameter is entry or 'None', skip it
1258       if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1259         continue;
1260
1261       if(iVar >= aVariables.size())
1262         continue;
1263
1264       aReplacedVar = aVariables[iVar].myVariable;
1265       if(aReplacedVar.IsEmpty()) {
1266         iVar++;
1267         continue;
1268       }
1269
1270       if(aVariables[iVar].isVariable) {
1271         aReplacedVar.InsertBefore(1,"\"");
1272         aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1273       }
1274
1275       aCommand.Remove(aStartPos, aEndPos - aStartPos);
1276       aCommand.Insert(aStartPos, aReplacedVar);
1277       iVar++;
1278     }
1279
1280     theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1281     theCommand.Insert(aStartCommandPos, aCommand);
1282
1283     aCommandIndex++;
1284
1285     aStates->IncrementState();
1286   }
1287
1288   if (MYDEBUG)
1289     cout<<"Command : "<<theCommand<<endl;
1290 }
1291
1292 //=============================================================================
1293 /*!
1294  *  ReplaceEntriesByNames: Replace object entries by their names
1295  */
1296 //=============================================================================
1297 void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
1298                             TSting2ObjDataMap&                        aEntry2ObjData,
1299                             const bool                                theIsPublished,
1300                             TColStd_SequenceOfAsciiString&            theObjListToPublish,
1301                             Standard_Integer&                         objectCounter,
1302                             Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
1303 {
1304   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1305   Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
1306
1307   //Replace entries by the names
1308   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1309     allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1310   if (aLen == 0) anUpdatedScript = theScript;
1311
1312   for (Standard_Integer i = 1; i <= aLen; i+=2) {
1313     anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1314     anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1315     theObjListToPublish.Append( anEntry );
1316     
1317     TObjectData& data = aEntry2ObjData[ anEntry ];
1318     if ( data._pyName.IsEmpty() ) { // encounted for the 1st time
1319       if ( !data._name.IsEmpty() ) { // published object
1320         data._pyName = data._name;
1321         healPyName( data._pyName, anEntry, aNameToEntry);
1322       }
1323       else {
1324         do {
1325           data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
1326         } while(aNameToEntry.IsBound(data._pyName));
1327       }
1328     }
1329     
1330     aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
1331     
1332     anUpdatedScript += data._pyName;
1333     aStart = aSeq->Value(i+1) + 1;
1334   }
1335   
1336   //Add final part of the script
1337   if (aLen && aSeq->Value(aLen) < aScriptLength)
1338     anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1339   
1340   theScript = anUpdatedScript;
1341 }
1342
1343 //=============================================================================
1344 /*!
1345  *  AddObjectColors: Add color to objects
1346  */
1347 //=============================================================================
1348 void AddObjectColors (int                      theDocID,
1349                       TCollection_AsciiString& theScript,
1350                       const TSting2ObjDataMap& theEntry2ObjData)
1351 {
1352   GEOM_Engine* engine = GEOM_Engine::GetEngine();
1353   Handle(TDocStd_Document) aDoc = engine->GetDocument(theDocID);
1354
1355   TSting2ObjDataMap::const_iterator anEntryToNameIt;
1356   for (anEntryToNameIt = theEntry2ObjData.begin();
1357        anEntryToNameIt!= theEntry2ObjData.end();
1358        ++anEntryToNameIt)
1359   {
1360     const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
1361     const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
1362
1363     TDF_Label L;
1364     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
1365     if ( L.IsNull() )
1366       continue;
1367
1368     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1369     if ( obj.IsNull() )
1370       continue;
1371
1372     bool anAutoColor = obj->GetAutoColor();
1373     if ( anAutoColor )
1374     {
1375       TCollection_AsciiString aCommand( "\n\t" );
1376       aCommand += aName + ".SetAutoColor(1)";
1377       theScript += aCommand.ToCString();
1378     }
1379
1380     GEOM_Object::Color aColor = obj->GetColor();
1381     if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
1382     {
1383       TCollection_AsciiString aCommand( "\n\t" );
1384       aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1385       theScript += aCommand.ToCString();
1386     }
1387
1388     Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
1389     if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
1390       TCollection_AsciiString aCommand( "\n\t" );
1391       aCommand += aName + ".SetMarkerStd(";
1392       switch (aMarkerType) {
1393       case Aspect_TOM_POINT:   aCommand += "GEOM.MT_POINT";   break;
1394       case Aspect_TOM_PLUS:    aCommand += "GEOM.MT_PLUS";    break;
1395       case Aspect_TOM_STAR:    aCommand += "GEOM.MT_STAR";    break;
1396       case Aspect_TOM_O:       aCommand += "GEOM.MT_O";       break;
1397       case Aspect_TOM_X:       aCommand += "GEOM.MT_X";       break;
1398       case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break;
1399       case Aspect_TOM_O_PLUS:  aCommand += "GEOM.MT_O_PLUS";  break;
1400       case Aspect_TOM_O_STAR:  aCommand += "GEOM.MT_O_STAR";  break;
1401       case Aspect_TOM_O_X:     aCommand += "GEOM.MT_O_X";     break;
1402       case Aspect_TOM_BALL:    aCommand += "GEOM.MT_BALL";    break;
1403       case Aspect_TOM_RING1:   aCommand += "GEOM.MT_RING1";   break;
1404       case Aspect_TOM_RING2:   aCommand += "GEOM.MT_RING2";   break;
1405       case Aspect_TOM_RING3:   aCommand += "GEOM.MT_RING3";   break;
1406       default:                 aCommand += "GEOM.MT_NONE";    break; // just for completeness, should not get here
1407       }
1408       aCommand += ", ";
1409       int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1;
1410       switch (aSize) {
1411       case  1: aCommand += "GEOM.MS_10";   break;
1412       case  2: aCommand += "GEOM.MS_15";   break;
1413       case  3: aCommand += "GEOM.MS_20";   break;
1414       case  4: aCommand += "GEOM.MS_25";   break;
1415       case  5: aCommand += "GEOM.MS_30";   break;
1416       case  6: aCommand += "GEOM.MS_35";   break;
1417       case  7: aCommand += "GEOM.MS_40";   break;
1418       case  8: aCommand += "GEOM.MS_45";   break;
1419       case  9: aCommand += "GEOM.MS_50";   break;
1420       case 10: aCommand += "GEOM.MS_55";   break;
1421       case 11: aCommand += "GEOM.MS_60";   break;
1422       case 12: aCommand += "GEOM.MS_65";   break;
1423       case 13: aCommand += "GEOM.MS_70";   break;
1424       default: aCommand += "GEOM.MS_NONE"; break;
1425       }
1426       aCommand += ")";
1427       theScript += aCommand.ToCString();
1428     }
1429     else if (aMarkerType == Aspect_TOM_USERDEFINED) {
1430       int aMarkerTextureID = obj->GetMarkerTexture();
1431       if (aMarkerTextureID >= 0) {
1432         TCollection_AsciiString aCommand( "\n\t" );
1433         aCommand += aName + ".SetMarkerTexture(texture_map[";
1434         aCommand += aMarkerTextureID;
1435         aCommand += "])";
1436         theScript += aCommand.ToCString();
1437       }
1438     }
1439   }
1440 }
1441
1442 static TCollection_AsciiString pack_data(const Handle(TDataStd_HArray1OfByte)& aData )
1443 {
1444   TCollection_AsciiString stream;
1445   if (!aData.IsNull()) {
1446     for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) {
1447       Standard_Byte byte = aData->Value(i);
1448       TCollection_AsciiString strByte = "";
1449       for (int j = 0; j < 8; j++)
1450         strByte.Prepend((byte & (1<<j)) ? "1" : "0");
1451       stream += strByte;
1452     }
1453   }
1454   return stream;
1455 }
1456
1457 void AddTextures (int theDocID, TCollection_AsciiString& theScript)
1458 {
1459   GEOM_Engine* engine = GEOM_Engine::GetEngine();
1460   std::list<int> allTextures = engine->getAllTextures(theDocID);
1461   std::list<int>::const_iterator it;
1462
1463   if (allTextures.size() > 0) {
1464     theScript += "\n\ttexture_map = {}\n";
1465
1466     for (it = allTextures.begin(); it != allTextures.end(); ++it) {
1467       if (*it <= 0) continue;
1468       Standard_Integer aWidth, aHeight;
1469       TCollection_AsciiString aFileName;
1470       Handle(TDataStd_HArray1OfByte) aTexture = engine->getTexture(theDocID, *it, aWidth, aHeight, aFileName);
1471       if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
1472         TCollection_AsciiString aCommand = "\n\t";
1473         aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
1474         if (aFileName != "" ) {
1475           aCommand += "geompy.LoadTexture(\"";
1476           aCommand += aFileName.ToCString();
1477           aCommand += "\")";
1478         }
1479         else {
1480           aCommand += "geompy.AddTexture(";
1481           aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \"";
1482           aCommand += pack_data(aTexture);
1483           aCommand += "\")";
1484         }
1485         theScript += aCommand;
1486       }
1487     }
1488     theScript += "\n";
1489   }
1490 }
1491
1492 //=============================================================================
1493 /*!
1494  *  PublishObject: publish object in study script
1495  */
1496 //=============================================================================
1497 void PublishObject (TObjectData&                              theObjectData,
1498                     TSting2ObjDataMap&                        theEntry2ObjData,
1499                     const TSting2ObjDataPtrMap&               theStEntry2ObjDataPtr,
1500                     Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
1501                     std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
1502                     std::set< TCollection_AsciiString>&       theIgnoreMap)
1503 {
1504   if ( theObjectData._studyEntry.IsEmpty() )
1505     return; // was not published
1506   if ( theIgnoreMap.count( theObjectData._entry ) )
1507     return; // not to publish
1508
1509   TCollection_AsciiString aCommand("\n\tgeompy.");
1510
1511   // find a father entry
1512   TObjectData* aFatherData = 0;
1513   TCollection_AsciiString aFatherStudyEntry =
1514     theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
1515   TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
1516     theStEntry2ObjDataPtr.find( aFatherStudyEntry );
1517   if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
1518     aFatherData = stEntry2DataPtr->second;
1519
1520   const int geomObjDepth = 3;
1521
1522   // treat multiply published object
1523   if ( theObjectData._pyName.IsEmpty() )
1524   {
1525     TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
1526     if ( data0._pyName.IsEmpty() ) return; // something wrong
1527
1528     theObjectData._pyName = theObjectData._name;
1529     healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
1530
1531     TCollection_AsciiString aCreationCommand("\n\t");
1532     aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
1533
1534     // store aCreationCommand before publishing commands
1535     int tag = theObjectData._entry.Token( ":", geomObjDepth ).IntegerValue();
1536     theEntryToCmdMap.insert( std::make_pair( tag + 2*theEntry2ObjData.size(), aCreationCommand ));
1537   }
1538
1539   // make a command
1540   if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
1541     aCommand += "addToStudyInFather( ";
1542     aCommand += aFatherData->_pyName + ", ";
1543   }
1544   else {
1545     aCommand += "addToStudy( ";
1546   }
1547   aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
1548
1549   // bind a command to the study entry
1550   int tag = theObjectData._entry.Token( ":", geomObjDepth ).IntegerValue();
1551   theEntryToCmdMap.insert( std::make_pair( tag, aCommand ));
1552
1553   theObjectData._studyEntry.Clear(); // not to publish any more
1554 }
1555
1556 //================================================================================
1557 /*!
1558  * \brief Constructor
1559  */
1560 //================================================================================
1561 ObjectStates::ObjectStates()
1562 {
1563   _dumpstate = 0;
1564 }
1565
1566 //================================================================================
1567 /*!
1568  * \brief Destructor
1569  */
1570 //================================================================================
1571 ObjectStates::~ObjectStates()
1572 {
1573 }
1574
1575 //================================================================================
1576 /*!
1577  * \brief Return current object state
1578  * \retval state - Object state (vector of notebook variable)
1579  */
1580 //================================================================================
1581 TState ObjectStates::GetCurrectState() const
1582 {
1583   if(_states.size() > _dumpstate)
1584     return _states[_dumpstate];
1585   return TState();
1586 }
1587
1588 //================================================================================
1589 /*!
1590  * \brief Add new object state
1591  * \param theState - Object state (vector of notebook variable)
1592  */
1593 //================================================================================
1594 void ObjectStates::AddState(const TState &theState)
1595 {
1596   _states.push_back(theState);
1597 }
1598
1599 //================================================================================
1600 /*!
1601  * \brief Increment object state
1602  */
1603 //================================================================================
1604 void ObjectStates::IncrementState()
1605 {
1606   _dumpstate++;
1607 }