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