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