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