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