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