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