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