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