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