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