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