Salome HOME
compatibility windows compilation with cmake
[modules/geom.git] / src / GEOM / GEOM_Engine.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 #ifdef WNT
23 #pragma warning( disable:4786 )
24 #endif
25
26 #include "GEOM_Engine.hxx"
27
28 #include "GEOM_Solver.hxx"
29 #include "GEOM_Function.hxx"
30 #include "GEOM_ISubShape.hxx"
31 #include "GEOM_SubShapeDriver.hxx"
32 #include "GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient.hxx"
33 #include "GEOM_PythonDump.hxx"
34
35 #include "utilities.h"
36
37 #include <TDF_Tool.hxx>
38 #include <TDF_Data.hxx>
39 #include <TDF_Reference.hxx>
40 #include <TDF_LabelSequence.hxx>
41 #include <TDataStd_Integer.hxx>
42 #include <TDataStd_ChildNodeIterator.hxx>
43 #include <TFunction_Driver.hxx>
44 #include <TFunction_DriverTable.hxx>
45
46 #include <TopExp.hxx>
47 #include <TopTools_IndexedMapOfShape.hxx>
48
49 #include <TCollection_AsciiString.hxx>
50 #include <TCollection_ExtendedString.hxx>
51 #include <TColStd_SequenceOfAsciiString.hxx>
52 #include <TColStd_MapOfTransient.hxx>
53 #include <TColStd_HSequenceOfInteger.hxx>
54
55 #include <Interface_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
56 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
57
58 #include <set>
59 #include <map>
60 #include <string>
61 #include <vector>
62
63 #include <Standard_Failure.hxx>
64 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
65
66 #define COMMA ','
67 #define O_BRACKET '('
68 #define C_BRACKET ')'
69 #define O_SQR_BRACKET '['
70 #define C_SQR_BRACKET ']'
71 #define PY_NULL "None"
72
73 #ifdef _DEBUG_
74 static int MYDEBUG = 0;
75 #else
76 static int MYDEBUG = 0;
77 #endif
78
79 static GEOM_Engine* TheEngine = NULL;
80
81 using namespace std;
82
83 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
84 {
85   TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
86   TDF_Tool::Entry(theObject->GetEntry(), anEntry);
87   anID+=(TCollection_AsciiString("_")+anEntry);
88   return anID;
89 }
90
91 static TCollection_AsciiString BuildID(Standard_Integer theDocID, char* theEntry)
92 {
93   TCollection_AsciiString anID(theDocID);
94   anID+=(TCollection_AsciiString("_")+theEntry);
95   return anID;
96 }
97
98 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
99 {
100   TCollection_AsciiString aDocID = theID.Token("_");
101   if(aDocID.Length() < 1) return -1;
102   return aDocID.IntegerValue();
103 }
104
105 void ProcessFunction(Handle(GEOM_Function)&   theFunction,
106                      TCollection_AsciiString& theScript,
107                      const TVariablesList&    theVariables,
108                      TDF_LabelMap&            theProcessed,
109                      std::set<std::string>&   theDumpedObjs);
110
111 void ReplaceVariables(TCollection_AsciiString& theCommand, 
112                       const TVariablesList&    theVariables);
113
114
115
116 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
117
118
119 //=============================================================================
120 /*!
121  *  GetEngine
122  */
123 //=============================================================================
124 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
125
126 //=============================================================================
127 /*!
128  *  SetEngine
129  */
130 //=============================================================================
131 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
132
133 //=============================================================================
134 /*!
135  *  Constructor
136  */
137 //=============================================================================
138 GEOM_Engine::GEOM_Engine()
139 {
140   TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
141
142   _OCAFApp = new GEOM_Application();
143   _UndoLimit = 10;
144 }
145
146 /*!
147  *  Destructor
148  */
149 GEOM_Engine::~GEOM_Engine()
150 {
151   GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
152   for(; It.More(); It.Next())
153     {
154       RemoveObject(Handle(GEOM_Object)::DownCast(It.Value()));
155     }
156
157   //Close all documents not closed
158   for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
159     Close(anItr.Key());
160
161   _mapIDDocument.Clear();
162   _objects.Clear();
163 }
164
165 //=============================================================================
166 /*!
167  *  GetDocument
168  */
169 //=============================================================================
170 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID)
171 {
172   Handle(TDocStd_Document) aDoc;
173   if(!_mapIDDocument.IsBound(theDocID)) {
174     _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
175     aDoc->SetUndoLimit(_UndoLimit);
176     _mapIDDocument.Bind(theDocID, aDoc);
177     TDataStd_Integer::Set(aDoc->Main(), theDocID);
178   }
179
180   return Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
181 }
182
183 //=============================================================================
184 /*!
185  *  GetDocID
186  */
187 //=============================================================================
188 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
189 {
190   if(theDocument.IsNull()) return -1;
191   for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
192     if(anItr.Value() == theDocument) return anItr.Key();
193
194   return -1;
195
196 }
197
198 //=============================================================================
199 /*!
200  *  GetObject
201  */
202 //=============================================================================
203 Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry)
204 {
205   TCollection_AsciiString anID = BuildID(theDocID, theEntry);
206   if(_objects.IsBound(anID)) return Handle(GEOM_Object)::DownCast(_objects(anID));
207
208   TDF_Label aLabel;
209   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
210   TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
211   Handle(GEOM_Object) anObject = new GEOM_Object(aLabel);
212
213   _objects.Bind(anID, anObject);
214
215   return anObject;
216 }
217
218 //=============================================================================
219 /*!
220  *  AddObject
221  */
222 //=============================================================================
223 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
224 {
225   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
226   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
227
228   // NPAL18604: use existing label to decrease memory usage,
229   //            if this label has been freed (object deleted)
230   bool useExisting = false;
231   TDF_Label aChild;
232   if (!_lastCleared.IsNull()) {
233     if (_lastCleared.Root() == aDoc->Main().Root()) {
234       useExisting = true;
235       aChild = _lastCleared;
236       _lastCleared.Nullify();
237     }
238   }
239   if (!useExisting) {
240     // create new label
241     aChild = TDF_TagSource::NewChild(aDoc->Main());
242   }
243
244   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
245
246   //Put an object in the map of created objects
247   TCollection_AsciiString anID = BuildIDFromObject(anObject);
248   if(_objects.IsBound(anID)) _objects.UnBind(anID);
249   _objects.Bind(anID, anObject);
250
251   return anObject;
252 }
253
254 //=============================================================================
255 /*!
256  *  AddSubShape
257  */
258 //=============================================================================
259 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
260                                              Handle(TColStd_HArray1OfInteger) theIndices,
261                                              bool isStandaloneOperation)
262 {
263   if(theMainShape.IsNull() || theIndices.IsNull()) return NULL;
264
265   Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
266   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
267
268   // NPAL18604: use existing label to decrease memory usage,
269   //            if this label has been freed (object deleted)
270   bool useExisting = false;
271   TDF_Label aChild;
272   if (!_lastCleared.IsNull()) {
273     if (_lastCleared.Root() == aDoc->Main().Root()) {
274       useExisting = true;
275       aChild = _lastCleared;
276       _lastCleared.Nullify();
277     }
278   }
279   if (!useExisting) {
280     // create new label
281     aChild = TDF_TagSource::NewChild(aDoc->Main());
282   }
283
284   Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
285   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type
286   Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
287
288   GEOM_ISubShape aSSI(aFunction);
289   aSSI.SetMainShape(aMainShape);
290   aSSI.SetIndices(theIndices);
291
292   try {
293 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
294     OCC_CATCH_SIGNALS;
295 #endif
296     GEOM_Solver aSolver (GEOM_Engine::GetEngine());
297     if (!aSolver.ComputeFunction(aFunction)) {
298       MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
299       return NULL;
300     }
301   }
302   catch (Standard_Failure) {
303     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
304     MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
305     return NULL;
306   }
307
308   //Put an object in the map of created objects
309   TCollection_AsciiString anID = BuildIDFromObject(anObject);
310   if(_objects.IsBound(anID)) _objects.UnBind(anID);
311   _objects.Bind(anID, anObject);
312
313   GEOM::TPythonDump pd (aFunction);
314
315   if (isStandaloneOperation) {
316     pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
317     Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
318     for (; i <= up - 1; i++) {
319       pd << theIndices->Value(i) << ", ";
320     }
321     pd << theIndices->Value(up) << "])";
322   }
323   else
324     pd << "None";
325
326   return anObject;
327 }
328
329 //=============================================================================
330 /*!
331  *  RemoveObject
332  */
333 //=============================================================================
334 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
335 {
336   if (!theObject) return false;
337
338   //Remove an object from the map of available objects
339   TCollection_AsciiString anID = BuildIDFromObject(theObject);
340   if (_objects.IsBound(anID)) _objects.UnBind(anID);
341
342   int nb = theObject->GetNbFunctions();
343   Handle(TDataStd_TreeNode) aNode;
344   for (int i = 1; i<=nb; i++) {
345     Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
346     if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
347       aNode->Remove();
348   }
349
350   TDF_Label aLabel = theObject->GetEntry();
351   aLabel.ForgetAllAttributes(Standard_True);
352   _lastCleared = aLabel;
353
354   theObject.Nullify();
355
356   return true;
357 }
358
359 //=============================================================================
360 /*!
361  *  Undo
362  */
363 //=============================================================================
364 void GEOM_Engine::Undo(int theDocID)
365 {
366   GetDocument(theDocID)->Undo();
367 }
368
369 //=============================================================================
370 /*!
371  *  Redo
372  */
373 //=============================================================================
374 void GEOM_Engine::Redo(int theDocID)
375 {
376   GetDocument(theDocID)->Redo();
377 }
378
379 //=============================================================================
380 /*!
381  *  Save
382  */
383 //=============================================================================
384 bool GEOM_Engine::Save(int theDocID, char* theFileName)
385 {
386   if(!_mapIDDocument.IsBound(theDocID)) return false;
387   Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
388
389   _OCAFApp->SaveAs(aDoc, theFileName);
390
391   return true;
392 }
393
394 //=============================================================================
395 /*!
396  *  Load
397  */
398 //=============================================================================
399 bool GEOM_Engine::Load(int theDocID, char* theFileName)
400 {
401   Handle(TDocStd_Document) aDoc;
402   if(_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
403     return false;
404   }
405
406   aDoc->SetUndoLimit(_UndoLimit);
407
408   if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
409   _mapIDDocument.Bind(theDocID, aDoc);
410
411   TDataStd_Integer::Set(aDoc->Main(), theDocID);
412
413   return true;
414 }
415
416 //=============================================================================
417 /*!
418  *  Close
419  */
420 //=============================================================================
421 void GEOM_Engine::Close(int theDocID)
422 {
423   if (_mapIDDocument.IsBound(theDocID)) {
424     Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
425
426     //Remove all GEOM Objects associated to the given document
427     TColStd_SequenceOfAsciiString aSeq;
428     GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
429     for (; It.More(); It.Next()) {
430       TCollection_AsciiString anObjID (It.Key());
431       Standard_Integer anID = ExtractDocID(anObjID);
432       if (theDocID == anID) aSeq.Append(It.Key());
433     }
434     for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
435
436     _lastCleared.Nullify();
437
438     _mapIDDocument.UnBind(theDocID);
439     _OCAFApp->Close(aDoc);
440     aDoc.Nullify();
441   }
442 }
443
444 //=============================================================================
445 /*!
446  *  DumpPython
447  */
448 //=============================================================================
449 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
450                                                 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
451                                                 TVariablesList theVariables,
452                                                 bool isPublished,
453                                                 bool& aValidScript)
454 {
455   TCollection_AsciiString aScript;
456   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
457
458   if (aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
459
460   aScript  = "import geompy\n";
461   aScript += "import math\n";
462   aScript += "import SALOMEDS\n\n";
463   aScript += "def RebuildData(theStudy):";
464   aScript += "\n\tgeompy.init_geom(theStudy)";
465
466   Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
467
468   Handle(TDataStd_TreeNode) aNode, aRoot;
469   Handle(GEOM_Function) aFunction;
470   TDF_LabelMap aCheckedFuncMap;
471   std::set<std::string> anIgnoreObjMap;
472
473   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
474     TDataStd_ChildNodeIterator Itr(aRoot);
475     for (; Itr.More(); Itr.Next()) {
476       aNode = Itr.Value();
477       aFunction = GEOM_Function::GetFunction(aNode->Label());
478       if (aFunction.IsNull()) {
479         MESSAGE ( "Null function !!!!" );
480         continue;
481       }
482       ProcessFunction(aFunction, aScript, theVariables, aCheckedFuncMap, anIgnoreObjMap);
483     }
484   }
485
486   Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry;
487   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
488   // build maps entry <-> studyEntry
489   for (anEntryToNameIt.Initialize( theObjectNames );
490        anEntryToNameIt.More();
491        anEntryToNameIt.Next())
492   {
493     const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
494     // look for an object by entry
495     TDF_Label L;
496     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
497     if ( L.IsNull() ) continue;
498     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
499     // fill maps
500     if ( !obj.IsNull() ) {
501       TCollection_AsciiString aStudyEntry (obj->GetAuxData());
502       aEntry2StEntry.Bind( aEntry,  aStudyEntry);
503       aStEntry2Entry.Bind( aStudyEntry, aEntry );
504     }
505   }
506
507   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
508   Standard_Integer aLen = aSeq->Length(), objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
509   Resource_DataMapOfAsciiStringAsciiString aNameToEntry, anEntryToBadName;
510
511   //Replace entries by the names
512   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
513     allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
514   if (aLen == 0) anUpdatedScript = aScript;
515
516   for (Standard_Integer i = 1; i <= aLen; i+=2) {
517     anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i)-1);
518     anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
519     if (theObjectNames.IsBound(anEntry)) {
520       aName = theObjectNames.Find(anEntry);
521       // check validity of aName
522       bool isValidName = true;
523       if ( aName.IsIntegerValue() ) { // aName must not start with a digit
524         aName.Insert( 1, 'a' );
525         isValidName = false;
526       }
527       int p, p2=1; // replace not allowed chars
528       while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
529         aName.SetValue(p, '_');
530         p2=p;
531         isValidName = false;
532       }
533       if ( aNameToEntry.IsBound( aName ) && anEntry != aNameToEntry( aName ))
534       {  // diff objects have same name - make a new name by appending a digit
535         TCollection_AsciiString aName2;
536         Standard_Integer i = 0;
537         do {
538           aName2 = aName + "_" + ++i;
539         } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
540         aName = aName2;
541         isValidName = false;
542       }
543       if ( !isValidName ) {
544         if ( isPublished )
545           anEntryToBadName.Bind( anEntry, theObjectNames.Find(anEntry) );
546         theObjectNames( anEntry ) = aName;
547       }
548     }
549     else {
550       do {
551         aName = aBaseName + TCollection_AsciiString(++objectCounter);
552       } while(aNameToEntry.IsBound(aName));
553       theObjectNames.Bind(anEntry, aName);
554     }
555     aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
556
557     anUpdatedScript += aName;
558     aStart = aSeq->Value(i+1) + 1;
559   }
560
561   //Add final part of the script
562   if (aLen && aSeq->Value(aLen) < aScriptLength)
563     anUpdatedScript += aScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
564
565   // ouv : NPAL12872
566   for (anEntryToNameIt.Initialize( theObjectNames );
567        anEntryToNameIt.More();
568        anEntryToNameIt.Next())
569   {
570     const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
571     const TCollection_AsciiString& aName = anEntryToNameIt.Value();
572
573     TDF_Label L;
574     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
575     if ( L.IsNull() )
576       continue;
577
578     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
579     if ( obj.IsNull() )
580       continue;
581
582     bool anAutoColor = obj->GetAutoColor();
583     if ( anAutoColor )
584     {
585       TCollection_AsciiString aCommand( "\n\t" );
586       aCommand += aName + ".SetAutoColor(1)";
587       anUpdatedScript += aCommand.ToCString();
588     }
589
590     SALOMEDS::Color aColor = obj->GetColor();
591     if ( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 )
592     {
593       TCollection_AsciiString aCommand( "\n\t" );
594       aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
595       anUpdatedScript += aCommand.ToCString();
596     }
597   }
598
599   // Make script to publish in study
600   if ( isPublished )
601   {
602     std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
603     for (anEntryToNameIt.Initialize( theObjectNames );
604          anEntryToNameIt.More();
605          anEntryToNameIt.Next())
606     {
607       const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
608       const TCollection_AsciiString& aName = anEntryToNameIt.Value();
609       if (anIgnoreObjMap.count(aEntry.ToCString()))
610         continue; // should not be dumped
611       if ( !aEntry2StEntry.IsBound( aEntry ))
612         continue; // was not published
613       TCollection_AsciiString aCommand("\n\tgeompy."), aFatherEntry;
614
615       // find a father entry
616       const TCollection_AsciiString& aStudyEntry = aEntry2StEntry( aEntry );
617       TCollection_AsciiString aFatherStudyEntry =
618         aStudyEntry.SubString( 1, aStudyEntry.SearchFromEnd(":") - 1 );
619       if ( aStEntry2Entry.IsBound( aFatherStudyEntry ))
620         aFatherEntry = aStEntry2Entry( aFatherStudyEntry );
621
622       // make a command
623       if ( !aFatherEntry.IsEmpty() && theObjectNames.IsBound( aFatherEntry )) {
624         aCommand += "addToStudyInFather( ";
625         aCommand += theObjectNames( aFatherEntry ) + ", ";
626       }
627       else
628         aCommand += "addToStudy( ";
629       if ( anEntryToBadName.IsBound( aEntry ))
630         aCommand += aName + ", \"" + anEntryToBadName( aEntry ) + "\" )";
631       else
632         aCommand += aName + ", \"" + aName + "\" )";
633
634       // bind a command to the last digit of the entry
635       int tag =
636         aEntry.SubString( aEntry.SearchFromEnd(":")+1, aEntry.Length() ).IntegerValue();
637       anEntryToCommandMap.insert( std::make_pair( tag, aCommand.ToCString() ));
638     }
639
640     // add publishing commands to the script
641     std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
642     for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand ) {
643       anUpdatedScript += (char*)anEntryToCommand->second.c_str();
644     }
645   }
646
647   //anUpdatedScript += "\n\tpass\n";
648   anUpdatedScript += "\n";
649   aValidScript = true;
650
651   // fill _studyEntry2NameMap and build globalVars
652   TCollection_AsciiString globalVars;
653   _studyEntry2NameMap.Clear();
654   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString aStEntryToEntryIt;
655   for (aStEntryToEntryIt.Initialize( aStEntry2Entry );
656        aStEntryToEntryIt.More();
657        aStEntryToEntryIt.Next() )
658   {
659     const TCollection_AsciiString & name = theObjectNames( aStEntryToEntryIt.Value() );
660     _studyEntry2NameMap.Bind (aStEntryToEntryIt.Key(), name );
661     if ( !globalVars.IsEmpty() )
662       globalVars += ", ";
663     globalVars += name;
664   }
665   if ( !globalVars.IsEmpty() ) {
666     globalVars.Insert( 1, "\n\tglobal " );
667     anUpdatedScript.Insert( posToInsertGlobalVars, globalVars );
668   }
669
670   return anUpdatedScript;
671 }
672
673 //=======================================================================
674 //function : GetDumpName
675 //purpose  :
676 //=======================================================================
677
678 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
679 {
680   if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
681     return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
682
683   return NULL;
684 }
685
686 //=======================================================================
687 //function : GetAllDumpNames
688 //purpose  :
689 //=======================================================================
690
691 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
692 {
693   Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
694
695   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
696   for (; it.More(); it.Next()) {
697     aRetSeq->Append(it.Value());
698   }
699
700   return aRetSeq;
701 }
702
703
704 //===========================================================================
705 //                     Internal functions
706 //===========================================================================
707 void ProcessFunction(Handle(GEOM_Function)&   theFunction,
708                      TCollection_AsciiString& theScript,
709                      const TVariablesList&    theVariables,
710                      TDF_LabelMap&            theProcessed,
711                      std::set<std::string>&   theIgnoreObjs)
712 {
713   if (theFunction.IsNull()) return;
714
715   if (theProcessed.Contains(theFunction->GetEntry())) return;
716
717   // pass functions, that depends on nonexisting ones
718   bool doNotProcess = false;
719   TDF_LabelSequence aSeq;
720   theFunction->GetDependency(aSeq);
721   Standard_Integer aLen = aSeq.Length();
722   for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
723     TDF_Label aRefLabel = aSeq.Value(i);
724     Handle(TDF_Reference) aRef;
725     if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
726       doNotProcess = true;
727     }
728     else {
729       if (aRef.IsNull() || aRef->Get().IsNull()) {
730         doNotProcess = true;
731       }
732       else {
733         Handle(TDataStd_TreeNode) aT;
734         if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
735           doNotProcess = true;
736         }
737         else {
738           TDF_Label aDepLabel = aT->Label();
739           Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
740
741           if (aFunction.IsNull()) doNotProcess = true;
742           else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
743         }
744       }
745     }
746   }
747
748   if (doNotProcess) {
749     TCollection_AsciiString anObjEntry;
750     TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
751     theIgnoreObjs.insert(anObjEntry.ToCString());
752     return;
753   }
754   theProcessed.Add(theFunction->GetEntry());
755
756   TCollection_AsciiString aDescr = theFunction->GetDescription();
757   if(aDescr.Length() == 0) return;
758
759   //Check if its internal function which doesn't requires dumping
760   if(aDescr == "None") return;
761
762   //Replace parameter by notebook variables
763   ReplaceVariables(aDescr,theVariables);
764   theScript += "\n\t";
765   theScript += aDescr;
766 }
767
768 //=============================================================================
769 /*!
770  *  FindEntries: Returns a sequence of start/end positions of entries in the string
771  */
772 //=============================================================================
773 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
774 {
775   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
776   Standard_Integer aLen = theString.Length();
777   Standard_Boolean isFound = Standard_False;
778
779   const char* arr = theString.ToCString();
780   Standard_Integer i = 0, j;
781
782   while(i < aLen) {
783     int c = (int)arr[i];
784     j = i+1;
785     if(c >= 48 && c <= 57) { //Is digit?
786
787       isFound = Standard_False;
788       while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
789         c = (int)arr[j++];
790         if(c == 58) isFound = Standard_True;
791       }
792
793       if(isFound && arr[j-2] != 58) { // last char should be a diggit
794         aSeq->Append(i+1); // +1 because AsciiString starts from 1
795         aSeq->Append(j-1);
796       }
797     }
798
799     i = j;
800   }
801
802   return aSeq;
803 }
804
805 //=============================================================================
806 /*!
807  *  ReplaceVariables: Replace parameters of the function by variales from 
808  *                    Notebook if need
809  */
810 //=============================================================================
811 void ReplaceVariables(TCollection_AsciiString& theCommand, 
812                       const TVariablesList&    theVariables)
813 {
814   if (MYDEBUG)
815     cout<<"Command : "<<theCommand<<endl;
816
817   if (MYDEBUG) {
818     cout<<"All Entries:"<<endl;
819     TVariablesList::const_iterator it = theVariables.begin();
820     for(;it != theVariables.end();it++)
821       cout<<"\t'"<<(*it).first<<"'"<<endl;
822   }
823
824   //Additional case - multi-row commands
825   int aCommandIndex = 1;
826   while( aCommandIndex < 10 ) { // tmp check
827     TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
828     if( aCommand.Length() == 0 )
829       break;
830
831     if (MYDEBUG)
832       cout<<"Sub-command : "<<aCommand<<endl;
833
834     Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
835     Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
836
837     //Get Entry of the result object
838     TCollection_AsciiString anEntry;
839     if( aCommand.Search("=") != -1 ) // command returns an object
840       anEntry = aCommand.Token("=",1);
841     else { // command modifies the object
842       int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length());
843       int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length());
844       anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
845     }
846
847     //Remove white spaces
848     anEntry.RightAdjust();
849     anEntry.LeftAdjust();
850     if(MYDEBUG)
851       cout<<"Result entry : '" <<anEntry<<"'"<<endl;
852
853     //Check if result is list of entries - enough to get the first entry in this case
854     int aNbEntries = 1;
855     if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
856       while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
857         aNbEntries++;
858       TCollection_AsciiString aSeparator(COMMA);
859       anEntry = anEntry.Token(aSeparator.ToCString(),1);
860       anEntry.Remove( 1, 1 );
861       anEntry.RightAdjust();
862       anEntry.LeftAdjust();
863       if(MYDEBUG)
864         cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
865     }
866     
867     //Find variables used for object construction
868     ObjectStates* aStates = 0;
869     TVariablesList::const_iterator it = theVariables.find(anEntry);
870     if( it != theVariables.end() )
871       aStates = (*it).second;
872
873     if(!aStates) {
874       if(MYDEBUG)
875         cout<<"Valiables list empty!!!"<<endl;
876       aCommandIndex++;
877       continue;
878     }
879
880     TState aVariables = aStates->GetCurrectState();
881
882     if(MYDEBUG) {
883       cout<<"Variables from SObject:"<<endl;
884       for (int i = 0; i < aVariables.size();i++)
885         cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
886     }
887
888     //Calculate total number of parameters
889     Standard_Integer aTotalNbParams = 1;
890     while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
891       aTotalNbParams++;
892
893     if(MYDEBUG)
894       cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
895
896     Standard_Integer aFirstParam = aNbEntries;
897
898     //Replace parameters by variables
899     Standard_Integer aStartPos = 0;
900     Standard_Integer aEndPos = 0;
901     int iVar = 0;
902     TCollection_AsciiString aVar, aReplacedVar;
903     for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
904       //Replace first parameter (bettwen '(' character and first ',' character)
905       if(i == aFirstParam)
906       {
907         aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
908         if(aTotalNbParams - aNbEntries > 0 )
909           aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
910         else
911           aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length()); 
912       }
913       //Replace last parameter (bettwen ',' character and ')' character)
914       else if(i == aTotalNbParams)
915       {
916         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
917         aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
918       }
919       //Replace other parameters (bettwen two ',' characters)
920       else if(i != aFirstParam && i != aTotalNbParams )
921       {
922         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
923         aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
924       }
925
926       if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
927         aStartPos++;
928       if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
929         aEndPos--;
930       if ( aStartPos == aEndPos )
931         continue; // PAL20889: for "[]"
932
933       if(MYDEBUG) 
934         cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
935
936       aVar = aCommand.SubString(aStartPos, aEndPos-1);
937       aVar.RightAdjust();
938       aVar.LeftAdjust();
939     
940       if(MYDEBUG) 
941         cout<<"Variable: '"<< aVar <<"'"<<endl;
942
943       // specific case for sketcher
944       if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
945         Standard_Integer aNbSections = 1;
946         while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
947           aNbSections++;
948         aNbSections--;
949
950         int aStartSectionPos = 0, aEndSectionPos = 0;
951         TCollection_AsciiString aSection, aReplacedSection;
952         for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
953           aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
954           if( aSectionIndex != aNbSections )
955             aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
956           else
957             aEndSectionPos = aVar.Length();
958
959           aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
960           if(MYDEBUG) 
961             cout<<"aSection: "<<aSection<<endl;
962
963           Standard_Integer aNbParams = 1;
964           while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
965             aNbParams++;
966           aNbParams--;
967
968           int aStartParamPos = 0, aEndParamPos = 0;
969           TCollection_AsciiString aParameter, aReplacedParameter;
970           for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
971             aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
972             if( aParamIndex != aNbParams )
973               aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
974             else
975               aEndParamPos = aSection.Length() + 1;
976
977             aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
978             if(MYDEBUG) 
979               cout<<"aParameter: "<<aParameter<<endl;
980
981             if(iVar >= aVariables.size())
982               continue;
983
984             aReplacedParameter = aVariables[iVar].myVariable;
985             if(aReplacedParameter.IsEmpty()) {
986               iVar++;
987               continue;
988             }
989
990             if(aVariables[iVar].isVariable) {
991               aReplacedParameter.InsertBefore(1,"'");
992               aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
993             }
994
995             if(MYDEBUG) 
996               cout<<"aSection before : "<<aSection<<endl;
997             aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
998             aSection.Insert(aStartParamPos, aReplacedParameter);
999             if(MYDEBUG) 
1000               cout<<"aSection after  : "<<aSection<<endl<<endl;
1001             iVar++;
1002           }
1003           if(MYDEBUG) 
1004             cout<<"aVar before : "<<aVar<<endl;
1005           aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1006           aVar.Insert(aStartSectionPos, aSection);
1007           if(MYDEBUG) 
1008             cout<<"aVar after  : "<<aVar<<endl<<endl;
1009         }
1010
1011         if(MYDEBUG) 
1012           cout<<"aCommand before : "<<aCommand<<endl;
1013         aCommand.Remove(aStartPos, aEndPos - aStartPos);
1014         aCommand.Insert(aStartPos, aVar);
1015         if(MYDEBUG) 
1016           cout<<"aCommand after  : "<<aCommand<<endl;
1017
1018         break;
1019       } // end of specific case for sketcher
1020
1021       //If parameter is entry or 'None', skip it
1022       if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1023         continue;
1024
1025       if(iVar >= aVariables.size())
1026         continue;
1027
1028       aReplacedVar = aVariables[iVar].myVariable;
1029       if(aReplacedVar.IsEmpty()) {
1030         iVar++;
1031         continue;
1032       }
1033
1034       if(aVariables[iVar].isVariable) {
1035         aReplacedVar.InsertBefore(1,"\"");
1036         aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1037       }
1038
1039       aCommand.Remove(aStartPos, aEndPos - aStartPos);
1040       aCommand.Insert(aStartPos, aReplacedVar);
1041       iVar++;
1042     }
1043
1044     theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1045     theCommand.Insert(aStartCommandPos, aCommand);
1046
1047     aCommandIndex++;
1048
1049     aStates->IncrementState();
1050   }
1051
1052   if (MYDEBUG)
1053     cout<<"Command : "<<theCommand<<endl;
1054 }
1055
1056 //================================================================================
1057 /*!
1058  * \brief Constructor
1059  */
1060 //================================================================================
1061 ObjectStates::ObjectStates()
1062 {
1063   _dumpstate = 0;
1064 }
1065
1066 //================================================================================
1067 /*!
1068  * \brief Destructor
1069  */
1070 //================================================================================
1071 ObjectStates::~ObjectStates()
1072 {
1073 }
1074
1075 //================================================================================
1076 /*!
1077  * \brief Return current object state
1078  * \retval state - Object state (vector of notebook variable)
1079  */
1080 //================================================================================
1081 TState ObjectStates::GetCurrectState() const
1082 {
1083   if(_states.size() > _dumpstate)
1084     return _states[_dumpstate];
1085   return TState();
1086 }
1087
1088 //================================================================================
1089 /*!
1090  * \brief Add new object state 
1091  * \param theState - Object state (vector of notebook variable)
1092  */
1093 //================================================================================
1094 void ObjectStates::AddState(const TState &theState)
1095 {
1096   _states.push_back(theState);
1097 }
1098
1099 //================================================================================
1100 /*!
1101  * \brief Increment object state
1102  */
1103 //================================================================================
1104 void ObjectStates::IncrementState()
1105 {
1106   _dumpstate++;
1107 }