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