Salome HOME
choice of MED format, minor version, for backward compatibility
[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_NodeConnectivityNumber:myStream<< "aNodeConnectivityNumber";break;
435       case FT_BelongToMeshGroup:     myStream<< "aBelongToMeshGroup";     break;
436       case FT_BelongToGeom:          myStream<< "aBelongToGeom";          break;
437       case FT_BelongToPlane:         myStream<< "aBelongToPlane";         break;
438       case FT_BelongToCylinder:      myStream<< "aBelongToCylinder";      break;
439       case FT_BelongToGenSurface:    myStream<< "aBelongToGenSurface";    break;
440       case FT_LyingOnGeom:           myStream<< "aLyingOnGeom";           break;
441       case FT_RangeOfIds:            myStream<< "aRangeOfIds";            break;
442       case FT_BadOrientedVolume:     myStream<< "aBadOrientedVolume";     break;
443       case FT_BareBorderVolume:      myStream<< "aBareBorderVolume";      break;
444       case FT_BareBorderFace:        myStream<< "aBareBorderFace";        break;
445       case FT_OverConstrainedVolume: myStream<< "aOverConstrainedVolume"; break;
446       case FT_OverConstrainedFace:   myStream<< "aOverConstrainedFace";   break;
447       case FT_LinearOrQuadratic:     myStream<< "aLinearOrQuadratic";     break;
448       case FT_GroupColor:            myStream<< "aGroupColor";            break;
449       case FT_ElemGeomType:          myStream<< "aElemGeomType";          break;
450       case FT_EntityType:            myStream<< "aEntityType";            break;
451       case FT_CoplanarFaces:         myStream<< "aCoplanarFaces";         break;
452       case FT_BallDiameter:          myStream<< "aBallDiameter";          break;
453       case FT_ConnectedElements:     myStream<< "aConnectedElements";     break;
454       case FT_LessThan:              myStream<< "aLessThan";              break;
455       case FT_MoreThan:              myStream<< "aMoreThan";              break;
456       case FT_EqualTo:               myStream<< "aEqualTo";               break;
457       case FT_LogicalNOT:            myStream<< "aLogicalNOT";            break;
458       case FT_LogicalAND:            myStream<< "aLogicalAND";            break;
459       case FT_LogicalOR:             myStream<< "aLogicalOR";             break;
460       case FT_Undefined:             myStream<< "anUndefined";            break;
461         //default: -- commented to have a compilation warning
462       }
463       myStream<<theArg;
464     }
465     return *this;
466   }
467
468   TPythonDump&
469   TPythonDump::
470   operator<<(SMESH::Measurements_i* theArg)
471   {
472     myStream<<"aMeasurements";
473     return *this;
474   }
475
476
477   TPythonDump& TPythonDump:: operator<<(SMESH_Gen_i* theArg)
478   {
479     myStream << SMESHGenName(); return *this;
480   }
481
482   TPythonDump& TPythonDump::operator<<(SMESH_MeshEditor_i* theArg)
483   {
484     myStream << MeshEditorName() << "_" << ( theArg ? theArg->GetMeshId() : -1 ); return *this;
485   }
486
487   TPythonDump& TPythonDump::operator<<(const TCollection_AsciiString & theStr)
488   {
489     myStream << theStr; return *this;
490   }
491
492
493   TPythonDump& TPythonDump::operator<<(SMESH::MED_VERSION theVersion)
494   {
495     switch (theVersion) {
496     case SMESH::MED_V2_1: myStream << "SMESH.MED_V2_1"; break;
497     case SMESH::MED_V2_2: myStream << "SMESH.MED_V2_2"; break;
498     case SMESH::MED_LATEST: myStream << "SMESH.MED_LATEST"; break;
499     case SMESH::MED_MINOR_0: myStream << "SMESH.MED_MINOR_0"; break;
500     case SMESH::MED_MINOR_1: myStream << "SMESH.MED_MINOR_1"; break;
501     case SMESH::MED_MINOR_2: myStream << "SMESH.MED_MINOR_2"; break;
502     case SMESH::MED_MINOR_3: myStream << "SMESH.MED_MINOR_3"; break;
503     case SMESH::MED_MINOR_4: myStream << "SMESH.MED_MINOR_4"; break;
504     case SMESH::MED_MINOR_5: myStream << "SMESH.MED_MINOR_5"; break;
505     case SMESH::MED_MINOR_6: myStream << "SMESH.MED_MINOR_6"; break;
506     case SMESH::MED_MINOR_7: myStream << "SMESH.MED_MINOR_7"; break;
507     case SMESH::MED_MINOR_8: myStream << "SMESH.MED_MINOR_8"; break;
508     case SMESH::MED_MINOR_9: myStream << "SMESH.MED_MINOR_9"; break;
509     default: myStream << theVersion;
510     }
511     return *this;
512   }
513
514   TPythonDump& TPythonDump::operator<<(const SMESH::AxisStruct & theAxis)
515   {
516     *this << "SMESH.AxisStruct( "
517           << TVar( theAxis.x  ) << ", "
518           << TVar( theAxis.y  ) << ", "
519           << TVar( theAxis.z  ) << ", "
520           << TVar( theAxis.vx ) << ", "
521           << TVar( theAxis.vy ) << ", "
522           << TVar( theAxis.vz ) << " )";
523     return *this;
524   }
525
526   TPythonDump& TPythonDump::operator<<(const SMESH::DirStruct & theDir)
527   {
528     const SMESH::PointStruct & P = theDir.PS;
529     *this << "SMESH.DirStruct( SMESH.PointStruct ( "
530           << TVar( P.x ) << ", "
531           << TVar( P.y ) << ", "
532           << TVar( P.z ) << " ))";
533     return *this;
534   }
535
536   TPythonDump& TPythonDump::operator<<(const SMESH::PointStruct & P)
537   {
538     *this << "SMESH.PointStruct ( "
539           << TVar( P.x ) << ", "
540           << TVar( P.y ) << ", "
541           << TVar( P.z ) << " )";
542     return *this;
543   }
544
545   TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups& theList)
546   {
547     DumpArray( theList, *this );
548     return *this;
549   }
550   TPythonDump& TPythonDump::operator<<(const SMESH::ListOfGroups * theList)
551   {
552     DumpArray( *theList, *this );
553     return *this;
554   }
555   TPythonDump& TPythonDump::operator<<(const GEOM::ListOfGO& theList)
556   {
557     DumpArray( theList, *this );
558     return *this;
559   }
560   TPythonDump& TPythonDump::operator<<(const GEOM::ListOfGBO& theList)
561   {
562     DumpArray( theList, *this );
563     return *this;
564   }
565   TPythonDump& TPythonDump::operator<<(const SMESH::ListOfIDSources& theList)
566   {
567     DumpArray( theList, *this );
568     return *this;
569   }
570   TPythonDump& TPythonDump::operator<<(const SMESH::CoincidentFreeBorders& theCFB)
571   {
572     // dump CoincidentFreeBorders as a list of lists, each enclosed list
573     // contains node IDs of a group of coincident free borders where
574     // each consequent triple of IDs describe a free border: (n1, n2, nLast)
575     // For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes
576     // two groups of coincident free borders, each group including two borders
577
578     myStream << "[";
579     for ( CORBA::ULong i = 0; i < theCFB.coincidentGroups.length(); ++i )
580     {
581       const SMESH::FreeBordersGroup& aGRP = theCFB.coincidentGroups[ i ];
582       if ( i ) myStream << ",";
583       myStream << "[";
584       for ( CORBA::ULong iP = 0; iP < aGRP.length(); ++iP )
585       {
586         const SMESH::FreeBorderPart& aPART = aGRP[ iP ];
587         if ( 0 <= aPART.border && aPART.border < (CORBA::Long)theCFB.borders.length() )
588         {
589           if ( iP ) myStream << ", ";
590           const SMESH::FreeBorder& aBRD = theCFB.borders[ aPART.border ];
591           myStream << aBRD.nodeIDs[ aPART.node1    ] << ",";
592           myStream << aBRD.nodeIDs[ aPART.node2    ] << ",";
593           myStream << aBRD.nodeIDs[ aPART.nodeLast ];
594         }
595       }
596       myStream << "]";
597     }
598     myStream << "]";
599
600     return *this;
601   }
602
603   const char* TPythonDump::NotPublishedObjectName()
604   {
605     return theNotPublishedObjectName;
606   }
607
608   TCollection_AsciiString myLongStringStart( "TPythonDump::LongStringStart" );
609   TCollection_AsciiString myLongStringEnd  ( "TPythonDump::LongStringEnd" );
610
611   //================================================================================
612   /*!
613    * \brief Return marker of long string literal beginning
614    * \param type - a name of functionality producing the string literal
615    * \retval TCollection_AsciiString - the marker string to be written into
616    * a raw python script
617    */
618   //================================================================================
619
620   TCollection_AsciiString TPythonDump::LongStringStart(const char* type)
621   {
622     return
623       myLongStringStart +
624       (Standard_Integer) strlen(type) +
625       " " +
626       (char*) type;
627   }
628
629   //================================================================================
630   /*!
631      * \brief Return marker of long string literal end
632       * \retval TCollection_AsciiString - the marker string to be written into
633       * a raw python script
634    */
635   //================================================================================
636
637   TCollection_AsciiString TPythonDump::LongStringEnd()
638   {
639     return myLongStringEnd;
640   }
641
642   //================================================================================
643   /*!
644      * \brief Cut out a long string literal from a string
645       * \param theText - text possibly containing string literals
646       * \param theFrom - position in the text to search from
647       * \param theLongString - the retrieved literal
648       * \param theStringType - a name of functionality produced the literal
649       * \retval bool - true if a string literal found
650      *
651      * The literal is removed from theText; theFrom points position right after
652      * the removed literal
653    */
654   //================================================================================
655
656   bool  TPythonDump::CutoutLongString( TCollection_AsciiString & theText,
657                                        int                     & theFrom,
658                                        TCollection_AsciiString & theLongString,
659                                        TCollection_AsciiString & theStringType)
660   {
661     if ( theFrom < 1 || theFrom > theText.Length() )
662       return false;
663
664     // ...script \  beg marker    \ \ type \       literal              \  end marker  \ script...
665     //  "theText myLongStringStart7 Pattern!!! SALOME Mesh Pattern file myLongStringEndtextEnd"
666     //  012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
667     //  0         1         2         3         4         5         6         7         8
668
669     theFrom = theText.Location( myLongStringStart, theFrom, theText.Length() ); // = 09
670     if ( !theFrom )
671       return false;
672
673     // find where literal begins
674     int literalBeg = theFrom + myLongStringStart.Length(); // = 26
675     char* typeLenStr = (char*) theText.ToCString() + literalBeg - 1; // = "7 Pattern!!! SALO...."
676     int typeLen = atoi ( typeLenStr ); // = 7
677     while ( *typeLenStr != ' ' ) { // look for ' ' after typeLen
678       literalBeg++; // 26 -> 27
679       typeLenStr++;
680     }
681     literalBeg += typeLen + 1; // = 35
682     if ( literalBeg > theText.Length() )
683       return false;
684
685     // where literal ends (i.e. end marker begins)
686     int literalEnd = theText.Location( myLongStringEnd, literalBeg, theText.Length() ); // = 64
687     if ( !literalEnd )
688       literalEnd = theText.Length();
689
690     // literal
691     theLongString = theText.SubString( literalBeg, literalEnd - 1); // "!!! SALOME Mesh Pattern file "
692     // type
693     theStringType = theText.SubString( literalBeg - typeLen, literalBeg - 1 ); // "Pattern"
694     // cut off literal
695     literalEnd += myLongStringEnd.Length(); // = 79
696     TCollection_AsciiString textEnd = theText.SubString( literalEnd, theText.Length() ); // "textE..."
697     theText = theText.SubString( 1, theFrom - 1 ) + textEnd;
698
699     return true;
700   }
701
702   void printException( const char* text )
703   {
704 #ifdef _DEBUG_
705     cout << "Exception in SMESH_Gen_i::DumpPython(): " << text << endl;
706 #endif
707   }
708 }
709
710 //=======================================================================
711 //function : RemoveTabulation
712 //purpose  : 
713 //=======================================================================
714 void RemoveTabulation( TCollection_AsciiString& theScript )
715 {
716   std::string aString( theScript.ToCString() );
717   std::string::size_type aPos = 0;
718   while( aPos < aString.length() )
719   {
720     aPos = aString.find( "\n\t", aPos );
721     if( aPos == std::string::npos )
722       break;
723     aString.replace( aPos, 2, "\n" );
724     aPos++;
725   }
726   theScript = aString.c_str();
727 }
728
729 //=======================================================================
730 //function : DumpPython
731 //purpose  :
732 //=======================================================================
733 Engines::TMPFile* SMESH_Gen_i::DumpPython (CORBA::Object_ptr theStudy,
734                                            CORBA::Boolean isPublished,
735                                            CORBA::Boolean isMultiFile,
736                                            CORBA::Boolean& isValidScript)
737 {
738   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
739   if (CORBA::is_nil(aStudy))
740     return new Engines::TMPFile(0);
741
742   CORBA::String_var compDataType = ComponentDataType();
743   SALOMEDS::SObject_wrap aSO = aStudy->FindComponent( compDataType.in() );
744   if (CORBA::is_nil(aSO))
745     return new Engines::TMPFile(0);
746
747   // Map study entries to object names
748   Resource_DataMapOfAsciiStringAsciiString aMap;
749   Resource_DataMapOfAsciiStringAsciiString aMapNames;
750
751   SALOMEDS::ChildIterator_wrap Itr = aStudy->NewChildIterator(aSO);
752   for (Itr->InitEx(true); Itr->More(); Itr->Next()) {
753     SALOMEDS::SObject_wrap aValue = Itr->Value();
754     CORBA::String_var anID = aValue->GetID();
755     CORBA::String_var aName = aValue->GetName();
756     TCollection_AsciiString aGUIName ( (char*) aName.in() );
757     TCollection_AsciiString anEntry ( (char*) anID.in() );
758     if (aGUIName.Length() > 0) {
759       aMapNames.Bind( anEntry, aGUIName );
760       aMap.Bind( anEntry, aGUIName );
761     }
762   }
763
764   // Get trace of restored study
765   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
766   SALOMEDS::GenericAttribute_wrap anAttr =
767     aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
768
769   SALOMEDS::AttributePythonObject_var pyAttr =
770     SALOMEDS::AttributePythonObject::_narrow(anAttr);
771   CORBA::String_var oldValue = pyAttr->GetObject();
772   TCollection_AsciiString aSavedTrace (oldValue.in());
773
774   // Add trace of API methods calls and replace study entries by names
775   TCollection_AsciiString aScript;
776   aScript += DumpPython_impl(aStudy, aMap, aMapNames, isPublished, isMultiFile,
777                              myIsHistoricalPythonDump, isValidScript, aSavedTrace);
778
779   int aLen = aScript.Length();
780   unsigned char* aBuffer = new unsigned char[aLen+1];
781   strcpy((char*)aBuffer, aScript.ToCString());
782
783   CORBA::Octet* anOctetBuf =  (CORBA::Octet*)aBuffer;
784   Engines::TMPFile_var aStreamFile = new Engines::TMPFile(aLen+1, aLen+1, anOctetBuf, 1);
785
786   bool hasNotPublishedObjects = aScript.Location( SMESH::theNotPublishedObjectName, 1, aLen);
787   isValidScript = isValidScript && !hasNotPublishedObjects;
788
789   return aStreamFile._retn();
790 }
791
792 //=============================================================================
793 /*!
794  *  AddToPythonScript
795  */
796 //=============================================================================
797 void SMESH_Gen_i::AddToPythonScript (int theStudyID, const TCollection_AsciiString& theString)
798 {
799   if (myPythonScripts.find(theStudyID) == myPythonScripts.end()) {
800     myPythonScripts[theStudyID] = new TColStd_HSequenceOfAsciiString;
801   }
802   myPythonScripts[theStudyID]->Append(theString);
803 }
804
805 //=============================================================================
806 /*!
807  *  RemoveLastFromPythonScript
808  */
809 //=============================================================================
810 void SMESH_Gen_i::RemoveLastFromPythonScript (int theStudyID)
811 {
812   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
813     int aLen = myPythonScripts[theStudyID]->Length();
814     myPythonScripts[theStudyID]->Remove(aLen);
815   }
816 }
817
818 //=======================================================================
819 //function : SavePython
820 //purpose  :
821 //=======================================================================
822 void SMESH_Gen_i::SavePython (SALOMEDS::Study_ptr theStudy)
823 {
824   // Dump trace of API methods calls
825   TCollection_AsciiString aScript = GetNewPythonLines(theStudy->StudyId());
826
827   // Check contents of PythonObject attribute
828   CORBA::String_var compDataType = ComponentDataType();
829   SALOMEDS::SObject_wrap aSO = theStudy->FindComponent( compDataType.in() );
830   SALOMEDS::StudyBuilder_var aStudyBuilder = theStudy->NewBuilder();
831   SALOMEDS::GenericAttribute_wrap anAttr =
832     aStudyBuilder->FindOrCreateAttribute(aSO, "AttributePythonObject");
833
834   SALOMEDS::AttributePythonObject_var pyAttr =
835     SALOMEDS::AttributePythonObject::_narrow(anAttr);
836   CORBA::String_var oldValue = pyAttr->GetObject();
837   TCollection_AsciiString oldScript (oldValue.in());
838
839   if (oldScript.Length() > 0) {
840     oldScript += "\n";
841     oldScript += aScript;
842   } else {
843     oldScript = aScript;
844   }
845
846   // Store in PythonObject attribute
847   pyAttr->SetObject(oldScript.ToCString(), 1);
848
849   // Clean trace of API methods calls
850   CleanPythonTrace(theStudy->StudyId());
851 }
852
853
854 // impl
855
856
857 //=============================================================================
858 /*!
859  *  FindEntries: Returns a sequence of start/end positions of entries in the string
860  */
861 //=============================================================================
862 Handle(TColStd_HSequenceOfInteger) FindEntries (TCollection_AsciiString& theString)
863 {
864   Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
865   Standard_Integer aLen = theString.Length();
866   Standard_Boolean isFound = Standard_False;
867
868   char* arr = (char*) theString.ToCString();
869   Standard_Integer i = 0, j;
870
871   while(i < aLen) {
872     int c = (int)arr[i];
873     j = i+1;
874     if ( isdigit( c )) { //Is digit?
875
876       isFound = Standard_False;
877       while((j < aLen) && ( isdigit(c) || c == ':' )) { //Check if it is an entry
878         c = (int)arr[j++];
879         if(c == ':') isFound = Standard_True;
880       }
881
882       if (isFound) {
883         int prev = (i < 1) ? 0 : (int)arr[i - 1];
884         // to distinguish from a sketcher command:
885         // last char should be a digit, not ":",
886         // previous char should not be '"'.
887         if (arr[j-2] != ':' && prev != '"') {
888           aSeq->Append(i+1); // +1 because AsciiString starts from 1
889           aSeq->Append(j-1);
890         }
891       }
892     }
893
894     i = j;
895   }
896
897   return aSeq;
898 }
899
900 namespace {
901
902   //================================================================================
903   /*!
904    * \brief Make a string be a valid python name
905     * \param aName - a string to fix
906     * \retval bool - true if aName was not modified
907    */
908   //================================================================================
909
910   bool fixPythonName(TCollection_AsciiString & aName)
911   {
912     bool isValidName = true;
913     int nbUnderscore = 0;
914     int p;
915     // replace not allowed chars by underscore
916     const char* name = aName.ToCString();
917     for ( p = 0; name[p]; ++p ) {
918       if ( !isalnum( name[p] ) && name[p] != '_' )
919       {
920         if ( p == 0 || p+1 == aName.Length() || name[p-1] == '_')
921         {
922           aName.Remove( p+1, 1 ); // remove __ and _ from the start and the end
923           --p;
924           name = aName.ToCString();
925         }
926         else
927         {
928           aName.SetValue( p+1, '_');
929           nbUnderscore++;
930         }
931         isValidName = false;
932       }
933     }
934     // aName must not start with a digit
935     if ( aName.IsIntegerValue() ) {
936       aName.Insert( 1, 'a' );
937       isValidName = false;
938     }
939     // shorten names like CartesianParameters3D_400_400_400_1000000_1
940     const int nbAllowedUnderscore = 3; /* changed from 2 to 3 by an user request
941                                           posted to SALOME Forum */
942     if ( aName.Length() > 20 && nbUnderscore > nbAllowedUnderscore )
943     {
944       p = aName.Location( "_", 20, aName.Length());
945       if ( p > 1 )
946         aName.Trunc( p-1 );
947     }
948     return isValidName;
949   }
950
951   //================================================================================
952   /*!
953    * \brief Return Python module names of available plug-ins.
954    */
955   //================================================================================
956
957   std::vector<std::string> getPluginNames()
958   {
959     std::vector<std::string> pluginNames;
960     std::vector< std::string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
961     LDOMParser xmlParser;
962     for ( size_t i = 0; i < xmlPaths.size(); ++i )
963     {
964       bool error = xmlParser.parse( xmlPaths[i].c_str() );
965       if ( error )
966       {
967         TCollection_AsciiString data;
968         INFOS( xmlParser.GetError(data) );
969         continue;
970       }
971       // <meshers-group name="Standard Meshers"
972       //                resources="StdMeshers"
973       //                idl-module="StdMeshers"
974       //                server-lib="StdMeshersEngine"
975       //                gui-lib="StdMeshersGUI">
976       LDOM_Document xmlDoc   = xmlParser.getDocument();
977       LDOM_NodeList nodeList = xmlDoc.getElementsByTagName( "meshers-group" );
978       for ( int i = 0; i < nodeList.getLength(); ++i )
979       {
980         LDOM_Node       node = nodeList.item( i );
981         LDOM_Element&   elem = (LDOM_Element&) node;
982         LDOMString idlModule = elem.getAttribute( "idl-module" );
983         if ( strlen( idlModule.GetString() ) > 0 )
984           pluginNames.push_back( idlModule.GetString() );
985       }
986     }
987     return pluginNames;
988   }
989 }
990
991 //================================================================================
992 /*!
993  * \brief Createa a Dump Python script
994  *  \param [in] theStudy - the study to dump
995  *  \param [in,out] theObjectNames - map of an entry to a study and python name
996  *  \param [in] theNames -  - map of an entry to a study name
997  *  \param [in] isPublished - \c true if dump of object publication in study is needed
998  *  \param [in] isMultiFile - \c true if dump of each module goes to a separate file
999  *  \param [in] isHistoricalDump - \c true if removed object should be dumped
1000  *  \param [out] aValidScript - returns \c true if the returned script seems valid
1001  *  \param [in,out] theSavedTrace - the dump stored in the study. It's cleared to
1002  *         decrease memory usage.
1003  *  \return TCollection_AsciiString - the result dump script.
1004  */
1005 //================================================================================
1006
1007 TCollection_AsciiString SMESH_Gen_i::DumpPython_impl
1008                         (SALOMEDS::Study_ptr                       theStudy,
1009                          Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
1010                          Resource_DataMapOfAsciiStringAsciiString& theNames,
1011                          bool                                      isPublished,
1012                          bool                                      isMultiFile,
1013                          bool                                      isHistoricalDump,
1014                          bool&                                     aValidScript,
1015                          TCollection_AsciiString&                  theSavedTrace)
1016 {
1017   SMESH_TRY;
1018   const int aStudyID = theStudy->StudyId();
1019
1020   const TCollection_AsciiString aSmeshpy ( SMESH_2smeshpy::SmeshpyName() );
1021   const TCollection_AsciiString aSMESHGen( SMESH_2smeshpy::GenName() );
1022   const TCollection_AsciiString anOldGen ( SMESH::TPythonDump::SMESHGenName() );
1023   const TCollection_AsciiString helper; // to comfortably append C strings to TCollection_AsciiString
1024   const TCollection_AsciiString tab( isMultiFile ? "\t" : "" ), nt = helper + "\n" + tab;
1025
1026   std::list< TCollection_AsciiString > lines; // lines of a script
1027   std::list< TCollection_AsciiString >::iterator linesIt;
1028   
1029   if ( isPublished )
1030     lines.push_back(  aSMESHGen + " = smeshBuilder.New(theStudy)" );
1031    else
1032     lines.push_back(  aSMESHGen + " = smeshBuilder.New(None)" );
1033   lines.push_back( helper + "aFilterManager = " + aSMESHGen + ".CreateFilterManager()" );
1034   lines.push_back( helper + "aMeasurements = "  + aSMESHGen + ".CreateMeasurements()" );
1035
1036   // Treat dump trace of restored study
1037   if (theSavedTrace.Length() > 0)
1038   {
1039     linesIt = --lines.end();
1040     // Split theSavedTrace into lines
1041     int from = 1, end = theSavedTrace.Length(), to;
1042     while ( from < end && ( to = theSavedTrace.Location( "\n", from, end )))
1043     {
1044       if ( theSavedTrace.ToCString()[from-1] == '\t' )
1045         ++from;
1046       if ( to != from )
1047         lines.push_back( theSavedTrace.SubString( from, to - 1 ));
1048       from = to + 1;
1049     }
1050     // For the conversion of IDL API calls -> smeshBuilder.py API, "smesh" standing for SMESH_Gen
1051     // was replaces with "smeshgen" (==TPythonDump::SMESHGenName()).
1052     // Change "smesh" -> "smeshgen" in the trace saved before passage to smeshBuilder.py API
1053     bool isNewVersion =
1054       theSavedTrace.Location( anOldGen + ".", 1, theSavedTrace.Length() );
1055     theSavedTrace.Clear();
1056     if ( !isNewVersion )
1057     {
1058       const TCollection_AsciiString aSmeshCall ( "smesh." ), gen( "gen" );
1059       int beg, end, from;
1060       for ( ++linesIt; linesIt != lines.end(); ++linesIt )
1061       {
1062         TCollection_AsciiString& aSavedLine = *linesIt;
1063         end = aSavedLine.Length(), from = 1;
1064         while ( from < end && ( beg = aSavedLine.Location( aSmeshCall, from, end )))
1065         {
1066           char charBefore = ( beg == 1 ) ? ' ' : aSavedLine.Value( beg - 1 );
1067           if ( isspace( charBefore ) || charBefore == '=' ) { // "smesh." is not a part of a long word
1068             aSavedLine.Insert( beg + aSmeshCall.Length() - 1, gen );// "smesh" -> "smeshgen"
1069             end += gen.Length();
1070           }
1071           from = beg + aSmeshCall.Length();
1072         }
1073       }
1074     }
1075   }
1076
1077   // Add new dump trace of API methods calls to script lines
1078   if (myPythonScripts.find( aStudyID ) != myPythonScripts.end())
1079   {
1080     Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[ aStudyID ];
1081     Standard_Integer istr, aLen = aPythonScript->Length();
1082     for (istr = 1; istr <= aLen; istr++)
1083       lines.push_back( aPythonScript->Value( istr ));
1084   }
1085
1086   // Convert IDL API calls into smeshBuilder.py API.
1087   // Some objects are wrapped with python classes and
1088   // Resource_DataMapOfAsciiStringAsciiString holds methods returning wrapped objects
1089   Resource_DataMapOfAsciiStringAsciiString anEntry2AccessorMethod;
1090   std::set< TCollection_AsciiString >      aRemovedObjIDs;
1091   if ( !getenv("NO_2smeshpy_conversion"))
1092     SMESH_2smeshpy::ConvertScript( lines, anEntry2AccessorMethod,
1093                                    theObjectNames, aRemovedObjIDs,
1094                                    theStudy, isHistoricalDump );
1095
1096   bool importGeom = false;
1097   GEOM::GEOM_Gen_ptr geom = GetGeomEngine();
1098   {
1099     // Add names of GEOM objects to theObjectNames to exclude same names of SMESH objects
1100     GEOM::string_array_var aGeomNames = geom->GetAllDumpNames();
1101     int ign = 0, nbgn = aGeomNames->length();
1102     for (; ign < nbgn; ign++) {
1103       TCollection_AsciiString aName = aGeomNames[ign].in();
1104       theObjectNames.Bind(aName, "1");
1105     }
1106   }
1107
1108   TCollection_AsciiString anUpdatedScript;
1109
1110   Resource_DataMapOfAsciiStringAsciiString mapRemoved;
1111   Resource_DataMapOfAsciiStringAsciiString mapEntries; // names and entries present in anUpdatedScript
1112   Standard_Integer objectCounter = 0;
1113   TCollection_AsciiString anEntry, aName, aGUIName, aBaseName("smeshObj_");
1114
1115   // Treat every script line and add it to anUpdatedScript
1116   for ( linesIt = lines.begin(); linesIt != lines.end(); ++linesIt )
1117   {
1118     TCollection_AsciiString& aLine = *linesIt;
1119     anUpdatedScript += tab;
1120     {
1121       //Replace characters used instead of quote marks to quote notebook variables
1122       int pos = 1;
1123       while (( pos = aLine.Location( 1, SMESH::TVar::Quote(), pos, aLine.Length() )))
1124         aLine.SetValue( pos, '"' );
1125     }
1126     // Find entries to be replaced by names
1127     Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aLine);
1128     const Standard_Integer aSeqLen = aSeq->Length();
1129     Standard_Integer aStart = 1;
1130     for (Standard_Integer i = 1; i <= aSeqLen; i += 2)
1131     {
1132       if ( aStart < aSeq->Value(i) )
1133         anUpdatedScript += aLine.SubString( aStart, aSeq->Value(i) - 1 ); // line part before i-th entry
1134       anEntry = aLine.SubString( aSeq->Value(i), aSeq->Value(i + 1) );
1135       // is a GEOM object?
1136       CORBA::String_var geomName = geom->GetDumpName( anEntry.ToCString() );
1137       if ( !geomName.in() || !geomName.in()[0] ) {
1138         // is a SMESH object
1139         if ( theObjectNames.IsBound( anEntry )) {
1140           // The Object is in Study
1141           aName = theObjectNames.Find( anEntry );
1142           // check validity of aName
1143           bool isValidName = fixPythonName( aName );
1144           if (theObjectNames.IsBound(aName) && anEntry != theObjectNames(aName)) {
1145             // diff objects have same name - make a new name by appending a digit
1146             TCollection_AsciiString aName2;
1147             Standard_Integer i = 0;
1148             do {
1149               aName2 = aName + "_" + ++i;
1150             } while (theObjectNames.IsBound(aName2) && anEntry != theObjectNames(aName2));
1151             aName = aName2;
1152             isValidName = false;
1153           }
1154           if ( !isValidName )
1155             theObjectNames(anEntry) = aName;
1156
1157           if ( aLine.Value(1) != '#' )
1158             mapEntries.Bind(anEntry, aName);
1159         }
1160         else
1161         {
1162           // Removed Object
1163           do {
1164             aName = aBaseName + (++objectCounter);
1165           } while (theObjectNames.IsBound(aName));
1166
1167           if ( !aRemovedObjIDs.count( anEntry ) && aLine.Value(1) != '#')
1168             mapRemoved.Bind(anEntry, aName);
1169
1170           theObjectNames.Bind(anEntry, aName);
1171         }
1172         theObjectNames.Bind(aName, anEntry); // to detect same name of diff objects
1173       }
1174       else
1175       {
1176         aName = geomName.in();
1177         importGeom = true;
1178       }
1179       anUpdatedScript += aName;
1180       aStart = aSeq->Value(i + 1) + 1;
1181
1182     } // loop on entries within aLine
1183
1184     if ( aSeqLen == 0 )
1185       anUpdatedScript += aLine;
1186     else if ( aSeq->Value( aSeqLen ) < aLine.Length() )
1187       anUpdatedScript += aLine.SubString( aSeq->Value(aSeqLen) + 1, aLine.Length() );
1188
1189     anUpdatedScript += '\n';
1190   }
1191
1192   // Make an initial part of aSript
1193
1194   TCollection_AsciiString initPart = "import ";
1195   if ( isMultiFile )
1196     initPart += "salome, ";
1197   initPart += " SMESH, SALOMEDS\n";
1198   initPart += "from salome.smesh import smeshBuilder\n";
1199   if ( importGeom && isMultiFile )
1200   {
1201     initPart += ("\n## import GEOM dump file ## \n"
1202                  "import string, os, sys, re, inspect\n"
1203                  "thisFile   = inspect.getfile( inspect.currentframe() )\n"
1204                  "thisModule = os.path.splitext( os.path.basename( thisFile ))[0]\n"
1205                  "sys.path.insert( 0, os.path.dirname( thisFile ))\n"
1206                  "exec(\"from \"+re.sub(\"SMESH$\",\"GEOM\",thisModule)+\" import *\")\n\n");
1207   }
1208   // import python files corresponding to plugins if they are used in anUpdatedScript
1209   {
1210     TCollection_AsciiString importStr;
1211     std::vector<std::string> pluginNames = getPluginNames();
1212     for ( size_t i = 0; i < pluginNames.size(); ++i )
1213     {
1214       // Convert access to plugin members:
1215       // e.g. StdMeshers.QUAD_REDUCED -> StdMeshersBuilder.QUAD_REDUCED
1216       TCollection_AsciiString pluginAccess = (pluginNames[i] + ".").c_str() ;
1217       int iFrom = 1, iPos;
1218       while (( iPos = anUpdatedScript.Location( pluginAccess, iFrom, anUpdatedScript.Length() )))
1219       {
1220         anUpdatedScript.Insert( iPos + pluginNames[i].size(), "Builder" );
1221         iFrom = iPos + pluginNames[i].size() + 8;
1222       }
1223       // if any plugin member is used, import the plugin
1224       if ( iFrom > 1 )
1225         importStr += ( helper + "\n" "from salome." + pluginNames[i].c_str() +
1226                        " import " + pluginNames[i].c_str() +"Builder" );
1227     }
1228     if ( !importStr.IsEmpty() )
1229       initPart += importStr + "\n";
1230   }
1231
1232   if ( isMultiFile )
1233     initPart += "def RebuildData(theStudy):";
1234   initPart += "\n";
1235
1236   anUpdatedScript.Prepend( initPart );
1237
1238   // Make a final part of aScript
1239
1240   // Dump object removal
1241   TCollection_AsciiString removeObjPart;
1242   if ( !mapRemoved.IsEmpty() ) {
1243     removeObjPart += nt + "## some objects were removed";
1244     removeObjPart += nt + "aStudyBuilder = theStudy.NewBuilder()";
1245     Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString mapRemovedIt;
1246     for ( mapRemovedIt.Initialize( mapRemoved ); mapRemovedIt.More(); mapRemovedIt.Next() ) {
1247       aName   = mapRemovedIt.Value(); // python name
1248       anEntry = mapRemovedIt.Key();
1249       removeObjPart += nt + "SO = theStudy.FindObjectIOR(theStudy.ConvertObjectToIOR(";
1250       removeObjPart += aName;
1251       // for object wrapped by class of smeshBuilder.py
1252       if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1253         removeObjPart += helper + "." + anEntry2AccessorMethod( anEntry );
1254       removeObjPart += helper + "))" + nt + "if SO: aStudyBuilder.RemoveObjectWithChildren(SO)";
1255     }
1256   }
1257
1258   // Set object names
1259   TCollection_AsciiString setNamePart;
1260   Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString mapEntriesIt;
1261   for ( mapEntriesIt.Initialize( mapEntries ); mapEntriesIt.More(); mapEntriesIt.Next() )
1262   {
1263     anEntry = mapEntriesIt.Key();
1264     aName   = mapEntriesIt.Value(); // python name
1265     if ( theNames.IsBound( anEntry ))
1266     {
1267       aGUIName = theNames.Find(anEntry);
1268       aGUIName.RemoveAll('\''); // remove a quote from a name (issue 22360)
1269       setNamePart += nt + aSMESHGen + ".SetName(" + aName;
1270       if ( anEntry2AccessorMethod.IsBound( anEntry ) )
1271         setNamePart += helper + "." + anEntry2AccessorMethod( anEntry );
1272       setNamePart += helper + ", '" + aGUIName + "')";
1273     }
1274   }
1275   if ( !setNamePart.IsEmpty() )
1276   {
1277     setNamePart.Insert( 1, nt + "## Set names of Mesh objects" );
1278   }
1279
1280   // Store visual properties of displayed objects
1281
1282   TCollection_AsciiString visualPropertiesPart;
1283   if (isPublished)
1284   {
1285     //Output the script that sets up the visual parameters.
1286     CORBA::String_var compDataType = ComponentDataType();
1287     CORBA::String_var script = theStudy->GetDefaultScript( compDataType.in(), tab.ToCString() );
1288     if ( script.in() && script.in()[0] ) {
1289       visualPropertiesPart += nt + "### Store presentation parameters of displayed objects\n";
1290       visualPropertiesPart += script.in();
1291     }
1292   }
1293
1294   anUpdatedScript += removeObjPart + '\n' + setNamePart + '\n' + visualPropertiesPart;
1295
1296   if ( isMultiFile )
1297   {
1298     anUpdatedScript +=
1299       "\n\tpass"
1300       "\n"
1301       "\nif __name__ == '__main__':"
1302       "\n\tSMESH_RebuildData = RebuildData"
1303       "\n\texec('import '+re.sub('SMESH$','GEOM',thisModule)+' as GEOM_dump')"
1304       "\n\tGEOM_dump.RebuildData( salome.myStudy )"
1305       "\n\texec('from '+re.sub('SMESH$','GEOM',thisModule)+' import * ')"
1306       "\n\tSMESH_RebuildData( salome.myStudy )";
1307   }
1308   anUpdatedScript += "\n";
1309
1310   // no need now as we use 'tab' and 'nt' variables depending on isMultiFile
1311   // if( !isMultiFile ) // remove unnecessary tabulation
1312   //   RemoveTabulation( anUpdatedScript );
1313
1314   // -----------------------------------------------------------------
1315   // put string literals describing patterns into separate functions
1316   // -----------------------------------------------------------------
1317
1318   TCollection_AsciiString aLongString, aFunctionType;
1319   int where = 1;
1320   std::set< std::string > functionNameSet;
1321   while ( SMESH::TPythonDump::CutoutLongString( anUpdatedScript, where, aLongString, aFunctionType ))
1322   {
1323     // make a python string literal
1324     aLongString.Prepend(":\n\treturn '''\n");
1325     aLongString += "\n\t'''\n\tpass\n";
1326
1327     TCollection_AsciiString functionName;
1328
1329     // check if the function returning this literal is already defined
1330     int posAlready = anUpdatedScript.Location( aLongString, where, anUpdatedScript.Length() );
1331     if ( posAlready ) // already defined
1332     {
1333       // find the function name
1334       int functBeg = posAlready;
1335       char* script = (char*) anUpdatedScript.ToCString() + posAlready - 1; // look at ":" after "def fuction()"
1336       while ( *script != ' ' ) {
1337         script--;
1338         functBeg--;
1339       }
1340       functBeg++; // do not take ' '
1341       posAlready--; // do not take ':'
1342       functionName = anUpdatedScript.SubString( functBeg, posAlready );
1343     }
1344     else // not defined yet
1345     {
1346       // find a unique function name
1347       fixPythonName( aFunctionType );
1348       Standard_Integer nb = 0;
1349       do functionName = aFunctionType + "_" + ( nb++ ) + "()";
1350       while ( !functionNameSet.insert( functionName.ToCString() ).second );
1351
1352       // define function
1353       TCollection_AsciiString funDef = helper + "def " + functionName + aLongString;
1354       if ( isMultiFile )
1355       {
1356         anUpdatedScript += helper + "\n\n" + funDef;
1357       }
1358       else
1359       {
1360         funDef += "\n\n";
1361         anUpdatedScript.Insert( 1, funDef);
1362         where += funDef.Length();
1363       }
1364     }
1365     anUpdatedScript.InsertBefore( where, functionName ); // call function
1366   }
1367
1368   aValidScript = true;
1369
1370   return anUpdatedScript;
1371
1372   SMESH_CATCH( SMESH::printException );
1373
1374   aValidScript = false;
1375   return "";
1376 }
1377
1378 //=============================================================================
1379 /*!
1380  *  GetNewPythonLines
1381  */
1382 //=============================================================================
1383 TCollection_AsciiString SMESH_Gen_i::GetNewPythonLines (int theStudyID)
1384 {
1385   TCollection_AsciiString aScript;
1386
1387   // Dump trace of API methods calls
1388   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1389     Handle(TColStd_HSequenceOfAsciiString) aPythonScript = myPythonScripts[theStudyID];
1390     Standard_Integer istr, aLen = aPythonScript->Length();
1391     for (istr = 1; istr <= aLen; istr++) {
1392       aScript += "\n";
1393       aScript += aPythonScript->Value(istr);
1394     }
1395     aScript += "\n";
1396   }
1397
1398   return aScript;
1399 }
1400
1401 //=============================================================================
1402 /*!
1403  *  CleanPythonTrace
1404  */
1405 //=============================================================================
1406 void SMESH_Gen_i::CleanPythonTrace (int theStudyID)
1407 {
1408   TCollection_AsciiString aScript;
1409
1410   // Clean trace of API methods calls
1411   if (myPythonScripts.find(theStudyID) != myPythonScripts.end()) {
1412     myPythonScripts[theStudyID]->Clear();
1413   }
1414 }