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