Salome HOME
Fix for issue 19964 EDF SMESH 803( Bad dump script of revolutionned mesh with groups).
[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_BelongToGenSurface:myStream<<"aBelongToGenSurface";break;
235       case FT_LyingOnGeom:      myStream<< "aLyingOnGeom";      break;
236       case FT_RangeOfIds:       myStream<< "aRangeOfIds";       break;
237       case FT_BadOrientedVolume:myStream<< "aBadOrientedVolume";break;
238       case FT_LessThan:         myStream<< "aLessThan";         break;
239       case FT_MoreThan:         myStream<< "aMoreThan";         break;
240       case FT_EqualTo:          myStream<< "anEqualTo";         break;
241       case FT_LogicalNOT:       myStream<< "aLogicalNOT";       break;
242       case FT_LogicalAND:       myStream<< "aLogicalAND";       break;
243       case FT_LogicalOR:        myStream<< "aLogicalOR";        break;
244       case FT_Undefined:        myStream<< "anUndefined";       break;
245       }
246       myStream<<theArg;
247     }
248     return *this;
249   }
250
251   TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
252   {
253     myStream << SMESHGenName(); return *this;
254   }
255
256   TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
257   {
258     myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
259   }
260
261   TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
262   {
263     myStream << theStr; return *this;
264   }
265
266
267   TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
268   {
269     switch (theVersion) {
270     case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
271     case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
272     default: myStream << theVersion;
273     }
274     return *this;
275   }
276
277   TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
278   {
279     myStream << "SMESH.AxisStruct( "
280              << theAxis.x  << ", "
281              << theAxis.y  << ", "
282              << theAxis.z  << ", "
283              << theAxis.vx << ", "
284              << theAxis.vy << ", "
285              << theAxis.vz << " )";
286     return *this;
287   }
288
289   TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
290   {
291     const SMESH::PointStruct & P = theDir.PS;
292     myStream << "SMESH.DirStruct( SMESH.PointStruct ( "
293              << P.x  << ", "
294              << P.y  << ", "
295              << P.z  << " ))";
296     return *this;
297   }
298
299   TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList){
300     if(theList && theList->length() > 0 ) {
301       SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
302       SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
303       myStream << "[";
304       int aListLen = theList->length();
305       for(int i = 0 ; i < aListLen; i++){
306         SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,(*theList)[i]);
307         if(!aSObject->_is_nil()) {
308           myStream << aSObject->GetID();
309           i < (aListLen - 1) ? myStream<<", " : myStream<<"]";
310         }
311         
312       }
313     }
314     return *this;
315   }
316
317   TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
318   TCollection_AsciiString myLongStringEnd  ( "TPythonDump::LongStringEnd" );
319
320   //================================================================================
321   /*!
322      * \brief Return marker of long string literal beginning
323       * \param type - a name of functionality producing the string literal 
324       * \retval TCollection_AsciiString - the marker string to be written into
325       * a raw python script
326    */
327   //================================================================================
328
329   TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
330   {
331     return
332       myLongStringStart +
333       (Standard_Integer) strlen(type) +
334       " " +
335       (char*) type;
336   }
337
338   //================================================================================
339   /*!
340      * \brief Return marker of long string literal end
341       * \retval TCollection_AsciiString - the marker string to be written into
342       * a raw python script
343    */
344   //================================================================================
345
346   TCollection_AsciiString TPythonDump::LongStringEnd()
347   {
348     return myLongStringEnd;
349   }
350
351   //================================================================================
352   /*!
353      * \brief Cut out a long string literal from a string
354       * \param theText - text possibly containing string literals
355       * \param theFrom - position in the text to search from
356       * \param theLongString - the retrieved literal
357       * \param theStringType - a name of functionality produced the literal
358       * \retval bool - true if a string literal found
359      * 
360      * The literal is removed from theText; theFrom points position right after
361      * the removed literal
362    */
363   //================================================================================
364
365   bool  TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
366                                        int                     & theFrom,
367                                        TCollection_AsciiString & theLongString,
368                                        TCollection_AsciiString & theStringType)
369   {
370     if ( theFrom < 1 || theFrom > theText.Length() )
371       return false;
372
373     // ...script \  beg marker    \ \ type \       literal              \  end marker  \ script...
374     //  "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
375     //  012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
376     //  0         1         2         3         4         5         6         7         8
377
378     theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
379     if ( !theFrom )
380       return false;
381
382     // find where literal begins
383     int literalBeg = theFrom + myLongStringStart.Length(); // = 26
384     char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
385     int typeLen = atoi ( typeLenStr ); // = 7
386     while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
387       literalBeg++; // 26 -> 27
388       typeLenStr++;
389     }
390     literalBeg += typeLen + 1; // = 35
391     if ( literalBeg > theText.Length() )
392       return false;
393
394     // where literal ends (i.e. end marker begins)
395     int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
396     if ( !literalEnd )
397       literalEnd = theText.Length();
398
399     // literal
400     theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
401     // type
402     theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
403     // cut off literal
404     literalEnd += myLongStringEnd.Length(); // = 79
405     TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
406     theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
407
408     return true;
409   }
410 }
411
412 //=======================================================================
413 //function : DumpPython
414 //purpose  : 
415 //=======================================================================
416 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
417                                            CORBA::Boolean isPublished,
418                                            CORBA::Boolean& isValidScript)
419 {
420   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
421   if (CORBA::is_nil(aStudy))
422     return new Engines::TMPFile(0);
423
424   SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
425   if (CORBA::is_nil(aSO))
426     return new Engines::TMPFile(0);
427
428   // Map study entries to object names
429   Resource_DataMapOfAsciiStringAsciiString aMap;
430   Resource_DataMapOfAsciiStringAsciiString aMapNames;
431   //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
432
433   SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
434   for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
435     SALOMEDS::SObject_var aValue = Itr->Value();
436     CORBA::String_var anID = aValue->GetID();
437     CORBA::String_var aName = aValue->GetName();
438     TCollection_AsciiString aGUIName ( (char*) aName.in() );
439     TCollection_AsciiString anEnrty ( (char*) anID.in() );
440     if (aGUIName.Length() > 0) {
441       aMapNames.Bind( anEnrty, aGUIName );
442       aMap.Bind( anEnrty, aGUIName );
443     }
444   }
445
446   // Get trace of restored study
447   //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
448   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
449   SALOMEDS::GenericAttribute_var anAttr =
450     aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
451
452   char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
453   TCollection_AsciiString aSavedTrace (oldValue);
454
455   // Add trace of API methods calls and replace study entries by names
456   TCollection_AsciiString aScript =
457     "### This file is generated by SALOME automatically by dump python functionality of SMESH component\n\n";
458   aScript += DumpPython_impl(aStudy->StudyId(), aMap, aMapNames,
459                              isPublished, isValidScript, aSavedTrace);
460
461   int aLen = aScript.Length(); 
462   unsigned char* aBuffer = new unsigned char[aLen+1];
463   strcpy((char*)aBuffer, aScript.ToCString());
464
465   CORBA::Octet* anOctetBuf =  (CORBA::Octet*)aBuffer;
466   Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1); 
467
468   bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
469   isValidScript = isValidScript && !hasNotPublishedObjects;
470
471   return aStreamFile._retn(); 
472 }
473
474 //=============================================================================
475 /*!
476  *  AddToPythonScript
477  */
478 //=============================================================================
479 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
480 {
481   if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
482     myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
483   }
484   myPythonScripts[theStudyID]->Append(theString);
485 }
486
487 //=============================================================================
488 /*!
489  *  RemoveLastFromPythonScript
490  */
491 //=============================================================================
492 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
493 {
494   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
495     int aLen = myPythonScripts[theStudyID]->Length();
496     myPythonScripts[theStudyID]->Remove(aLen);
497   }
498 }
499
500 //=======================================================================
501 //function : SavePython
502 //purpose  : 
503 //=======================================================================
504 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
505 {
506   // Dump trace of API methods calls
507   TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
508
509   // Check contents of PythonObject attribute
510   SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
511   //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
512   SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
513   SALOMEDS::GenericAttribute_var anAttr =
514     aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
515
516   char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
517   TCollection_AsciiString oldScript (oldValue);
518
519   if (oldScript.Length() > 0) {
520     oldScript += "\n";
521     oldScript += aScript;
522   } else {
523     oldScript = aScript;
524   }
525
526   // Store in PythonObject attribute
527   SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
528
529   // Clean trace of API methods calls
530   CleanPythonTrace(theStudy->StudyId());
531 }
532
533
534 // impl
535
536
537 //=============================================================================
538 /*!
539  *  FindEntries: Returns a sequence of start/end positions of entries in the string
540  */
541 //=============================================================================
542 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
543 {
544   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
545   Standard_Integer aLen = theString.Length();
546   Standard_Boolean isFound = Standard_False;
547
548   char* arr = (char*) theString.ToCString();
549   Standard_Integer i = 0, j;
550
551   while(i < aLen) {
552     int c = (int)arr[i];
553     j = i+1;
554     if ( isdigit( c )) { //Is digit?
555  
556       isFound = Standard_False;
557       while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
558         c = (int)arr[j++];  
559         if(c == ':') isFound = Standard_True;
560       }
561
562       if (isFound) {
563         int prev = (i < 1) ? 0 : (int)arr[i - 1];
564         // to distinguish from a sketcher command:
565         // last char should be a digit, not ":",
566         // previous char should not be '"'.
567         if (arr[j-2] != ':' && prev != '"') {
568           aSeq->Append(i+1); // +1 because AsciiString starts from 1
569           aSeq->Append(j-1);
570         }
571       }
572     }
573
574     i = j;
575   }
576
577   return aSeq;
578 }
579
580 namespace {
581
582   //================================================================================
583   /*!
584    * \brief Make a string be a valid python name
585     * \param aName - a string to fix
586     * \retval bool - true if aName was not modified
587    */
588   //================================================================================
589
590   bool fixPythonName(TCollection_AsciiString & aName )
591   {
592     const TCollection_AsciiString allowedChars =
593       "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
594     bool isValidName = true;
595     int p=1; // replace not allowed chars with underscore
596     while (p <= aName.Length() &&
597            (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
598     {
599       if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
600         aName.Remove( p, 1 ); // remove double _ and from the start and the end
601       else
602         aName.SetValue(p, '_');
603       isValidName = false;
604     }
605     if ( aName.IsIntegerValue() ) { // aName must not start with a digit
606       aName.Insert( 1, 'a' );
607       isValidName = false;
608     }
609     return isValidName;
610   }
611 }
612
613 //=============================================================================
614 /*!
615  *  DumpPython
616  */
617 //=============================================================================
618 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
619                         (int theStudyID, 
620                          Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
621                          Resource_DataMapOfAsciiStringAsciiString& theNames,
622                          bool isPublished, 
623                          bool& aValidScript,
624                          const TCollection_AsciiString& theSavedTrace)
625 {
626   TCollection_AsciiString helper; // to comfortably concatenate C strings
627   TCollection_AsciiString aSmeshpy( SMESH_2smeshpy::SmeshpyName() );
628   TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
629   TCollection_AsciiString anOldGen( SMESH::TPythonDump::SMESHGenName() );
630
631   TCollection_AsciiString aScript;
632   aScript = "def RebuildData(theStudy):\n\t";
633   aScript += helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()\n\t";
634   if ( isPublished )
635     aScript += aSMESHGen + ".SetCurrentStudy(theStudy)";
636   else
637     aScript += aSMESHGen + ".SetCurrentStudy(None)";
638
639   // import python files corresponding to plugins
640   set<string> moduleNameSet;
641   map<string, GenericHypothesisCreator_i*>::iterator hyp_creator = myHypCreatorMap.begin();
642   for ( ; hyp_creator != myHypCreatorMap.end(); ++hyp_creator ) {
643     string moduleName = hyp_creator->second->GetModuleName();
644     bool newModule = moduleNameSet.insert( moduleName ).second;
645     if ( newModule )
646       aScript += helper + "\n\t" + "import " + (char*) moduleName.c_str();
647   }
648
649   // Dump trace of restored study
650   if (theSavedTrace.Length() > 0) {
651     // For the convertion of IDL API calls -> smesh.py API, "smesh" standing for SMESH_Gen
652     // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
653     // Change "smesh" -> "smeshgen" in the trace saved before passage to smesh.py API
654     bool isNewVersion =
655       theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
656     if ( !isNewVersion ) {
657       TCollection_AsciiString aSavedTrace( theSavedTrace );
658       TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
659       int beg, end = aSavedTrace.Length(), from = 1;
660       while ( from < end && ( beg = aSavedTrace.Location( aSmeshCall, from, end ))) {
661         char charBefore = ( beg == 1 ) ? ' ' : aSavedTrace.Value( beg - 1 );
662         if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
663           aSavedTrace.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
664           end += gen.Length();
665         }
666         from = beg + aSmeshCall.Length();
667       }
668       aScript += helper + "\n" + aSavedTrace;
669     }
670     else
671       // append a saved trace to the script
672       aScript += helper + "\n" + theSavedTrace;
673   }
674
675   // Dump trace of API methods calls
676   TCollection_AsciiString aNewLines = GetNewPythonLines(theStudyID);
677   if (aNewLines.Length() > 0) {
678     aScript += helper + "\n" + aNewLines;
679   }
680
681   // Convert IDL API calls into smesh.py API.
682   // Some objects are wrapped with python classes and
683   // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
684   Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
685   aScript = SMESH_2smeshpy::ConvertScript( aScript, anEntry2AccessorMethod );
686
687   // Find entries to be replaced by names
688   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
689   Standard_Integer aLen = aSeq->Length();
690
691   if (aLen == 0)
692     return aScript;
693
694   // Replace entries by the names
695   GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
696   TColStd_SequenceOfAsciiString seqRemoved;
697   Resource_DataMapOfAsciiStringAsciiString mapRemoved;
698   Standard_Integer objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
699   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("smeshObj_");
700
701   // Collect names of GEOM objects to exclude same names for SMESH objects
702   GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
703   int ign = 0, nbgn = aGeomNames->length();
704   for (; ign < nbgn; ign++) {
705     aName = aGeomNames[ign];
706     theObjectNames.Bind(aName, "1");
707   }
708
709   bool importGeom = false;
710   for (Standard_Integer i = 1; i <= aLen; i += 2) {
711     anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i) - 1);
712     anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
713     // is a GEOM object?
714     aName = geom->GetDumpName( anEntry.ToCString() );
715     if (aName.IsEmpty()) {
716       // is a SMESH object
717       if (theObjectNames.IsBound(anEntry)) {
718         // The Object is in Study
719         aName = theObjectNames.Find(anEntry);
720         // check validity of aName
721         bool isValidName = fixPythonName( aName );
722         if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
723           // diff objects have same name - make a new name by appending a digit
724           TCollection_AsciiString aName2;
725           Standard_Integer i = 0;
726           do {
727             aName2 = aName + "_" + ++i;
728           } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
729           aName = aName2;
730           isValidName = false;
731         }
732         if ( !isValidName )
733           theObjectNames(anEntry) = aName;
734
735       } else {
736         // Removed Object
737         do {
738           aName = aBaseName + (++objectCounter);
739         } while (theObjectNames.IsBound(aName));
740         seqRemoved.Append(aName);
741         mapRemoved.Bind(anEntry, "1");
742         theObjectNames.Bind(anEntry, aName);
743       }
744       theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
745     }
746     else
747     {
748       importGeom = true;
749     }
750     anUpdatedScript += aName;
751     aStart = aSeq->Value(i + 1) + 1;
752   }
753
754   // set initial part of aSript
755   TCollection_AsciiString initPart = "import salome, SMESH\n";
756   initPart += helper + "import " + aSmeshpy + "\n\n";
757   if ( importGeom )
758   {
759     initPart += ("## import GEOM dump file ## \n"
760                  "import string, os, sys, re\n"
761                  "sys.path.insert( 0, os.path.dirname(__file__) )\n"
762                  "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",__name__)+\" import *\")\n\n");
763   }
764   anUpdatedScript.Insert ( 1, initPart );
765
766   // add final part of aScript
767   if (aSeq->Value(aLen) < aScriptLength)
768     anUpdatedScript += aScript.SubString(aSeq->Value(aLen) + 1, aScriptLength);
769
770
771   SMESH_Gen_i* aSMESHGenI = SMESH_Gen_i::GetSMESHGen();
772   SALOMEDS::Study_ptr aStudy = aSMESHGenI->GetCurrentStudy();
773   if( !CORBA::is_nil(aStudy) )
774   {
775     SALOMEDS::SObject_var aComp = aStudy->FindComponent(ComponentDataType());
776     if( !CORBA::is_nil(aComp) )
777     {
778       SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aComp);
779       for( Itr->InitEx(true); Itr->More(); Itr->Next() )
780       {
781         SALOMEDS::SObject_var aSObj = Itr->Value();
782         CORBA::String_var aName = aSObj->GetName();
783
784         SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_narrow( SMESH_Gen_i::SObjectToObject( aSObj ) );
785         if( !CORBA::is_nil(aMesh) )
786         {
787           bool isAutoColor = aMesh->GetAutoColor();
788           if( isAutoColor )
789           {
790             anUpdatedScript += "\n\t";
791             anUpdatedScript += (char*)aName.in();
792             anUpdatedScript += ".SetAutoColor(1)";
793           }
794         }
795  
796         SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( SMESH_Gen_i::SObjectToObject( aSObj ) );
797         if( !CORBA::is_nil(aGroup) )
798         {
799           SALOMEDS::Color aColor = aGroup->GetColor();
800           if ( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 )
801           {
802             anUpdatedScript += "\n\t";
803             anUpdatedScript += (char*)aName.in();
804             anUpdatedScript += ".SetColor(SALOMEDS.Color(";
805             anUpdatedScript += aColor.R;
806             anUpdatedScript += ",";
807             anUpdatedScript += aColor.G;
808             anUpdatedScript += ",";
809             anUpdatedScript += aColor.B;
810             anUpdatedScript += "))";
811           }
812         }
813       }
814     }
815   }
816
817   // Remove removed objects
818   if ( seqRemoved.Length() > 0 ) {
819     anUpdatedScript += "\n\t## some objects were removed";
820     anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
821   }
822   for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
823     anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
824     anUpdatedScript += seqRemoved.Value(ir);
825     // for object wrapped by class of smesh.py
826     anEntry = theObjectNames( seqRemoved.Value(ir) );
827     if ( anEntry2AccessorMethod.IsBound( anEntry ) )
828       anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
829     anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
830   }
831
832   // Set object names
833   anUpdatedScript += "\n\t## set object names";
834   anUpdatedScript += helper + "  \n\tisGUIMode = " + isPublished;
835   anUpdatedScript += "\n\tif isGUIMode and salome.sg.hasDesktop():";
836 //   anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
837 //   anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
838 //   anUpdatedScript += "\n";
839
840   TCollection_AsciiString aGUIName;
841   Resource_DataMapOfAsciiStringAsciiString mapEntries;
842   for (Standard_Integer i = 1; i <= aLen; i += 2)
843   {
844     anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
845     aName = geom->GetDumpName( anEntry.ToCString() );
846     if (aName.IsEmpty() && // Not a GEOM object
847         theNames.IsBound(anEntry) &&
848         !mapEntries.IsBound(anEntry) && // Not yet processed
849         !mapRemoved.IsBound(anEntry)) // Was not removed
850     {
851       aName = theObjectNames.Find(anEntry);
852       aGUIName = theNames.Find(anEntry);
853       mapEntries.Bind(anEntry, aName);
854       anUpdatedScript += helper + "\n\t\t" + aSmeshpy + ".SetName(" + aName;
855       if ( anEntry2AccessorMethod.IsBound( anEntry ) )
856         anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
857       anUpdatedScript += helper + ", '" + aGUIName + "')";
858     }
859   }
860   anUpdatedScript += "\n\n\t\tsalome.sg.updateObjBrowser(0)";
861
862   anUpdatedScript += "\n\n\tpass\n";
863
864   // -----------------------------------------------------------------
865   // put string literals describing patterns into separate functions
866   // -----------------------------------------------------------------
867
868   TCollection_AsciiString aLongString, aFunctionType;
869   int where = 1;
870   set< string > functionNameSet;
871   while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
872   {
873     // make a python string literal
874     aLongString.Prepend(":\n\treturn '''\n");
875     aLongString += "\n\t'''\n\tpass\n";
876
877     TCollection_AsciiString functionName;
878
879     // check if the function returning this literal is already defined
880     int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
881     if ( posAlready ) // already defined
882     {
883       // find the function name
884       int functBeg = posAlready;
885       char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
886       while ( *script != ' ' ) {
887         script--;
888         functBeg--;
889       }
890       functBeg++; // do not take ' '
891       posAlready--; // do not take ':'
892       functionName = anUpdatedScript.SubString( functBeg, posAlready );
893     }
894     else // not defined yet
895     {
896       // find a unique function name
897       fixPythonName( aFunctionType );
898       Standard_Integer nb = 0;
899       do functionName = aFunctionType + "_" + ( nb++ ) + "()";
900       while ( !functionNameSet.insert( functionName.ToCString() ).second );
901
902       anUpdatedScript += helper + "\n\ndef " + functionName + aLongString; // define function
903     }
904     anUpdatedScript.InsertBefore( where, functionName ); // call function
905   }
906
907   aValidScript = true;
908
909   return anUpdatedScript;
910 }
911
912 //=============================================================================
913 /*!
914  *  GetNewPythonLines
915  */
916 //=============================================================================
917 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
918 {
919   TCollection_AsciiString aScript;
920
921   // Dump trace of API methods calls
922   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
923     Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
924     Standard_Integer istr, aLen = aPythonScript->Length();
925     for (istr = 1; istr <= aLen; istr++) {
926       aScript += "\n\t";
927       aScript += aPythonScript->Value(istr);
928     }
929     aScript += "\n";
930   }
931
932   return aScript;
933 }
934
935 //=============================================================================
936 /*!
937  *  CleanPythonTrace
938  */
939 //=============================================================================
940 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
941 {
942   TCollection_AsciiString aScript;
943
944   // Clean trace of API methods calls
945   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
946     myPythonScripts[theStudyID]->Clear();
947   }
948 }