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