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