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