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