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