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