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