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