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