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