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