Salome HOME
Update from BR_V5_DEV 13Feb2009
[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   // not to process twice
716   if (theProcessed.Contains(theFunction->GetEntry())) return;
717   theProcessed.Add(theFunction->GetEntry());
718
719   // pass functions, that depends on nonexisting ones
720   bool doNotProcess = false;
721   TDF_LabelSequence aSeq;
722   theFunction->GetDependency(aSeq);
723   Standard_Integer aLen = aSeq.Length();
724   for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
725     TDF_Label aRefLabel = aSeq.Value(i);
726     Handle(TDF_Reference) aRef;
727     if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
728       doNotProcess = true;
729     }
730     else {
731       if (aRef.IsNull() || aRef->Get().IsNull()) {
732         doNotProcess = true;
733       }
734       else {
735         Handle(TDataStd_TreeNode) aT;
736         if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
737           doNotProcess = true;
738         }
739         else {
740           TDF_Label aDepLabel = aT->Label();
741           Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
742
743           if (aFunction.IsNull()) doNotProcess = true;
744           else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
745         }
746       }
747     }
748   }
749
750   if (doNotProcess) {
751     TCollection_AsciiString anObjEntry;
752     TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
753     theIgnoreObjs.insert(anObjEntry.ToCString());
754     return;
755   }
756
757   TCollection_AsciiString aDescr = theFunction->GetDescription();
758   if(aDescr.Length() == 0) return;
759
760   //Check if its internal function which doesn't requires dumping
761   if(aDescr == "None") return;
762
763   //Replace parameter by notebook variables
764   ReplaceVariables(aDescr,theVariables);
765   theScript += "\n\t";
766   theScript += aDescr;
767 }
768
769 //=============================================================================
770 /*!
771  *  FindEntries: Returns a sequence of start/end positions of entries in the string
772  */
773 //=============================================================================
774 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
775 {
776   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
777   Standard_Integer aLen = theString.Length();
778   Standard_Boolean isFound = Standard_False;
779
780   const char* arr = theString.ToCString();
781   Standard_Integer i = 0, j;
782
783   while(i < aLen) {
784     int c = (int)arr[i];
785     j = i+1;
786     if(c >= 48 && c <= 57) { //Is digit?
787
788       isFound = Standard_False;
789       while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
790         c = (int)arr[j++];
791         if(c == 58) isFound = Standard_True;
792       }
793
794       if(isFound && arr[j-2] != 58) { // last char should be a diggit
795         aSeq->Append(i+1); // +1 because AsciiString starts from 1
796         aSeq->Append(j-1);
797       }
798     }
799
800     i = j;
801   }
802
803   return aSeq;
804 }
805
806 //=============================================================================
807 /*!
808  *  ReplaceVariables: Replace parameters of the function by variales from 
809  *                    Notebook if need
810  */
811 //=============================================================================
812 void ReplaceVariables(TCollection_AsciiString& theCommand, 
813                       const TVariablesList&    theVariables)
814 {
815   if (MYDEBUG)
816     cout<<"Command : "<<theCommand<<endl;
817
818   if (MYDEBUG) {
819     cout<<"All Entries:"<<endl;
820     TVariablesList::const_iterator it = theVariables.begin();
821     for(;it != theVariables.end();it++)
822       cout<<"\t'"<<(*it).first<<"'"<<endl;
823   }
824
825   //Additional case - multi-row commands
826   int aCommandIndex = 1;
827   while( aCommandIndex < 10 ) { // tmp check
828     TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
829     if( aCommand.Length() == 0 )
830       break;
831
832     if (MYDEBUG)
833       cout<<"Sub-command : "<<aCommand<<endl;
834
835     Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
836     Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
837
838     //Get Entry of the result object
839     TCollection_AsciiString anEntry;
840     if( aCommand.Search("=") != -1 ) // command returns an object
841       anEntry = aCommand.Token("=",1);
842     else { // command modifies the object
843       int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length());
844       int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length());
845       anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
846     }
847
848     //Remove white spaces
849     anEntry.RightAdjust();
850     anEntry.LeftAdjust();
851     if(MYDEBUG)
852       cout<<"Result entry : '" <<anEntry<<"'"<<endl;
853
854     //Check if result is list of entries - enough to get the first entry in this case
855     int aNbEntries = 1;
856     if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
857       while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
858         aNbEntries++;
859       TCollection_AsciiString aSeparator(COMMA);
860       anEntry = anEntry.Token(aSeparator.ToCString(),1);
861       anEntry.Remove( 1, 1 );
862       anEntry.RightAdjust();
863       anEntry.LeftAdjust();
864       if(MYDEBUG)
865         cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
866     }
867     
868     //Find variables used for object construction
869     ObjectStates* aStates = 0;
870     TVariablesList::const_iterator it = theVariables.find(anEntry);
871     if( it != theVariables.end() )
872       aStates = (*it).second;
873
874     if(!aStates) {
875       if(MYDEBUG)
876         cout<<"Valiables list empty!!!"<<endl;
877       aCommandIndex++;
878       continue;
879     }
880
881     TState aVariables = aStates->GetCurrectState();
882
883     if(MYDEBUG) {
884       cout<<"Variables from SObject:"<<endl;
885       for (int i = 0; i < aVariables.size();i++)
886         cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
887     }
888
889     //Calculate total number of parameters
890     Standard_Integer aTotalNbParams = 1;
891     while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
892       aTotalNbParams++;
893
894     if(MYDEBUG)
895       cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
896
897     Standard_Integer aFirstParam = aNbEntries;
898
899     //Replace parameters by variables
900     Standard_Integer aStartPos = 0;
901     Standard_Integer aEndPos = 0;
902     int iVar = 0;
903     TCollection_AsciiString aVar, aReplacedVar;
904     for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
905       //Replace first parameter (bettwen '(' character and first ',' character)
906       if(i == aFirstParam)
907       {
908         aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
909         if(aTotalNbParams - aNbEntries > 0 )
910           aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
911         else
912           aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length()); 
913       }
914       //Replace last parameter (bettwen ',' character and ')' character)
915       else if(i == aTotalNbParams)
916       {
917         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
918         aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
919       }
920       //Replace other parameters (bettwen two ',' characters)
921       else if(i != aFirstParam && i != aTotalNbParams )
922       {
923         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
924         aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
925       }
926
927       if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
928         aStartPos++;
929       if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
930         aEndPos--;
931
932       if(MYDEBUG) 
933         cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
934
935       aVar = aCommand.SubString(aStartPos, aEndPos-1);
936       aVar.RightAdjust();
937       aVar.LeftAdjust();
938     
939       if(MYDEBUG) 
940         cout<<"Variable: '"<< aVar <<"'"<<endl;
941
942       // specific case for sketcher
943       if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
944         Standard_Integer aNbSections = 1;
945         while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
946           aNbSections++;
947         aNbSections--;
948
949         int aStartSectionPos = 0, aEndSectionPos = 0;
950         TCollection_AsciiString aSection, aReplacedSection;
951         for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
952           aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
953           if( aSectionIndex != aNbSections )
954             aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
955           else
956             aEndSectionPos = aVar.Length();
957
958           aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
959           if(MYDEBUG) 
960             cout<<"aSection: "<<aSection<<endl;
961
962           Standard_Integer aNbParams = 1;
963           while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
964             aNbParams++;
965           aNbParams--;
966
967           int aStartParamPos = 0, aEndParamPos = 0;
968           TCollection_AsciiString aParameter, aReplacedParameter;
969           for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
970             aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
971             if( aParamIndex != aNbParams )
972               aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
973             else
974               aEndParamPos = aSection.Length() + 1;
975
976             aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
977             if(MYDEBUG) 
978               cout<<"aParameter: "<<aParameter<<endl;
979
980             if(iVar >= aVariables.size())
981               continue;
982
983             aReplacedParameter = aVariables[iVar].myVariable;
984             if(aReplacedParameter.IsEmpty()) {
985               iVar++;
986               continue;
987             }
988
989             if(aVariables[iVar].isVariable) {
990               aReplacedParameter.InsertBefore(1,"'");
991               aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
992             }
993
994             if(MYDEBUG) 
995               cout<<"aSection before : "<<aSection<<endl;
996             aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
997             aSection.Insert(aStartParamPos, aReplacedParameter);
998             if(MYDEBUG) 
999               cout<<"aSection after  : "<<aSection<<endl<<endl;
1000             iVar++;
1001           }
1002           if(MYDEBUG) 
1003             cout<<"aVar before : "<<aVar<<endl;
1004           aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1005           aVar.Insert(aStartSectionPos, aSection);
1006           if(MYDEBUG) 
1007             cout<<"aVar after  : "<<aVar<<endl<<endl;
1008         }
1009
1010         if(MYDEBUG) 
1011           cout<<"aCommand before : "<<aCommand<<endl;
1012         aCommand.Remove(aStartPos, aEndPos - aStartPos);
1013         aCommand.Insert(aStartPos, aVar);
1014         if(MYDEBUG) 
1015           cout<<"aCommand after  : "<<aCommand<<endl;
1016
1017         break;
1018       } // end of specific case for sketcher
1019
1020       //If parameter is entry or 'None', skip it
1021       if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1022         continue;
1023
1024       if(iVar >= aVariables.size())
1025         continue;
1026
1027       aReplacedVar = aVariables[iVar].myVariable;
1028       if(aReplacedVar.IsEmpty()) {
1029         iVar++;
1030         continue;
1031       }
1032
1033       if(aVariables[iVar].isVariable) {
1034         aReplacedVar.InsertBefore(1,"\"");
1035         aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1036       }
1037
1038       aCommand.Remove(aStartPos, aEndPos - aStartPos);
1039       aCommand.Insert(aStartPos, aReplacedVar);
1040       iVar++;
1041     }
1042
1043     theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1044     theCommand.Insert(aStartCommandPos, aCommand);
1045
1046     aCommandIndex++;
1047
1048     aStates->IncrementState();
1049   }
1050
1051   if (MYDEBUG)
1052     cout<<"Command : "<<theCommand<<endl;
1053 }
1054
1055 //================================================================================
1056 /*!
1057  * \brief Constructor
1058  */
1059 //================================================================================
1060 ObjectStates::ObjectStates()
1061 {
1062   _dumpstate = 0;
1063 }
1064
1065 //================================================================================
1066 /*!
1067  * \brief Destructor
1068  */
1069 //================================================================================
1070 ObjectStates::~ObjectStates()
1071 {
1072 }
1073
1074 //================================================================================
1075 /*!
1076  * \brief Return current object state
1077  * \retval state - Object state (vector of notebook variable)
1078  */
1079 //================================================================================
1080 TState ObjectStates::GetCurrectState() const
1081 {
1082   if(_states.size() > _dumpstate)
1083     return _states[_dumpstate];
1084   return TState();
1085 }
1086
1087 //================================================================================
1088 /*!
1089  * \brief Add new object state 
1090  * \param theState - Object state (vector of notebook variable)
1091  */
1092 //================================================================================
1093 void ObjectStates::AddState(const TState &theState)
1094 {
1095   _states.push_back(theState);
1096 }
1097
1098 //================================================================================
1099 /*!
1100  * \brief Increment object state
1101  */
1102 //================================================================================
1103 void ObjectStates::IncrementState()
1104 {
1105   _dumpstate++;
1106 }