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