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