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