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