Salome HOME
Join modifications from branch BR_DEBUG_3_2_0b1
[modules/smesh.git] / src / SMESH_I / SMESH_DumpPython.cxx
1 // Copyright (C) 2005  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
3 // 
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either 
7 // version 2.1 of the License.
8 // 
9 // This library is distributed in the hope that it will be useful 
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
12 // Lesser General Public License for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public  
15 // License along with this library; if not, write to the Free Software 
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 //
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 //
20 // File    : SMESH_Gen_i_DumpPython.cxx
21 // Created : Thu Mar 24 17:17:59 2005
22 // Author  : Julia DOROVSKIKH
23 // Module  : SMESH
24 // $Header : $
25
26 #include "SMESH_PythonDump.hxx"
27 #include "SMESH_Gen_i.hxx"
28 #include "SMESH_Filter_i.hxx"
29 #include "SMESH_MeshEditor_i.hxx"
30 #include "SMESH_2smeshpy.hxx"
31
32 #include <TColStd_HSequenceOfInteger.hxx>
33 #include <TCollection_AsciiString.hxx>
34
35
36 #ifdef _DEBUG_
37 static int MYDEBUG = 0;
38 #else
39 static int MYDEBUG = 0;
40 #endif
41
42 static TCollection_AsciiString NotPublishedObjectName()
43 {
44   return "__NOT__Published__Object__";
45 }
46
47 namespace SMESH
48 {
49
50   size_t TPythonDump::myCounter = 0;
51
52   TPythonDump::
53   TPythonDump()
54   {
55     ++myCounter;
56   }
57   TPythonDump::
58   ~TPythonDump()
59   {
60     if(--myCounter == 0){
61       SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
62       SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
63       if(!aStudy->_is_nil()){
64         std::string aString = myStream.str();
65         TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
66         aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
67         if(MYDEBUG) MESSAGE(aString);
68       }
69     }
70   }
71
72   TPythonDump& 
73   TPythonDump::
74   operator<<(long int theArg){
75     myStream<<theArg;
76     return *this;
77   }
78
79   TPythonDump& 
80   TPythonDump::
81   operator<<(int theArg){
82     myStream<<theArg;
83     return *this;
84   }
85
86   TPythonDump& 
87   TPythonDump::
88   operator<<(double theArg){
89     myStream<<theArg;
90     return *this;
91   }
92
93   TPythonDump& 
94   TPythonDump::
95   operator<<(float theArg){
96     myStream<<theArg;
97     return *this;
98   }
99
100   TPythonDump& 
101   TPythonDump::
102   operator<<(const void* theArg){
103     myStream<<theArg;
104     return *this;
105   }
106
107   TPythonDump& 
108   TPythonDump::
109   operator<<(const char* theArg){
110     if ( theArg )
111       myStream<<theArg;
112     return *this;
113   }
114
115   TPythonDump& 
116   TPythonDump::
117   operator<<(const SMESH::ElementType& theArg)
118   {
119     myStream<<"SMESH.";
120     switch(theArg){
121     case ALL:   myStream<<"ALL";break;
122     case NODE:  myStream<<"NODE";break;
123     case EDGE:  myStream<<"EDGE";break;
124     case FACE:  myStream<<"FACE";break;
125     case VOLUME:myStream<<"VOLUME";break;
126     }
127     return *this;
128   }
129
130   template<class TArray>
131   void DumpArray(const TArray& theArray, std::ostringstream & theStream)
132   {
133     theStream << "[ ";
134     for (int i = 1; i <= theArray.length(); i++) {
135       theStream << theArray[i-1];
136       if ( i < theArray.length() )
137         theStream << ", ";
138     }
139     theStream << " ]";
140   }
141
142   TPythonDump& 
143   TPythonDump::operator<<(const SMESH::long_array& theArg)
144   {
145     DumpArray( theArg, myStream );
146     return *this;
147   }
148
149   TPythonDump& 
150   TPythonDump::operator<<(const SMESH::double_array& theArg)
151   {
152     DumpArray( theArg, myStream );
153     return *this;
154   }
155
156   TPythonDump& 
157   TPythonDump::
158   operator<<(SALOMEDS::SObject_ptr aSObject)
159   {
160     if ( !aSObject->_is_nil() )
161       myStream << aSObject->GetID();
162     else
163       myStream << NotPublishedObjectName();
164     return *this;
165   }
166
167   TPythonDump& 
168   TPythonDump::
169   operator<<(CORBA::Object_ptr theArg)
170   {
171     SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
172     SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
173     SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
174     if(!aSObject->_is_nil()) {
175       myStream << aSObject->GetID();
176     } else if ( !CORBA::is_nil(theArg)) {
177       if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
178         myStream << "smeshObj_" << size_t(theArg);
179       else
180         myStream << NotPublishedObjectName();
181     }
182     else
183       myStream << "None";
184     return *this;
185   }
186
187   TPythonDump& 
188   TPythonDump::
189   operator<<(SMESH::FilterLibrary_i* theArg)
190   {
191     myStream<<"aFilterLibrary"<<theArg;
192     return *this;
193   }
194
195   TPythonDump& 
196   TPythonDump::
197   operator<<(SMESH::FilterManager_i* theArg)
198   {
199     myStream<<"aFilterManager";
200     return *this;
201   }
202
203   TPythonDump& 
204   TPythonDump::
205   operator<<(SMESH::Filter_i* theArg)
206   {
207     myStream<<"aFilter"<<theArg;
208     return *this;
209   }
210
211   TPythonDump& 
212   TPythonDump::
213   operator<<(SMESH::Functor_i* theArg)
214   {
215     if ( theArg ) {
216       FunctorType aFunctorType = theArg->GetFunctorType();
217       switch(aFunctorType){
218       case FT_AspectRatio:      myStream<< "anAspectRatio";     break;
219       case FT_AspectRatio3D:    myStream<< "anAspectRatio3D";   break;
220       case FT_Warping:          myStream<< "aWarping";          break;
221       case FT_MinimumAngle:     myStream<< "aMinimumAngle";     break;
222       case FT_Taper:            myStream<< "aTaper";            break;
223       case FT_Skew:             myStream<< "aSkew";             break;
224       case FT_Area:             myStream<< "aArea";             break;
225       case FT_FreeBorders:      myStream<< "aFreeBorders";      break;
226       case FT_FreeEdges:        myStream<< "aFreeEdges";        break;
227       case FT_MultiConnection:  myStream<< "aMultiConnection";  break;
228       case FT_MultiConnection2D:myStream<< "aMultiConnection2D";break;
229       case FT_Length:           myStream<< "aLength";           break;
230       case FT_Length2D:         myStream<< "aLength";           break;
231       case FT_BelongToGeom:     myStream<< "aBelongToGeom";     break;
232       case FT_BelongToPlane:    myStream<< "aBelongToPlane";    break;
233       case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
234       case FT_LyingOnGeom:      myStream<< "aLyingOnGeom";      break;
235       case FT_RangeOfIds:       myStream<< "aRangeOfIds";       break;
236       case FT_BadOrientedVolume:myStream<< "aBadOrientedVolume";break;
237       case FT_LessThan:         myStream<< "aLessThan";         break;
238       case FT_MoreThan:         myStream<< "aMoreThan";         break;
239       case FT_EqualTo:          myStream<< "anEqualTo";         break;
240       case FT_LogicalNOT:       myStream<< "aLogicalNOT";       break;
241       case FT_LogicalAND:       myStream<< "aLogicalAND";       break;
242       case FT_LogicalOR:        myStream<< "aLogicalOR";        break;
243       case FT_Undefined:        myStream<< "anUndefined";       break;
244       }
245       myStream<<theArg;
246     }
247     return *this;
248   }
249
250   TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
251   {
252     myStream << SMESHGenName(); return *this;
253   }
254
255   TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
256   {
257     myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
258   }
259
260   TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
261   {
262     myStream << theStr; return *this;
263   }
264
265
266   TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
267   {
268     switch (theVersion) {
269     case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
270     case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
271     default: myStream << theVersion;
272     }
273     return *this;
274   }
275
276   TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
277   {
278     myStream << "SMESH.AxisStruct( "
279              << theAxis.x  << ", "
280              << theAxis.y  << ", "
281              << theAxis.z  << ", "
282              << theAxis.vx << ", "
283              << theAxis.vy << ", "
284              << theAxis.vz << " )";
285     return *this;
286   }
287
288   TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
289   {
290     const SMESH::PointStruct & P = theDir.PS;
291     myStream << "SMESH.DirStruct( SMESH.PointStruct ( "
292              << P.x  << ", "
293              << P.y  << ", "
294              << P.z  << " ))";
295     return *this;
296   }
297
298   TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
299   TCollection_AsciiString myLongStringEnd  ( "TPythonDump::LongStringEnd" );
300
301   //================================================================================
302   /*!
303      * \brief Return marker of long string literal beginning
304       * \param type - a name of functionality producing the string literal 
305       * \retval TCollection_AsciiString - the marker string to be written into
306       * a raw python script
307    */
308   //================================================================================
309
310   TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
311   {
312     return
313       myLongStringStart +
314       (Standard_Integer) strlen(type) +
315       " " +
316       (char*) type;
317   }
318
319   //================================================================================
320   /*!
321      * \brief Return marker of long string literal end
322       * \retval TCollection_AsciiString - the marker string to be written into
323       * a raw python script
324    */
325   //================================================================================
326
327   TCollection_AsciiString TPythonDump::LongStringEnd()
328   {
329     return myLongStringEnd;
330   }
331
332   //================================================================================
333   /*!
334      * \brief Cut out a long string literal from a string
335       * \param theText - text possibly containing string literals
336       * \param theFrom - position in the text to search from
337       * \param theLongString - the retrieved literal
338       * \param theStringType - a name of functionality produced the literal
339       * \retval bool - true if a string literal found
340      * 
341      * The literal is removed from theText; theFrom points position right after
342      * the removed literal
343    */
344   //================================================================================
345
346   bool  TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
347                                        int                     & theFrom,
348                                        TCollection_AsciiString & theLongString,
349                                        TCollection_AsciiString & theStringType)
350   {
351     if ( theFrom < 1 || theFrom > theText.Length() )
352       return false;
353
354     // ...script \  beg marker    \ \ type \       literal              \  end marker  \ script...
355     //  "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
356     //  012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
357     //  0         1         2         3         4         5         6         7         8
358
359     theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
360     if ( !theFrom )
361       return false;
362
363     // find where literal begins
364     int literalBeg = theFrom + myLongStringStart.Length(); // = 26
365     char* typeLenStr = theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
366     int typeLen = atoi ( typeLenStr ); // = 7
367     while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
368       literalBeg++; // 26 -> 27
369       typeLenStr++;
370     }
371     literalBeg += typeLen + 1; // = 35
372     if ( literalBeg > theText.Length() )
373       return false;
374
375     // where literal ends (i.e. end marker begins)
376     int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
377     if ( !literalEnd )
378       literalEnd = theText.Length();
379
380     // literal
381     theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
382     // type
383     theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
384     // cut off literal
385     literalEnd += myLongStringEnd.Length(); // = 79
386     TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
387     theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
388
389     return true;
390   }
391 }
392
393 //=======================================================================
394 //function : DumpPython
395 //purpose  : 
396 //=======================================================================
397 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
398                                            CORBA::Boolean isPublished,
399                                            CORBA::Boolean& isValidScript)
400 {
401   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
402   if (CORBA::is_nil(aStudy))
403     return new Engines::TMPFile(0);
404
405   SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
406   if (CORBA::is_nil(aSO))
407     return new Engines::TMPFile(0);
408
409   // Map study entries to object names
410   Resource_DataMapOfAsciiStringAsciiString aMap;
411   Resource_DataMapOfAsciiStringAsciiString aMapNames;
412   //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
413
414   SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
415   for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
416     SALOMEDS::SObject_var aValue = Itr->Value();
417     CORBA::String_var anID = aValue->GetID();
418     CORBA::String_var aName = aValue->GetName();
419     TCollection_AsciiString aGUIName ( (char*) aName.in() );
420     TCollection_AsciiString anEnrty ( (char*) anID.in() );
421     if (aGUIName.Length() > 0) {
422       aMapNames.Bind( anEnrty, aGUIName );
423       aMap.Bind( anEnrty, aGUIName );
424     }
425   }
426
427   // Get trace of restored study
428   //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
429   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
430   SALOMEDS::GenericAttribute_var anAttr =
431     aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
432
433   char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
434   TCollection_AsciiString aSavedTrace (oldValue);
435
436   // Add trace of API methods calls and replace study entries by names
437   TCollection_AsciiString aScript =
438     "### This file is generated by SALOME automatically by dump python functionality of SMESH component\n\n";
439   aScript += DumpPython_impl(aStudy->StudyId(), aMap, aMapNames,
440                              isPublished, isValidScript, aSavedTrace);
441
442   int aLen = aScript.Length(); 
443   unsigned char* aBuffer = new unsigned char[aLen+1];
444   strcpy((char*)aBuffer, aScript.ToCString());
445
446   CORBA::Octet* anOctetBuf =  (CORBA::Octet*)aBuffer;
447   Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1); 
448
449   bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
450   isValidScript = isValidScript && !hasNotPublishedObjects;
451
452   return aStreamFile._retn(); 
453 }
454
455 //=============================================================================
456 /*!
457  *  AddToPythonScript
458  */
459 //=============================================================================
460 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
461 {
462   if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
463     myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
464   }
465   myPythonScripts[theStudyID]->Append(theString);
466 }
467
468 //=============================================================================
469 /*!
470  *  RemoveLastFromPythonScript
471  */
472 //=============================================================================
473 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
474 {
475   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
476     int aLen = myPythonScripts[theStudyID]->Length();
477     myPythonScripts[theStudyID]->Remove(aLen);
478   }
479 }
480
481 //=======================================================================
482 //function : SavePython
483 //purpose  : 
484 //=======================================================================
485 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
486 {
487   // Dump trace of API methods calls
488   TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
489
490   // Check contents of PythonObject attribute
491   SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
492   //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
493   SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
494   SALOMEDS::GenericAttribute_var anAttr =
495     aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
496
497   char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
498   TCollection_AsciiString oldScript (oldValue);
499
500   if (oldScript.Length() > 0) {
501     oldScript += "\n";
502     oldScript += aScript;
503   } else {
504     oldScript = aScript;
505   }
506
507   // Store in PythonObject attribute
508   SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
509
510   // Clean trace of API methods calls
511   CleanPythonTrace(theStudy->StudyId());
512 }
513
514
515 // impl
516
517
518 //=============================================================================
519 /*!
520  *  FindEntries: Returns a sequence of start/end positions of entries in the string
521  */
522 //=============================================================================
523 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
524 {
525   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
526   Standard_Integer aLen = theString.Length();
527   Standard_Boolean isFound = Standard_False;
528
529   char* arr = theString.ToCString();
530   Standard_Integer i = 0, j;
531
532   while(i < aLen) {
533     int c = (int)arr[i];
534     j = i+1;
535     if ( isdigit( c )) { //Is digit?
536  
537       isFound = Standard_False;
538       while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
539         c = (int)arr[j++];  
540         if(c == ':') isFound = Standard_True;
541       }
542
543       if (isFound) {
544         int prev = (i < 1) ? 0 : (int)arr[i - 1];
545         // to distinguish from a sketcher command:
546         // last char should be a digit, not ":",
547         // previous char should not be '"'.
548         if (arr[j-2] != ':' && prev != '"') {
549           aSeq->Append(i+1); // +1 because AsciiString starts from 1
550           aSeq->Append(j-1);
551         }
552       }
553     }
554
555     i = j;
556   }
557
558   return aSeq;
559 }
560
561 namespace {
562
563   //================================================================================
564   /*!
565    * \brief Make a string be a valid python name
566     * \param aName - a string to fix
567     * \retval bool - true if aName was not modified
568    */
569   //================================================================================
570
571   bool fixPythonName(TCollection_AsciiString & aName )
572   {
573     const TCollection_AsciiString allowedChars =
574       "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
575     bool isValidName = true;
576     int p=1; // replace not allowed chars with underscore
577     while (p <= aName.Length() &&
578            (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
579     {
580       if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
581         aName.Remove( p, 1 ); // remove double _ and from the start and the end
582       else
583         aName.SetValue(p, '_');
584       isValidName = false;
585     }
586     if ( aName.IsIntegerValue() ) { // aName must not start with a digit
587       aName.Insert( 1, 'a' );
588       isValidName = false;
589     }
590     return isValidName;
591   }
592 }
593
594 //=============================================================================
595 /*!
596  *  DumpPython
597  */
598 //=============================================================================
599 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
600                         (int theStudyID, 
601                          Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
602                          Resource_DataMapOfAsciiStringAsciiString& theNames,
603                          bool isPublished, 
604                          bool& aValidScript,
605                          const TCollection_AsciiString& theSavedTrace)
606 {
607   TCollection_AsciiString helper; // to comfortably concatenate C strings
608   TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
609   TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
610   TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
611
612   TCollection_AsciiString aScript;
613   aScript = "def RebuildData(theStudy):\n\t";
614   aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
615   if ( isPublished )
616     aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
617   else
618     aScript += aSMESHGen + ".SetCurrentStudy(None)";
619
620   // import python files corresponding to plugins
621   set<string> moduleNameSet;
622   map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
623   for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
624     string moduleName = hyp_creator->second->GetModuleName();
625     bool newModule = moduleNameSet.insert( moduleName ).second;
626     if ( newModule )
627       aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
628   }
629
630   // Dump trace of restored study
631   if (theSavedTrace.Length() > 0) {
632     // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
633     // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
634     // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
635     bool isNewVersion =
636       theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
637     if ( !isNewVersion ) {
638       TCollection_AsciiString aSavedTrace( theSavedTrace );
639       TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
640       int beg, end = aSavedTrace.Length(), from = 1;
641       while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
642         char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
643         if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
644           aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
645           end += gen.Length();
646         }
647         from = beg + aSmeshCall.Length();
648       }
649       aScript += helper + "\n" + aSavedTrace;
650     }
651     else
652       // append a saved trace to the script
653       aScript += helper + "\n" + theSavedTrace;
654   }
655
656   // Dump trace of API methods calls
657   TCollection_AsciiString aNewLines = GetNewPythonLines(theStudyID);
658   if (aNewLines.Length() > 0) {
659     aScript += helper + "\n" + aNewLines;
660   }
661
662   // Convert IDL API calls into smesh.py API.
663   // Some objects are wrapped with python classes and
664   // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
665   Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
666   aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod );
667
668   // Find entries to be replaced by names
669   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
670   Standard_Integer aLen = aSeq->Length();
671
672   if (aLen == 0)
673     return aScript;
674
675   // Replace entries by the names
676   GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
677   TColStd_SequenceOfAsciiString seqRemoved;
678   Resource_DataMapOfAsciiStringAsciiString mapRemoved;
679   Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
680   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
681
682   // Collect names of GEOM objects to exclude same names for SMESH objects
683   GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
684   int ign = 0, nbgn = aGeomNames->length();
685   for (; ign < nbgn; ign++) {
686     aName = aGeomNames[ign];
687     theObjectNames.Bind(aName, "1");
688   }
689
690   bool importGeom = false;
691   for (Standard_Integer i = 1; i <= aLen; i += 2) {
692     anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
693     anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
694     // is a GEOM object?
695     aName = geom->GetDumpName( anEntry.ToCString() );
696     if (aName.IsEmpty()) {
697       // is a SMESH object
698       if (theObjectNames.IsBound(anEntry)) {
699         // The Object is in Study
700         aName = theObjectNames.Find(anEntry);
701         // check validity of aName
702         bool isValidName = fixPythonName( aName );
703         if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
704           // diff objects have same name - make a new name by appending a digit
705           TCollection_AsciiString aName2;
706           Standard_Integer i = 0;
707           do {
708             aName2 = aName + "_" + ++i;
709           } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
710           aName = aName2;
711           isValidName = false;
712         }
713         if ( !isValidName )
714           theObjectNames(anEntry) = aName;
715
716       } else {
717         // Removed Object
718         do {
719           aName = aBaseName + (++objectCounter);
720         } while (theObjectNames.IsBound(aName));
721         seqRemoved.Append(aName);
722         mapRemoved.Bind(anEntry, "1");
723         theObjectNames.Bind(anEntry, aName);
724       }
725       theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
726     }
727     else
728     {
729       importGeom = true;
730     }
731     anUpdatedScript += aName;
732     aStart = aSeq->Value(i + 1) + 1;
733   }
734
735   // set initial part of aSript
736   TCollection_AsciiString initPart = "import salome, SMESH\n";
737   initPart += helper + "import " + aSmeshpy + "\n\n";
738   if ( importGeom )
739   {
740     initPart += ("## import GEOM dump file ## \n"
741                  "import string, os, sys, re\n"
742                  "sys.path.insert( 0, os.path.dirname(__file__) )\n"
743                  "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n\n");
744   }
745   anUpdatedScript.Insert ( 1, initPart );
746
747   // add final part of aScript
748   if (aSeq->Value(aLen) < aScriptLength)
749     anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
750
751   // Remove removed objects
752   if ( seqRemoved.Length() > 0 ) {
753     anUpdatedScript += "\n\t## some objects were removed";
754     anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
755   }
756   for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
757     anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
758     anUpdatedScript += seqRemoved.Value(ir);
759     // for object wrapped by class of smesh.py
760     anEntry = theObjectNames( seqRemoved.Value(ir) );
761     if ( anEntry2AccessorMethod.IsBound( anEntry ) )
762       anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
763     anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
764   }
765
766   // Set object names
767   anUpdatedScript += "\n\t## set object names";
768   anUpdatedScript += helper + "  \n\tisGUIMode = " + isPublished;
769   anUpdatedScript += "\n\tif isGUIMode and salome.sg.hasDesktop():";
770 //   anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
771 //   anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
772 //   anUpdatedScript += "\n";
773
774   TCollection_AsciiString aGUIName;
775   Resource_DataMapOfAsciiStringAsciiString mapEntries;
776   for (Standard_Integer i = 1; i <= aLen; i += 2)
777   {
778     anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
779     aName = geom->GetDumpName( anEntry.ToCString() );
780     if (aName.IsEmpty() && // Not a GEOM object
781         theNames.IsBound(anEntry) &&
782         !mapEntries.IsBound(anEntry) && // Not yet processed
783         !mapRemoved.IsBound(anEntry)) // Was not removed
784     {
785       aName = theObjectNames.Find(anEntry);
786       aGUIName = theNames.Find(anEntry);
787       mapEntries.Bind(anEntry, aName);
788       anUpdatedScript += helper + "\n\t\t" + aSmeshpy + ".SetName(" + aName;
789       if ( anEntry2AccessorMethod.IsBound( anEntry ) )
790         anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
791       anUpdatedScript += helper + ", '" + aGUIName + "')";
792     }
793   }
794   anUpdatedScript += "\n\n\t\tsalome.sg.updateObjBrowser(0)";
795
796   anUpdatedScript += "\n\n\tpass\n";
797
798   // -----------------------------------------------------------------
799   // put string literals describing patterns into separate functions
800   // -----------------------------------------------------------------
801
802   TCollection_AsciiString aLongString, aFunctionType;
803   int where = 1;
804   set< string > functionNameSet;
805   while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
806   {
807     // make a python string literal
808     aLongString.Prepend(":\n\treturn '''\n");
809     aLongString += "\n\t'''\n\tpass\n";
810
811     TCollection_AsciiString functionName;
812
813     // check if the function returning this literal is already defined
814     int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
815     if ( posAlready ) // already defined
816     {
817       // find the function name
818       int functBeg = posAlready;
819       char* script = anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
820       while ( *script != ' ' ) {
821         script--;
822         functBeg--;
823       }
824       functBeg++; // do not take ' '
825       posAlready--; // do not take ':'
826       functionName = anUpdatedScript.SubString( functBeg, posAlready );
827     }
828     else // not defined yet
829     {
830       // find a unique function name
831       fixPythonName( aFunctionType );
832       Standard_Integer nb = 0;
833       do functionName = aFunctionType + "_" + ( nb++ ) + "()";
834       while ( !functionNameSet.insert( functionName.ToCString() ).second );
835
836       anUpdatedScript += helper + "\n\ndef " + functionName + aLongString; // define function
837     }
838     anUpdatedScript.InsertBefore( where, functionName ); // call function
839   }
840
841   aValidScript = true;
842
843   return anUpdatedScript;
844 }
845
846 //=============================================================================
847 /*!
848  *  GetNewPythonLines
849  */
850 //=============================================================================
851 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
852 {
853   TCollection_AsciiString aScript;
854
855   // Dump trace of API methods calls
856   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
857     Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
858     Standard_Integer istr, aLen = aPythonScript->Length();
859     for (istr = 1; istr <= aLen; istr++) {
860       aScript += "\n\t";
861       aScript += aPythonScript->Value(istr);
862     }
863     aScript += "\n";
864   }
865
866   return aScript;
867 }
868
869 //=============================================================================
870 /*!
871  *  CleanPythonTrace
872  */
873 //=============================================================================
874 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
875 {
876   TCollection_AsciiString aScript;
877
878   // Clean trace of API methods calls
879   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
880     myPythonScripts[theStudyID]->Clear();
881   }
882 }