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