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