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