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