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