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