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