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