]> SALOME platform Git repositories - modules/geom.git/blob - src/GEOM/GEOM_Engine.cxx
Salome HOME
Implementation of the issue 0020151 (SALOME: Light Python module):
[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       // 0020229: if next label exists and is empty, try to reuse it
237       Standard_Integer aNextTag = aChild.Tag() + 1;
238       TDF_Label aNextL = aDoc->Main().FindChild(aNextTag, Standard_False);
239       if (!aNextL.IsNull() && !aNextL.HasAttribute())
240         _lastCleared = aNextL;
241       else
242         _lastCleared.Nullify();
243     }
244   }
245   if (!useExisting) {
246     // create new label
247     aChild = TDF_TagSource::NewChild(aDoc->Main());
248   }
249
250   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
251
252   //Put an object in the map of created objects
253   TCollection_AsciiString anID = BuildIDFromObject(anObject);
254   if(_objects.IsBound(anID)) _objects.UnBind(anID);
255   _objects.Bind(anID, anObject);
256
257   return anObject;
258 }
259
260 //=============================================================================
261 /*!
262  *  AddSubShape
263  */
264 //=============================================================================
265 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
266                                              Handle(TColStd_HArray1OfInteger) theIndices,
267                                              bool isStandaloneOperation)
268 {
269   if(theMainShape.IsNull() || theIndices.IsNull()) return NULL;
270
271   Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
272   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
273
274   // NPAL18604: use existing label to decrease memory usage,
275   //            if this label has been freed (object deleted)
276   bool useExisting = false;
277   TDF_Label aChild;
278   if (!_lastCleared.IsNull()) {
279     if (_lastCleared.Root() == aDoc->Main().Root()) {
280       useExisting = true;
281       aChild = _lastCleared;
282       // 0020229: if next label exists and is empty, try to reuse it
283       Standard_Integer aNextTag = aChild.Tag() + 1;
284       TDF_Label aNextL = aDoc->Main().FindChild(aNextTag, Standard_False);
285       if (!aNextL.IsNull() && !aNextL.HasAttribute())
286         _lastCleared = aNextL;
287       else
288         _lastCleared.Nullify();
289     }
290   }
291   if (!useExisting) {
292     // create new label
293     aChild = TDF_TagSource::NewChild(aDoc->Main());
294   }
295
296   Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
297   Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type
298   Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
299
300   GEOM_ISubShape aSSI(aFunction);
301   aSSI.SetMainShape(aMainShape);
302   aSSI.SetIndices(theIndices);
303
304   try {
305 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
306     OCC_CATCH_SIGNALS;
307 #endif
308     GEOM_Solver aSolver (GEOM_Engine::GetEngine());
309     if (!aSolver.ComputeFunction(aFunction)) {
310       MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
311       return NULL;
312     }
313   }
314   catch (Standard_Failure) {
315     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
316     MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
317     return NULL;
318   }
319
320   //Put an object in the map of created objects
321   TCollection_AsciiString anID = BuildIDFromObject(anObject);
322   if(_objects.IsBound(anID)) _objects.UnBind(anID);
323   _objects.Bind(anID, anObject);
324
325   GEOM::TPythonDump pd (aFunction);
326
327   if (isStandaloneOperation) {
328     pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
329     Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
330     for (; i <= up - 1; i++) {
331       pd << theIndices->Value(i) << ", ";
332     }
333     pd << theIndices->Value(up) << "])";
334   }
335   else
336     pd << "None";
337
338   return anObject;
339 }
340
341 //=============================================================================
342 /*!
343  *  RemoveObject
344  */
345 //=============================================================================
346 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
347 {
348   if (!theObject) return false;
349
350   //Remove an object from the map of available objects
351   TCollection_AsciiString anID = BuildIDFromObject(theObject);
352   if (_objects.IsBound(anID)) _objects.UnBind(anID);
353
354   int nb = theObject->GetNbFunctions();
355   Handle(TDataStd_TreeNode) aNode;
356   for (int i = 1; i<=nb; i++) {
357     Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
358     if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
359       aNode->Remove();
360   }
361
362   TDF_Label aLabel = theObject->GetEntry();
363   aLabel.ForgetAllAttributes(Standard_True);
364   _lastCleared = aLabel;
365
366   theObject.Nullify();
367
368   return true;
369 }
370
371 //=============================================================================
372 /*!
373  *  Undo
374  */
375 //=============================================================================
376 void GEOM_Engine::Undo(int theDocID)
377 {
378   GetDocument(theDocID)->Undo();
379 }
380
381 //=============================================================================
382 /*!
383  *  Redo
384  */
385 //=============================================================================
386 void GEOM_Engine::Redo(int theDocID)
387 {
388   GetDocument(theDocID)->Redo();
389 }
390
391 //=============================================================================
392 /*!
393  *  Save
394  */
395 //=============================================================================
396 bool GEOM_Engine::Save(int theDocID, char* theFileName)
397 {
398   if(!_mapIDDocument.IsBound(theDocID)) return false;
399   Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
400
401   _OCAFApp->SaveAs(aDoc, theFileName);
402
403   return true;
404 }
405
406 //=============================================================================
407 /*!
408  *  Load
409  */
410 //=============================================================================
411 bool GEOM_Engine::Load(int theDocID, char* theFileName)
412 {
413   Handle(TDocStd_Document) aDoc;
414   if(_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
415     return false;
416   }
417
418   aDoc->SetUndoLimit(_UndoLimit);
419
420   if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
421   _mapIDDocument.Bind(theDocID, aDoc);
422
423   TDataStd_Integer::Set(aDoc->Main(), theDocID);
424
425   return true;
426 }
427
428 //=============================================================================
429 /*!
430  *  Close
431  */
432 //=============================================================================
433 void GEOM_Engine::Close(int theDocID)
434 {
435   if (_mapIDDocument.IsBound(theDocID)) {
436     Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
437
438     //Remove all GEOM Objects associated to the given document
439     TColStd_SequenceOfAsciiString aSeq;
440     GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
441     for (; It.More(); It.Next()) {
442       TCollection_AsciiString anObjID (It.Key());
443       Standard_Integer anID = ExtractDocID(anObjID);
444       if (theDocID == anID) aSeq.Append(It.Key());
445     }
446     for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
447
448     _lastCleared.Nullify();
449
450     _mapIDDocument.UnBind(theDocID);
451     _OCAFApp->Close(aDoc);
452     aDoc.Nullify();
453   }
454 }
455
456 //=============================================================================
457 /*!
458  *  DumpPython
459  */
460 //=============================================================================
461 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
462                                                 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
463                                                 TVariablesList theVariables,
464                                                 bool isPublished,
465                                                 bool& aValidScript)
466 {
467   TCollection_AsciiString aScript;
468   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
469
470   if (aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
471
472   aScript  = "import geompy\n";
473   aScript += "import math\n";
474   aScript += "import SALOMEDS\n\n";
475   aScript += "def RebuildData(theStudy):";
476   aScript += "\n\tgeompy.init_geom(theStudy)";
477
478   Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
479
480   Handle(TDataStd_TreeNode) aNode, aRoot;
481   Handle(GEOM_Function) aFunction;
482   TDF_LabelMap aCheckedFuncMap;
483   std::set<std::string> anIgnoreObjMap;
484
485   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
486     TDataStd_ChildNodeIterator Itr(aRoot);
487     for (; Itr.More(); Itr.Next()) {
488       aNode = Itr.Value();
489       aFunction = GEOM_Function::GetFunction(aNode->Label());
490       if (aFunction.IsNull()) {
491         MESSAGE ( "Null function !!!!" );
492         continue;
493       }
494       ProcessFunction(aFunction, aScript, theVariables, aCheckedFuncMap, anIgnoreObjMap);
495     }
496   }
497
498   Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry;
499   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
500   // build maps entry <-> studyEntry
501   for (anEntryToNameIt.Initialize( theObjectNames );
502        anEntryToNameIt.More();
503        anEntryToNameIt.Next())
504   {
505     const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
506     // look for an object by entry
507     TDF_Label L;
508     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
509     if ( L.IsNull() ) continue;
510     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
511     // fill maps
512     if ( !obj.IsNull() ) {
513       TCollection_AsciiString aStudyEntry (obj->GetAuxData());
514       aEntry2StEntry.Bind( aEntry,  aStudyEntry);
515       aStEntry2Entry.Bind( aStudyEntry, aEntry );
516     }
517   }
518
519   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
520   Standard_Integer aLen = aSeq->Length(), objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
521   Resource_DataMapOfAsciiStringAsciiString aNameToEntry, anEntryToBadName;
522
523   //Replace entries by the names
524   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
525     allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
526   if (aLen == 0) anUpdatedScript = aScript;
527
528   for (Standard_Integer i = 1; i <= aLen; i+=2) {
529     anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i)-1);
530     anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
531     if (theObjectNames.IsBound(anEntry)) {
532       aName = theObjectNames.Find(anEntry);
533       // check validity of aName
534       bool isValidName = true;
535       if ( aName.IsIntegerValue() ) { // aName must not start with a digit
536         aName.Insert( 1, 'a' );
537         isValidName = false;
538       }
539       int p, p2=1; // replace not allowed chars
540       while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
541         aName.SetValue(p, '_');
542         p2=p;
543         isValidName = false;
544       }
545       if ( aNameToEntry.IsBound( aName ) && anEntry != aNameToEntry( aName ))
546       {  // diff objects have same name - make a new name by appending a digit
547         TCollection_AsciiString aName2;
548         Standard_Integer i = 0;
549         do {
550           aName2 = aName + "_" + ++i;
551         } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
552         aName = aName2;
553         isValidName = false;
554       }
555       if ( !isValidName ) {
556         if ( isPublished )
557           anEntryToBadName.Bind( anEntry, theObjectNames.Find(anEntry) );
558         theObjectNames( anEntry ) = aName;
559       }
560     }
561     else {
562       do {
563         aName = aBaseName + TCollection_AsciiString(++objectCounter);
564       } while(aNameToEntry.IsBound(aName));
565       theObjectNames.Bind(anEntry, aName);
566     }
567     aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
568
569     anUpdatedScript += aName;
570     aStart = aSeq->Value(i+1) + 1;
571   }
572
573   //Add final part of the script
574   if (aLen && aSeq->Value(aLen) < aScriptLength)
575     anUpdatedScript += aScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
576
577   // ouv : NPAL12872
578   for (anEntryToNameIt.Initialize( theObjectNames );
579        anEntryToNameIt.More();
580        anEntryToNameIt.Next())
581   {
582     const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
583     const TCollection_AsciiString& aName = anEntryToNameIt.Value();
584
585     TDF_Label L;
586     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
587     if ( L.IsNull() )
588       continue;
589
590     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
591     if ( obj.IsNull() )
592       continue;
593
594     bool anAutoColor = obj->GetAutoColor();
595     if ( anAutoColor )
596     {
597       TCollection_AsciiString aCommand( "\n\t" );
598       aCommand += aName + ".SetAutoColor(1)";
599       anUpdatedScript += aCommand.ToCString();
600     }
601
602     SALOMEDS::Color aColor = obj->GetColor();
603     if ( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 )
604     {
605       TCollection_AsciiString aCommand( "\n\t" );
606       aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
607       anUpdatedScript += aCommand.ToCString();
608     }
609   }
610
611   // Make script to publish in study
612   if ( isPublished )
613   {
614     std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
615     for (anEntryToNameIt.Initialize( theObjectNames );
616          anEntryToNameIt.More();
617          anEntryToNameIt.Next())
618     {
619       const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
620       const TCollection_AsciiString& aName = anEntryToNameIt.Value();
621       if (anIgnoreObjMap.count(aEntry.ToCString()))
622         continue; // should not be dumped
623       if ( !aEntry2StEntry.IsBound( aEntry ))
624         continue; // was not published
625       TCollection_AsciiString aCommand("\n\tgeompy."), aFatherEntry;
626
627       // find a father entry
628       const TCollection_AsciiString& aStudyEntry = aEntry2StEntry( aEntry );
629       TCollection_AsciiString aFatherStudyEntry =
630         aStudyEntry.SubString( 1, aStudyEntry.SearchFromEnd(":") - 1 );
631       if ( aStEntry2Entry.IsBound( aFatherStudyEntry ))
632         aFatherEntry = aStEntry2Entry( aFatherStudyEntry );
633
634       // make a command
635       if ( !aFatherEntry.IsEmpty() && theObjectNames.IsBound( aFatherEntry )) {
636         aCommand += "addToStudyInFather( ";
637         aCommand += theObjectNames( aFatherEntry ) + ", ";
638       }
639       else
640         aCommand += "addToStudy( ";
641       if ( anEntryToBadName.IsBound( aEntry ))
642         aCommand += aName + ", \"" + anEntryToBadName( aEntry ) + "\" )";
643       else
644         aCommand += aName + ", \"" + aName + "\" )";
645
646       // bind a command to the last digit of the entry
647       int tag =
648         aEntry.SubString( aEntry.SearchFromEnd(":")+1, aEntry.Length() ).IntegerValue();
649       anEntryToCommandMap.insert( std::make_pair( tag, aCommand.ToCString() ));
650     }
651
652     // add publishing commands to the script
653     std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
654     for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand ) {
655       anUpdatedScript += (char*)anEntryToCommand->second.c_str();
656     }
657   }
658
659   //anUpdatedScript += "\n\tpass\n";
660   anUpdatedScript += "\n";
661   aValidScript = true;
662
663   // fill _studyEntry2NameMap and build globalVars
664   TCollection_AsciiString globalVars;
665   _studyEntry2NameMap.Clear();
666   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString aStEntryToEntryIt;
667   for (aStEntryToEntryIt.Initialize( aStEntry2Entry );
668        aStEntryToEntryIt.More();
669        aStEntryToEntryIt.Next() )
670   {
671     const TCollection_AsciiString & name = theObjectNames( aStEntryToEntryIt.Value() );
672     _studyEntry2NameMap.Bind (aStEntryToEntryIt.Key(), name );
673     if ( !globalVars.IsEmpty() )
674       globalVars += ", ";
675     globalVars += name;
676   }
677   if ( !globalVars.IsEmpty() ) {
678     globalVars.Insert( 1, "\n\tglobal " );
679     anUpdatedScript.Insert( posToInsertGlobalVars, globalVars );
680   }
681
682   return anUpdatedScript;
683 }
684
685 //=======================================================================
686 //function : GetDumpName
687 //purpose  :
688 //=======================================================================
689
690 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
691 {
692   if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
693     return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
694
695   return NULL;
696 }
697
698 //=======================================================================
699 //function : GetAllDumpNames
700 //purpose  :
701 //=======================================================================
702
703 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
704 {
705   Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
706
707   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
708   for (; it.More(); it.Next()) {
709     aRetSeq->Append(it.Value());
710   }
711
712   return aRetSeq;
713 }
714
715
716 //===========================================================================
717 //                     Internal functions
718 //===========================================================================
719 void ProcessFunction(Handle(GEOM_Function)&   theFunction,
720                      TCollection_AsciiString& theScript,
721                      const TVariablesList&    theVariables,
722                      TDF_LabelMap&            theProcessed,
723                      std::set<std::string>&   theIgnoreObjs)
724 {
725   if (theFunction.IsNull()) return;
726
727   if (theProcessed.Contains(theFunction->GetEntry())) return;
728
729   // pass functions, that depends on nonexisting ones
730   bool doNotProcess = false;
731   TDF_LabelSequence aSeq;
732   theFunction->GetDependency(aSeq);
733   Standard_Integer aLen = aSeq.Length();
734   for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
735     TDF_Label aRefLabel = aSeq.Value(i);
736     Handle(TDF_Reference) aRef;
737     if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
738       doNotProcess = true;
739     }
740     else {
741       if (aRef.IsNull() || aRef->Get().IsNull()) {
742         doNotProcess = true;
743       }
744       else {
745         Handle(TDataStd_TreeNode) aT;
746         if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
747           doNotProcess = true;
748         }
749         else {
750           TDF_Label aDepLabel = aT->Label();
751           Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
752
753           if (aFunction.IsNull()) doNotProcess = true;
754           else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
755         }
756       }
757     }
758   }
759
760   if (doNotProcess) {
761     TCollection_AsciiString anObjEntry;
762     TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
763     theIgnoreObjs.insert(anObjEntry.ToCString());
764     return;
765   }
766   theProcessed.Add(theFunction->GetEntry());
767
768   TCollection_AsciiString aDescr = theFunction->GetDescription();
769   if(aDescr.Length() == 0) return;
770
771   //Check if its internal function which doesn't requires dumping
772   if(aDescr == "None") return;
773
774   //Replace parameter by notebook variables
775   ReplaceVariables(aDescr,theVariables);
776   theScript += "\n\t";
777   theScript += aDescr;
778 }
779
780 //=============================================================================
781 /*!
782  *  FindEntries: Returns a sequence of start/end positions of entries in the string
783  */
784 //=============================================================================
785 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
786 {
787   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
788   Standard_Integer aLen = theString.Length();
789   Standard_Boolean isFound = Standard_False;
790
791   const char* arr = theString.ToCString();
792   Standard_Integer i = 0, j;
793
794   while(i < aLen) {
795     int c = (int)arr[i];
796     j = i+1;
797     if(c >= 48 && c <= 57) { //Is digit?
798
799       isFound = Standard_False;
800       while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
801         c = (int)arr[j++];
802         if(c == 58) isFound = Standard_True;
803       }
804
805       if(isFound && arr[j-2] != 58) { // last char should be a diggit
806         aSeq->Append(i+1); // +1 because AsciiString starts from 1
807         aSeq->Append(j-1);
808       }
809     }
810
811     i = j;
812   }
813
814   return aSeq;
815 }
816
817 //=============================================================================
818 /*!
819  *  ReplaceVariables: Replace parameters of the function by variales from 
820  *                    Notebook if need
821  */
822 //=============================================================================
823 void ReplaceVariables(TCollection_AsciiString& theCommand, 
824                       const TVariablesList&    theVariables)
825 {
826   if (MYDEBUG)
827     cout<<"Command : "<<theCommand<<endl;
828
829   if (MYDEBUG) {
830     cout<<"All Entries:"<<endl;
831     TVariablesList::const_iterator it = theVariables.begin();
832     for(;it != theVariables.end();it++)
833       cout<<"\t'"<<(*it).first<<"'"<<endl;
834   }
835
836   //Additional case - multi-row commands
837   int aCommandIndex = 1;
838   while( aCommandIndex < 10 ) { // tmp check
839     TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
840     if( aCommand.Length() == 0 )
841       break;
842
843     if (MYDEBUG)
844       cout<<"Sub-command : "<<aCommand<<endl;
845
846     Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
847     Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
848
849     //Get Entry of the result object
850     TCollection_AsciiString anEntry;
851     if( aCommand.Search("=") != -1 ) // command returns an object
852       anEntry = aCommand.Token("=",1);
853     else { // command modifies the object
854       if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
855         if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
856           anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
857     }
858     //Remove white spaces
859     anEntry.RightAdjust();
860     anEntry.LeftAdjust();
861     if(MYDEBUG)
862       cout<<"Result entry : '" <<anEntry<<"'"<<endl;
863
864     if ( anEntry.IsEmpty() ) {
865       aCommandIndex++;
866       continue;
867     }
868
869     //Check if result is list of entries - enough to get the first entry in this case
870     int aNbEntries = 1;
871     if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
872       while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
873         aNbEntries++;
874       TCollection_AsciiString aSeparator(COMMA);
875       anEntry = anEntry.Token(aSeparator.ToCString(),1);
876       anEntry.Remove( 1, 1 );
877       anEntry.RightAdjust();
878       anEntry.LeftAdjust();
879       if(MYDEBUG)
880         cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
881     }
882     
883     //Find variables used for object construction
884     ObjectStates* aStates = 0;
885     TVariablesList::const_iterator it = theVariables.find(anEntry);
886     if( it != theVariables.end() )
887       aStates = (*it).second;
888
889     if(!aStates) {
890       if(MYDEBUG)
891         cout<<"Valiables list empty!!!"<<endl;
892       aCommandIndex++;
893       continue;
894     }
895
896     TState aVariables = aStates->GetCurrectState();
897
898     if(MYDEBUG) {
899       cout<<"Variables from SObject:"<<endl;
900       for (int i = 0; i < aVariables.size();i++)
901         cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
902     }
903
904     //Calculate total number of parameters
905     Standard_Integer aTotalNbParams = 1;
906     while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
907       aTotalNbParams++;
908
909     if(MYDEBUG)
910       cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
911
912     Standard_Integer aFirstParam = aNbEntries;
913
914     //Replace parameters by variables
915     Standard_Integer aStartPos = 0;
916     Standard_Integer aEndPos = 0;
917     int iVar = 0;
918     TCollection_AsciiString aVar, aReplacedVar;
919     for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
920       //Replace first parameter (bettwen '(' character and first ',' character)
921       if(i == aFirstParam)
922       {
923         aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
924         if(aTotalNbParams - aNbEntries > 0 )
925           aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
926         else
927           aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length()); 
928       }
929       //Replace last parameter (bettwen ',' character and ')' character)
930       else if(i == aTotalNbParams)
931       {
932         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
933         aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
934       }
935       //Replace other parameters (bettwen two ',' characters)
936       else if(i != aFirstParam && i != aTotalNbParams )
937       {
938         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
939         aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
940       }
941
942       if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
943         aStartPos++;
944       if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
945         aEndPos--;
946       if ( aStartPos == aEndPos )
947         continue; // PAL20889: for "[]"
948
949       if(MYDEBUG) 
950         cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
951
952       aVar = aCommand.SubString(aStartPos, aEndPos-1);
953       aVar.RightAdjust();
954       aVar.LeftAdjust();
955     
956       if(MYDEBUG) 
957         cout<<"Variable: '"<< aVar <<"'"<<endl;
958
959       // specific case for sketcher
960       if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
961         Standard_Integer aNbSections = 1;
962         while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
963           aNbSections++;
964         aNbSections--;
965
966         int aStartSectionPos = 0, aEndSectionPos = 0;
967         TCollection_AsciiString aSection, aReplacedSection;
968         for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
969           aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
970           if( aSectionIndex != aNbSections )
971             aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
972           else
973             aEndSectionPos = aVar.Length();
974
975           aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
976           if(MYDEBUG) 
977             cout<<"aSection: "<<aSection<<endl;
978
979           Standard_Integer aNbParams = 1;
980           while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
981             aNbParams++;
982           aNbParams--;
983
984           int aStartParamPos = 0, aEndParamPos = 0;
985           TCollection_AsciiString aParameter, aReplacedParameter;
986           for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
987             aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
988             if( aParamIndex != aNbParams )
989               aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
990             else
991               aEndParamPos = aSection.Length() + 1;
992
993             aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
994             if(MYDEBUG) 
995               cout<<"aParameter: "<<aParameter<<endl;
996
997             if(iVar >= aVariables.size())
998               continue;
999
1000             aReplacedParameter = aVariables[iVar].myVariable;
1001             if(aReplacedParameter.IsEmpty()) {
1002               iVar++;
1003               continue;
1004             }
1005
1006             if(aVariables[iVar].isVariable) {
1007               aReplacedParameter.InsertBefore(1,"'");
1008               aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1009             }
1010
1011             if(MYDEBUG) 
1012               cout<<"aSection before : "<<aSection<<endl;
1013             aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1014             aSection.Insert(aStartParamPos, aReplacedParameter);
1015             if(MYDEBUG) 
1016               cout<<"aSection after  : "<<aSection<<endl<<endl;
1017             iVar++;
1018           }
1019           if(MYDEBUG) 
1020             cout<<"aVar before : "<<aVar<<endl;
1021           aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1022           aVar.Insert(aStartSectionPos, aSection);
1023           if(MYDEBUG) 
1024             cout<<"aVar after  : "<<aVar<<endl<<endl;
1025         }
1026
1027         if(MYDEBUG) 
1028           cout<<"aCommand before : "<<aCommand<<endl;
1029         aCommand.Remove(aStartPos, aEndPos - aStartPos);
1030         aCommand.Insert(aStartPos, aVar);
1031         if(MYDEBUG) 
1032           cout<<"aCommand after  : "<<aCommand<<endl;
1033
1034         break;
1035       } // end of specific case for sketcher
1036
1037       //If parameter is entry or 'None', skip it
1038       if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1039         continue;
1040
1041       if(iVar >= aVariables.size())
1042         continue;
1043
1044       aReplacedVar = aVariables[iVar].myVariable;
1045       if(aReplacedVar.IsEmpty()) {
1046         iVar++;
1047         continue;
1048       }
1049
1050       if(aVariables[iVar].isVariable) {
1051         aReplacedVar.InsertBefore(1,"\"");
1052         aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1053       }
1054
1055       aCommand.Remove(aStartPos, aEndPos - aStartPos);
1056       aCommand.Insert(aStartPos, aReplacedVar);
1057       iVar++;
1058     }
1059
1060     theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1061     theCommand.Insert(aStartCommandPos, aCommand);
1062
1063     aCommandIndex++;
1064
1065     aStates->IncrementState();
1066   }
1067
1068   if (MYDEBUG)
1069     cout<<"Command : "<<theCommand<<endl;
1070 }
1071
1072 //================================================================================
1073 /*!
1074  * \brief Constructor
1075  */
1076 //================================================================================
1077 ObjectStates::ObjectStates()
1078 {
1079   _dumpstate = 0;
1080 }
1081
1082 //================================================================================
1083 /*!
1084  * \brief Destructor
1085  */
1086 //================================================================================
1087 ObjectStates::~ObjectStates()
1088 {
1089 }
1090
1091 //================================================================================
1092 /*!
1093  * \brief Return current object state
1094  * \retval state - Object state (vector of notebook variable)
1095  */
1096 //================================================================================
1097 TState ObjectStates::GetCurrectState() const
1098 {
1099   if(_states.size() > _dumpstate)
1100     return _states[_dumpstate];
1101   return TState();
1102 }
1103
1104 //================================================================================
1105 /*!
1106  * \brief Add new object state 
1107  * \param theState - Object state (vector of notebook variable)
1108  */
1109 //================================================================================
1110 void ObjectStates::AddState(const TState &theState)
1111 {
1112   _states.push_back(theState);
1113 }
1114
1115 //================================================================================
1116 /*!
1117  * \brief Increment object state
1118  */
1119 //================================================================================
1120 void ObjectStates::IncrementState()
1121 {
1122   _dumpstate++;
1123 }