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