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