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