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