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