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