Salome HOME
Merge from V5_1_2_BR branch (14 July 2009)
[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 #include <SMESH_Comment.hxx>
37
38
39 #ifdef _DEBUG_
40 static int MYDEBUG = 0;
41 #else
42 static int MYDEBUG = 0;
43 #endif
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       std::string aString = myStream.str();
66       TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
67       SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
68       if(!aStudy->_is_nil() && !aCollection.IsEmpty()){
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   TPythonDump&
134   TPythonDump::
135   operator<<(const SMESH::GeometryType& theArg)
136   {
137     myStream<<"SMESH.";
138     switch(theArg){
139     case Geom_POINT:      myStream<<"Geom_POINT";      break;
140     case Geom_EDGE:       myStream<<"Geom_EDGE";       break;
141     case Geom_TRIANGLE:   myStream<<"Geom_TRIANGLE";   break;
142     case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
143     case Geom_POLYGON:    myStream<<"Geom_POLYGON";    break;
144     case Geom_TETRA:      myStream<<"Geom_TETRA";      break;
145     case Geom_PYRAMID:    myStream<<"Geom_PYRAMID";    break;
146     case Geom_HEXA:       myStream<<"Geom_HEXA";       break;
147     case Geom_PENTA:      myStream<<"Geom_PENTA";      break;
148     case Geom_POLYHEDRA:  myStream<<"Geom_POLYHEDRA";  break;
149    }
150     return *this;
151   }
152
153   template<class TArray>
154   void DumpArray(const TArray& theArray, std::ostringstream & theStream)
155   {
156     theStream << "[ ";
157     for (int i = 1; i <= theArray.length(); i++) {
158       theStream << theArray[i-1];
159       if ( i < theArray.length() )
160         theStream << ", ";
161     }
162     theStream << " ]";
163   }
164
165   TPythonDump& 
166   TPythonDump::operator<<(const SMESH::long_array& theArg)
167   {
168     DumpArray( theArg, myStream );
169     return *this;
170   }
171
172   TPythonDump& 
173   TPythonDump::operator<<(const SMESH::double_array& theArg)
174   {
175     DumpArray( theArg, myStream );
176     return *this;
177   }
178
179   TPythonDump& 
180   TPythonDump::
181   operator<<(SALOMEDS::SObject_ptr aSObject)
182   {
183     if ( !aSObject->_is_nil() )
184       myStream << aSObject->GetID();
185     else
186       myStream << NotPublishedObjectName();
187     return *this;
188   }
189
190   TPythonDump& 
191   TPythonDump::
192   operator<<(CORBA::Object_ptr theArg)
193   {
194     SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
195     SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
196     SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
197     if(!aSObject->_is_nil()) {
198       myStream << aSObject->GetID();
199     } else if ( !CORBA::is_nil(theArg)) {
200       if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
201         myStream << "smeshObj_" << size_t(theArg);
202       else
203         myStream << NotPublishedObjectName();
204     }
205     else
206       myStream << "None";
207     return *this;
208   }
209
210   TPythonDump& 
211   TPythonDump::
212   operator<<(SMESH::FilterLibrary_i* theArg)
213   {
214     myStream<<"aFilterLibrary"<<theArg;
215     return *this;
216   }
217
218   TPythonDump& 
219   TPythonDump::
220   operator<<(SMESH::FilterManager_i* theArg)
221   {
222     myStream<<"aFilterManager";
223     return *this;
224   }
225
226   TPythonDump& 
227   TPythonDump::
228   operator<<(SMESH::Filter_i* theArg)
229   {
230     myStream<<"aFilter"<<theArg;
231     return *this;
232   }
233
234   TPythonDump& 
235   TPythonDump::
236   operator<<(SMESH::Functor_i* theArg)
237   {
238     if ( theArg ) {
239       FunctorType aFunctorType = theArg->GetFunctorType();
240       switch(aFunctorType){
241       case FT_AspectRatio:      myStream<< "anAspectRatio";     break;
242       case FT_AspectRatio3D:    myStream<< "anAspectRatio3D";   break;
243       case FT_Warping:          myStream<< "aWarping";          break;
244       case FT_MinimumAngle:     myStream<< "aMinimumAngle";     break;
245       case FT_Taper:            myStream<< "aTaper";            break;
246       case FT_Skew:             myStream<< "aSkew";             break;
247       case FT_Area:             myStream<< "aArea";             break;
248       case FT_Volume3D:         myStream<< "aVolume3D";         break;
249       case FT_FreeBorders:      myStream<< "aFreeBorders";      break;
250       case FT_FreeEdges:        myStream<< "aFreeEdges";        break;
251       case FT_FreeNodes:        myStream<< "aFreeNodes";        break;
252       case FT_FreeFaces:        myStream<< "aFreeFaces";        break;
253       case FT_MultiConnection:  myStream<< "aMultiConnection";  break;
254       case FT_MultiConnection2D:myStream<< "aMultiConnection2D";break;
255       case FT_Length:           myStream<< "aLength";           break;
256       case FT_Length2D:         myStream<< "aLength";           break;
257       case FT_BelongToGeom:     myStream<< "aBelongToGeom";     break;
258       case FT_BelongToPlane:    myStream<< "aBelongToPlane";    break;
259       case FT_BelongToCylinder: myStream<< "aBelongToCylinder"; break;
260       case FT_BelongToGenSurface:myStream<<"aBelongToGenSurface";break;
261       case FT_LyingOnGeom:      myStream<< "aLyingOnGeom";      break;
262       case FT_RangeOfIds:       myStream<< "aRangeOfIds";       break;
263       case FT_BadOrientedVolume:myStream<< "aBadOrientedVolume";break;
264       case FT_LinearOrQuadratic:myStream<< "aLinearOrQuadratic";break;
265       case FT_GroupColor:       myStream<< "aGroupColor";       break;
266       case FT_ElemGeomType:     myStream<< "anElemGeomType";    break;
267       case FT_LessThan:         myStream<< "aLessThan";         break;
268       case FT_MoreThan:         myStream<< "aMoreThan";         break;
269       case FT_EqualTo:          myStream<< "anEqualTo";         break;
270       case FT_LogicalNOT:       myStream<< "aLogicalNOT";       break;
271       case FT_LogicalAND:       myStream<< "aLogicalAND";       break;
272       case FT_LogicalOR:        myStream<< "aLogicalOR";        break;
273       case FT_Undefined:
274       default:                  myStream<< "anUndefined";       break;
275       }
276       myStream<<theArg;
277     }
278     return *this;
279   }
280
281   TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
282   {
283     myStream << SMESHGenName(); return *this;
284   }
285
286   TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
287   {
288     myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
289   }
290
291   TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
292   {
293     myStream << theStr; return *this;
294   }
295
296
297   TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
298   {
299     switch (theVersion) {
300     case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
301     case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
302     default: myStream << theVersion;
303     }
304     return *this;
305   }
306
307   TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
308   {
309     myStream << "SMESH.AxisStruct( "
310              << theAxis.x  << ", "
311              << theAxis.y  << ", "
312              << theAxis.z  << ", "
313              << theAxis.vx << ", "
314              << theAxis.vy << ", "
315              << theAxis.vz << " )";
316     return *this;
317   }
318
319   TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
320   {
321     const SMESH::PointStruct & P = theDir.PS;
322     myStream << "SMESH.DirStruct( SMESH.PointStruct ( "
323              << P.x  << ", "
324              << P.y  << ", "
325              << P.z  << " ))";
326     return *this;
327   }
328
329   TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList){
330     if(theList && theList->length() > 0 ) {
331       SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
332       SALOMEDS::Study_ptr aStudy = aSMESHGen->GetCurrentStudy();
333       myStream << "[";
334       int aListLen = theList->length();
335       for(int i = 0 ; i < aListLen; i++){
336         SALOMEDS::SObject_var aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,(*theList)[i]);
337         if(!aSObject->_is_nil()) {
338           myStream << aSObject->GetID();
339           i < (aListLen - 1) ? myStream<<", " : myStream<<"]";
340         }
341         
342       }
343     }
344     return *this;
345   }
346
347   TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
348   TCollection_AsciiString myLongStringEnd  ( "TPythonDump::LongStringEnd" );
349
350   //================================================================================
351   /*!
352      * \brief Return marker of long string literal beginning
353       * \param type - a name of functionality producing the string literal 
354       * \retval TCollection_AsciiString - the marker string to be written into
355       * a raw python script
356    */
357   //================================================================================
358
359   TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
360   {
361     return
362       myLongStringStart +
363       (Standard_Integer) strlen(type) +
364       " " +
365       (char*) type;
366   }
367
368   //================================================================================
369   /*!
370      * \brief Return marker of long string literal end
371       * \retval TCollection_AsciiString - the marker string to be written into
372       * a raw python script
373    */
374   //================================================================================
375
376   TCollection_AsciiString TPythonDump::LongStringEnd()
377   {
378     return myLongStringEnd;
379   }
380
381   //================================================================================
382   /*!
383      * \brief Cut out a long string literal from a string
384       * \param theText - text possibly containing string literals
385       * \param theFrom - position in the text to search from
386       * \param theLongString - the retrieved literal
387       * \param theStringType - a name of functionality produced the literal
388       * \retval bool - true if a string literal found
389      * 
390      * The literal is removed from theText; theFrom points position right after
391      * the removed literal
392    */
393   //================================================================================
394
395   bool  TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
396                                        int                     & theFrom,
397                                        TCollection_AsciiString & theLongString,
398                                        TCollection_AsciiString & theStringType)
399   {
400     if ( theFrom < 1 || theFrom > theText.Length() )
401       return false;
402
403     // ...script \  beg marker    \ \ type \       literal              \  end marker  \ script...
404     //  "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
405     //  012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
406     //  0         1         2         3         4         5         6         7         8
407
408     theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
409     if ( !theFrom )
410       return false;
411
412     // find where literal begins
413     int literalBeg = theFrom + myLongStringStart.Length(); // = 26
414     char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
415     int typeLen = atoi ( typeLenStr ); // = 7
416     while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
417       literalBeg++; // 26 -> 27
418       typeLenStr++;
419     }
420     literalBeg += typeLen + 1; // = 35
421     if ( literalBeg > theText.Length() )
422       return false;
423
424     // where literal ends (i.e. end marker begins)
425     int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
426     if ( !literalEnd )
427       literalEnd = theText.Length();
428
429     // literal
430     theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
431     // type
432     theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
433     // cut off literal
434     literalEnd += myLongStringEnd.Length(); // = 79
435     TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
436     theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
437
438     return true;
439   }
440 }
441
442 //=======================================================================
443 //function : DumpPython
444 //purpose  : 
445 //=======================================================================
446 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
447                                            CORBA::Boolean isPublished,
448                                            CORBA::Boolean& isValidScript)
449 {
450   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
451   if (CORBA::is_nil(aStudy))
452     return new Engines::TMPFile(0);
453
454   SALOMEDS::SObject_var aSO = aStudy->FindComponent(ComponentDataType());
455   if (CORBA::is_nil(aSO))
456     return new Engines::TMPFile(0);
457
458   // Map study entries to object names
459   Resource_DataMapOfAsciiStringAsciiString aMap;
460   Resource_DataMapOfAsciiStringAsciiString aMapNames;
461   //TCollection_AsciiString s ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
462
463   SALOMEDS::ChildIterator_var Itr = aStudy->NewChildIterator(aSO);
464   for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
465     SALOMEDS::SObject_var aValue = Itr->Value();
466     CORBA::String_var anID = aValue->GetID();
467     CORBA::String_var aName = aValue->GetName();
468     TCollection_AsciiString aGUIName ( (char*) aName.in() );
469     TCollection_AsciiString anEnrty ( (char*) anID.in() );
470     if (aGUIName.Length() > 0) {
471       aMapNames.Bind( anEnrty, aGUIName );
472       aMap.Bind( anEnrty, aGUIName );
473     }
474   }
475
476   // Get trace of restored study
477   //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
478   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
479   SALOMEDS::GenericAttribute_var anAttr =
480     aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
481
482   char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
483   TCollection_AsciiString aSavedTrace (oldValue);
484
485   // Add trace of API methods calls and replace study entries by names
486   TCollection_AsciiString aScript =
487     "### This file is generated by SALOME automatically by dump python functionality of SMESH component\n\n";
488   aScript += DumpPython_impl(aStudy, aMap, aMapNames,
489                              isPublished, isValidScript, aSavedTrace);
490
491   int aLen = aScript.Length(); 
492   unsigned char* aBuffer = new unsigned char[aLen+1];
493   strcpy((char*)aBuffer, aScript.ToCString());
494
495   CORBA::Octet* anOctetBuf =  (CORBA::Octet*)aBuffer;
496   Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1); 
497
498   bool hasNotPublishedObjects = aScript.Location( NotPublishedObjectName(), 1, aLen);
499   isValidScript = isValidScript && !hasNotPublishedObjects;
500
501   return aStreamFile._retn(); 
502 }
503
504 //=============================================================================
505 /*!
506  *  AddToPythonScript
507  */
508 //=============================================================================
509 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
510 {
511   if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
512     myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
513   }
514   myPythonScripts[theStudyID]->Append(theString);
515 }
516
517 //=============================================================================
518 /*!
519  *  RemoveLastFromPythonScript
520  */
521 //=============================================================================
522 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
523 {
524   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
525     int aLen = myPythonScripts[theStudyID]->Length();
526     myPythonScripts[theStudyID]->Remove(aLen);
527   }
528 }
529
530 //=======================================================================
531 //function : SavePython
532 //purpose  : 
533 //=======================================================================
534 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
535 {
536   // Dump trace of API methods calls
537   TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
538
539   // Check contents of PythonObject attribute
540   SALOMEDS::SObject_var aSO = theStudy->FindComponent(ComponentDataType());
541   //SALOMEDS::SObject_var aSO = SMESH_Gen_i::ObjectToSObject(theStudy, _this());
542   SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
543   SALOMEDS::GenericAttribute_var anAttr =
544     aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
545
546   char* oldValue = SALOMEDS::AttributePythonObject::_narrow(anAttr)->GetObject();
547   TCollection_AsciiString oldScript (oldValue);
548
549   if (oldScript.Length() > 0) {
550     oldScript += "\n";
551     oldScript += aScript;
552   } else {
553     oldScript = aScript;
554   }
555
556   // Store in PythonObject attribute
557   SALOMEDS::AttributePythonObject::_narrow(anAttr)->SetObject(oldScript.ToCString(), 1);
558
559   // Clean trace of API methods calls
560   CleanPythonTrace(theStudy->StudyId());
561 }
562
563
564 // impl
565
566
567 //=============================================================================
568 /*!
569  *  FindEntries: Returns a sequence of start/end positions of entries in the string
570  */
571 //=============================================================================
572 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
573 {
574   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
575   Standard_Integer aLen = theString.Length();
576   Standard_Boolean isFound = Standard_False;
577
578   char* arr = (char*) theString.ToCString();
579   Standard_Integer i = 0, j;
580
581   while(i < aLen) {
582     int c = (int)arr[i];
583     j = i+1;
584     if ( isdigit( c )) { //Is digit?
585  
586       isFound = Standard_False;
587       while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
588         c = (int)arr[j++];  
589         if(c == ':') isFound = Standard_True;
590       }
591
592       if (isFound) {
593         int prev = (i < 1) ? 0 : (int)arr[i - 1];
594         // to distinguish from a sketcher command:
595         // last char should be a digit, not ":",
596         // previous char should not be '"'.
597         if (arr[j-2] != ':' && prev != '"') {
598           aSeq->Append(i+1); // +1 because AsciiString starts from 1
599           aSeq->Append(j-1);
600         }
601       }
602     }
603
604     i = j;
605   }
606
607   return aSeq;
608 }
609
610 namespace {
611
612   //================================================================================
613   /*!
614    * \brief Make a string be a valid python name
615     * \param aName - a string to fix
616     * \retval bool - true if aName was not modified
617    */
618   //================================================================================
619
620   bool fixPythonName(TCollection_AsciiString & aName )
621   {
622     const TCollection_AsciiString allowedChars =
623       "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_";
624     bool isValidName = true;
625     int p=1; // replace not allowed chars with underscore
626     while (p <= aName.Length() &&
627            (p = aName.FirstLocationNotInSet(allowedChars, p, aName.Length())))
628     {
629       if ( p == 1 || p == aName.Length() || aName.Value(p-1) == '_')
630         aName.Remove( p, 1 ); // remove double _ and from the start and the end
631       else
632         aName.SetValue(p, '_');
633       isValidName = false;
634     }
635     if ( aName.IsIntegerValue() ) { // aName must not start with a digit
636       aName.Insert( 1, 'a' );
637       isValidName = false;
638     }
639     return isValidName;
640   }
641 }
642
643 //=============================================================================
644 /*!
645  *  DumpPython
646  */
647 //=============================================================================
648 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
649                         (SALOMEDS::Study_ptr theStudy, 
650                          Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
651                          Resource_DataMapOfAsciiStringAsciiString& theNames,
652                          bool isPublished, 
653                          bool& aValidScript,
654                          const TCollection_AsciiString& theSavedTrace)
655 {
656   int aStudyID = theStudy->StudyId();
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(aStudyID);
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, theObjectNames );
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   // Set colors
803   SALOMEDS::SObject_var aComp = theStudy->FindComponent(ComponentDataType());
804   if( !CORBA::is_nil(aComp) )
805   {
806     SALOMEDS::ChildIterator_var Itr = theStudy->NewChildIterator(aComp);
807     for( Itr->InitEx(true); Itr->More(); Itr->Next() )
808     {
809       SALOMEDS::SObject_var aSObj = Itr->Value();
810       SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_narrow( SObjectToObject( aSObj ) );
811       // mesh auto color
812       if( !CORBA::is_nil(aMesh) && aMesh->GetAutoColor() )
813       {
814         CORBA::String_var anEntry = aSObj->GetID();
815         anUpdatedScript +=
816           SMESH_Comment("\n\t") << theObjectNames(anEntry.inout()) << ".SetAutoColor(1)";
817       }
818       SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( SObjectToObject(aSObj));
819       if( !CORBA::is_nil(aGroup) )
820       {
821         SALOMEDS::Color aColor = aGroup->GetColor();
822         if ( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 )
823         {
824           CORBA::String_var anEntry = aSObj->GetID();
825           anUpdatedScript += SMESH_Comment("\n\t")
826             << theObjectNames(anEntry.inout()) << ".SetColor(SALOMEDS.Color("
827             << aColor.R <<", "<< aColor.G <<", "<< aColor.B <<" ))";
828         }
829       }
830     }
831   }
832
833   // Remove removed objects
834   if ( seqRemoved.Length() > 0 ) {
835     anUpdatedScript += "\n\t## some objects were removed";
836     anUpdatedScript += "\n\taStudyBuilder = theStudy.NewBuilder()";
837   }
838   for (int ir = 1; ir <= seqRemoved.Length(); ir++) {
839     anUpdatedScript += "\n\tSO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
840     anUpdatedScript += seqRemoved.Value(ir);
841     // for object wrapped by class of smesh.py
842     anEntry = theObjectNames( seqRemoved.Value(ir) );
843     if ( anEntry2AccessorMethod.IsBound( anEntry ) )
844       anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
845     anUpdatedScript += "))\n\tif SO is not None: aStudyBuilder.RemoveObjectWithChildren(SO)";
846   }
847
848   // Set object names
849   anUpdatedScript += "\n\t## set object names";
850 //   anUpdatedScript += "\n\t\tsmeshgui = salome.ImportComponentGUI(\"SMESH\")";
851 //   anUpdatedScript += "\n\t\tsmeshgui.Init(theStudy._get_StudyId())";
852 //   anUpdatedScript += "\n";
853
854   TCollection_AsciiString aGUIName;
855   Resource_DataMapOfAsciiStringAsciiString mapEntries;
856   for (Standard_Integer i = 1; i <= aLen; i += 2)
857   {
858     anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i + 1));
859     aName = geom->GetDumpName( anEntry.ToCString() );
860     if (aName.IsEmpty() && // Not a GEOM object
861         theNames.IsBound(anEntry) &&
862         !mapEntries.IsBound(anEntry) && // Not yet processed
863         !mapRemoved.IsBound(anEntry)) // Was not removed
864     {
865       aName = theObjectNames.Find(anEntry);
866       aGUIName = theNames.Find(anEntry);
867       mapEntries.Bind(anEntry, aName);
868       anUpdatedScript += helper + "\n\t" + aSMESHGen + ".SetName(" + aName;
869       if ( anEntry2AccessorMethod.IsBound( anEntry ) )
870         anUpdatedScript += helper + "." + anEntry2AccessorMethod( anEntry );
871       anUpdatedScript += helper + ", '" + aGUIName + "')";
872     }
873   }
874   anUpdatedScript += "\n\tif salome.sg.hasDesktop():";
875   anUpdatedScript += "\n\t\tsalome.sg.updateObjBrowser(0)";
876
877   // -----------------------------------------------------------------
878   // store visual properties of displayed objects
879   // -----------------------------------------------------------------
880
881   if (isPublished)
882   {
883     //Output the script that sets up the visual parameters.
884     char* script = theStudy->GetDefaultScript(ComponentDataType(), "\t");
885     if (script && strlen(script) > 0) {
886       anUpdatedScript += "\n\n\t### Store presentation parameters of displayed objects\n";
887       anUpdatedScript += script;
888       CORBA::string_free(script);
889     }
890   }
891   anUpdatedScript += "\n\n\tpass\n";
892
893   // -----------------------------------------------------------------
894   // put string literals describing patterns into separate functions
895   // -----------------------------------------------------------------
896
897   TCollection_AsciiString aLongString, aFunctionType;
898   int where = 1;
899   set< string > functionNameSet;
900   while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
901   {
902     // make a python string literal
903     aLongString.Prepend(":\n\treturn '''\n");
904     aLongString += "\n\t'''\n\tpass\n";
905
906     TCollection_AsciiString functionName;
907
908     // check if the function returning this literal is already defined
909     int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
910     if ( posAlready ) // already defined
911     {
912       // find the function name
913       int functBeg = posAlready;
914       char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
915       while ( *script != ' ' ) {
916         script--;
917         functBeg--;
918       }
919       functBeg++; // do not take ' '
920       posAlready--; // do not take ':'
921       functionName = anUpdatedScript.SubString( functBeg, posAlready );
922     }
923     else // not defined yet
924     {
925       // find a unique function name
926       fixPythonName( aFunctionType );
927       Standard_Integer nb = 0;
928       do functionName = aFunctionType + "_" + ( nb++ ) + "()";
929       while ( !functionNameSet.insert( functionName.ToCString() ).second );
930
931       anUpdatedScript += helper + "\n\ndef " + functionName + aLongString; // define function
932     }
933     anUpdatedScript.InsertBefore( where, functionName ); // call function
934   }
935
936   aValidScript = true;
937
938   return anUpdatedScript;
939 }
940
941 //=============================================================================
942 /*!
943  *  GetNewPythonLines
944  */
945 //=============================================================================
946 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
947 {
948   TCollection_AsciiString aScript;
949
950   // Dump trace of API methods calls
951   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
952     Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
953     Standard_Integer istr, aLen = aPythonScript->Length();
954     for (istr = 1; istr <= aLen; istr++) {
955       aScript += "\n\t";
956       aScript += aPythonScript->Value(istr);
957     }
958     aScript += "\n";
959   }
960
961   return aScript;
962 }
963
964 //=============================================================================
965 /*!
966  *  CleanPythonTrace
967  */
968 //=============================================================================
969 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
970 {
971   TCollection_AsciiString aScript;
972
973   // Clean trace of API methods calls
974   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
975     myPythonScripts[theStudyID]->Clear();
976   }
977 }