Salome HOME
Increment version: 8.5.0
[modules/smesh.git] / src / SMESH_I / SMESH_DumpPython.cxx
1 // Copyright (C) 2007-2016  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, or (at your option) any later version.
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_DumpPython.cxx
23 //  Created : Thu Mar 24 17:17:59 2005
24 //  Author  : Julia DOROVSKIKH
25 //  Module  : SMESH
26
27 #include "SMESH_PythonDump.hxx"
28
29 #include "SMESH_2smeshpy.hxx"
30 #include "SMESH_Comment.hxx"
31 #include "SMESH_Filter_i.hxx"
32 #include "SMESH_Gen_i.hxx"
33 #include "SMESH_MeshEditor_i.hxx"
34
35 #include <SALOMEDS_wrap.hxx>
36
37 #include <LDOMParser.hxx>
38 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include <TColStd_HSequenceOfInteger.hxx>
40 #include <TCollection_AsciiString.hxx>
41
42 #ifdef _DEBUG_
43 static int MYDEBUG = 0;
44 #else
45 static int MYDEBUG = 0;
46 #endif
47
48 #include "SMESH_TryCatch.hxx"
49
50 namespace SMESH
51 {
52
53   size_t TPythonDump::myCounter = 0;
54   const char theNotPublishedObjectName[] = "__NOT__Published__Object__";
55
56   TVar::TVar(CORBA::Double value):myVals(1), myIsList(false) { myVals[0] = SMESH_Comment(value); }
57   TVar::TVar(CORBA::Long   value):myVals(1), myIsList(false) { myVals[0] = SMESH_Comment(value); }
58   TVar::TVar(CORBA::Short  value):myVals(1), myIsList(false) { myVals[0] = SMESH_Comment(value); }
59   TVar::TVar(const SMESH::double_array& value):myVals(value.length()), myIsList(true)
60   {
61     for ( size_t i = 0; i < value.length(); i++)
62       myVals[i] = SMESH_Comment(value[i]);
63   }
64
65   TPythonDump::
66   TPythonDump():myVarsCounter(0)
67   {
68     ++myCounter;
69   }
70   TPythonDump::
71   ~TPythonDump()
72   {
73     if(--myCounter == 0){
74       SMESH_Gen_i* aSMESHGen = SMESH_Gen_i::GetSMESHGen();
75       std::string aString = myStream.str();
76       TCollection_AsciiString aCollection(Standard_CString(aString.c_str()));
77       SALOMEDS::Study_var aStudy = aSMESHGen->GetCurrentStudy();
78       if(!aStudy->_is_nil() && !aCollection.IsEmpty())
79       {
80         const std::string & objEntry = SMESH_Gen_i::GetSMESHGen()->GetLastObjEntry();
81         if ( !objEntry.empty() )
82           aCollection += (TVar::ObjPrefix() + objEntry ).c_str();
83         aSMESHGen->AddToPythonScript(aStudy->StudyId(),aCollection);
84         if(MYDEBUG) MESSAGE(aString);
85         // prevent misuse of already treated variables
86         aSMESHGen->UpdateParameters(CORBA::Object_var().in(),"");
87       }
88     }
89   }
90
91   TPythonDump& //!< store a variable value. Write either a value or '$varID$'
92   TPythonDump::
93   operator<<(const TVar& theVarValue)
94   {
95     const std::vector< int >& varIDs = SMESH_Gen_i::GetSMESHGen()->GetLastParamIndices();
96     if ( theVarValue.myIsList )
97     {
98       myStream << "[ ";
99       for ( size_t i = 1; i <= theVarValue.myVals.size(); ++i )
100       {
101         if ( myVarsCounter < (int)varIDs.size() && varIDs[ myVarsCounter ] >= 0 )
102           myStream << TVar::Quote() << varIDs[ myVarsCounter ] << TVar::Quote();
103         else
104           myStream << theVarValue.myVals[i-1];
105         if ( i < theVarValue.myVals.size() )
106           myStream << ", ";
107         ++myVarsCounter;
108       }
109       myStream << " ]";
110     }
111     else
112     {
113       if ( myVarsCounter < (int)varIDs.size() && varIDs[ myVarsCounter ] >= 0 )
114         myStream << TVar::Quote() << varIDs[ myVarsCounter ] << TVar::Quote();
115       else
116         myStream << theVarValue.myVals[0];
117       ++myVarsCounter;
118     }
119     return *this;
120   }
121
122   TPythonDump&
123   TPythonDump::
124   operator<<(long int theArg){
125     myStream<<theArg;
126     return *this;
127   }
128
129   TPythonDump&
130   TPythonDump::
131   operator<<(int theArg){
132     myStream<<theArg;
133     return *this;
134   }
135
136   TPythonDump&
137   TPythonDump::
138   operator<<(double theArg){
139     myStream<<theArg;
140     return *this;
141   }
142
143   TPythonDump&
144   TPythonDump::
145   operator<<(float theArg){
146     myStream<<theArg;
147     return *this;
148   }
149
150   TPythonDump&
151   TPythonDump::
152   operator<<(const void* theArg){
153     myStream<<theArg;
154     return *this;
155   }
156
157   TPythonDump&
158   TPythonDump::
159   operator<<(const char* theArg){
160     if ( theArg )
161       myStream<<theArg;
162     return *this;
163   }
164
165   TPythonDump&
166   TPythonDump::
167   operator<<(const std::string& theArg){
168     myStream<<theArg;
169     return *this;
170   }
171
172   TPythonDump&
173   TPythonDump::
174   operator<<(const SMESH::ElementType& theArg)
175   {
176     myStream<<"SMESH.";
177     switch(theArg){
178     case ALL:    myStream<<"ALL";    break;
179     case NODE:   myStream<<"NODE";   break;
180     case EDGE:   myStream<<"EDGE";   break;
181     case FACE:   myStream<<"FACE";   break;
182     case VOLUME: myStream<<"VOLUME"; break;
183     case ELEM0D: myStream<<"ELEM0D"; break;
184     case BALL:   myStream<<"BALL";   break;
185     default:     myStream<<"__UNKNOWN__ElementType: " << theArg;
186     }
187     return *this;
188   }
189
190   TPythonDump&
191   TPythonDump::
192   operator<<(const SMESH::GeometryType& theArg)
193   {
194     myStream<<"SMESH.";
195     switch(theArg){
196     case Geom_POINT:      myStream<<"Geom_POINT";      break;
197     case Geom_EDGE:       myStream<<"Geom_EDGE";       break;
198     case Geom_TRIANGLE:   myStream<<"Geom_TRIANGLE";   break;
199     case Geom_QUADRANGLE: myStream<<"Geom_QUADRANGLE"; break;
200     case Geom_POLYGON:    myStream<<"Geom_POLYGON";    break;
201     case Geom_TETRA:      myStream<<"Geom_TETRA";      break;
202     case Geom_PYRAMID:    myStream<<"Geom_PYRAMID";    break;
203     case Geom_HEXA:       myStream<<"Geom_HEXA";       break;
204     case Geom_PENTA:      myStream<<"Geom_PENTA";      break;
205     case Geom_POLYHEDRA:  myStream<<"Geom_POLYHEDRA";  break;
206     case Geom_BALL:       myStream<<"Geom_BALL";       break;
207     default:    myStream<<"__UNKNOWN__GeometryType: " << theArg;
208     }
209     return *this;
210   }
211   TPythonDump&
212   TPythonDump::
213   operator<<(const SMESH::EntityType& theArg)
214   {
215     myStream<<"SMESH.";
216     switch(theArg){
217     case Entity_0D:                myStream<<"Entity_0D";                break;
218     case Entity_Edge:              myStream<<"Entity_Edge";              break;
219     case Entity_Quad_Edge:         myStream<<"Entity_Quad_Edge";         break;
220     case Entity_Triangle:          myStream<<"Entity_Triangle";          break;
221     case Entity_Quad_Triangle:     myStream<<"Entity_Quad_Triangle";     break;
222     case Entity_BiQuad_Triangle:   myStream<<"Entity_BiQuad_Triangle";   break;
223     case Entity_Quadrangle:        myStream<<"Entity_Quadrangle";        break;
224     case Entity_Quad_Quadrangle:   myStream<<"Entity_Quad_Quadrangle";   break;
225     case Entity_BiQuad_Quadrangle: myStream<<"Entity_BiQuad_Quadrangle"; break;
226     case Entity_Polygon:           myStream<<"Entity_Polygon";           break;
227     case Entity_Quad_Polygon:      myStream<<"Entity_Quad_Polygon";      break;
228     case Entity_Tetra:             myStream<<"Entity_Tetra";             break;
229     case Entity_Quad_Tetra:        myStream<<"Entity_Quad_Tetra";        break;
230     case Entity_Pyramid:           myStream<<"Entity_Pyramid";           break;
231     case Entity_Quad_Pyramid:      myStream<<"Entity_Quad_Pyramid";      break;
232     case Entity_Hexa:              myStream<<"Entity_Hexa";              break;
233     case Entity_Quad_Hexa:         myStream<<"Entity_Quad_Hexa";         break;
234     case Entity_TriQuad_Hexa:      myStream<<"Entity_TriQuad_Hexa";      break;
235     case Entity_Penta:             myStream<<"Entity_Penta";             break;
236     case Entity_Quad_Penta:        myStream<<"Entity_Quad_Penta";        break;
237     case Entity_BiQuad_Penta:      myStream<<"Entity_BiQuad_Penta";      break;
238     case Entity_Hexagonal_Prism:   myStream<<"Entity_Hexagonal_Prism";   break;
239     case Entity_Polyhedra:         myStream<<"Entity_Polyhedra";         break;
240     case Entity_Quad_Polyhedra:    myStream<<"Entity_Quad_Polyhedra";    break;
241     case Entity_Ball:              myStream<<"Entity_Ball";              break;
242     case Entity_Last:              myStream<<"Entity_Last";              break;
243     default:    myStream<<"__UNKNOWN__EntityType: " << theArg;
244     }
245     return *this;
246   }
247
248   template<class TArray>
249   void DumpArray(const TArray& theArray, TPythonDump & theStream)
250   {
251     if ( theArray.length() == 0 )
252     {
253       theStream << "[]";
254     }
255     else
256     {
257       theStream << "[ ";
258       for (CORBA::ULong i = 1; i <= theArray.length(); i++) {
259         theStream << theArray[i-1];
260         if ( i < theArray.length() )
261           theStream << ", ";
262       }
263       theStream << " ]";
264     }
265   }
266
267   TPythonDump&
268   TPythonDump::operator<<(const SMESH::long_array& theArg)
269   {
270     DumpArray( theArg, *this );
271     return *this;
272   }
273
274   TPythonDump&
275   TPythonDump::operator<<(const SMESH::double_array& theArg)
276   {
277     DumpArray( theArg, *this );
278     return *this;
279   }
280
281   TPythonDump&
282   TPythonDump::operator<<(const SMESH::nodes_array& theArg)
283   {
284     DumpArray( theArg, *this );
285     return *this;
286   }
287
288   TPythonDump&
289   TPythonDump::operator<<(const SMESH::string_array& theArray)
290   {
291     myStream << "[ ";
292     for ( CORBA::ULong i = 1; i <= theArray.length(); i++ ) {
293       myStream << "'" << theArray[i-1] << "'";
294       if ( i < theArray.length() )
295         myStream << ", ";
296     }
297     myStream << " ]";
298     return *this;
299   }
300
301   TPythonDump&
302   TPythonDump::
303   operator<<(SALOMEDS::SObject_ptr aSObject)
304   {
305     if ( !aSObject->_is_nil() ) {
306       CORBA::String_var entry = aSObject->GetID();
307       myStream << entry.in();
308     }
309     else {
310       myStream << theNotPublishedObjectName;
311     }
312     return *this;
313   }
314
315   TPythonDump&
316   TPythonDump::
317   operator<<(CORBA::Object_ptr theArg)
318   {
319     SMESH_Gen_i*          aSMESHGen = SMESH_Gen_i::GetSMESHGen();
320     SALOMEDS::Study_var      aStudy = aSMESHGen->GetCurrentStudy();
321     SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
322     if(!aSObject->_is_nil()) {
323       CORBA::String_var id = aSObject->GetID();
324       myStream << id;
325     } else if ( !CORBA::is_nil(theArg)) {
326       if ( aSMESHGen->CanPublishInStudy( theArg )) // not published SMESH object
327         myStream << "smeshObj_" << size_t(theArg);
328       else
329         myStream << theNotPublishedObjectName;
330     }
331     else
332       myStream << "None";
333     return *this;
334   }
335
336   TPythonDump&
337   TPythonDump::
338   operator<<(SMESH::SMESH_Hypothesis_ptr theArg)
339   {
340     SALOMEDS::Study_var     aStudy = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
341     SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
342     if(aSObject->_is_nil() && !CORBA::is_nil(theArg))
343       myStream << "hyp_" << theArg->GetId();
344     else
345       *this << aSObject;
346     return *this;
347   }
348
349   TPythonDump&
350   TPythonDump::
351   operator<<(SMESH::SMESH_IDSource_ptr theArg)
352   {
353     if ( CORBA::is_nil( theArg ) )
354       return *this << "None";
355     SMESH_Gen_i*          aSMESHGen = SMESH_Gen_i::GetSMESHGen();
356     SALOMEDS::Study_var      aStudy = aSMESHGen->GetCurrentStudy();
357     SALOMEDS::SObject_wrap aSObject = SMESH_Gen_i::ObjectToSObject(aStudy,theArg);
358     if(!aSObject->_is_nil())
359     {
360       return *this << aSObject;
361     }
362     if ( SMESH::Filter_i* filter = SMESH::DownCast<SMESH::Filter_i*>( theArg ))
363     {
364       return *this << filter;
365     }
366     if ( SMESH_MeshEditor_i::IsTemporaryIDSource( theArg ))
367     {
368       SMESH::SMESH_Mesh_var            mesh = theArg->GetMesh();
369       SMESH::long_array_var    anElementsId = theArg->GetIDs();
370       SMESH::array_of_ElementType_var types = theArg->GetTypes();
371       SMESH::ElementType               type = types->length() ? types[0] : SMESH::ALL;
372       SALOMEDS::SObject_wrap         meshSO = SMESH_Gen_i::ObjectToSObject(aStudy,mesh);
373       if ( meshSO->_is_nil() ) // don't waste memory for dumping not published objects
374         return *this << mesh << ".GetIDSource([], " << type << ")";
375       else
376         return *this << mesh << ".GetIDSource(" << anElementsId << ", " << type << ")";
377     }
378     return *this << theNotPublishedObjectName;
379   }
380
381   TPythonDump&
382   TPythonDump::
383   operator<<(SMESH::FilterLibrary_i* theArg)
384   {
385     myStream<<"aFilterLibrary"<<theArg;
386     return *this;
387   }
388
389   TPythonDump&
390   TPythonDump::
391   operator<<(SMESH::FilterManager_i* theArg)
392   {
393     myStream<<"aFilterManager";
394     return *this;
395   }
396
397   TPythonDump&
398   TPythonDump::
399   operator<<(SMESH::Filter_i* theArg)
400   {
401     myStream<<"aFilter"<<theArg;
402     return *this;
403   }
404
405   TPythonDump&
406   TPythonDump::
407   operator<<(SMESH::Functor_i* theArg)
408   {
409     if ( theArg ) {
410       FunctorType aFunctorType = theArg->GetFunctorType();
411       switch(aFunctorType) {
412       case FT_AspectRatio:           myStream<< "aAspectRatio";           break;
413       case FT_AspectRatio3D:         myStream<< "aAspectRatio3D";         break;
414       case FT_Warping:               myStream<< "aWarping";               break;
415       case FT_MinimumAngle:          myStream<< "aMinimumAngle";          break;
416       case FT_Taper:                 myStream<< "aTaper";                 break;
417       case FT_Skew:                  myStream<< "aSkew";                  break;
418       case FT_Area:                  myStream<< "aArea";                  break;
419       case FT_Volume3D:              myStream<< "aVolume3D";              break;
420       case FT_MaxElementLength2D:    myStream<< "aMaxElementLength2D";    break;
421       case FT_MaxElementLength3D:    myStream<< "aMaxElementLength3D";    break;
422       case FT_FreeBorders:           myStream<< "aFreeBorders";           break;
423       case FT_FreeEdges:             myStream<< "aFreeEdges";             break;
424       case FT_FreeNodes:             myStream<< "aFreeNodes";             break;
425       case FT_FreeFaces:             myStream<< "aFreeFaces";             break;
426       case FT_EqualNodes:            myStream<< "aEqualNodes";            break;
427       case FT_EqualEdges:            myStream<< "aEqualEdges";            break;
428       case FT_EqualFaces:            myStream<< "aEqualFaces";            break;
429       case FT_EqualVolumes:          myStream<< "aEqualVolumes";          break;
430       case FT_MultiConnection:       myStream<< "aMultiConnection";       break;
431       case FT_MultiConnection2D:     myStream<< "aMultiConnection2D";     break;
432       case FT_Length:                myStream<< "aLength";                break;
433       case FT_Length2D:              myStream<< "aLength2D";              break;
434       case FT_Deflection2D:          myStream<< "aDeflection2D";          break;
435       case FT_NodeConnectivityNumber:myStream<< "aNodeConnectivityNumber";break;
436       case FT_BelongToMeshGroup:     myStream<< "aBelongToMeshGroup";     break;
437       case FT_BelongToGeom:          myStream<< "aBelongToGeom";          break;
438       case FT_BelongToPlane:         myStream<< "aBelongToPlane";         break;
439       case FT_BelongToCylinder:      myStream<< "aBelongToCylinder";      break;
440       case FT_BelongToGenSurface:    myStream<< "aBelongToGenSurface";    break;
441       case FT_LyingOnGeom:           myStream<< "aLyingOnGeom";           break;
442       case FT_RangeOfIds:            myStream<< "aRangeOfIds";            break;
443       case FT_BadOrientedVolume:     myStream<< "aBadOrientedVolume";     break;
444       case FT_BareBorderVolume:      myStream<< "aBareBorderVolume";      break;
445       case FT_BareBorderFace:        myStream<< "aBareBorderFace";        break;
446       case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
447       case FT_OverConstrainedFace:   myStream<< "aOverConstrainedFace";   break;
448       case FT_LinearOrQuadratic:     myStream<< "aLinearOrQuadratic";     break;
449       case FT_GroupColor:            myStream<< "aGroupColor";            break;
450       case FT_ElemGeomType:          myStream<< "aElemGeomType";          break;
451       case FT_EntityType:            myStream<< "aEntityType";            break;
452       case FT_CoplanarFaces:         myStream<< "aCoplanarFaces";         break;
453       case FT_BallDiameter:          myStream<< "aBallDiameter";          break;
454       case FT_ConnectedElements:     myStream<< "aConnectedElements";     break;
455       case FT_LessThan:              myStream<< "aLessThan";              break;
456       case FT_MoreThan:              myStream<< "aMoreThan";              break;
457       case FT_EqualTo:               myStream<< "aEqualTo";               break;
458       case FT_LogicalNOT:            myStream<< "aLogicalNOT";            break;
459       case FT_LogicalAND:            myStream<< "aLogicalAND";            break;
460       case FT_LogicalOR:             myStream<< "aLogicalOR";             break;
461       case FT_Undefined:             myStream<< "anUndefined";            break;
462         //default: -- commented to have a compilation warning
463       }
464       myStream<<theArg;
465     }
466     return *this;
467   }
468
469   TPythonDump&
470   TPythonDump::
471   operator<<(SMESH::Measurements_i* theArg)
472   {
473     myStream<<"aMeasurements";
474     return *this;
475   }
476
477
478   TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
479   {
480     myStream << SMESHGenName(); return *this;
481   }
482
483   TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
484   {
485     myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
486   }
487
488   TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
489   {
490     myStream << theStr; return *this;
491   }
492
493
494   TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
495   {
496     switch (theVersion) {
497     case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
498     case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
499     case SMESH::MED_LATEST: myStream << "SMESH.MED_LATEST"; break;
500     case SMESH::MED_MINOR_0: myStream << "SMESH.MED_MINOR_0"; break;
501     case SMESH::MED_MINOR_1: myStream << "SMESH.MED_MINOR_1"; break;
502     case SMESH::MED_MINOR_2: myStream << "SMESH.MED_MINOR_2"; break;
503     case SMESH::MED_MINOR_3: myStream << "SMESH.MED_MINOR_3"; break;
504     case SMESH::MED_MINOR_4: myStream << "SMESH.MED_MINOR_4"; break;
505     case SMESH::MED_MINOR_5: myStream << "SMESH.MED_MINOR_5"; break;
506     case SMESH::MED_MINOR_6: myStream << "SMESH.MED_MINOR_6"; break;
507     case SMESH::MED_MINOR_7: myStream << "SMESH.MED_MINOR_7"; break;
508     case SMESH::MED_MINOR_8: myStream << "SMESH.MED_MINOR_8"; break;
509     case SMESH::MED_MINOR_9: myStream << "SMESH.MED_MINOR_9"; break;
510     default: myStream << theVersion;
511     }
512     return *this;
513   }
514
515   TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
516   {
517     *this << "SMESH.AxisStruct( "
518           << TVar( theAxis.x  ) << ", "
519           << TVar( theAxis.y  ) << ", "
520           << TVar( theAxis.z  ) << ", "
521           << TVar( theAxis.vx ) << ", "
522           << TVar( theAxis.vy ) << ", "
523           << TVar( theAxis.vz ) << " )";
524     return *this;
525   }
526
527   TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
528   {
529     const SMESH::PointStruct & P = theDir.PS;
530     *this << "SMESH.DirStruct( SMESH.PointStruct ( "
531           << TVar( P.x ) << ", "
532           << TVar( P.y ) << ", "
533           << TVar( P.z ) << " ))";
534     return *this;
535   }
536
537   TPythonDump& TPythonDump::operator<<(const SMESH::PointStruct & P)
538   {
539     *this << "SMESH.PointStruct ( "
540           << TVar( P.x ) << ", "
541           << TVar( P.y ) << ", "
542           << TVar( P.z ) << " )";
543     return *this;
544   }
545
546   TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
547   {
548     DumpArray( theList, *this );
549     return *this;
550   }
551   TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
552   {
553     DumpArray( *theList, *this );
554     return *this;
555   }
556   TPythonDump& TPythonDump::operator<<(const GEOM::ListOfGO& theList)
557   {
558     DumpArray( theList, *this );
559     return *this;
560   }
561   TPythonDump& TPythonDump::operator<<(const GEOM::ListOfGBO& theList)
562   {
563     DumpArray( theList, *this );
564     return *this;
565   }
566   TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
567   {
568     DumpArray( theList, *this );
569     return *this;
570   }
571   TPythonDump& TPythonDump::operator<<(const SMESH::CoincidentFreeBorders& theCFB)
572   {
573     // dump CoincidentFreeBorders as a list of lists, each enclosed list
574     // contains node IDs of a group of coincident free borders where
575     // each consequent triple of IDs describe a free border: (n1, n2, nLast)
576     // For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes
577     // two groups of coincident free borders, each group including two borders
578
579     myStream << "[";
580     for ( CORBA::ULong i = 0; i < theCFB.coincidentGroups.length(); ++i )
581     {
582       const SMESH::FreeBordersGroup& aGRP = theCFB.coincidentGroups[ i ];
583       if ( i ) myStream << ",";
584       myStream << "[";
585       for ( CORBA::ULong iP = 0; iP < aGRP.length(); ++iP )
586       {
587         const SMESH::FreeBorderPart& aPART = aGRP[ iP ];
588         if ( 0 <= aPART.border && aPART.border < (CORBA::Long)theCFB.borders.length() )
589         {
590           if ( iP ) myStream << ", ";
591           const SMESH::FreeBorder& aBRD = theCFB.borders[ aPART.border ];
592           myStream << aBRD.nodeIDs[ aPART.node1    ] << ",";
593           myStream << aBRD.nodeIDs[ aPART.node2    ] << ",";
594           myStream << aBRD.nodeIDs[ aPART.nodeLast ];
595         }
596       }
597       myStream << "]";
598     }
599     myStream << "]";
600
601     return *this;
602   }
603
604   const char* TPythonDump::NotPublishedObjectName()
605   {
606     return theNotPublishedObjectName;
607   }
608
609   TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
610   TCollection_AsciiString myLongStringEnd  ( "TPythonDump::LongStringEnd" );
611
612   //================================================================================
613   /*!
614    * \brief Return marker of long string literal beginning
615    * \param type - a name of functionality producing the string literal
616    * \retval TCollection_AsciiString - the marker string to be written into
617    * a raw python script
618    */
619   //================================================================================
620
621   TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
622   {
623     return
624       myLongStringStart +
625       (Standard_Integer) strlen(type) +
626       " " +
627       (char*) type;
628   }
629
630   //================================================================================
631   /*!
632      * \brief Return marker of long string literal end
633       * \retval TCollection_AsciiString - the marker string to be written into
634       * a raw python script
635    */
636   //================================================================================
637
638   TCollection_AsciiString TPythonDump::LongStringEnd()
639   {
640     return myLongStringEnd;
641   }
642
643   //================================================================================
644   /*!
645      * \brief Cut out a long string literal from a string
646       * \param theText - text possibly containing string literals
647       * \param theFrom - position in the text to search from
648       * \param theLongString - the retrieved literal
649       * \param theStringType - a name of functionality produced the literal
650       * \retval bool - true if a string literal found
651      *
652      * The literal is removed from theText; theFrom points position right after
653      * the removed literal
654    */
655   //================================================================================
656
657   bool  TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
658                                        int                     & theFrom,
659                                        TCollection_AsciiString & theLongString,
660                                        TCollection_AsciiString & theStringType)
661   {
662     if ( theFrom < 1 || theFrom > theText.Length() )
663       return false;
664
665     // ...script \  beg marker    \ \ type \       literal              \  end marker  \ script...
666     //  "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
667     //  012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
668     //  0         1         2         3         4         5         6         7         8
669
670     theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
671     if ( !theFrom )
672       return false;
673
674     // find where literal begins
675     int literalBeg = theFrom + myLongStringStart.Length(); // = 26
676     char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
677     int typeLen = atoi ( typeLenStr ); // = 7
678     while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
679       literalBeg++; // 26 -> 27
680       typeLenStr++;
681     }
682     literalBeg += typeLen + 1; // = 35
683     if ( literalBeg > theText.Length() )
684       return false;
685
686     // where literal ends (i.e. end marker begins)
687     int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
688     if ( !literalEnd )
689       literalEnd = theText.Length();
690
691     // literal
692     theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
693     // type
694     theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
695     // cut off literal
696     literalEnd += myLongStringEnd.Length(); // = 79
697     TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
698     theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
699
700     return true;
701   }
702
703   void printException( const char* text )
704   {
705 #ifdef _DEBUG_
706     cout << "Exception in SMESH_Gen_i::DumpPython(): " << text << endl;
707 #endif
708   }
709 }
710
711 //=======================================================================
712 //function : RemoveTabulation
713 //purpose  : 
714 //=======================================================================
715 void RemoveTabulation( TCollection_AsciiString& theScript )
716 {
717   std::string aString( theScript.ToCString() );
718   std::string::size_type aPos = 0;
719   while( aPos < aString.length() )
720   {
721     aPos = aString.find( "\n\t", aPos );
722     if( aPos == std::string::npos )
723       break;
724     aString.replace( aPos, 2, "\n" );
725     aPos++;
726   }
727   theScript = aString.c_str();
728 }
729
730 //=======================================================================
731 //function : DumpPython
732 //purpose  :
733 //=======================================================================
734 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
735                                            CORBA::Boolean isPublished,
736                                            CORBA::Boolean isMultiFile,
737                                            CORBA::Boolean& isValidScript)
738 {
739   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
740   if (CORBA::is_nil(aStudy))
741     return new Engines::TMPFile(0);
742
743   CORBA::String_var compDataType = ComponentDataType();
744   SALOMEDS::SObject_wrap aSO = aStudy->FindComponent( compDataType.in() );
745   if (CORBA::is_nil(aSO))
746     return new Engines::TMPFile(0);
747
748   // Map study entries to object names
749   Resource_DataMapOfAsciiStringAsciiString aMap;
750   Resource_DataMapOfAsciiStringAsciiString aMapNames;
751
752   SALOMEDS::ChildIterator_wrap Itr = aStudy->NewChildIterator(aSO);
753   for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
754     SALOMEDS::SObject_wrap aValue = Itr->Value();
755     CORBA::String_var anID = aValue->GetID();
756     CORBA::String_var aName = aValue->GetName();
757     TCollection_AsciiString aGUIName ( (char*) aName.in() );
758     TCollection_AsciiString anEntry ( (char*) anID.in() );
759     if (aGUIName.Length() > 0) {
760       aMapNames.Bind( anEntry, aGUIName );
761       aMap.Bind( anEntry, aGUIName );
762     }
763   }
764
765   // Get trace of restored study
766   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
767   SALOMEDS::GenericAttribute_wrap anAttr =
768     aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
769
770   SALOMEDS::AttributePythonObject_var pyAttr =
771     SALOMEDS::AttributePythonObject::_narrow(anAttr);
772   CORBA::String_var oldValue = pyAttr->GetObject();
773   TCollection_AsciiString aSavedTrace (oldValue.in());
774
775   // Add trace of API methods calls and replace study entries by names
776   TCollection_AsciiString aScript;
777   aScript += DumpPython_impl(aStudy, aMap, aMapNames, isPublished, isMultiFile,
778                              myIsHistoricalPythonDump, isValidScript, aSavedTrace);
779
780   int aLen = aScript.Length();
781   unsigned char* aBuffer = new unsigned char[aLen+1];
782   strcpy((char*)aBuffer, aScript.ToCString());
783
784   CORBA::Octet* anOctetBuf =  (CORBA::Octet*)aBuffer;
785   Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
786
787   bool hasNotPublishedObjects = aScript.Location( SMESH::theNotPublishedObjectName, 1, aLen);
788   isValidScript = isValidScript && !hasNotPublishedObjects;
789
790   return aStreamFile._retn();
791 }
792
793 //=============================================================================
794 /*!
795  *  AddToPythonScript
796  */
797 //=============================================================================
798 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
799 {
800   if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
801     myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
802   }
803   myPythonScripts[theStudyID]->Append(theString);
804 }
805
806 //=============================================================================
807 /*!
808  *  RemoveLastFromPythonScript
809  */
810 //=============================================================================
811 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
812 {
813   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
814     int aLen = myPythonScripts[theStudyID]->Length();
815     myPythonScripts[theStudyID]->Remove(aLen);
816   }
817 }
818
819 //=======================================================================
820 //function : SavePython
821 //purpose  :
822 //=======================================================================
823 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
824 {
825   // Dump trace of API methods calls
826   TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
827
828   // Check contents of PythonObject attribute
829   CORBA::String_var compDataType = ComponentDataType();
830   SALOMEDS::SObject_wrap aSO = theStudy->FindComponent( compDataType.in() );
831   SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
832   SALOMEDS::GenericAttribute_wrap anAttr =
833     aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
834
835   SALOMEDS::AttributePythonObject_var pyAttr =
836     SALOMEDS::AttributePythonObject::_narrow(anAttr);
837   CORBA::String_var oldValue = pyAttr->GetObject();
838   TCollection_AsciiString oldScript (oldValue.in());
839
840   if (oldScript.Length() > 0) {
841     oldScript += "\n";
842     oldScript += aScript;
843   } else {
844     oldScript = aScript;
845   }
846
847   // Store in PythonObject attribute
848   pyAttr->SetObject(oldScript.ToCString(), 1);
849
850   // Clean trace of API methods calls
851   CleanPythonTrace(theStudy->StudyId());
852 }
853
854
855 // impl
856
857
858 //=============================================================================
859 /*!
860  *  FindEntries: Returns a sequence of start/end positions of entries in the string
861  */
862 //=============================================================================
863 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
864 {
865   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
866   Standard_Integer aLen = theString.Length();
867   Standard_Boolean isFound = Standard_False;
868
869   char* arr = (char*) theString.ToCString();
870   Standard_Integer i = 0, j;
871
872   while(i < aLen) {
873     int c = (int)arr[i];
874     j = i+1;
875     if ( isdigit( c )) { //Is digit?
876
877       isFound = Standard_False;
878       while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
879         c = (int)arr[j++];
880         if(c == ':') isFound = Standard_True;
881       }
882
883       if (isFound) {
884         int prev = (i < 1) ? 0 : (int)arr[i - 1];
885         // to distinguish from a sketcher command:
886         // last char should be a digit, not ":",
887         // previous char should not be '"'.
888         if (arr[j-2] != ':' && prev != '"') {
889           aSeq->Append(i+1); // +1 because AsciiString starts from 1
890           aSeq->Append(j-1);
891         }
892       }
893     }
894
895     i = j;
896   }
897
898   return aSeq;
899 }
900
901 namespace {
902
903   //================================================================================
904   /*!
905    * \brief Make a string be a valid python name
906     * \param aName - a string to fix
907     * \retval bool - true if aName was not modified
908    */
909   //================================================================================
910
911   bool fixPythonName(TCollection_AsciiString & aName)
912   {
913     bool isValidName = true;
914     int nbUnderscore = 0;
915     int p;
916     // replace not allowed chars by underscore
917     const char* name = aName.ToCString();
918     for ( p = 0; name[p]; ++p ) {
919       if ( !isalnum( name[p] ) && name[p] != '_' )
920       {
921         if ( p == 0 || p+1 == aName.Length() || name[p-1] == '_')
922         {
923           aName.Remove( p+1, 1 ); // remove __ and _ from the start and the end
924           --p;
925           name = aName.ToCString();
926         }
927         else
928         {
929           aName.SetValue( p+1, '_');
930           nbUnderscore++;
931         }
932         isValidName = false;
933       }
934     }
935     // aName must not start with a digit
936     if ( aName.IsIntegerValue() ) {
937       aName.Insert( 1, 'a' );
938       isValidName = false;
939     }
940     // shorten names like CartesianParameters3D_400_400_400_1000000_1
941     const int nbAllowedUnderscore = 3; /* changed from 2 to 3 by an user request
942                                           posted to SALOME Forum */
943     if ( aName.Length() > 20 && nbUnderscore > nbAllowedUnderscore )
944     {
945       p = aName.Location( "_", 20, aName.Length());
946       if ( p > 1 )
947         aName.Trunc( p-1 );
948     }
949     return isValidName;
950   }
951
952   //================================================================================
953   /*!
954    * \brief Return Python module names of available plug-ins.
955    */
956   //================================================================================
957
958   std::vector<std::string> getPluginNames()
959   {
960     std::vector<std::string> pluginNames;
961     std::vector< std::string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
962     LDOMParser xmlParser;
963     for ( size_t i = 0; i < xmlPaths.size(); ++i )
964     {
965       bool error = xmlParser.parse( xmlPaths[i].c_str() );
966       if ( error )
967       {
968         TCollection_AsciiString data;
969         INFOS( xmlParser.GetError(data) );
970         continue;
971       }
972       // <meshers-group name="Standard Meshers"
973       //                resources="StdMeshers"
974       //                idl-module="StdMeshers"
975       //                server-lib="StdMeshersEngine"
976       //                gui-lib="StdMeshersGUI">
977       LDOM_Document xmlDoc   = xmlParser.getDocument();
978       LDOM_NodeList nodeList = xmlDoc.getElementsByTagName( "meshers-group" );
979       for ( int i = 0; i < nodeList.getLength(); ++i )
980       {
981         LDOM_Node       node = nodeList.item( i );
982         LDOM_Element&   elem = (LDOM_Element&) node;
983         LDOMString idlModule = elem.getAttribute( "idl-module" );
984         if ( strlen( idlModule.GetString() ) > 0 )
985           pluginNames.push_back( idlModule.GetString() );
986       }
987     }
988     return pluginNames;
989   }
990 }
991
992 //================================================================================
993 /*!
994  * \brief Createa a Dump Python script
995  *  \param [in] theStudy - the study to dump
996  *  \param [in,out] theObjectNames - map of an entry to a study and python name
997  *  \param [in] theNames -  - map of an entry to a study name
998  *  \param [in] isPublished - \c true if dump of object publication in study is needed
999  *  \param [in] isMultiFile - \c true if dump of each module goes to a separate file
1000  *  \param [in] isHistoricalDump - \c true if removed object should be dumped
1001  *  \param [out] aValidScript - returns \c true if the returned script seems valid
1002  *  \param [in,out] theSavedTrace - the dump stored in the study. It's cleared to
1003  *         decrease memory usage.
1004  *  \return TCollection_AsciiString - the result dump script.
1005  */
1006 //================================================================================
1007
1008 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
1009                         (SALOMEDS::Study_ptr                       theStudy,
1010                          Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
1011                          Resource_DataMapOfAsciiStringAsciiString& theNames,
1012                          bool                                      isPublished,
1013                          bool                                      isMultiFile,
1014                          bool                                      isHistoricalDump,
1015                          bool&                                     aValidScript,
1016                          TCollection_AsciiString&                  theSavedTrace)
1017 {
1018   SMESH_TRY;
1019   const int aStudyID = theStudy->StudyId();
1020
1021   const TCollection_AsciiString aSmeshpy ( SMESH_2smeshpy::SmeshpyName() );
1022   const TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
1023   const TCollection_AsciiString anOldGen ( SMESH::TPythonDump::SMESHGenName() );
1024   const TCollection_AsciiString helper; // to comfortably append C strings to TCollection_AsciiString
1025   const TCollection_AsciiString tab( isMultiFile ? "\t" : "" ), nt = helper + "\n" + tab;
1026
1027   std::list< TCollection_AsciiString > lines; // lines of a script
1028   std::list< TCollection_AsciiString >::iterator linesIt;
1029   
1030   if ( isPublished )
1031     lines.push_back(  aSMESHGen + " = smeshBuilder.New(theStudy)" );
1032    else
1033     lines.push_back(  aSMESHGen + " = smeshBuilder.New(None)" );
1034   lines.push_back( helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()" );
1035   lines.push_back( helper + "aMeasurements = "  + aSMESHGen + ".CreateMeasurements()" );
1036
1037   // Treat dump trace of restored study
1038   if (theSavedTrace.Length() > 0)
1039   {
1040     linesIt = --lines.end();
1041     // Split theSavedTrace into lines
1042     int from = 1, end = theSavedTrace.Length(), to;
1043     while ( from < end && ( to = theSavedTrace.Location( "\n", from, end )))
1044     {
1045       if ( theSavedTrace.ToCString()[from-1] == '\t' )
1046         ++from;
1047       if ( to != from )
1048         lines.push_back( theSavedTrace.SubString( from, to - 1 ));
1049       from = to + 1;
1050     }
1051     // For the conversion of IDL API calls -> smeshBuilder.py API, "smesh" standing for SMESH_Gen
1052     // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
1053     // Change "smesh" -> "smeshgen" in the trace saved before passage to smeshBuilder.py API
1054     bool isNewVersion =
1055       theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
1056     theSavedTrace.Clear();
1057     if ( !isNewVersion )
1058     {
1059       const TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
1060       int beg, end, from;
1061       for ( ++linesIt; linesIt != lines.end(); ++linesIt )
1062       {
1063         TCollection_AsciiString& aSavedLine = *linesIt;
1064         end = aSavedLine.Length(), from = 1;
1065         while ( from < end && ( beg = aSavedLine.Location( aSmeshCall, from, end )))
1066         {
1067           char charBefore = ( beg == 1 ) ? ' ' : aSavedLine.Value( beg - 1 );
1068           if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
1069             aSavedLine.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
1070             end += gen.Length();
1071           }
1072           from = beg + aSmeshCall.Length();
1073         }
1074       }
1075     }
1076   }
1077
1078   // Add new dump trace of API methods calls to script lines
1079   if (myPythonScripts.find( aStudyID ) != myPythonScripts.end())
1080   {
1081     Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[ aStudyID ];
1082     Standard_Integer istr, aLen = aPythonScript->Length();
1083     for (istr = 1; istr <= aLen; istr++)
1084       lines.push_back( aPythonScript->Value( istr ));
1085   }
1086
1087   // Convert IDL API calls into smeshBuilder.py API.
1088   // Some objects are wrapped with python classes and
1089   // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
1090   Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
1091   std::set< TCollection_AsciiString >      aRemovedObjIDs;
1092   if ( !getenv("NO_2smeshpy_conversion"))
1093     SMESH_2smeshpy::ConvertScript( lines, anEntry2AccessorMethod,
1094                                    theObjectNames, aRemovedObjIDs,
1095                                    theStudy, isHistoricalDump );
1096
1097   bool importGeom = false;
1098   GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
1099   {
1100     // Add names of GEOM objects to theObjectNames to exclude same names of SMESH objects
1101     GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
1102     int ign = 0, nbgn = aGeomNames->length();
1103     for (; ign < nbgn; ign++) {
1104       TCollection_AsciiString aName = aGeomNames[ign].in();
1105       theObjectNames.Bind(aName, "1");
1106     }
1107   }
1108
1109   TCollection_AsciiString anUpdatedScript;
1110
1111   Resource_DataMapOfAsciiStringAsciiString mapRemoved;
1112   Resource_DataMapOfAsciiStringAsciiString mapEntries; // names and entries present in anUpdatedScript
1113   Standard_Integer objectCounter = 0;
1114   TCollection_AsciiString anEntry, aName, aGUIName, aBaseName("smeshObj_");
1115
1116   // Treat every script line and add it to anUpdatedScript
1117   for ( linesIt = lines.begin(); linesIt != lines.end(); ++linesIt )
1118   {
1119     TCollection_AsciiString& aLine = *linesIt;
1120     anUpdatedScript += tab;
1121     {
1122       //Replace characters used instead of quote marks to quote notebook variables
1123       int pos = 1;
1124       while (( pos = aLine.Location( 1, SMESH::TVar::Quote(), pos, aLine.Length() )))
1125         aLine.SetValue( pos, '"' );
1126     }
1127     // Find entries to be replaced by names
1128     Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aLine);
1129     const Standard_Integer aSeqLen = aSeq->Length();
1130     Standard_Integer aStart = 1;
1131     for (Standard_Integer i = 1; i <= aSeqLen; i += 2)
1132     {
1133       if ( aStart < aSeq->Value(i) )
1134         anUpdatedScript += aLine.SubString( aStart, aSeq->Value(i) - 1 ); // line part before i-th entry
1135       anEntry = aLine.SubString( aSeq->Value(i), aSeq->Value(i + 1) );
1136       // is a GEOM object?
1137       CORBA::String_var geomName = geom->GetDumpName( anEntry.ToCString() );
1138       if ( !geomName.in() || !geomName.in()[0] ) {
1139         // is a SMESH object
1140         if ( theObjectNames.IsBound( anEntry )) {
1141           // The Object is in Study
1142           aName = theObjectNames.Find( anEntry );
1143           // check validity of aName
1144           bool isValidName = fixPythonName( aName );
1145           if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
1146             // diff objects have same name - make a new name by appending a digit
1147             TCollection_AsciiString aName2;
1148             Standard_Integer i = 0;
1149             do {
1150               aName2 = aName + "_" + ++i;
1151             } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
1152             aName = aName2;
1153             isValidName = false;
1154           }
1155           if ( !isValidName )
1156             theObjectNames(anEntry) = aName;
1157
1158           if ( aLine.Value(1) != '#' )
1159             mapEntries.Bind(anEntry, aName);
1160         }
1161         else
1162         {
1163           // Removed Object
1164           do {
1165             aName = aBaseName + (++objectCounter);
1166           } while (theObjectNames.IsBound(aName));
1167
1168           if ( !aRemovedObjIDs.count( anEntry ) && aLine.Value(1) != '#')
1169             mapRemoved.Bind(anEntry, aName);
1170
1171           theObjectNames.Bind(anEntry, aName);
1172         }
1173         theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
1174       }
1175       else
1176       {
1177         aName = geomName.in();
1178         importGeom = true;
1179       }
1180       anUpdatedScript += aName;
1181       aStart = aSeq->Value(i + 1) + 1;
1182
1183     } // loop on entries within aLine
1184
1185     if ( aSeqLen == 0 )
1186       anUpdatedScript += aLine;
1187     else if ( aSeq->Value( aSeqLen ) < aLine.Length() )
1188       anUpdatedScript += aLine.SubString( aSeq->Value(aSeqLen) + 1, aLine.Length() );
1189
1190     anUpdatedScript += '\n';
1191   }
1192
1193   // Make an initial part of aSript
1194
1195   TCollection_AsciiString initPart = "import ";
1196   if ( isMultiFile )
1197     initPart += "salome, ";
1198   initPart += " SMESH, SALOMEDS\n";
1199   initPart += "from salome.smesh import smeshBuilder\n";
1200   if ( importGeom && isMultiFile )
1201   {
1202     initPart += ("\n## import GEOM dump file ## \n"
1203                  "import string, os, sys, re, inspect\n"
1204                  "thisFile   = inspect.getfile( inspect.currentframe() )\n"
1205                  "thisModule = os.path.splitext( os.path.basename( thisFile ))[0]\n"
1206                  "sys.path.insert( 0, os.path.dirname( thisFile ))\n"
1207                  "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",thisModule)+\" import *\")\n\n");
1208   }
1209   // import python files corresponding to plugins if they are used in anUpdatedScript
1210   {
1211     TCollection_AsciiString importStr;
1212     std::vector<std::string> pluginNames = getPluginNames();
1213     for ( size_t i = 0; i < pluginNames.size(); ++i )
1214     {
1215       // Convert access to plugin members:
1216       // e.g. StdMeshers.QUAD_REDUCED -> StdMeshersBuilder.QUAD_REDUCED
1217       TCollection_AsciiString pluginAccess = (pluginNames[i] + ".").c_str() ;
1218       int iFrom = 1, iPos;
1219       while (( iPos = anUpdatedScript.Location( pluginAccess, iFrom, anUpdatedScript.Length() )))
1220       {
1221         anUpdatedScript.Insert( iPos + pluginNames[i].size(), "Builder" );
1222         iFrom = iPos + pluginNames[i].size() + 8;
1223       }
1224       // if any plugin member is used, import the plugin
1225       if ( iFrom > 1 )
1226         importStr += ( helper + "\n" "from salome." + pluginNames[i].c_str() +
1227                        " import " + pluginNames[i].c_str() +"Builder" );
1228     }
1229     if ( !importStr.IsEmpty() )
1230       initPart += importStr + "\n";
1231   }
1232
1233   if ( isMultiFile )
1234     initPart += "def RebuildData(theStudy):";
1235   initPart += "\n";
1236
1237   anUpdatedScript.Prepend( initPart );
1238
1239   // Make a final part of aScript
1240
1241   // Dump object removal
1242   TCollection_AsciiString removeObjPart;
1243   if ( !mapRemoved.IsEmpty() ) {
1244     removeObjPart += nt + "## some objects were removed";
1245     removeObjPart += nt + "aStudyBuilder = theStudy.NewBuilder()";
1246     Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString mapRemovedIt;
1247     for ( mapRemovedIt.Initialize( mapRemoved ); mapRemovedIt.More(); mapRemovedIt.Next() ) {
1248       aName   = mapRemovedIt.Value(); // python name
1249       anEntry = mapRemovedIt.Key();
1250       removeObjPart += nt + "SO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
1251       removeObjPart += aName;
1252       // for object wrapped by class of smeshBuilder.py
1253       if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1254         removeObjPart += helper + "." + anEntry2AccessorMethod( anEntry );
1255       removeObjPart += helper + "))" + nt + "if SO: aStudyBuilder.RemoveObjectWithChildren(SO)";
1256     }
1257   }
1258
1259   // Set object names
1260   TCollection_AsciiString setNamePart;
1261   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString mapEntriesIt;
1262   for ( mapEntriesIt.Initialize( mapEntries ); mapEntriesIt.More(); mapEntriesIt.Next() )
1263   {
1264     anEntry = mapEntriesIt.Key();
1265     aName   = mapEntriesIt.Value(); // python name
1266     if ( theNames.IsBound( anEntry ))
1267     {
1268       aGUIName = theNames.Find(anEntry);
1269       aGUIName.RemoveAll('\''); // remove a quote from a name (issue 22360)
1270       setNamePart += nt + aSMESHGen + ".SetName(" + aName;
1271       if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1272         setNamePart += helper + "." + anEntry2AccessorMethod( anEntry );
1273       setNamePart += helper + ", '" + aGUIName + "')";
1274     }
1275   }
1276   if ( !setNamePart.IsEmpty() )
1277   {
1278     setNamePart.Insert( 1, nt + "## Set names of Mesh objects" );
1279   }
1280
1281   // Store visual properties of displayed objects
1282
1283   TCollection_AsciiString visualPropertiesPart;
1284   if (isPublished)
1285   {
1286     //Output the script that sets up the visual parameters.
1287     CORBA::String_var compDataType = ComponentDataType();
1288     CORBA::String_var script = theStudy->GetDefaultScript( compDataType.in(), tab.ToCString() );
1289     if ( script.in() && script.in()[0] ) {
1290       visualPropertiesPart += nt + "### Store presentation parameters of displayed objects\n";
1291       visualPropertiesPart += script.in();
1292     }
1293   }
1294
1295   anUpdatedScript += removeObjPart + '\n' + setNamePart + '\n' + visualPropertiesPart;
1296
1297   if ( isMultiFile )
1298   {
1299     anUpdatedScript +=
1300       "\n\tpass"
1301       "\n"
1302       "\nif __name__ == '__main__':"
1303       "\n\tSMESH_RebuildData = RebuildData"
1304       "\n\texec('import '+re.sub('SMESH$','GEOM',thisModule)+' as GEOM_dump')"
1305       "\n\tGEOM_dump.RebuildData( salome.myStudy )"
1306       "\n\texec('from '+re.sub('SMESH$','GEOM',thisModule)+' import * ')"
1307       "\n\tSMESH_RebuildData( salome.myStudy )";
1308   }
1309   anUpdatedScript += "\n";
1310
1311   // no need now as we use 'tab' and 'nt' variables depending on isMultiFile
1312   // if( !isMultiFile ) // remove unnecessary tabulation
1313   //   RemoveTabulation( anUpdatedScript );
1314
1315   // -----------------------------------------------------------------
1316   // put string literals describing patterns into separate functions
1317   // -----------------------------------------------------------------
1318
1319   TCollection_AsciiString aLongString, aFunctionType;
1320   int where = 1;
1321   std::set< std::string > functionNameSet;
1322   while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
1323   {
1324     // make a python string literal
1325     aLongString.Prepend(":\n\treturn '''\n");
1326     aLongString += "\n\t'''\n\tpass\n";
1327
1328     TCollection_AsciiString functionName;
1329
1330     // check if the function returning this literal is already defined
1331     int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
1332     if ( posAlready ) // already defined
1333     {
1334       // find the function name
1335       int functBeg = posAlready;
1336       char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def function()"
1337       while ( *script != ' ' ) {
1338         script--;
1339         functBeg--;
1340       }
1341       functBeg++; // do not take ' '
1342       posAlready--; // do not take ':'
1343       functionName = anUpdatedScript.SubString( functBeg, posAlready );
1344     }
1345     else // not defined yet
1346     {
1347       // find a unique function name
1348       fixPythonName( aFunctionType );
1349       Standard_Integer nb = 0;
1350       do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1351       while ( !functionNameSet.insert( functionName.ToCString() ).second );
1352
1353       // define function
1354       TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1355       if ( isMultiFile )
1356       {
1357         anUpdatedScript += helper + "\n\n" + funDef;
1358       }
1359       else
1360       {
1361         funDef += "\n\n";
1362         anUpdatedScript.Insert( 1, funDef);
1363         where += funDef.Length();
1364       }
1365     }
1366     anUpdatedScript.InsertBefore( where, functionName ); // call function
1367   }
1368
1369   aValidScript = true;
1370
1371   return anUpdatedScript;
1372
1373   SMESH_CATCH( SMESH::printException );
1374
1375   aValidScript = false;
1376   return "";
1377 }
1378
1379 //=============================================================================
1380 /*!
1381  *  GetNewPythonLines
1382  */
1383 //=============================================================================
1384 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
1385 {
1386   TCollection_AsciiString aScript;
1387
1388   // Dump trace of API methods calls
1389   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1390     Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
1391     Standard_Integer istr, aLen = aPythonScript->Length();
1392     for (istr = 1; istr <= aLen; istr++) {
1393       aScript += "\n";
1394       aScript += aPythonScript->Value(istr);
1395     }
1396     aScript += "\n";
1397   }
1398
1399   return aScript;
1400 }
1401
1402 //=============================================================================
1403 /*!
1404  *  CleanPythonTrace
1405  */
1406 //=============================================================================
1407 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1408 {
1409   TCollection_AsciiString aScript;
1410
1411   // Clean trace of API methods calls
1412   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1413     myPythonScripts[theStudyID]->Clear();
1414   }
1415 }