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