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