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