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