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