Salome HOME
Typo-fix by Kunda + fix user doc generation
[modules/smesh.git] / src / SMESH_I / SMESH_2smeshpy.cxx
1 // Copyright (C) 2007-2016  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, or (at your option) any later version.
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_2smeshpy.cxx
24 // Created   : Fri Nov 18 13:20:10 2005
25 // Author    : Edward AGAPOV (eap)
26 //
27 #include "SMESH_2smeshpy.hxx"
28
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
32
33 #include <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
35
36 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
38
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41  * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42  * that declare methods named GetObject - to apply the same rules of GetObject renaming
43  * and thus to avoid mess with GetObject symbol on Windows */
44
45 #include <LDOMParser.hxx>
46
47 #ifdef WIN32
48 #include <windows.h>
49 #else
50 #include <unistd.h>
51 #endif
52
53 IMPLEMENT_STANDARD_RTTIEXT(_pyObject          ,Standard_Transient);
54 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand         ,Standard_Transient);
55 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
56 IMPLEMENT_STANDARD_RTTIEXT(_pyGen             ,_pyObject);
57 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh            ,_pyObject);
58 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh         ,_pyObject);
59 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor      ,_pyObject);
60 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis      ,_pyObject);
61 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser      ,_pyObject);
62 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup           ,_pyObject);
63 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter          ,_pyObject);
64 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm       ,_pyHypothesis);
65 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
66 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
67 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
68 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
69
70 using namespace std;
71 using SMESH::TPythonDump;
72
73 /*!
74  * \brief Container of commands into which the initial script is split.
75  *        It also contains data corresponding to SMESH_Gen contents
76  */
77 static Handle(_pyGen) theGen;
78
79 static TCollection_AsciiString theEmptyString;
80
81 //#define DUMP_CONVERSION
82
83 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
84 #undef DUMP_CONVERSION
85 #endif
86
87
88 namespace {
89
90   //================================================================================
91   /*!
92    * \brief Set of TCollection_AsciiString initialized by C array of C strings
93    */
94   //================================================================================
95
96   struct TStringSet: public set<TCollection_AsciiString>
97   {
98     /*!
99      * \brief Filling. The last string must be ""
100      */
101     void Insert(const char* names[]) {
102       for ( int i = 0; names[i][0] ; ++i )
103         insert( (char*) names[i] );
104     }
105     /*!
106      * \brief Check if a string is in
107      */
108     bool Contains(const TCollection_AsciiString& name ) {
109       return find( name ) != end();
110     }
111   };
112
113   //================================================================================
114   /*!
115    * \brief Map of TCollection_AsciiString initialized by C array of C strings.
116    *        Odd items of the C array are map keys, and even items are values
117    */
118   //================================================================================
119
120   struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
121   {
122     /*!
123      * \brief Filling. The last string must be ""
124      */
125     void Insert(const char* names_values[]) {
126       for ( int i = 0; names_values[i][0] ; i += 2 )
127         insert( make_pair( (char*) names_values[i], names_values[i+1] ));
128     }
129     /*!
130      * \brief Check if a string is in
131      */
132     TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
133       map< _AString, _AString >::iterator it = find( name );
134       return it == end() ? "" : it->second;
135     }
136   };
137
138   //================================================================================
139   /*!
140    * \brief Returns a mesh by object
141    */
142   //================================================================================
143
144   Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
145   {
146     if ( !obj.IsNull() )
147     {
148       if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
149         return Handle(_pyMesh)::DownCast( obj );
150       else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
151         return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
152       else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
153         return Handle(_pyGroup)::DownCast( obj )->GetMesh();
154     }
155     return Handle(_pyMesh)();
156   }
157
158   //================================================================================
159   /*!
160    * \brief Check if objects used as args have been created by previous commands
161    */
162   //================================================================================
163
164   void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
165   {
166     // either comment or erase a command including NotPublishedObjectName()
167     if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
168     {
169       bool isResultPublished = false;
170       const int nbRes = cmd->GetNbResultValues();
171       for ( int i = 0; i < nbRes; i++ )
172       {
173         _pyID objID = cmd->GetResultValue( i+1 );
174         if ( cmd->IsStudyEntry( objID ))
175           isResultPublished = (! theGen->IsNotPublished( objID ));
176         theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
177       }
178       if ( isResultPublished )
179         cmd->Comment();
180       else
181         cmd->Clear();
182       return;
183     }
184     // check if an Object was created in the script
185     _AString comment;
186
187     _pyID obj = cmd->GetObject();
188     if ( obj.Search( "print(" ) == 1 )
189       return; // print statement
190
191     if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
192       // remove an accessor method
193       obj = _pyCommand( obj ).GetObject();
194
195     const bool isMethodCall = cmd->IsMethodCall();
196     if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
197     {
198       comment = "not created Object";
199       theGen->ObjectCreationRemoved( obj );
200     }
201     // check if a command has not created args
202     for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
203     {
204       const _pyID& arg = cmd->GetArg( iArg );
205       if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
206         continue;
207       list< _pyID > idList = cmd->GetStudyEntries( arg );
208       list< _pyID >::iterator id = idList.begin();
209       for ( ; id != idList.end(); ++id )
210         if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
211         {
212           comment += *id + " has not been yet created";
213           break;
214         }
215       // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
216       //   comment += arg + " has not been yet created";
217     }
218     // treat result objects
219     const _pyID& result = cmd->GetResultValue();
220     if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
221     {
222       list< _pyID > idList = cmd->GetStudyEntries( result );
223       list< _pyID >::iterator id = idList.begin();
224       for ( ; id != idList.end(); ++id )
225       {
226         if ( comment.IsEmpty() )
227           presentObjects.insert( *id );
228         else
229           theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
230       }
231       if ( idList.empty() && cmd->IsID( result ))
232         presentObjects.insert( result );
233     }
234     // comment the command
235     if ( !comment.IsEmpty() )
236     {
237       cmd->Comment();
238       cmd->GetString() += " ### ";
239       cmd->GetString() += comment;
240     }
241   }
242
243   //================================================================================
244   /*!
245    * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
246    */
247   //================================================================================
248
249   void fixFunctorType( TCollection_AsciiString& Type,
250                        TCollection_AsciiString& Compare,
251                        TCollection_AsciiString& UnaryOp,
252                        TCollection_AsciiString& BinaryOp )
253   {
254     // The problem is that dumps of old studies created using filters becomes invalid
255     // when new items are inserted in the enum SMESH::FunctorType since values
256     // of this enum are dumped as integer values.
257     // This function corrects enum values of old studies given as args (Type,Compare,...)
258     // We can find out how to correct them by value of BinaryOp which can have only two
259     // values: FT_Undefined or FT_LogicalNOT.
260     // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
261     // where PythonDump appeared
262     // v 3.0.0: FT_Undefined == 25
263     // v 3.1.0: FT_Undefined == 26, new items:
264     //   - FT_Volume3D              = 7
265     // v 4.1.2: FT_Undefined == 27, new items:
266     //   - FT_BelongToGenSurface    = 17
267     // v 5.1.1: FT_Undefined == 32, new items:
268     //   - FT_FreeNodes             = 10
269     //   - FT_FreeFaces             = 11
270     //   - FT_LinearOrQuadratic     = 23
271     //   - FT_GroupColor            = 24
272     //   - FT_ElemGeomType          = 25
273     // v 5.1.5: FT_Undefined == 33, new items:
274     //   - FT_CoplanarFaces         = 26
275     // v 6.2.0: FT_Undefined == 39, new items:
276     //   - FT_MaxElementLength2D    = 8
277     //   - FT_MaxElementLength3D    = 9
278     //   - FT_BareBorderVolume      = 25
279     //   - FT_BareBorderFace        = 26
280     //   - FT_OverConstrainedVolume = 27
281     //   - FT_OverConstrainedFace   = 28
282     // v 6.5.0: FT_Undefined == 43, new items:
283     //   - FT_EqualNodes            = 14
284     //   - FT_EqualEdges            = 15
285     //   - FT_EqualFaces            = 16
286     //   - FT_EqualVolumes          = 17
287     // v 6.6.0: FT_Undefined == 44, new items:
288     //   - FT_BallDiameter          = 37
289     // v 6.7.1: FT_Undefined == 45, new items:
290     //   - FT_EntityType            = 36
291     // v 7.3.0: FT_Undefined == 46, new items:
292     //   - FT_ConnectedElements     = 39
293     // v 7.6.0: FT_Undefined == 47, new items:
294     //   - FT_BelongToMeshGroup     = 22
295     // v 8.1.0: FT_Undefined == 48, new items:
296     //   - FT_NodeConnectivityNumber= 22
297     // v 8.5.0: FT_Undefined == 49, new items:
298     //   - FT_Deflection2D          = 22
299     //
300     // It's necessary to continue recording this history and to fill
301     // undef2newItems (see below) accordingly.
302
303     typedef map< int, vector< int > > TUndef2newItems;
304     static TUndef2newItems undef2newItems;
305     if ( undef2newItems.empty() )
306     {
307       undef2newItems[ 26 ].push_back( 7 );
308       undef2newItems[ 27 ].push_back( 17 );
309       { int items[] = { 10, 11, 23, 24, 25 };
310         undef2newItems[ 32 ].assign( items, items+5 ); }
311       undef2newItems[ 33 ].push_back( 26 );
312       { int items[] = { 8, 9, 25, 26, 27, 28 };
313         undef2newItems[ 39 ].assign( items, items+6 ); }
314       { int items[] = { 14, 15, 16, 17 };
315         undef2newItems[ 43 ].assign( items, items+4 ); }
316       undef2newItems[ 44 ].push_back( 37 );
317       undef2newItems[ 45 ].push_back( 36 );
318       undef2newItems[ 46 ].push_back( 39 );
319       undef2newItems[ 47 ].push_back( 22 );
320       undef2newItems[ 48 ].push_back( 22 );
321       undef2newItems[ 49 ].push_back( 22 );
322
323       ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
324     }
325
326     int iType     = Type.IntegerValue();
327     int iCompare  = Compare.IntegerValue();
328     int iUnaryOp  = UnaryOp.IntegerValue();
329     int iBinaryOp = BinaryOp.IntegerValue();
330
331     // find out integer value of FT_Undefined at the moment of dump
332     int oldUndefined = iBinaryOp;
333     if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
334       oldUndefined += 3;
335
336     // apply history to args
337     TUndef2newItems::const_iterator undef_items =
338       undef2newItems.upper_bound( oldUndefined );
339     if ( undef_items != undef2newItems.end() )
340     {
341       int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
342       for ( ; undef_items != undef2newItems.end(); ++undef_items )
343       {
344         const vector< int > & addedItems = undef_items->second;
345         for ( size_t i = 0; i < addedItems.size(); ++i )
346           for ( int iArg = 0; iArg < 4; ++iArg )
347           {
348             int& arg = *pArg[iArg];
349             if ( arg >= addedItems[i] )
350               arg++;
351           }
352       }
353       Type     = TCollection_AsciiString( iType     );
354       Compare  = TCollection_AsciiString( iCompare  );
355       UnaryOp  = TCollection_AsciiString( iUnaryOp  );
356       BinaryOp = TCollection_AsciiString( iBinaryOp );
357     }
358   }
359
360   //================================================================================
361   /*!
362    * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
363    *        arguments of a given command by a list "[x,y,z]" if the list is accessible
364    *        type of argument.
365    */
366   //================================================================================
367
368   void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
369   {
370     static TStringSet methodsAcceptingList;
371     if ( methodsAcceptingList.empty() ) {
372       const char * methodNames[] = {
373         "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
374         "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
375         "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
376         "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
377         "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
378         "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
379         "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
380         "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
381         "Translate","TranslateMakeGroups","TranslateMakeMesh",
382         "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
383         "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
384         ,"" }; // <- mark of the end
385       methodsAcceptingList.Insert( methodNames );
386     }
387     if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
388     {
389       for ( int i = theCommand->GetNbArgs(); i > 0; --i )
390       {
391         const _AString & arg = theCommand->GetArg( i );
392         if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
393              arg.Search( "SMESH.DirStruct"   ) == 1 )
394         {
395           Handle(_pyCommand) workCmd = new _pyCommand( arg );
396           if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
397           {
398             workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
399           }
400           if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
401           {
402             _AString newArg = "[ ";
403             newArg += ( workCmd->GetArg( 1 ) + ", " +
404                         workCmd->GetArg( 2 ) + ", " +
405                         workCmd->GetArg( 3 ) + " ]");
406             theCommand->SetArg( i, newArg );
407           }
408         }
409       }
410     }
411   }
412   //================================================================================
413   /*!
414    * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
415    *        a list "[id1,id2]" if the list is an accessible type of argument.
416    */
417   //================================================================================
418
419   void GetIDSourceToList( Handle( _pyCommand)& theCommand )
420   {
421     static TStringSet methodsAcceptingList;
422     if ( methodsAcceptingList.empty() ) {
423       const char * methodNames[] = {
424         "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
425         "ExportCGNS","ExportGMF",
426         "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
427         "ScaleMakeGroups","Scale","ScaleMakeMesh",
428         "FindCoincidentNodesOnPartBut","DoubleElements",
429         "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
430         ,"" }; // <- mark of the end
431       methodsAcceptingList.Insert( methodNames );
432     }
433     if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
434     {
435       for ( int i = theCommand->GetNbArgs(); i > 0; --i )
436       {
437         _pyCommand argCmd( theCommand->GetArg( i ));
438         if ( argCmd.GetMethod() == "GetIDSource" &&
439              argCmd.GetNbArgs() == 2 )
440         {
441           theCommand->SetArg( i, argCmd.GetArg( 1 ));
442         }
443       }
444     }
445   }
446
447   bool _FilterArg( const _AString& theArg  )
448   {
449     static std::list<_AString> filteredArgs;
450     static bool initialized = false;
451     if ( !initialized ) {
452       initialized = true;
453       filteredArgs.push_back( "SMESH.MED_V2_1" );
454       filteredArgs.push_back( "SMESH.MED_V2_2" );
455     }  
456     return std::find( filteredArgs.begin(), filteredArgs.end(), theArg ) != filteredArgs.end();
457   }
458 }
459
460 //================================================================================
461 /*!
462  * \brief Convert a python script using commands of smeshBuilder.py
463  *  \param theScriptLines - Lines of the input script
464  *  \param theEntry2AccessorMethod - returns method names to access to
465  *         objects wrapped with python class
466  *  \param theObjectNames - names of objects
467  *  \param theRemovedObjIDs - entries of objects whose created commands were removed
468  *  \param theHistoricalDump - true means to keep all commands, false means
469  *         to exclude commands relating to objects removed from study
470  *  \retval TCollection_AsciiString - Conversion result
471  */
472 //================================================================================
473
474 void
475 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >&     theScriptLines,
476                               Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
477                               Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
478                               std::set< TCollection_AsciiString >&      theRemovedObjIDs,
479                               const bool                                theToKeepAllCommands)
480 {
481   std::list< TCollection_AsciiString >::iterator lineIt;
482   // process notebook variables
483   {
484     SMESH_NoteBook aNoteBook;
485
486     for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
487       aNoteBook.AddCommand( *lineIt );
488
489     theScriptLines.clear();
490
491     aNoteBook.ReplaceVariables();
492
493     aNoteBook.GetResultLines( theScriptLines );
494   }
495
496   // convert to smeshBuilder.py API
497
498   theGen = new _pyGen( theEntry2AccessorMethod,
499                        theObjectNames,
500                        theRemovedObjIDs,
501                        theToKeepAllCommands );
502
503   for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
504     theGen->AddCommand( *lineIt );
505
506   theScriptLines.clear();
507
508   // finish conversion
509   theGen->Flush();
510 #ifdef DUMP_CONVERSION
511   MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
512 #endif
513
514   // clean commands of removed objects depending on myIsPublished flag
515   theGen->ClearCommands();
516
517   // reorder commands after conversion
518   list< Handle(_pyCommand) >::iterator cmd;
519   bool orderChanges;
520   do {
521     orderChanges = false;
522     for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
523       if ( (*cmd)->SetDependentCmdsAfter() )
524         orderChanges = true;
525   } while ( orderChanges );
526
527   // concat commands back into a script
528   TCollection_AsciiString aPrevCmd;
529   set<_pyID> createdObjects;
530   createdObjects.insert( "smeshBuilder" );
531   createdObjects.insert( "smesh" );
532   for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
533   {
534 #ifdef DUMP_CONVERSION
535     MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
536 #endif
537     if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
538       CheckObjectPresence( *cmd, createdObjects );
539       if ( !(*cmd)->IsEmpty() ) {
540         aPrevCmd = (*cmd)->GetString();
541         theScriptLines.push_back( aPrevCmd );
542       }
543     }
544   }
545
546   theGen->Free();
547   theGen.Nullify();
548 }
549
550 //================================================================================
551 /*!
552  * \brief _pyGen constructor
553  */
554 //================================================================================
555
556 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
557                Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
558                std::set< TCollection_AsciiString >&      theRemovedObjIDs,
559                const bool                                theToKeepAllCommands)
560   : _pyObject( new _pyCommand( "", 0 )),
561     myNbCommands( 0 ),
562     myID2AccessorMethod( theEntry2AccessorMethod ),
563     myObjectNames( theObjectNames ),
564     myRemovedObjIDs( theRemovedObjIDs ),
565     myNbFilters( 0 ),
566     myToKeepAllCommands( theToKeepAllCommands ),
567     myGeomIDNb(0), myGeomIDIndex(-1)
568 {
569   // make that GetID() to return TPythonDump::SMESHGenName()
570   GetCreationCmd()->Clear();
571   GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
572   GetCreationCmd()->GetString() += "=";
573
574   // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
575   if ( !theObjectNames.IsEmpty() )
576   {
577     // find a GEOM entry
578     _pyID geomID;
579     SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::getStudyServant()->FindComponent("GEOM");
580     if ( geomComp->_is_nil() ) return;
581     CORBA::String_var entry = geomComp->GetID();
582     geomID = entry.in();
583
584     // find a SMESH entry
585     _pyID smeshID;
586     Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
587     for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
588       if ( _pyCommand::IsStudyEntry( e2n.Key() ))
589         smeshID = e2n.Key();
590
591     // find 1st difference between smeshID and geomID
592     if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
593       for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
594         if ( geomID.Value( i ) != smeshID.Value( i ))
595         {
596           myGeomIDNb = geomID.Value( i );
597           myGeomIDIndex = i;
598         }
599   }
600 }
601
602 //================================================================================
603 /*!
604  * \brief name of SMESH_Gen in smeshBuilder.py
605  */
606 //================================================================================
607
608 const char* _pyGen::AccessorMethod() const
609 {
610   return SMESH_2smeshpy::GenName();
611 }
612
613 //================================================================================
614 /*!
615  * \brief Convert a command using a specific converter
616  *  \param theCommand - the command to convert
617  */
618 //================================================================================
619
620 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
621 {
622   // store theCommand in the sequence
623   myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
624
625   Handle(_pyCommand) aCommand = myCommands.back();
626 #ifdef DUMP_CONVERSION
627   MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
628 #endif
629
630   const _pyID& objID = aCommand->GetObject();
631
632   if ( objID.IsEmpty() )
633     return aCommand;
634
635   // Prevent moving a command creating a sub-mesh to the end of the script
636   // if the sub-mesh is used in theCommand as argument
637   // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
638   // {
639   //   PlaceSubmeshAfterItsCreation( aCommand );
640   // }
641
642   // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
643   StructToList( aCommand );
644
645   const TCollection_AsciiString& method = aCommand->GetMethod();
646
647   // not to erase _pySelfEraser's etc. used as args in some commands
648   {
649 #ifdef USE_STRING_FAMILY
650     std::list<_pyID>  objIDs;
651     if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
652     {
653       std::list<_pyID>::iterator objID = objIDs.begin();
654       for ( ; objID != objIDs.end(); ++objID )
655       {
656         Handle(_pyObject) obj = FindObject( *objID );
657         if ( !obj.IsNull() )
658         {
659           obj->AddArgCmd( aCommand );
660           //cout << objID << " found in " << theCommand << endl;
661         }
662       }
663     }
664 #else
665     std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
666     for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
667       if ( *id != objID && theCommand.Search( *id ) > id->Length() )
668       {
669         Handle(_pyObject) obj = FindObject( *id );
670         if ( !obj.IsNull() )
671           obj->AddArgCmd( aCommand );
672       }
673 #endif
674   }
675
676   // Find an object to process theCommand
677
678   // SMESH_Gen method?
679   if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
680   {
681     this->Process( aCommand );
682     //addFilterUser( aCommand, theGen ); // protect filters from clearing
683     return aCommand;
684   }
685
686   // SMESH_Mesh method?
687   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
688   if ( id_mesh != myMeshes.end() )
689   {
690     //id_mesh->second->AddProcessedCmd( aCommand );
691
692     // Wrap Export*() into try-except
693     if ( aCommand->MethodStartsFrom("Export"))
694     {
695       _AString    tab = "\t";
696       _AString indent = aCommand->GetIndentation();
697       _AString tryStr = indent + "try:";
698       _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
699       _AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
700       _AString excStr = indent + "except:";
701       _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
702
703       myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
704       aCommand->Clear();
705       aCommand->GetString() = newCmd;
706       aCommand->SetOrderNb( ++myNbCommands );
707       myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
708       myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
709       myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
710     }
711     // check for mesh editor object
712     if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
713       _pyID editorID = aCommand->GetResultValue();
714       Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
715       myMeshEditors.insert( make_pair( editorID, editor ));
716       return aCommand;
717     }
718     // check for SubMesh objects
719     else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
720       _pyID subMeshID = aCommand->GetResultValue();
721       Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
722       AddObject( subMesh );
723     }
724
725     // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
726     GetIDSourceToList( aCommand );
727
728     //addFilterUser( aCommand, theGen ); // protect filters from clearing
729
730     id_mesh->second->Process( aCommand );
731     id_mesh->second->AddProcessedCmd( aCommand );
732     return aCommand;
733   }
734
735   // SMESH_MeshEditor method?
736   map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
737   if ( id_editor != myMeshEditors.end() )
738   {
739     // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
740     GetIDSourceToList( aCommand );
741
742     //addFilterUser( aCommand, theGen ); // protect filters from clearing
743
744     // some commands of SMESH_MeshEditor create meshes and groups
745     _pyID meshID, groups;
746     if ( method.Search("MakeMesh") != -1 )
747       meshID = aCommand->GetResultValue();
748     else if ( method == "MakeBoundaryMesh")
749       meshID = aCommand->GetResultValue(1);
750     else if ( method == "MakeBoundaryElements")
751       meshID = aCommand->GetResultValue(2);
752
753     if ( method.Search("MakeGroups") != -1      ||
754          method == "ExtrusionAlongPathX"        ||
755          method == "ExtrusionAlongPathObjX"     ||
756          method == "DoubleNodeGroupNew"         ||
757          method == "DoubleNodeGroupsNew"        ||
758          method == "DoubleNodeElemGroupNew"     ||
759          method == "DoubleNodeElemGroupsNew"    ||
760          method == "DoubleNodeElemGroup2New"    ||
761          method == "DoubleNodeElemGroups2New"   ||
762          method == "AffectedElemGroupsInRegion"
763          )
764       groups = aCommand->GetResultValue();
765     else if ( method == "MakeBoundaryMesh" )
766       groups = aCommand->GetResultValue(2);
767     else if ( method == "MakeBoundaryElements")
768       groups = aCommand->GetResultValue(3);
769     else if ( method == "Create0DElementsOnAllNodes" &&
770               aCommand->GetArg(2).Length() > 2 ) // group name != ''
771       groups = aCommand->GetResultValue();
772
773     id_editor->second->Process( aCommand );
774     id_editor->second->AddProcessedCmd( aCommand );
775
776     // create meshes
777     if ( !meshID.IsEmpty() &&
778          !myMeshes.count( meshID ) &&
779          aCommand->IsStudyEntry( meshID ))
780     {
781       _AString processedCommand = aCommand->GetString();
782       Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
783       CheckObjectIsReCreated( mesh );
784       myMeshes.insert( make_pair( meshID, mesh ));
785       aCommand->Clear();
786       aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
787     }
788     // create groups
789     if ( !groups.IsEmpty() )
790     {
791       if ( !aCommand->IsStudyEntry( meshID ))
792         meshID = id_editor->second->GetMesh();
793       Handle(_pyMesh) mesh = myMeshes[ meshID ];
794
795       list< _pyID > idList = aCommand->GetStudyEntries( groups );
796       list< _pyID >::iterator grID = idList.begin();
797       for ( ; grID != idList.end(); ++grID )
798         if ( !myObjects.count( *grID ))
799         {
800           Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
801           AddObject( group );
802           if ( !mesh.IsNull() ) mesh->AddGroup( group );
803         }
804     }
805     return aCommand;
806   } // SMESH_MeshEditor methods
807
808   // SMESH_Hypothesis method?
809   Handle(_pyHypothesis) hyp = FindHyp( objID );
810   if ( !hyp.IsNull() && !hyp->IsAlgo() )
811   {
812     hyp->Process( aCommand );
813     hyp->AddProcessedCmd( aCommand );
814     return aCommand;
815   }
816
817   // aFilterManager.CreateFilter() ?
818   if ( aCommand->GetMethod() == "CreateFilter" )
819   {
820     // Set a more human readable name to a filter
821     // aFilter0x7fbf6c71cfb0 -> aFilter_nb
822     _pyID newID, filterID = aCommand->GetResultValue();
823     int pos = filterID.Search( "0x" );
824     if ( pos > 1 )
825       newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
826
827     Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
828     AddObject( filter );
829   }
830   // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
831   else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
832   {
833     // create _pySelfEraser for functors
834     Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
835     functor->IgnoreOwnCalls(); // to erase if not used as an argument
836     AddObject( functor );
837   }
838
839   // other object method?
840   map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
841   if ( id_obj != myObjects.end() ) {
842     id_obj->second->Process( aCommand );
843     id_obj->second->AddProcessedCmd( aCommand );
844     return aCommand;
845   }
846
847   // Add access to a wrapped mesh
848   AddMeshAccessorMethod( aCommand );
849
850   // Add access to a wrapped algorithm
851   //  AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
852
853   // PAL12227. PythonDump was not updated at proper time; result is
854   //     aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
855   // TypeError: __init__() takes exactly 11 arguments (10 given)
856   const char wrongCommand[] = "SMESH.Filter.Criterion(";
857   if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
858   {
859     _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
860     // there must be 10 arguments, 5-th arg ThresholdID is missing,
861     const int wrongNbArgs = 9, missingArg = 5;
862     if ( tmpCmd.GetNbArgs() == wrongNbArgs )
863     {
864       for ( int i = wrongNbArgs; i > missingArg; --i )
865         tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
866       tmpCmd.SetArg(  missingArg, "''");
867       aCommand->GetString().Trunc( beg - 1 );
868       aCommand->GetString() += tmpCmd.GetString();
869     }
870     // IMP issue 0021014
871     // set GetCriterion(elementType,CritType,Compare,Threshold,UnaryOp,BinaryOp,Tolerance)
872     //                  1           2        3       4         5       6        7
873     // instead of "SMESH.Filter.Criterion(
874     // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
875     // 1    2       3         4            5           6       7        8         9             10
876     // in order to avoid the problem of type mismatch of long and FunctorType
877     const TCollection_AsciiString
878       SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
879     TCollection_AsciiString
880       Type          = aCommand->GetArg(1),  // long
881       Compare       = aCommand->GetArg(2),  // long
882       Threshold     = aCommand->GetArg(3),  // double
883       ThresholdStr  = aCommand->GetArg(4),  // string
884       ThresholdID   = aCommand->GetArg(5),  // string
885       UnaryOp       = aCommand->GetArg(6),  // long
886       BinaryOp      = aCommand->GetArg(7),  // long
887       Tolerance     = aCommand->GetArg(8),  // double
888       TypeOfElement = aCommand->GetArg(9),  // ElementType
889       Precision     = aCommand->GetArg(10); // long
890     fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
891     Type     = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
892     Compare  = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
893     UnaryOp  = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
894     BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
895
896     if ( Compare == "SMESH.FT_EqualTo" )
897       Compare = "'='";
898
899     aCommand->RemoveArgs();
900     aCommand->SetObject( SMESH_2smeshpy::GenName() );
901     aCommand->SetMethod( "GetCriterion" );
902
903     aCommand->SetArg( 1, TypeOfElement );
904     aCommand->SetArg( 2, Type );
905     aCommand->SetArg( 3, Compare );
906
907     if ( Threshold.IsIntegerValue() )
908     {
909       int iGeom = Threshold.IntegerValue();
910       if ( Type == "SMESH.FT_ElemGeomType" )
911       {
912         // set SMESH.GeometryType instead of a numerical Threshold
913         const int nbTypes = SMESH::Geom_LAST;
914         const char* types[] = {
915           "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
916           "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
917           "Geom_POLYHEDRA", "Geom_BALL" };
918         if ( -1 < iGeom && iGeom < nbTypes )
919           Threshold = SMESH + types[ iGeom ];
920 #ifdef _DEBUG_
921         // is types complete? (compilation failure mains that enum GeometryType changed)
922         int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
923 #endif
924       }
925       if (Type == "SMESH.FT_EntityType")
926       {
927         // set SMESH.EntityType instead of a numerical Threshold
928         const int nbTypes = SMESH::Entity_Last;
929         const char* types[] = {
930           "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
931           "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
932           "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
933           "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
934           "Entity_Pyramid", "Entity_Quad_Pyramid",
935           "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
936           "Entity_Penta", "Entity_Quad_Penta", "Entity_BiQuad_Penta", "Entity_Hexagonal_Prism",
937           "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
938         if ( -1 < iGeom && iGeom < nbTypes )
939           Threshold = SMESH + types[ iGeom ];
940 #ifdef _DEBUG_
941         // is 'types' complete? (compilation failure mains that enum EntityType changed)
942         int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
943 #endif
944       }
945     }
946     if ( ThresholdID.Length() != 2 ) // neither '' nor ""
947       aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
948     else if ( ThresholdStr.Length() != 2 )
949       aCommand->SetArg( 4, ThresholdStr );
950     else if ( ThresholdID.Length() != 2 )
951       aCommand->SetArg( 4, ThresholdID );
952     else
953       aCommand->SetArg( 4, Threshold );
954     // find the last not default arg
955     int lastDefault = 8;
956     if ( Tolerance == dfltTol ) {
957       lastDefault = 7;
958       if ( BinaryOp == dfltFunctor ) {
959         lastDefault = 6;
960         if ( UnaryOp == dfltFunctor )
961           lastDefault = 5;
962       }
963     }
964     if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
965     if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
966     if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
967     if ( Precision != dfltPreci )
968     {
969       TCollection_AsciiString crit = aCommand->GetResultValue();
970       aCommand->GetString() += "; ";
971       aCommand->GetString() += crit + ".Precision = " + Precision;
972     }
973   }
974   return aCommand;
975 }
976
977 //================================================================================
978 /*!
979  * \brief Convert the command or remember it for later conversion
980  *  \param theCommand - The python command calling a method of SMESH_Gen
981  */
982 //================================================================================
983
984 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
985 {
986   // there are methods to convert:
987   // CreateMesh( shape )
988   // Concatenate( [mesh1, ...], ... )
989   // CreateHypothesis( theHypType, theLibName )
990   // Compute( mesh, geom )
991   // Evaluate( mesh, geom )
992   // mesh creation
993   TCollection_AsciiString method = theCommand->GetMethod();
994
995   if ( method == "CreateMesh" || method == "CreateEmptyMesh")
996   {
997     Handle(_pyMesh) mesh = new _pyMesh( theCommand );
998     AddObject( mesh );
999     return;
1000   }
1001   if ( method == "CreateMeshesFromUNV" ||
1002        method == "CreateMeshesFromSTL" ||
1003        method == "CopyMesh" ) // command result is a mesh
1004   {
1005     Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1006     AddObject( mesh );
1007     return;
1008   }
1009   if( method == "CreateMeshesFromMED" ||
1010       method == "CreateMeshesFromSAUV"||
1011       method == "CreateMeshesFromCGNS" ||
1012       method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1013   {
1014     std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1015     std::list< _pyID >::iterator meshID = meshIDs.begin();
1016     for ( ; meshID != meshIDs.end(); ++meshID )
1017     {
1018       Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1019       AddObject( mesh );
1020     }
1021     if ( method == "CreateMeshesFromGMF" )
1022     {
1023       // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1024       // CreateMeshesFromGMF( theFileName )
1025       _AString file = theCommand->GetArg(1);
1026       theCommand->RemoveArgs();
1027       theCommand->SetArg( 1, file );
1028     }
1029   }
1030
1031   // CreateHypothesis()
1032   if ( method == "CreateHypothesis" )
1033   {
1034     // issue 199929, remove standard library name (default parameter)
1035     const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1036     if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1037       // keep the first argument
1038       TCollection_AsciiString arg = theCommand->GetArg( 1 );
1039       theCommand->RemoveArgs();
1040       theCommand->SetArg( 1, arg );
1041     }
1042
1043     Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1044     CheckObjectIsReCreated( hyp );
1045     myHypos.insert( make_pair( hyp->GetID(), hyp ));
1046
1047     return;
1048   }
1049
1050   // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1051   if ( method == "Compute" )
1052   {
1053     const _pyID& meshID = theCommand->GetArg( 1 );
1054     map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1055     if ( id_mesh != myMeshes.end() ) {
1056       theCommand->SetObject( meshID );
1057       theCommand->RemoveArgs();
1058       id_mesh->second->Process( theCommand );
1059       id_mesh->second->AddProcessedCmd( theCommand );
1060       return;
1061     }
1062   }
1063
1064   // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1065   if ( method == "Evaluate" )
1066   {
1067     const _pyID& meshID = theCommand->GetArg( 1 );
1068     map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1069     if ( id_mesh != myMeshes.end() ) {
1070       theCommand->SetObject( meshID );
1071       _pyID geom = theCommand->GetArg( 2 );
1072       theCommand->RemoveArgs();
1073       theCommand->SetArg( 1, geom );
1074       id_mesh->second->AddProcessedCmd( theCommand );
1075       return;
1076     }
1077   }
1078
1079   // objects erasing creation command if no more its commands invoked:
1080   // SMESH_Pattern, FilterManager
1081   if ( method == "GetPattern" ||
1082        method == "CreateFilterManager" ||
1083        method == "CreateMeasurements" )
1084   {
1085     Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1086     if ( !AddObject( obj ) )
1087       theCommand->Clear(); // already created
1088   }
1089   // Concatenate( [mesh1, ...], ... )
1090   else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1091   {
1092     if ( method == "ConcatenateWithGroups" ) {
1093       theCommand->SetMethod( "Concatenate" );
1094       theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1095     }
1096     Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1097     AddObject( mesh );
1098     AddMeshAccessorMethod( theCommand );
1099   }
1100   else if ( method == "SetName" ) // SetName(obj,name)
1101   {
1102     // store theCommand as one of object commands to erase it along with the object
1103     const _pyID& objID = theCommand->GetArg( 1 );
1104     Handle(_pyObject) obj = FindObject( objID );
1105     if ( !obj.IsNull() )
1106       obj->AddProcessedCmd( theCommand );
1107   }
1108
1109   // Replace name of SMESH_Gen
1110
1111   // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1112   static TStringSet smeshpyMethods;
1113   if ( smeshpyMethods.empty() ) {
1114     const char * names[] =
1115       { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1116         "GetPattern","GetSubShapesId",
1117         "" }; // <- mark of array end
1118     smeshpyMethods.Insert( names );
1119   }
1120   if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1121     // smeshgen.Method() --> smesh.Method()
1122     theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1123   else
1124     // smeshgen.Method() --> smesh.Method()
1125     theCommand->SetObject( SMESH_2smeshpy::GenName() );
1126 }
1127
1128 //================================================================================
1129 /*!
1130  * \brief Convert the remembered commands
1131  */
1132 //================================================================================
1133
1134 void _pyGen::Flush()
1135 {
1136   // create an empty command
1137   myLastCommand = new _pyCommand();
1138
1139   map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1140   map< _pyID, Handle(_pyObject) >::iterator id_obj;
1141   map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1142
1143   if ( IsToKeepAllCommands() ) // historical dump
1144   {
1145     // set myIsPublished = true to all objects
1146     for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1147       id_mesh->second->SetRemovedFromStudy( false );
1148     for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1149       id_hyp->second->SetRemovedFromStudy( false );
1150     for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1151       id_obj->second->SetRemovedFromStudy( false );
1152   }
1153   else
1154   {
1155     // let hypotheses find referred objects in order to prevent clearing
1156     // not published referred hyps (it's needed for hyps like "LayerDistribution")
1157     list< Handle(_pyMesh) > fatherMeshes;
1158     for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1159       if ( !id_hyp->second.IsNull() )
1160         id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1161   }
1162   // set myIsPublished = false to all objects depending on
1163   // meshes built on a removed geometry
1164   for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1165     if ( id_mesh->second->IsNotGeomPublished() )
1166       id_mesh->second->SetRemovedFromStudy( true );
1167
1168   // Flush meshes
1169   for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1170     if ( ! id_mesh->second.IsNull() )
1171       id_mesh->second->Flush();
1172
1173   // Flush hyps
1174   for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1175     if ( !id_hyp->second.IsNull() ) {
1176       id_hyp->second->Flush();
1177       // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1178       if ( !id_hyp->second->IsWrapped() )
1179         id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1180     }
1181
1182   // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1183   std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1184   for ( ; robj != myOrderedObjects.rend(); ++robj )
1185     if ( ! robj->IsNull() )
1186       (*robj)->Flush();
1187   std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1188   for ( ; obj != myOrderedObjects.end(); ++obj )
1189     if ( ! obj->IsNull() )
1190       (*obj)->Flush();
1191
1192   myLastCommand->SetOrderNb( ++myNbCommands );
1193   myCommands.push_back( myLastCommand );
1194 }
1195
1196 //================================================================================
1197 /*!
1198  * \brief Prevent moving a command creating a sub-mesh to the end of the script
1199  *        if the sub-mesh is used in theCmdUsingSubmesh as argument
1200  */
1201 //================================================================================
1202
1203 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1204 {
1205   // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1206   // for ( ; id_obj != myObjects.end(); ++id_obj )
1207   // {
1208   //   if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1209   //   for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1210   //   {
1211   //     const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1212   //     if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1213   //       continue;
1214   //     list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1215   //     list< _pyID >::iterator id = idList.begin();
1216   //     for ( ; id != idList.end(); ++id )
1217   //       if ( id_obj->first == *id )
1218   //         // _pySubMesh::Process() does what we need
1219   //         Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1220   //   }
1221   // }
1222 }
1223
1224 //================================================================================
1225 /*!
1226  * \brief Clean commands of removed objects depending on myIsPublished flag
1227  */
1228 //================================================================================
1229
1230 void _pyGen::ClearCommands()
1231 {
1232   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1233   for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1234     id_mesh->second->ClearCommands();
1235
1236   map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1237   for ( ; id_hyp != myHypos.end(); ++id_hyp )
1238     if ( !id_hyp->second.IsNull() )
1239       id_hyp->second->ClearCommands();
1240
1241   // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1242   std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1243   for ( ; robj != myOrderedObjects.rend(); ++robj )
1244     if ( ! robj->IsNull() )
1245       (*robj)->ClearCommands();
1246   std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1247   for ( ; obj != myOrderedObjects.end(); ++obj )
1248     if ( ! obj->IsNull() )
1249       (*obj)->ClearCommands();
1250 }
1251
1252 //================================================================================
1253 /*!
1254  * \brief Release mutual handles of objects
1255  */
1256 //================================================================================
1257
1258 void _pyGen::Free()
1259 {
1260   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1261   for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1262     id_mesh->second->Free();
1263   myMeshes.clear();
1264
1265   map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1266   for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1267     id_ed->second->Free();
1268   myMeshEditors.clear();
1269
1270   map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1271   for ( ; id_obj != myObjects.end(); ++id_obj )
1272     id_obj->second->Free();
1273   myObjects.clear();
1274
1275   map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1276   for ( ; id_hyp != myHypos.end(); ++id_hyp )
1277     if ( !id_hyp->second.IsNull() )
1278       id_hyp->second->Free();
1279   myHypos.clear();
1280
1281   myFile2ExportedMesh.clear();
1282
1283   //myKeepAgrCmdsIDs.Print();
1284 }
1285
1286 //================================================================================
1287 /*!
1288  * \brief Add access method to mesh that is an argument
1289  *  \param theCmd - command to add access method
1290  * \retval bool - true if added
1291  */
1292 //================================================================================
1293
1294 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1295 {
1296   bool added = false;
1297   map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1298   for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1299     if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1300       added = true;
1301   }
1302   return added;
1303 }
1304
1305 //================================================================================
1306 /*!
1307  * \brief Add access method to algo that is an object or an argument
1308  *  \param theCmd - command to add access method
1309  * \retval bool - true if added
1310  */
1311 //================================================================================
1312
1313 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1314 {
1315   bool added = false;
1316   map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1317   for ( ; id_hyp != myHypos.end(); ++id_hyp )
1318     if ( !id_hyp->second.IsNull() &&
1319          id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1320          theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1321                                     id_hyp->second->AccessorMethod() ))
1322       added = true;
1323
1324   return added;
1325 }
1326
1327 //================================================================================
1328 /*!
1329  * \brief Find hypothesis by ID (entry)
1330  *  \param theHypID - The hypothesis ID
1331  * \retval Handle(_pyHypothesis) - The found hypothesis
1332  */
1333 //================================================================================
1334
1335 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1336 {
1337   map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1338   if ( id_hyp != myHypos.end() &&
1339        !id_hyp->second.IsNull() &&
1340        theHypID == id_hyp->second->GetID() )
1341     return id_hyp->second;
1342   return Handle(_pyHypothesis)();
1343 }
1344
1345 //================================================================================
1346 /*!
1347  * \brief Find algorithm able to create a hypothesis
1348  *  \param theGeom - The shape ID the algorithm was created on
1349  *  \param theMesh - The mesh ID that created the algorithm
1350  *  \param theHypothesis - The hypothesis the algorithm should be able to create
1351  * \retval Handle(_pyHypothesis) - The found algo
1352  */
1353 //================================================================================
1354
1355 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1356                                         const Handle(_pyHypothesis)& theHypothesis )
1357 {
1358   map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1359   for ( ; id_hyp != myHypos.end(); ++id_hyp )
1360     if ( !id_hyp->second.IsNull() &&
1361          id_hyp->second->IsAlgo() &&
1362          theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1363          id_hyp->second->GetGeom() == theGeom &&
1364          id_hyp->second->GetMesh() == theMesh )
1365       return id_hyp->second;
1366   return Handle(_pyHypothesis)();
1367 }
1368
1369 //================================================================================
1370 /*!
1371  * \brief Find subMesh by ID (entry)
1372  *  \param theSubMeshID - The subMesh ID
1373  * \retval Handle(_pySubMesh) - The found subMesh
1374  */
1375 //================================================================================
1376
1377 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1378 {
1379   map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1380   if ( id_subMesh != myObjects.end() )
1381     return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1382   return Handle(_pySubMesh)();
1383 }
1384
1385
1386 //================================================================================
1387 /*!
1388  * \brief Change order of commands in the script
1389  *  \param theCmd1 - One command
1390  *  \param theCmd2 - Another command
1391  */
1392 //================================================================================
1393
1394 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1395 {
1396   list< Handle(_pyCommand) >::iterator pos1, pos2;
1397   pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1398   pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1399   myCommands.insert( pos1, theCmd2 );
1400   myCommands.insert( pos2, theCmd1 );
1401   myCommands.erase( pos1 );
1402   myCommands.erase( pos2 );
1403
1404   int nb1 = theCmd1->GetOrderNb();
1405   theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1406   theCmd2->SetOrderNb( nb1 );
1407   //   cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1408   //        << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1409 }
1410
1411 //================================================================================
1412 /*!
1413  * \brief Set one command after the other
1414  *  \param theCmd - Command to move
1415  *  \param theAfterCmd - Command ater which to insert the first one
1416  */
1417 //================================================================================
1418
1419 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1420 {
1421   setNeighbourCommand( theCmd, theAfterCmd, true );
1422 }
1423
1424 //================================================================================
1425 /*!
1426  * \brief Set one command before the other
1427  *  \param theCmd - Command to move
1428  *  \param theBeforeCmd - Command before which to insert the first one
1429  */
1430 //================================================================================
1431
1432 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1433 {
1434   setNeighbourCommand( theCmd, theBeforeCmd, false );
1435 }
1436
1437 //================================================================================
1438 /*!
1439  * \brief Set one command before or after the other
1440  *  \param theCmd - Command to move
1441  *  \param theOtherCmd - Command ater or before which to insert the first one
1442  */
1443 //================================================================================
1444
1445 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1446                                   Handle(_pyCommand)& theOtherCmd,
1447                                   const bool theIsAfter )
1448 {
1449   list< Handle(_pyCommand) >::iterator pos;
1450   pos = find( myCommands.begin(), myCommands.end(), theCmd );
1451   myCommands.erase( pos );
1452   pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1453   myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1454
1455   int i = 1;
1456   for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1457     (*pos)->SetOrderNb( i++ );
1458 }
1459
1460 //================================================================================
1461 /*!
1462  * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1463  */
1464 //================================================================================
1465
1466 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1467 // {
1468 // No more needed after adding _pyObject::myArgCommands
1469
1470 //   const char filterPrefix[] = "aFilter0x";
1471 //   if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1472 //     return;
1473
1474 //   for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1475 //   {
1476 //     const _AString & arg = theCommand->GetArg( i );
1477 //     // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1478 //     if ( arg.Search( filterPrefix ) != 1 )
1479 //       continue;
1480
1481 //     Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1482 //     if ( !filter.IsNull() )
1483 //     {
1484 //       filter->AddUser( user );
1485 //       if ( !filter->GetNewID().IsEmpty() )
1486 //         theCommand->SetArg( i, filter->GetNewID() );
1487 //     }
1488 //   }
1489 //}
1490
1491 //================================================================================
1492 /*!
1493  * \brief Set command be last in list of commands
1494  *  \param theCmd - Command to be last
1495  */
1496 //================================================================================
1497
1498 Handle(_pyCommand)& _pyGen::GetLastCommand()
1499 {
1500   return myLastCommand;
1501 }
1502
1503 //================================================================================
1504 /*!
1505  * \brief Set method to access to object wrapped with python class
1506  *  \param theID - The wrapped object entry
1507  *  \param theMethod - The accessor method
1508  */
1509 //================================================================================
1510
1511 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1512 {
1513   myID2AccessorMethod.Bind( theID, (char*) theMethod );
1514 }
1515
1516 //================================================================================
1517 /*!
1518  * \brief Generated new ID for object and assign with existing name
1519  *  \param theID - ID of existing object
1520  */
1521 //================================================================================
1522
1523 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1524 {
1525   int index = 1;
1526   _pyID aNewID;
1527   do {
1528     aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1529   }
1530   while ( myObjectNames.IsBound( aNewID ) );
1531
1532   if ( myObjectNames.IsBound( theID ) )
1533     myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1534   else
1535     myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1536   return aNewID;
1537 }
1538
1539 //================================================================================
1540 /*!
1541  * \brief Stores theObj in myObjects
1542  */
1543 //================================================================================
1544
1545 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1546 {
1547   if ( theObj.IsNull() ) return false;
1548
1549   CheckObjectIsReCreated( theObj );
1550
1551   bool add;
1552
1553   if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1554     add = myMeshes.insert( make_pair( theObj->GetID(),
1555                                       Handle(_pyMesh)::DownCast( theObj ))).second;
1556   }
1557   else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1558     add = myMeshEditors.insert( make_pair( theObj->GetID(),
1559                                            Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1560   }
1561   else {
1562     add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1563     if ( add ) myOrderedObjects.push_back( theObj );
1564   }
1565   return add;
1566 }
1567
1568 //================================================================================
1569 /*!
1570  * \brief Erases an existing object with the same ID. This method should be called
1571  *        before storing theObj in _pyGen
1572  */
1573 //================================================================================
1574
1575 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1576 {
1577   if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1578     return;
1579
1580   const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1581   Handle(_pyObject) existing;
1582   if( isHyp )
1583     existing = FindHyp( theObj->GetID() );
1584   else
1585     existing = FindObject( theObj->GetID() );
1586   if ( !existing.IsNull() && existing != theObj )
1587   {
1588     existing->SetRemovedFromStudy( true );
1589     existing->ClearCommands();
1590     if ( isHyp )
1591     {
1592       if ( myHypos.count( theObj->GetID() ))
1593         myHypos.erase( theObj->GetID() );
1594     }
1595     else if ( myMeshes.count( theObj->GetID() ))
1596     {
1597       myMeshes.erase( theObj->GetID() );
1598     }
1599     else if ( myObjects.count( theObj->GetID() ))
1600     {
1601       myObjects.erase( theObj->GetID() );
1602     }
1603   }
1604 }
1605
1606 //================================================================================
1607 /*!
1608  * \brief Re-register an object with other ID to make it Process() commands of
1609  * other object having this ID
1610  */
1611 //================================================================================
1612
1613 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1614 {
1615   if ( theObj.IsNull() ) return;
1616
1617   if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1618     myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1619
1620   else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1621     myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1622
1623   else
1624     myObjects.insert( make_pair( theID, theObj ));
1625 }
1626
1627 //================================================================================
1628 /*!
1629  * \brief Finds a _pyObject by ID
1630  */
1631 //================================================================================
1632
1633 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID )  const
1634 {
1635   {
1636     map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1637     if ( id_obj != myObjects.end() )
1638       return id_obj->second;
1639   }
1640   {
1641     _pyGen* me = const_cast< _pyGen* >( this );
1642     map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1643     if ( id_obj != myMeshes.end() )
1644       return id_obj->second;
1645   }
1646   // {
1647   //   map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1648   //   if ( id_obj != myMeshEditors.end() )
1649   //     return id_obj->second;
1650   // }
1651   return Handle(_pyObject)();
1652 }
1653
1654 //================================================================================
1655 /*!
1656  * \brief Check if a study entry is under GEOM component
1657  */
1658 //================================================================================
1659
1660 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1661 {
1662   if ( myGeomIDNb )
1663   {
1664     return ( myGeomIDIndex <= theObjID.Length() &&
1665              int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1666              _pyCommand::IsStudyEntry( theObjID ));
1667   }
1668   return false;
1669 }
1670
1671 //================================================================================
1672 /*!
1673  * \brief Returns true if an object is not present in a study
1674  */
1675 //================================================================================
1676
1677 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1678 {
1679   if ( theObjID.IsEmpty() ) return false;
1680
1681   if ( myObjectNames.IsBound( theObjID ))
1682     return false; // SMESH object is in study
1683
1684   // either the SMESH object is not in study or it is a GEOM object
1685   if ( IsGeomObject( theObjID ))
1686   {
1687     SALOMEDS::SObject_wrap so = SMESH_Gen_i::getStudyServant()->FindObjectID( theObjID.ToCString() );
1688     if ( so->_is_nil() ) return true;
1689     CORBA::Object_var obj = so->GetObject();
1690     return CORBA::is_nil( obj );
1691   }
1692   return true; // SMESH object not in study
1693 }
1694
1695 //================================================================================
1696 /*!
1697  * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1698  *        this object is not dumped
1699  *  \param [in] theObjID - entry of the object whose creation command was eliminated
1700  */
1701 //================================================================================
1702
1703 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1704 {
1705   myRemovedObjIDs.insert( theObjID );
1706 }
1707
1708 //================================================================================
1709 /*!
1710  * \brief Return reader of  hypotheses of plugins
1711  */
1712 //================================================================================
1713
1714 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1715 {
1716   if (myHypReader.IsNull() )
1717     ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1718
1719   return myHypReader;
1720 }
1721
1722
1723 //================================================================================
1724 /*!
1725  * \brief Mesh created by SMESH_Gen
1726  */
1727 //================================================================================
1728
1729 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1730   : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1731 {
1732   if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1733     myGeomNotInStudy = true;
1734
1735   // convert my creation command --> smeshpy.Mesh(...)
1736   Handle(_pyCommand) creationCmd = GetCreationCmd();
1737   creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1738   creationCmd->SetMethod( "Mesh" );
1739   theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1740 }
1741
1742 //================================================================================
1743 /*!
1744  * \brief Mesh created by SMESH_MeshEditor
1745  */
1746 //================================================================================
1747
1748 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1749   _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1750 {
1751   if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1752   {
1753     // this mesh depends on the exported mesh
1754     const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1755     if ( !file.IsEmpty() )
1756     {
1757       ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1758       addFatherMesh( exportData.myMesh );
1759       if ( !exportData.myLastComputeCmd.IsNull() )
1760       {
1761         // restore cleared Compute() by which the exported mesh was generated
1762         exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1763         // protect that Compute() cmd from clearing
1764         if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1765           exportData.myMesh->myLastComputeCmd.Nullify();
1766       }
1767     }
1768   }
1769   else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1770   {
1771     // this mesh depends on concatenated meshes
1772     const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1773     list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1774     list< _pyID >::iterator meshID = idList.begin();
1775     for ( ; meshID != idList.end(); ++meshID )
1776       addFatherMesh( *meshID );
1777   }
1778   else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1779   {
1780     // this mesh depends on a copied IdSource
1781     const _pyID& objID = theCreationCmd->GetArg( 1 );
1782     addFatherMesh( objID );
1783   }
1784   else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1785             theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1786             theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1787   {
1788     // this mesh depends on a source mesh
1789     // (theCreationCmd is already Process()ed by _pyMeshEditor)
1790     const _pyID& meshID = theCreationCmd->GetObject();
1791     addFatherMesh( meshID );
1792   }
1793     
1794   // convert my creation command
1795   Handle(_pyCommand) creationCmd = GetCreationCmd();
1796   creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1797   theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1798 }
1799
1800 //================================================================================
1801 /*!
1802  * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1803  *  \param theCommand - Engine method called for this mesh
1804  */
1805 //================================================================================
1806
1807 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1808 {
1809   // some methods of SMESH_Mesh interface needs special conversion
1810   // to methods of Mesh python class
1811   //
1812   // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1813   //     --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1814   // 2. AddHypothesis(geom, hyp)
1815   //     --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1816   // 3. CreateGroupFromGEOM(type, name, grp)
1817   //     --> in Mesh.Group(grp, name="")
1818   // 4. ExportToMED(f, auto_groups, version)
1819   //     --> in Mesh.ExportMED( f, auto_groups, version )
1820   // 5. etc
1821
1822   const TCollection_AsciiString& method = theCommand->GetMethod();
1823   // ----------------------------------------------------------------------
1824   if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1825   {
1826     if ( !theGen->IsToKeepAllCommands() ) // !historical
1827     {
1828       list< Handle(_pyHypothesis) >::iterator hyp;
1829       if ( !myLastComputeCmd.IsNull() )
1830       {
1831         // check if the previously computed mesh has been edited,
1832         // if so then we do not clear the previous Compute()
1833         bool toClear = true;
1834         if ( myLastComputeCmd->GetMethod() == "Compute" )
1835         {
1836           list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1837           for ( ; e != myEditors.end() && toClear; ++e )
1838           {
1839             list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1840             list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1841             if ( cmd != cmds.rend() &&
1842                  (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1843               toClear = false;
1844           }
1845         }
1846         if ( toClear )
1847         {
1848           // clear hyp commands called before myLastComputeCmd
1849           for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1850             (*hyp)->ComputeDiscarded( myLastComputeCmd );
1851
1852           myLastComputeCmd->Clear();
1853         }
1854       }
1855       myLastComputeCmd = theCommand;
1856
1857       for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1858         (*hyp)->MeshComputed( myLastComputeCmd );
1859     }
1860     Flush();
1861   }
1862   // ----------------------------------------------------------------------
1863   else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1864   {
1865     if ( !theGen->IsToKeepAllCommands() ) // !historical
1866     {
1867       int untilCmdNb =
1868         myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1869       // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1870       // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1871       //   (*cmd)->Clear();
1872       if ( !myLastComputeCmd.IsNull() )
1873       {
1874         list< Handle(_pyHypothesis) >::iterator hyp;
1875         for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1876           (*hyp)->ComputeDiscarded( myLastComputeCmd );
1877
1878         myLastComputeCmd->Clear();
1879       }
1880
1881       list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1882       for ( ; e != myEditors.end(); ++e )
1883       {
1884         list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1885         list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1886         for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1887           if ( !(*cmd)->IsEmpty() )
1888           {
1889             if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1890               (*cmd)->Clear();
1891           }
1892       }
1893       myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1894     }
1895   }
1896   // ----------------------------------------------------------------------
1897   else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1898     Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1899     if ( !subMesh.IsNull() ) {
1900       subMesh->SetCreator( this );
1901       mySubmeshes.push_back( subMesh );
1902     }
1903   }
1904   // ----------------------------------------------------------------------
1905   else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1906     theCommand->Clear();
1907   }
1908   // ----------------------------------------------------------------------
1909   else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1910     myAddHypCmds.push_back( theCommand );
1911     // set mesh to hypo
1912     const _pyID& hypID = theCommand->GetArg( 2 );
1913     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1914     if ( !hyp.IsNull() ) {
1915       myHypos.push_back( hyp );
1916       if ( hyp->GetMesh().IsEmpty() )
1917         hyp->SetMesh( this->GetID() );
1918     }
1919   }
1920   // ----------------------------------------------------------------------
1921   else if ( method == "CreateGroup" ||
1922             method == "CreateGroupFromGEOM" ||
1923             method == "CreateGroupFromFilter" ||
1924             method == "CreateDimGroup" )
1925   {
1926     Handle(_pyGroup) group = new _pyGroup( theCommand );
1927     myGroups.push_back( group );
1928     theGen->AddObject( group );
1929   }
1930   // ----------------------------------------------------------------------
1931   // update list of groups
1932   else if ( method == "GetGroups" )
1933   {
1934     bool allGroupsRemoved = true;
1935     TCollection_AsciiString grIDs = theCommand->GetResultValue();
1936     list< _pyID >          idList = theCommand->GetStudyEntries( grIDs );
1937     list< _pyID >::iterator  grID = idList.begin();
1938     const size_t nbGroupsBefore = myGroups.size();
1939     Handle(_pyObject) obj;
1940     for ( ; grID != idList.end(); ++grID )
1941     {
1942       obj = theGen->FindObject( *grID );
1943       if ( obj.IsNull() )
1944       {
1945         Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1946         theGen->AddObject( group );
1947         myGroups.push_back( group );
1948         obj = group;
1949       }
1950       if ( !obj->CanClear() )
1951         allGroupsRemoved = false;
1952     }
1953     if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1954       obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1955
1956     if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1957     {
1958       // check if the preceding command is Compute();
1959       // if GetGroups() is just after Compute(), this can mean that the groups
1960       // were created by some algorithm and hence Compute() should not be discarded
1961       std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1962       std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1963       while ( (*cmd)->GetMethod() == "GetGroups" )
1964         ++cmd;
1965       if ( myLastComputeCmd == (*cmd))
1966         // protect last Compute() from clearing by the next Compute()
1967         myLastComputeCmd.Nullify();
1968     }
1969   }
1970   // ----------------------------------------------------------------------
1971   // notify a group about full removal
1972   else if ( method == "RemoveGroupWithContents" ||
1973             method == "RemoveGroup")
1974   {
1975     if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1976       const _pyID groupID = theCommand->GetArg( 1 );
1977       Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1978       if ( !grp.IsNull() )
1979       {
1980         if ( method == "RemoveGroupWithContents" )
1981           grp->RemovedWithContents();
1982         // to clear RemoveGroup() if the group creation is cleared
1983         grp->AddProcessedCmd( theCommand );
1984       }
1985     }
1986   }
1987   // ----------------------------------------------------------------------
1988   else if ( theCommand->MethodStartsFrom( "Export" ))
1989   {
1990     if ( method == "ExportToMED"  || // ExportToMED()  --> ExportMED()
1991          method == "ExportToMEDX" || // ExportToMEDX() --> ExportMED()
1992          method == "ExportMED" )
1993     {
1994       theCommand->SetMethod( "ExportMED" );
1995       // filter out deprecated version parameter
1996       vector< _AString > args;
1997       for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
1998         if ( !_FilterArg( theCommand->GetArg( i ) ) )
1999           args.push_back( theCommand->GetArg( i ) );
2000       }
2001       theCommand->RemoveArgs();
2002       for ( uint i = 0; i < args.size(); i++ )
2003         theCommand->SetArg( i+1, args[i] );
2004       if ( theCommand->GetNbArgs() == 4 )
2005       {
2006         // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
2007         _AString autoDimension = theCommand->GetArg( 4 );
2008         theCommand->SetArg( 4, "None" );
2009         theCommand->SetArg( 5, autoDimension );
2010       }
2011     }
2012     else if ( method == "ExportCGNS" )
2013     { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
2014       _pyID partID = theCommand->GetArg( 1 );
2015       int nbArgs = theCommand->GetNbArgs();
2016       for ( int i = 2; i <= nbArgs; ++i )
2017         theCommand->SetArg( i-1, theCommand->GetArg( i ));
2018       theCommand->SetArg( nbArgs, partID );
2019     }
2020     else if ( method == "ExportGMF" )
2021     { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2022       _pyID partID  = theCommand->GetArg( 1 );
2023       _AString file = theCommand->GetArg( 2 );
2024       theCommand->RemoveArgs();
2025       theCommand->SetArg( 1, file );
2026       theCommand->SetArg( 2, partID );
2027     }
2028     else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2029     { // ExportPartTo*(part, ...) -> Export*(..., part)
2030       //
2031       // remove "PartTo" from the method
2032       TCollection_AsciiString newMethod = method;
2033       newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2034       theCommand->SetMethod( newMethod );
2035       // filter out deprecated version parameter
2036       vector< _AString > args;
2037       for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2038         if ( !_FilterArg( theCommand->GetArg( i ) ) )
2039           args.push_back( theCommand->GetArg( i ) );
2040       }
2041       theCommand->RemoveArgs();
2042       for ( uint i = 0; i < args.size(); i++ )
2043         theCommand->SetArg( i+1, args[i] );
2044       // make the 1st arg be the last one (or last but three for ExportMED())
2045       _pyID partID = theCommand->GetArg( 1 );
2046       int nbArgs = theCommand->GetNbArgs() - 3 * (newMethod == "ExportMED");
2047       for ( int i = 2; i <= nbArgs; ++i )
2048         theCommand->SetArg( i-1, theCommand->GetArg( i ));
2049       theCommand->SetArg( nbArgs, partID );
2050     }
2051     // remember file name
2052     theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2053                              ExportedMeshData( this, myLastComputeCmd ));
2054   }
2055   // ----------------------------------------------------------------------
2056   else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2057   {
2058     _pyID hypID  = theCommand->GetArg( 2 );
2059     _pyID geomID = theCommand->GetArg( 1 );
2060     bool isLocal = ( geomID != GetGeom() );
2061
2062     // check if this mesh still has corresponding addition command
2063     Handle(_pyCommand) addCmd;
2064     list< Handle(_pyCommand) >::iterator cmd;
2065     list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2066     for ( int i = 0; i < 2; ++i )
2067     {
2068       list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2069       for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2070       {
2071         bool sameHyp = true;
2072         if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2073           sameHyp = false; // other hyp
2074         if ( (*cmd)->GetNbArgs() == 2 &&
2075              geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2076           sameHyp = false; // other geom
2077         if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2078           sameHyp = false; // other geom
2079         if ( sameHyp )
2080         {
2081           addCmd = *cmd;
2082           cmd    = addHypCmds.erase( cmd );
2083           if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2084             addCmd->Clear();
2085             theCommand->Clear();
2086           }
2087           else
2088           {
2089             // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2090             addCmd->RemoveArgs();
2091             addCmd->SetArg( 1, hypID );
2092             if ( isLocal )
2093               addCmd->SetArg( 2, geomID );
2094           }
2095         }
2096         else
2097         {
2098           ++cmd;
2099         }
2100       }
2101     }
2102     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2103     if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2104       // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2105       _pyID geom = theCommand->GetArg( 1 );
2106       theCommand->RemoveArgs();
2107       theCommand->SetArg( 1, hypID );
2108       if ( geom != GetGeom() )
2109         theCommand->SetArg( 2, geom );
2110     }
2111     // remove hyp from myHypos
2112     myHypos.remove( hyp );
2113   }
2114   // check for SubMesh order commands
2115   else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2116   {
2117     // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2118     // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2119     // commands are moved at the end of the script
2120     TCollection_AsciiString subIDs =
2121       ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2122     list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2123     list< _pyID >::iterator subID = idList.begin();
2124     for ( ; subID != idList.end(); ++subID )
2125     {
2126       Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2127       if ( !subMesh.IsNull() )
2128         subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2129     }
2130   }
2131   // add accessor method if necessary
2132   else
2133   {
2134     if ( NeedMeshAccess( theCommand ))
2135       // apply theCommand to the mesh wrapped by smeshpy mesh
2136       AddMeshAccess( theCommand );
2137   }
2138 }
2139
2140 //================================================================================
2141 /*!
2142  * \brief Return True if addition of accesor method is needed
2143  */
2144 //================================================================================
2145
2146 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2147 {
2148   // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2149   // so no conversion is needed for them at all:
2150   static TStringSet sameMethods;
2151   if ( sameMethods.empty() ) {
2152     const char * names[] =
2153       { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2154         "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2155         "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2156         "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2157         "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2158         "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2159         "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2160         "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2161         "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2162         "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2163         "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2164         "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2165         "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2166         "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2167         ,"" }; // <- mark of end
2168     sameMethods.Insert( names );
2169   }
2170
2171   return !sameMethods.Contains( theCommand->GetMethod() );
2172 }
2173
2174 //================================================================================
2175 /*!
2176  * \brief Convert creation and addition of all algos and hypos
2177  */
2178 //================================================================================
2179
2180 void _pyMesh::Flush()
2181 {
2182   {
2183     // get the meshes this mesh depends on via hypotheses
2184     list< Handle(_pyMesh) > fatherMeshes;
2185     list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2186     for ( ; hyp != myHypos.end(); ++hyp )
2187       if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2188         myGeomNotInStudy = true;
2189
2190     list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2191     for ( ; m != fatherMeshes.end(); ++m )
2192       addFatherMesh( *m );
2193     // if ( removedGeom )
2194     //     SetRemovedFromStudy(); // as referred geometry not in study
2195   }
2196   if ( myGeomNotInStudy )
2197     return;
2198
2199   list < Handle(_pyCommand) >::iterator cmd;
2200
2201   // try to convert algo addition like this:
2202   // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2203   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2204   {
2205     Handle(_pyCommand) addCmd = *cmd;
2206
2207     _pyID algoID = addCmd->GetArg( 2 );
2208     Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2209     if ( algo.IsNull() || !algo->IsAlgo() )
2210       continue;
2211
2212     // check and create new algorithm instance if it is already wrapped
2213     if ( algo->IsWrapped() ) {
2214       _pyID localAlgoID = theGen->GenerateNewID( algoID );
2215       TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2216         TCollection_AsciiString( " = " ) + theGen->GetID() +
2217         TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2218         TCollection_AsciiString( "\" )" );
2219
2220       Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2221       Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2222       if ( !newAlgo.IsNull() ) {
2223         newAlgo->Assign( algo, this->GetID() );
2224         newAlgo->SetCreationCmd( newCmd );
2225         algo = newAlgo;
2226         // set algorithm creation
2227         theGen->SetCommandBefore( newCmd, addCmd );
2228         myHypos.push_back( newAlgo );
2229         if ( !myLastComputeCmd.IsNull() &&
2230              newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2231           newAlgo->MeshComputed( myLastComputeCmd );
2232       }
2233       else
2234         newCmd->Clear();
2235     }
2236     _pyID geom = addCmd->GetArg( 1 );
2237     bool isLocalAlgo = ( geom != GetGeom() );
2238
2239     // try to convert
2240     if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2241     {
2242       // wrapped algo is created after mesh creation
2243       GetCreationCmd()->AddDependantCmd( addCmd );
2244
2245       if ( isLocalAlgo ) {
2246         // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2247         addCmd->SetArg( addCmd->GetNbArgs() + 1,
2248                         TCollection_AsciiString( "geom=" ) + geom );
2249         // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2250         list < Handle(_pySubMesh) >::iterator smIt;
2251         for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2252           Handle(_pySubMesh) subMesh = *smIt;
2253           Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2254           if ( geom == subCmd->GetArg( 1 )) {
2255             subCmd->SetObject( algo->GetID() );
2256             subCmd->RemoveArgs();
2257             subMesh->SetCreator( algo );
2258           }
2259         }
2260       }
2261     }
2262     else // KO - ALGO was already created
2263     {
2264       // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2265       addCmd->RemoveArgs();
2266       addCmd->SetArg( 1, algoID );
2267       if ( isLocalAlgo )
2268         addCmd->SetArg( 2, geom );
2269       myNotConvertedAddHypCmds.push_back( addCmd );
2270     }
2271   }
2272
2273   // try to convert hypo addition like this:
2274   // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2275   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2276   {
2277     Handle(_pyCommand) addCmd = *cmd;
2278     _pyID hypID = addCmd->GetArg( 2 );
2279     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2280     if ( hyp.IsNull() || hyp->IsAlgo() )
2281       continue;
2282     bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2283     if ( !converted ) {
2284       // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2285       _pyID geom = addCmd->GetArg( 1 );
2286       addCmd->RemoveArgs();
2287       addCmd->SetArg( 1, hypID );
2288       if ( geom != GetGeom() )
2289         addCmd->SetArg( 2, geom );
2290       myNotConvertedAddHypCmds.push_back( addCmd );
2291     }
2292   }
2293
2294   myAddHypCmds.clear();
2295   mySubmeshes.clear();
2296
2297   // flush hypotheses
2298   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2299   for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2300     (*hyp)->Flush();
2301 }
2302
2303 //================================================================================
2304 /*!
2305  * \brief Sets myIsPublished of me and of all objects depending on me.
2306  */
2307 //================================================================================
2308
2309 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2310 {
2311   _pyObject::SetRemovedFromStudy(isRemoved);
2312
2313   list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2314   for ( ; sm != mySubmeshes.end(); ++sm )
2315     (*sm)->SetRemovedFromStudy(isRemoved);
2316
2317   list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2318   for ( ; gr != myGroups.end(); ++gr )
2319     (*gr)->SetRemovedFromStudy(isRemoved);
2320
2321   list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2322   for ( ; m != myChildMeshes.end(); ++m )
2323     (*m)->SetRemovedFromStudy(isRemoved);
2324
2325   list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2326   for ( ; e != myEditors.end(); ++e )
2327     (*e)->SetRemovedFromStudy(isRemoved);
2328 }
2329
2330 //================================================================================
2331 /*!
2332  * \brief Return true if none of myChildMeshes is in study
2333  */
2334 //================================================================================
2335
2336 bool _pyMesh::CanClear()
2337 {
2338   if ( IsInStudy() )
2339     return false;
2340
2341   list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2342   for ( ; m != myChildMeshes.end(); ++m )
2343     if ( !(*m)->CanClear() )
2344       return false;
2345
2346   return true;
2347 }
2348
2349 //================================================================================
2350 /*!
2351  * \brief Clear my commands and commands of mesh editor
2352  */
2353 //================================================================================
2354
2355 void _pyMesh::ClearCommands()
2356 {
2357   if ( !CanClear() )
2358   {
2359     if ( !IsInStudy() )
2360     {
2361       // mark all sub-objects as not removed, except child meshes
2362       list< Handle(_pyMesh) > children;
2363       children.swap( myChildMeshes );
2364       SetRemovedFromStudy( false );
2365       children.swap( myChildMeshes );
2366     }
2367     return;
2368   }
2369   _pyObject::ClearCommands();
2370
2371   list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2372   for ( ; sm != mySubmeshes.end(); ++sm )
2373     (*sm)->ClearCommands();
2374   
2375   list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2376   for ( ; gr != myGroups.end(); ++gr )
2377     (*gr)->ClearCommands();
2378
2379   list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2380   for ( ; e != myEditors.end(); ++e )
2381     (*e)->ClearCommands();
2382 }
2383
2384 //================================================================================
2385 /*!
2386  * \brief Add a father mesh by ID
2387  */
2388 //================================================================================
2389
2390 void _pyMesh::addFatherMesh( const _pyID& meshID )
2391 {
2392   if ( !meshID.IsEmpty() && meshID != GetID() )
2393     addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2394 }
2395
2396 //================================================================================
2397 /*!
2398  * \brief Add a father mesh
2399  */
2400 //================================================================================
2401
2402 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2403 {
2404   if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2405   {
2406     //myFatherMeshes.push_back( mesh );
2407     mesh->myChildMeshes.push_back( this );
2408
2409     // protect last Compute() from clearing by the next Compute()
2410     mesh->myLastComputeCmd.Nullify();
2411   }
2412 }
2413
2414 //================================================================================
2415 /*!
2416  * \brief MeshEditor convert its commands to ones of mesh
2417  */
2418 //================================================================================
2419
2420 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2421   _pyObject( theCreationCmd )
2422 {
2423   myMesh = theCreationCmd->GetObject();
2424   myCreationCmdStr = theCreationCmd->GetString();
2425   theCreationCmd->Clear();
2426
2427   Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2428   if ( !mesh.IsNull() )
2429     mesh->AddEditor( this );
2430 }
2431
2432 //================================================================================
2433 /*!
2434  * \brief convert its commands to ones of mesh
2435  */
2436 //================================================================================
2437
2438 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2439 {
2440   // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2441   // commands calling these methods are converted to calls of Mesh methods without
2442   // additional modifs, only object is changed from MeshEditor to Mesh.
2443   static TStringSet sameMethods;
2444   if ( sameMethods.empty() ) {
2445     const char * names[] = {
2446       "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2447       "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2448       "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2449       "MoveNode", "MoveClosestNodeToPoint",
2450       "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2451       "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2452       "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2453       "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2454       "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2455       "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2456       "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2457       "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2458       "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2459       "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2460       "FindCoincidentNodes","MergeNodes","FindEqualElements","FillHole",
2461       "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2462       "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2463       "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2464       "GetLastCreatedElems",
2465       "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2466       "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2467       "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2468       "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2469       "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup","AffectedElemGroupsInRegion",
2470       "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2471       "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2472       ,"" }; // <- mark of the end
2473     sameMethods.Insert( names );
2474   }
2475
2476   // names of SMESH_MeshEditor commands in which only a method name must be replaced
2477   TStringMap diffMethods;
2478   if ( diffMethods.empty() ) {
2479     const char * orig2newName[] = {
2480       // original name --------------> new name
2481       "ExtrusionAlongPathObjX"      , "ExtrusionAlongPathX",
2482       "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2483       "ConvertToQuadraticObject"    , "ConvertToQuadratic",
2484       "ConvertFromQuadraticObject"  , "ConvertFromQuadratic",
2485       "Create0DElementsOnAllNodes"  , "Add0DElementsToAllNodes",
2486       ""};// <- mark of the end
2487     diffMethods.Insert( orig2newName );
2488   }
2489
2490   // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2491   // only by last two arguments
2492   static TStringSet diffLastTwoArgsMethods;
2493   if (diffLastTwoArgsMethods.empty() ) {
2494     const char * names[] = {
2495       "MirrorMakeGroups","MirrorObjectMakeGroups",
2496       "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2497       "RotateMakeGroups","RotateObjectMakeGroups",
2498       ""};// <- mark of the end
2499     diffLastTwoArgsMethods.Insert( names );
2500   }
2501
2502   // only a method name is to change?
2503   const TCollection_AsciiString & method = theCommand->GetMethod();
2504   bool isPyMeshMethod = sameMethods.Contains( method );
2505   if ( !isPyMeshMethod )
2506   {
2507     TCollection_AsciiString newMethod = diffMethods.Value( method );
2508     if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2509       theCommand->SetMethod( newMethod );
2510   }
2511   // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2512   if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2513   {
2514     isPyMeshMethod = true;
2515     theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2516     theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2517   }
2518
2519   if ( !isPyMeshMethod )
2520   {
2521     // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2522     // functions with the flag "theMakeGroups = True" like:
2523     // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2524     int pos = method.Search("MakeGroups");
2525     if( pos != -1)
2526     {
2527       isPyMeshMethod = true;
2528       bool is0DmethId  = ( method == "ExtrusionSweepMakeGroups0D" );
2529       bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2530
2531       // 1. Remove "MakeGroups" from the Command
2532       TCollection_AsciiString aMethod = theCommand->GetMethod();
2533       int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2534       
2535       if(is0DmethObj)
2536         pos = pos-2;  //Remove "0D" from the Command too
2537       aMethod.Trunc(pos-1);
2538       theCommand->SetMethod(aMethod);
2539
2540       // 2. And add last "True" argument(s)
2541       while(nbArgsToAdd--)
2542         theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2543       if( is0DmethId || is0DmethObj )
2544         theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2545     }
2546   }
2547
2548   // ExtrusionSweep0D()       -> ExtrusionSweep()
2549   // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2550   if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D"  ||
2551                             method == "ExtrusionSweepObject0D" ))
2552   {
2553     isPyMeshMethod = true;
2554     theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2555     theCommand->SetArg(theCommand->GetNbArgs()+1,"False");  //sets flag "MakeGroups = False"
2556     theCommand->SetArg(theCommand->GetNbArgs()+1,"True");  //sets flag "IsNode = True"
2557   }
2558
2559   // DoubleNode...New(...) -> DoubleNode...(...,True)
2560   if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew"  ||
2561                             method == "DoubleNodeElemGroupsNew" ||
2562                             method == "DoubleNodeGroupNew"      ||
2563                             method == "DoubleNodeGroupsNew"     ||
2564                             method == "DoubleNodeElemGroup2New" ||
2565                             method == "DoubleNodeElemGroups2New"))
2566   {
2567     isPyMeshMethod = true;
2568     const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2569     theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2570     if ( excessLen == 3 )
2571     {
2572       theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2573     }
2574     else if ( theCommand->GetArg(4) == "0" ||
2575               theCommand->GetArg(5) == "0" )
2576     {
2577       // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2578       // Group = DoubleNodeGroup2New(,,,False, True)
2579       _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2580       theCommand->SetResultValue( groupID );
2581     }
2582   }
2583   // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2584   // FindElementsByPoint(x, y, z, elementType, meshPart)
2585   if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2586   {
2587     isPyMeshMethod = true;
2588     theCommand->SetMethod( "FindElementsByPoint" );
2589     // make the 1st arg be the last one
2590     _pyID partID = theCommand->GetArg( 1 );
2591     int nbArgs = theCommand->GetNbArgs();
2592     for ( int i = 2; i <= nbArgs; ++i )
2593       theCommand->SetArg( i-1, theCommand->GetArg( i ));
2594     theCommand->SetArg( nbArgs, partID );
2595   }
2596   // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2597   if ( !isPyMeshMethod && method == "Reorient2D" )
2598   {
2599     isPyMeshMethod = true;
2600     _AString mesh  = theCommand->GetArg( 1 );
2601     _AString dir   = theCommand->GetArg( 2 );
2602     _AString face  = theCommand->GetArg( 3 );
2603     _AString point = theCommand->GetArg( 4 );
2604     theCommand->RemoveArgs();
2605     theCommand->SetArg( 1, mesh );
2606     theCommand->SetArg( 2, dir );
2607     if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2608       theCommand->SetArg( 3, point );
2609     else
2610       theCommand->SetArg( 3, face );
2611   }
2612
2613   if ( method == "QuadToTri" || method == "QuadToTriObject" )
2614   {
2615     isPyMeshMethod = true;
2616     int crit_arg = theCommand->GetNbArgs();
2617     const _AString& crit = theCommand->GetArg(crit_arg);
2618     if (crit.Search("MaxElementLength2D") != -1)
2619       theCommand->SetArg(crit_arg, "");
2620   }
2621
2622   if ( isPyMeshMethod )
2623   {
2624     theCommand->SetObject( myMesh );
2625   }
2626   else
2627   {
2628     // editor creation command is needed only if any editor function is called
2629     theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2630     if ( !myCreationCmdStr.IsEmpty() ) {
2631       GetCreationCmd()->GetString() = myCreationCmdStr;
2632       myCreationCmdStr.Clear();
2633     }
2634   }
2635 }
2636
2637 //================================================================================
2638 /*!
2639  * \brief Return true if my mesh can be removed
2640  */
2641 //================================================================================
2642
2643 bool _pyMeshEditor::CanClear()
2644 {
2645   Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2646   return mesh.IsNull() ? true : mesh->CanClear();
2647 }
2648
2649 //================================================================================
2650 /*!
2651  * \brief _pyHypothesis constructor
2652  *  \param theCreationCmd -
2653  */
2654 //================================================================================
2655
2656 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2657   _pyObject( theCreationCmd ), myCurCrMethod(0)
2658 {
2659   myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2660 }
2661
2662 //================================================================================
2663 /*!
2664  * \brief Creates algorithm or hypothesis
2665  *  \param theCreationCmd - The engine command creating a hypothesis
2666  * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2667  */
2668 //================================================================================
2669
2670 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2671 {
2672   // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2673   ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2674
2675   Handle(_pyHypothesis) hyp, algo;
2676
2677   // "theHypType"
2678   const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2679   if ( hypTypeQuoted.IsEmpty() )
2680     return hyp;
2681   // theHypType
2682   TCollection_AsciiString  hypType =
2683     hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2684
2685   algo = new _pyAlgorithm( theCreationCmd );
2686   hyp  = new _pyHypothesis( theCreationCmd );
2687
2688   if ( hypType == "NumberOfSegments" ) {
2689     hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2690     hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2691     // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2692     hyp->AddArgMethod( "SetNumberOfSegments" );
2693     // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2694     hyp->AddArgMethod( "SetScaleFactor" );
2695     hyp->AddArgMethod( "SetReversedEdges" );
2696     // same for ""CompositeSegment_1D:
2697     hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2698     hyp->AddArgMethod( "SetNumberOfSegments" );
2699     hyp->AddArgMethod( "SetScaleFactor" );
2700     hyp->AddArgMethod( "SetReversedEdges" );
2701   }
2702   else if ( hypType == "SegmentLengthAroundVertex" ) {
2703     hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2704     hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2705     hyp->AddArgMethod( "SetLength" );
2706     // same for ""CompositeSegment_1D:
2707     hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2708     hyp->AddArgMethod( "SetLength" );
2709   }
2710   else if ( hypType == "LayerDistribution2D" ) {
2711     hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2712     hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2713   }
2714   else if ( hypType == "LayerDistribution" ) {
2715     hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2716     hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2717   }
2718   else if ( hypType == "CartesianParameters3D" ) {
2719     hyp = new _pyComplexParamHypo( theCreationCmd );
2720     hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2721     for ( int iArg = 0; iArg < 4; ++iArg )
2722       hyp->setCreationArg( iArg+1, "[]");
2723     hyp->AddAccumulativeMethod( "SetGrid" );
2724     hyp->AddAccumulativeMethod( "SetGridSpacing" );
2725   }
2726   else
2727   {
2728     hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2729   }
2730
2731   return algo->IsValid() ? algo : hyp;
2732 }
2733
2734 //================================================================================
2735 /*!
2736  * \brief Returns true if addition of this hypothesis to a given mesh can be
2737  *        wrapped into hypothesis creation
2738  */
2739 //================================================================================
2740
2741 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2742 {
2743   if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2744   {
2745     Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2746     if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2747       return true;
2748   }
2749   return false;
2750 }
2751
2752 //================================================================================
2753 /*!
2754  * \brief Convert the command adding a hypothesis to mesh into a smesh command
2755  *  \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2756  *  \param theAlgo - The algo that can create this hypo
2757  * \retval bool - false if the command can't be converted
2758  */
2759 //================================================================================
2760
2761 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2762                                        const _pyID&              theMesh)
2763 {
2764   ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2765
2766   if ( !IsWrappable( theMesh ))
2767     return false;
2768
2769   myGeom = theCmd->GetArg( 1 );
2770
2771   Handle(_pyHypothesis) algo;
2772   if ( !IsAlgo() ) {
2773     // find algo created on myGeom in theMesh
2774     algo = theGen->FindAlgo( myGeom, theMesh, this );
2775     if ( algo.IsNull() )
2776       return false;
2777     // attach hypothesis creation command to be after algo creation command
2778     // because it can be new created instance of algorithm
2779     algo->GetCreationCmd()->AddDependantCmd( theCmd );
2780   }
2781   myIsWrapped = true;
2782
2783   // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2784   theCmd->SetResultValue( GetID() );
2785   theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2786   theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2787   // set args (geom will be set by _pyMesh calling this method)
2788   theCmd->RemoveArgs();
2789   for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2790     if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2791       theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2792     else
2793       theCmd->SetArg( i+1, "[]");
2794   }
2795   // set a new creation command
2796   GetCreationCmd()->Clear();
2797   // replace creation command by wrapped instance
2798   // please note, that hypothesis attaches to algo creation command (see upper)
2799   SetCreationCmd( theCmd );
2800
2801
2802   // clear commands setting arg values
2803   list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2804   for ( ; argCmd != myArgCommands.end(); ++argCmd )
2805     (*argCmd)->Clear();
2806
2807   // set unknown arg commands after hypo creation
2808   Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2809   list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2810   for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2811     afterCmd->AddDependantCmd( *cmd );
2812   }
2813
2814   return myIsWrapped;
2815 }
2816
2817 //================================================================================
2818 /*!
2819  * \brief Remember hypothesis parameter values
2820  *  \param theCommand - The called hypothesis method
2821  */
2822 //================================================================================
2823
2824 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2825 {
2826   ASSERT( !myIsAlgo );
2827   if ( !theGen->IsToKeepAllCommands() )
2828     rememberCmdOfParameter( theCommand );
2829   // set args
2830   bool usedCommand = false;
2831   TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2832   for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2833   {
2834     CreationMethod& crMethod = type2meth->second;
2835     for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2836       if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2837         if ( !usedCommand )
2838           myArgCommands.push_back( theCommand );
2839         usedCommand = true;
2840         while ( crMethod.myArgs.size() < i+1 )
2841           crMethod.myArgs.push_back( "None" );
2842         crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2843       }
2844     }
2845   }
2846   if ( !usedCommand )
2847     myUnusedCommands.push_back( theCommand );
2848 }
2849
2850 //================================================================================
2851 /*!
2852  * \brief Finish conversion
2853  */
2854 //================================================================================
2855
2856 void _pyHypothesis::Flush()
2857 {
2858   if ( !IsAlgo() )
2859   {
2860     list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2861     for ( ; cmd != myArgCommands.end(); ++cmd ) {
2862       // Add access to a wrapped mesh
2863       theGen->AddMeshAccessorMethod( *cmd );
2864       // Add access to a wrapped algorithm
2865       theGen->AddAlgoAccessorMethod( *cmd );
2866     }
2867     cmd = myUnusedCommands.begin();
2868     for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2869       // Add access to a wrapped mesh
2870       theGen->AddMeshAccessorMethod( *cmd );
2871       // Add access to a wrapped algorithm
2872       theGen->AddAlgoAccessorMethod( *cmd );
2873     }
2874   }
2875   // forget previous hypothesis modifications
2876   myArgCommands.clear();
2877   myUnusedCommands.clear();
2878 }
2879
2880 //================================================================================
2881 /*!
2882  * \brief clear creation, arg and unknown commands
2883  */
2884 //================================================================================
2885
2886 void _pyHypothesis::ClearAllCommands()
2887 {
2888   GetCreationCmd()->Clear();
2889   list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2890   for ( ; cmd != myArgCommands.end(); ++cmd )
2891     ( *cmd )->Clear();
2892   cmd = myUnusedCommands.begin();
2893   for ( ; cmd != myUnusedCommands.end(); ++cmd )
2894     ( *cmd )->Clear();
2895 }
2896
2897
2898 //================================================================================
2899 /*!
2900  * \brief Assign fields of theOther to me except myIsWrapped
2901  */
2902 //================================================================================
2903
2904 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2905                             const _pyID&                 theMesh )
2906 {
2907   // myCreationCmd = theOther->myCreationCmd;
2908   myIsAlgo                  = theOther->myIsAlgo;
2909   myIsWrapped               = false;
2910   myGeom                    = theOther->myGeom;
2911   myMesh                    = theMesh;
2912   myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2913   myAccumulativeMethods     = theOther->myAccumulativeMethods;
2914   //myUnusedCommands          = theOther->myUnusedCommands;
2915   // init myCurCrMethod
2916   GetCreationMethod( theOther->GetAlgoType() );
2917 }
2918
2919 //================================================================================
2920 /*!
2921  * \brief Analyze my erasability depending on myReferredObjs
2922  */
2923 //================================================================================
2924
2925 bool _pyHypothesis::CanClear()
2926 {
2927   if ( IsInStudy() )
2928   {
2929     list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2930     for ( ; obj != myReferredObjs.end(); ++obj )
2931       if ( (*obj)->CanClear() )
2932         return true;
2933     return false;
2934   }
2935   return true;
2936 }
2937
2938 //================================================================================
2939 /*!
2940  * \brief Clear my commands depending on usage by meshes
2941  */
2942 //================================================================================
2943
2944 void _pyHypothesis::ClearCommands()
2945 {
2946   // if ( !theGen->IsToKeepAllCommands() )
2947   // {
2948   //   bool isUsed = false;
2949   //   int lastComputeOrder = 0;
2950   //   list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2951   //   for ( ; cmd != myComputeCmds.end(); ++cmd )
2952   //     if ( ! (*cmd)->IsEmpty() )
2953   //     {
2954   //       isUsed = true;
2955   //       if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2956   //         lastComputeOrder = (*cmd)->GetOrderNb();
2957   //     }
2958   //   if ( !isUsed )
2959   //   {
2960   //     SetRemovedFromStudy( true );
2961   //   }
2962   //   else
2963   //   {
2964   //     // clear my commands invoked after lastComputeOrder
2965   //     // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2966   //     // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2967   //     // {
2968   //     //   list< Handle(_pyCommand)> & cmds = m2c->second;
2969   //     //   if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2970   //     //     cmds.back()->Clear();
2971   //     // }
2972   //   }
2973   // }
2974   _pyObject::ClearCommands();
2975 }
2976
2977 //================================================================================
2978 /*!
2979  * \brief Find arguments that are objects like mesh, group, geometry
2980  *  \param meshes - referred meshes (directly or indirrectly)
2981  *  \retval bool - false if a referred geometry is not in the study
2982  */
2983 //================================================================================
2984
2985 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2986 {
2987   if ( IsAlgo() ) return true;
2988
2989   bool geomPublished = true;
2990   vector< _AString > args;
2991   TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2992   for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2993   {
2994     CreationMethod& crMethod = type2meth->second;
2995     args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2996   }
2997   list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2998   for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2999     for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
3000       args.push_back( (*cmd)->GetArg( nb ));
3001   }
3002
3003   for ( size_t i = 0; i < args.size(); ++i )
3004   {
3005     list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
3006     if ( idList.empty() && !args[ i ].IsEmpty() )
3007       idList.push_back( args[ i ]);
3008     list< _pyID >::iterator id = idList.begin();
3009     for ( ; id != idList.end(); ++id )
3010     {
3011       Handle(_pyObject)   obj = theGen->FindObject( *id );
3012       if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
3013       if ( obj.IsNull() )
3014       {
3015         if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
3016           geomPublished = false;
3017       }
3018       else
3019       {
3020         myReferredObjs.push_back( obj );
3021         Handle(_pyMesh) mesh = ObjectToMesh( obj );
3022         if ( !mesh.IsNull() )
3023           meshes.push_back( mesh );
3024         // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3025         else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3026           obj->SetRemovedFromStudy( false );
3027       }
3028     }
3029   }
3030   return geomPublished;
3031 }
3032
3033 //================================================================================
3034 /*!
3035  * \brief Remember theCommand setting a parameter
3036  */
3037 //================================================================================
3038
3039 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3040 {
3041   // parameters are discriminated by method name
3042   _AString method = theCommand->GetMethod();
3043   if ( myAccumulativeMethods.count( method ))
3044     return; // this method adds values and not override the previus value
3045
3046   // discriminate commands setting different parameters via one method
3047   // by passing parameter names like e.g. SetOption("size", "0.2")
3048   if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3049        theCommand->GetNbArgs() > 1 )
3050   {
3051     // mangle method by appending a 1st textual arg
3052     for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3053     {
3054       const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3055       if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3056       if ( !isalpha( arg.Value(2))) continue;
3057       method += arg;
3058       break;
3059     }
3060   }
3061   // parameters are discriminated by method name
3062   list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3063   if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3064   {
3065     cmds.back()->Clear(); // previous parameter value has not been used
3066     cmds.back() = theCommand;
3067   }
3068   else
3069   {
3070     cmds.push_back( theCommand );
3071   }
3072 }
3073
3074 //================================================================================
3075 /*!
3076  * \brief Return true if a setting parameter command ha been used to compute mesh
3077  */
3078 //================================================================================
3079
3080 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3081                                          _pyCommand::TAddr          avoidComputeAddr ) const
3082 {
3083   bool isUsed = false;
3084   map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3085     myComputeAddr2Cmds.begin();
3086   for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3087   {
3088     if ( addr2cmds->first == avoidComputeAddr ) continue;
3089     const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3090     isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3091   }
3092   return isUsed;
3093 }
3094
3095 //================================================================================
3096 /*!
3097  * \brief Save commands setting parameters as they are used for a mesh computation
3098  */
3099 //================================================================================
3100
3101 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3102 {
3103   myComputeCmds.push_back( theComputeCmd );
3104   list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3105
3106   map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3107   for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3108     savedCmds.push_back( m2c->second.back() );
3109 }
3110
3111 //================================================================================
3112 /*!
3113  * \brief Clear commands setting parameters as a mesh computed using them is cleared
3114  */
3115 //================================================================================
3116
3117 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3118 {
3119   list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3120
3121   list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3122   for ( ; cmd != savedCmds.end(); ++cmd )
3123   {
3124     // check if a cmd has been used to compute another mesh
3125     if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3126       continue;
3127     // check if a cmd is a sole command setting its parameter;
3128     // don't use method name for search as it can change
3129     map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3130       m2cmds = myMeth2Commands.begin();
3131     for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3132     {
3133       list< Handle(_pyCommand)>& cmds = m2cmds->second;
3134       list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3135       if ( cmdIt != cmds.end() )
3136       {
3137         if ( cmds.back() != *cmd )
3138         {
3139           cmds.erase( cmdIt );
3140           (*cmd)->Clear();
3141         }
3142         break;
3143       }
3144     }
3145   }
3146   myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3147 }
3148
3149 //================================================================================
3150 /*!
3151  * \brief Sets an argNb-th argument of current creation command
3152  *  \param argNb - argument index countered from 1
3153  */
3154 //================================================================================
3155
3156 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3157 {
3158   if ( myCurCrMethod )
3159   {
3160     while ( (int) myCurCrMethod->myArgs.size() < argNb )
3161       myCurCrMethod->myArgs.push_back( "None" );
3162     if ( arg.IsEmpty() )
3163       myCurCrMethod->myArgs[ argNb-1 ] = "None";
3164     else
3165       myCurCrMethod->myArgs[ argNb-1 ] = arg;
3166   }
3167 }
3168
3169
3170 //================================================================================
3171 /*!
3172  * \brief Remember hypothesis parameter values
3173  *  \param theCommand - The called hypothesis method
3174  */
3175 //================================================================================
3176
3177 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3178 {
3179   if ( GetAlgoType() == "Cartesian_3D" )
3180   {
3181     // CartesianParameters3D hyp
3182
3183     if ( theCommand->GetMethod() == "SetSizeThreshold"  ||
3184          theCommand->GetMethod() == "SetToAddEdges" )
3185     {
3186       int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3187       setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3188       myArgCommands.push_back( theCommand );
3189       return;
3190     }
3191     if ( theCommand->GetMethod() == "SetGrid" ||
3192          theCommand->GetMethod() == "SetGridSpacing" )
3193     {
3194       TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3195       int iArg = axis.Value(1) - '0';
3196       if ( theCommand->GetMethod() == "SetGrid" )
3197       {
3198         setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3199       }
3200       else
3201       {
3202         myCurCrMethod->myArgs[ iArg ] = "[ ";
3203         myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3204         myCurCrMethod->myArgs[ iArg ] += ", ";
3205         myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3206         myCurCrMethod->myArgs[ iArg ] += "]";
3207       }
3208       myArgCommands.push_back( theCommand );
3209       //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3210       //                                  accumulative, else, if the creation
3211       //                 is not converted, commands for axes 1 and 2 are lost
3212       return;
3213     }
3214   }
3215
3216   if( theCommand->GetMethod() == "SetLength" )
3217   {
3218     // NOW it is OBSOLETE
3219     // ex: hyp.SetLength(start, 1)
3220     //     hyp.SetLength(end,   0)
3221     ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3222     int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3223     TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3224     for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3225     {
3226       CreationMethod& crMethod = type2meth->second;
3227       while ( (int) crMethod.myArgs.size() < i+1 )
3228         crMethod.myArgs.push_back( "[]" );
3229       crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3230     }
3231     myArgCommands.push_back( theCommand );
3232   }
3233   else
3234   {
3235     _pyHypothesis::Process( theCommand );
3236   }
3237 }
3238 //================================================================================
3239 /*!
3240  * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3241  */
3242 //================================================================================
3243
3244 void _pyComplexParamHypo::Flush()
3245 {
3246   list < Handle(_pyCommand) >::iterator cmd;
3247   if ( IsWrapped() )
3248   {
3249     for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3250       if ((*cmd)->GetMethod() == "SetObjectEntry" )
3251         (*cmd)->Clear();
3252   }
3253
3254   // if ( GetAlgoType() == "Cartesian_3D" )
3255   // {
3256   //   _pyID algo = myCreationCmd->GetObject();
3257   //   for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3258   //   {
3259   //     if ( IsWrapped() )
3260   //     {
3261   //       StructToList( *cmd, /*checkMethod=*/false );
3262   //       const _AString & method = (*cmd)->GetMethod();
3263   //       if ( method == "SetFixedPoint" )
3264   //         (*cmd)->SetObject( algo );
3265   //     }
3266   //   }
3267   // }
3268 }
3269
3270 //================================================================================
3271 /*!
3272  * \brief Convert methods of 1D hypotheses to my own methods
3273  *  \param theCommand - The called hypothesis method
3274  */
3275 //================================================================================
3276
3277 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3278 {
3279   if ( theCommand->GetMethod() != "SetLayerDistribution" )
3280     return;
3281
3282   const _pyID& hyp1dID = theCommand->GetArg( 1 );
3283   // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3284   // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3285   // {
3286   //   TCollection_AsciiString cmd =
3287   //     my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3288   //   Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3289   //   theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3290   //   hyp1d = my1dHyp;
3291   // }
3292   // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3293   // {
3294   //   // 1D hypo is already set, so distribution changes and the old
3295   //   // 1D hypo is thrown away
3296   //   my1dHyp->ClearAllCommands();
3297   // }
3298   // my1dHyp = hyp1d;
3299   // //my1dHyp->SetRemovedFromStudy( false );
3300
3301   // if ( !myArgCommands.empty() )
3302   //   myArgCommands.back()->Clear();
3303   myCurCrMethod->myArgs.push_back( hyp1dID );
3304   myArgCommands.push_back( theCommand );
3305 }
3306
3307 //================================================================================
3308 /*!
3309  * \brief
3310  *  \param theAdditionCmd - command to be converted
3311  *  \param theMesh - mesh instance
3312  * \retval bool - status
3313  */
3314 //================================================================================
3315
3316 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3317                                                   const _pyID&              theMesh)
3318 {
3319   myIsWrapped = false;
3320
3321   if ( my1dHyp.IsNull() )
3322     return false;
3323
3324   // set "SetLayerDistribution()" after addition cmd
3325   theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3326
3327   _pyID geom = theAdditionCmd->GetArg( 1 );
3328
3329   Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3330   if ( !algo.IsNull() )
3331   {
3332     my1dHyp->SetMesh( theMesh );
3333     my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3334                                   algo->GetAlgoType().ToCString());
3335     if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3336       return false;
3337
3338     // clear "SetLayerDistribution()" cmd
3339     myArgCommands.back()->Clear();
3340
3341     // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3342
3343     // find RadialPrism algo created on <geom> for theMesh
3344     GetCreationCmd()->SetObject( algo->GetID() );
3345     GetCreationCmd()->SetMethod( myAlgoMethod );
3346     GetCreationCmd()->RemoveArgs();
3347     theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3348     myIsWrapped = true;
3349   }
3350   return myIsWrapped;
3351 }
3352
3353 //================================================================================
3354 /*!
3355  * \brief
3356  */
3357 //================================================================================
3358
3359 void _pyLayerDistributionHypo::Flush()
3360 {
3361   // as creation of 1D hyp was written later then it's edition,
3362   // we need to find all it's edition calls and process them
3363   list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3364   _pyID prevNewName;
3365   for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3366   {    
3367     const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3368     if ( hyp1dID.IsEmpty() ) continue;
3369
3370     Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3371
3372     // make a new name for 1D hyp = "HypType" + "_Distribution"
3373     _pyID newName;
3374     if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3375     {
3376       if ( prevNewName.IsEmpty() ) continue;
3377       newName = prevNewName;
3378     }
3379     else
3380     {
3381       if ( hyp1d->IsWrapped() ) {
3382         newName = hyp1d->GetCreationCmd()->GetMethod();
3383       }
3384       else {
3385         TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3386         newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3387       }
3388       newName += "_Distribution";
3389       prevNewName = newName;
3390     
3391       hyp1d->GetCreationCmd()->SetResultValue( newName );
3392     }
3393     list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3394     list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3395     for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3396       const _pyID& objID = (*cmdIt)->GetObject();
3397       if ( objID == hyp1dID ) {
3398         if ( !hyp1d.IsNull() )
3399         {
3400           hyp1d->Process( *cmdIt );
3401           hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3402         }
3403         ( *cmdIt )->SetObject( newName );
3404       }
3405     }
3406     // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3407     (*cmd)->SetArg( 1, newName );
3408   }
3409 }
3410
3411 //================================================================================
3412 /*!
3413  * \brief additionally to Addition2Creation, clears SetDistrType() command
3414  *  \param theCmd - AddHypothesis() command
3415  *  \param theMesh - mesh to which a hypothesis is added
3416  * \retval bool - conversion result
3417  */
3418 //================================================================================
3419
3420 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3421                                                 const _pyID&              theMesh)
3422 {
3423   if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3424     // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3425     bool scaleDistrType = false;
3426     list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3427     for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3428       if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3429         if ( (*cmd)->GetArg( 1 ) == "1" ) {
3430           scaleDistrType = true;
3431           (*cmd)->Clear();
3432         }
3433         else if ( !scaleDistrType ) {
3434           // distribution type changed: remove scale factor from args
3435           TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3436           for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3437           {
3438             CreationMethod& crMethod = type2meth->second;
3439             if ( crMethod.myArgs.size() == 2 )
3440               crMethod.myArgs.pop_back();
3441           }
3442           break;
3443         }
3444       }
3445     }
3446   }
3447   return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3448 }
3449
3450 //================================================================================
3451 /*!
3452  * \brief remove repeated commands defining distribution
3453  */
3454 //================================================================================
3455
3456 void _pyNumberOfSegmentsHyp::Flush()
3457 {
3458   // find number of the last SetDistrType() command
3459   list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3460   int distrTypeNb = 0;
3461   for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3462     if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3463       if ( cmd != myUnusedCommands.rbegin() )
3464         distrTypeNb = (*cmd)->GetOrderNb();
3465     }
3466     else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3467       (*cmd)->Clear();
3468     }
3469   // clear commands before the last SetDistrType()
3470   list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3471   set< int > treatedCmdNbs; // avoid treating same cmd twice
3472   for ( int i = 0; i < 2; ++i ) {
3473     set<TCollection_AsciiString> uniqueMethods;
3474     list<Handle(_pyCommand)> & cmdList = *cmds[i];
3475     for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3476     {
3477       if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3478         continue;// avoid treating same cmd twice
3479       bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3480       const TCollection_AsciiString& method = (*cmd)->GetMethod();
3481       if ( !clear || method == "SetNumberOfSegments" ) {
3482         bool isNewInSet = uniqueMethods.insert( method ).second;
3483         clear = !isNewInSet;
3484       }
3485       if ( clear )
3486         (*cmd)->Clear();
3487     }
3488     cmdList.clear();
3489   }
3490 }
3491
3492 //================================================================================
3493 /*!
3494  * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3495  * into regular1D.LengthNearVertex( length, vertex )
3496  *  \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3497  *  \param theMesh - The mesh needing this hypo
3498  * \retval bool - false if the command can't be converted
3499  */
3500 //================================================================================
3501
3502 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3503                                                          const _pyID&              theMeshID)
3504 {
3505   if ( IsWrappable( theMeshID )) {
3506
3507     _pyID vertex = theCmd->GetArg( 1 );
3508
3509     // the problem here is that segment algo can be not found
3510     // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3511     // geometry where segment algorithm is assigned
3512     _pyID geom = vertex;
3513     Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3514     while ( algo.IsNull() && !geom.IsEmpty()) {
3515       // try to find geom as a father of <vertex>
3516       geom = FatherID( geom );
3517       algo = theGen->FindAlgo( geom, theMeshID, this );
3518     }
3519     if ( algo.IsNull() || geom.IsEmpty() )
3520       return false; // also possible to find geom as brother of veretex...
3521
3522     // set geom instead of vertex
3523     theCmd->SetArg( 1, geom );
3524
3525     // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3526     // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3527     if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3528     {
3529       // set vertex as a second arg
3530       theCmd->SetArg( 2, vertex );
3531
3532       return true;
3533     }
3534   }
3535   return false;
3536 }
3537
3538 //================================================================================
3539 /*!
3540  * \brief _pyAlgorithm constructor
3541  *  \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3542  */
3543 //================================================================================
3544
3545 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3546   : _pyHypothesis( theCreationCmd )
3547 {
3548   myIsAlgo = true;
3549 }
3550
3551 //================================================================================
3552 /*!
3553  * \brief Convert the command adding an algorithm to mesh
3554  *  \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3555  *  \param theMesh - The mesh needing this algo
3556  * \retval bool - false if the command can't be converted
3557  */
3558 //================================================================================
3559
3560 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3561                                       const _pyID&              theMeshID)
3562 {
3563   // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3564   if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3565     theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3566     return true;
3567   }
3568   return false;
3569 }
3570
3571 //================================================================================
3572 /*!
3573  * \brief Return starting position of a part of python command
3574  *  \param thePartIndex - The index of command part
3575  * \retval int - Part position
3576  */
3577 //================================================================================
3578
3579 int _pyCommand::GetBegPos( int thePartIndex ) const
3580 {
3581   if ( IsEmpty() )
3582     return EMPTY;
3583   if ( myBegPos.Length() < thePartIndex )
3584     return UNKNOWN;
3585   ASSERT( thePartIndex > 0 );
3586   return myBegPos( thePartIndex );
3587 }
3588
3589 //================================================================================
3590 /*!
3591  * \brief Store starting position of a part of python command
3592  *  \param thePartIndex - The index of command part
3593  *  \param thePosition - Part position
3594  */
3595 //================================================================================
3596
3597 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3598 {
3599   while ( myBegPos.Length() < thePartIndex )
3600     myBegPos.Append( UNKNOWN );
3601   ASSERT( thePartIndex > 0 );
3602   myBegPos( thePartIndex ) = thePosition;
3603 }
3604
3605 //================================================================================
3606 /*!
3607  * \brief Returns whitespace symbols at the line beginning
3608  * \retval TCollection_AsciiString - result
3609  */
3610 //================================================================================
3611
3612 TCollection_AsciiString _pyCommand::GetIndentation()
3613 {
3614   int end = 1;
3615   //while ( end <= Length() && isblank( myString.Value( end )))
3616   //ANA: isblank() function isn't provided in VC2010 compiler
3617   while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3618     ++end;
3619   return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3620 }
3621
3622 //================================================================================
3623 /*!
3624  * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3625  * \retval const TCollection_AsciiString & - ResultValue substring
3626  */
3627 //================================================================================
3628
3629 const TCollection_AsciiString & _pyCommand::GetResultValue()
3630 {
3631   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3632   {
3633     SetBegPos( RESULT_IND, EMPTY );
3634     int begPos, endPos = myString.Location( "=", 1, Length() );
3635     if ( endPos )
3636     {
3637       begPos = 1;
3638       while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3639       if ( begPos < endPos )
3640       {
3641         SetBegPos( RESULT_IND, begPos );
3642         --endPos;
3643         while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3644         myRes = myString.SubString( begPos, endPos );
3645       }
3646     }
3647   }
3648   return myRes;
3649 }
3650
3651 //================================================================================
3652 /*!
3653  * \brief Return number of python command result value ResultValue = Obj.Meth()
3654  */
3655 //================================================================================
3656
3657 int _pyCommand::GetNbResultValues()
3658 {
3659   GetResultValue(1);
3660   return myResults.Length();
3661 }
3662
3663
3664 //================================================================================
3665 /*!
3666  * \brief Return substring of python command looking like
3667  *  ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3668  * \retval const TCollection_AsciiString & - ResultValue with res index substring
3669  */
3670 //================================================================================
3671 const _AString& _pyCommand::GetResultValue(int res)
3672 {
3673   if ( GetResultValue().IsEmpty() )
3674     return theEmptyString;
3675
3676   if ( myResults.IsEmpty() )
3677   {
3678     int begPos = 1;
3679     if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3680       ++begPos; // skip [, else the whole list is returned
3681     while ( begPos < myRes.Length() ) {
3682       _AString result = GetWord( myRes, begPos, true );
3683       begPos += result.Length();
3684       // if(res == Nb) {
3685       //   result.RemoveAll('[');
3686       //   result.RemoveAll(']');
3687       //   return result;
3688       // }
3689       // if(Nb>res)
3690       //   break;
3691       myResults.Append( result );
3692     }
3693   }
3694   if ( res > 0 && res <= myResults.Length() )
3695     return myResults( res );
3696   return theEmptyString;
3697 }
3698
3699 //================================================================================
3700 /*!
3701  * \brief Return substring of python command looking like ResVal = Object.Meth()
3702  * \retval const TCollection_AsciiString & - Object substring
3703  */
3704 //================================================================================
3705
3706 const TCollection_AsciiString & _pyCommand::GetObject()
3707 {
3708   if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3709   {
3710     // beginning
3711     int begPos = GetBegPos( RESULT_IND );
3712     if ( begPos < 1 ) {
3713       begPos = myString.Location( "=", 1, Length() ) + 1;
3714       // is '=' in the string argument (for example, name) or not
3715       int nb1 = 0; // number of ' character at the left of =
3716       int nb2 = 0; // number of " character at the left of =
3717       for ( int i = 1; i < begPos-1; i++ ) {
3718         if ( myString.Value( i )=='\'' )
3719           nb1 += 1;
3720         else if ( myString.Value( i )=='"' )
3721           nb2 += 1;
3722       }
3723       // if number of ' or " is not divisible by 2,
3724       // then get an object at the start of the command
3725       if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3726         begPos = 1;
3727     }
3728     else {
3729       begPos += myRes.Length();
3730     }
3731     myObj = GetWord( myString, begPos, true );
3732     if ( begPos != EMPTY )
3733     {
3734       // check if object is complex,
3735       // so far consider case like "smesh.Method()"
3736       if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3737         //if ( bracketPos==0 ) bracketPos = Length();
3738         int dotPos = begPos+myObj.Length();
3739         while ( dotPos+1 < bracketPos ) {
3740           if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3741             dotPos = pos;
3742           else
3743             break;
3744         }
3745         if ( dotPos > begPos+myObj.Length() )
3746           myObj = myString.SubString( begPos, dotPos-1 );
3747       }
3748     }
3749     // 1st word after '=' is an object
3750     // else // no method -> no object
3751     // {
3752     //   myObj.Clear();
3753     //   begPos = EMPTY;
3754     // }
3755     // store
3756     SetBegPos( OBJECT_IND, begPos );
3757   }
3758   //SCRUTE(myObj);
3759   return myObj;
3760 }
3761
3762 //================================================================================
3763 /*!
3764  * \brief Return substring of python command looking like ResVal = Obj.Method()
3765  * \retval const TCollection_AsciiString & - Method substring
3766  */
3767 //================================================================================
3768
3769 const TCollection_AsciiString & _pyCommand::GetMethod()
3770 {
3771   if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3772   {
3773     // beginning
3774     int begPos = GetBegPos( OBJECT_IND );
3775     bool forward = true;
3776     if ( begPos < 1 ) {
3777       begPos = myString.Location( "(", 1, Length() ) - 1;
3778       forward = false;
3779     }
3780     else {
3781       begPos += myObj.Length();
3782     }
3783     // store
3784     myMeth = GetWord( myString, begPos, forward );
3785     SetBegPos( METHOD_IND, begPos );
3786   }
3787   //SCRUTE(myMeth);
3788   return myMeth;
3789 }
3790
3791 //================================================================================
3792 /*!
3793  * \brief Returns true if there are brackets after the method
3794  */
3795 //================================================================================
3796
3797 bool _pyCommand::IsMethodCall()
3798 {
3799   if ( GetMethod().IsEmpty() )
3800     return false;
3801   const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3802   return ( s[0] == '(' || s[1] == '(' );
3803 }
3804
3805 //================================================================================
3806 /*!
3807  * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3808  * \retval const TCollection_AsciiString & - Arg<index> substring
3809  */
3810 //================================================================================
3811
3812 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3813 {
3814   if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3815   {
3816     // Find all args
3817
3818     int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3819     if ( pos < 1 )
3820       pos = myString.Location( "(", 1, Length() );
3821     else
3822       --pos;
3823
3824     // we are at or before '(', skip it if present
3825     if ( pos > 0 ) {
3826       while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3827       if ( pos > Length() )
3828         pos = 0;
3829     }
3830     if ( pos < 1 ) {
3831       SetBegPos( ARG1_IND, 0 ); // even no '('
3832       return theEmptyString;
3833     }
3834     ++pos;
3835
3836     list< TCollection_AsciiString > separatorStack( 1, ",)");
3837     bool ignoreNesting = false;
3838     int prevPos = pos;
3839     while ( pos <= Length() )
3840     {
3841       const char chr = myString.Value( pos );
3842
3843       if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3844       {
3845         if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3846         {
3847           while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3848             ++prevPos;
3849           TCollection_AsciiString arg;
3850           if ( pos-1 >= prevPos ) {
3851             arg = myString.SubString( prevPos, pos-1 );
3852             arg.RightAdjust(); // remove spaces
3853             arg.LeftAdjust();
3854           }
3855           if ( !arg.IsEmpty() || chr == ',' )
3856           {
3857             SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3858             myArgs.Append( arg );
3859           }
3860           if ( chr == ')' )
3861             break;
3862           prevPos = pos+1;
3863         }
3864         else // end of nesting args found
3865         {
3866           separatorStack.pop_back();
3867           ignoreNesting = false;
3868         }
3869       }
3870       else if ( !ignoreNesting )
3871       {
3872         switch ( chr ) {
3873         case '(' : separatorStack.push_back(")"); break;
3874         case '[' : separatorStack.push_back("]"); break;
3875         case '\'': separatorStack.push_back("'");  ignoreNesting=true; break;
3876         case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3877         default:;
3878         }
3879       }
3880       ++pos;
3881     }
3882   }
3883   if ( myArgs.Length() < index )
3884     return theEmptyString;
3885   return myArgs( index );
3886 }
3887
3888 //================================================================================
3889 /*!
3890  * \brief Return position where arguments begin
3891  */
3892 //================================================================================
3893
3894 int _pyCommand::GetArgBeginning() const
3895 {
3896   int pos = GetBegPos( ARG1_IND );
3897   if ( pos == UNKNOWN )
3898   {
3899     pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3900     if ( pos < 1 )
3901       pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3902   }
3903   return pos;
3904 }
3905
3906 //================================================================================
3907 /*!
3908  * \brief Check if char is a word part
3909  *  \param c - The character to check
3910  * \retval bool - The check result
3911  */
3912 //================================================================================
3913
3914 static inline bool isWord(const char c, const bool dotIsWord)
3915 {
3916   return
3917     !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3918 }
3919
3920 //================================================================================
3921 /*!
3922  * \brief Looks for a word in the string and returns word's beginning
3923  *  \param theString - The input string
3924  *  \param theStartPos - The position to start the search, returning word's beginning
3925  *  \param theForward - The search direction
3926  * \retval TCollection_AsciiString - The found word
3927  */
3928 //================================================================================
3929
3930 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3931                                              int &            theStartPos,
3932                                              const bool       theForward,
3933                                              const bool       dotIsWord )
3934 {
3935   int beg = theStartPos, end = theStartPos;
3936   theStartPos = EMPTY;
3937   if ( beg < 1 || beg > theString.Length() )
3938     return theEmptyString;
3939
3940   if ( theForward ) { // search forward
3941     // beg
3942     while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3943       ++beg;
3944     if ( beg > theString.Length() )
3945       return theEmptyString; // no word found
3946     // end
3947     end = beg + 1;
3948     char begChar = theString.Value( beg );
3949     if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3950       char endChar = ( begChar == '[' ) ? ']' : begChar;
3951       // end is at the corresponding quoting mark or bracket
3952       while ( end < theString.Length() &&
3953               ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3954         ++end;
3955     }
3956     else {
3957       while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3958         ++end;
3959       --end;
3960     }
3961   }
3962   else {  // search backward
3963     // end
3964     while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3965       --end;
3966     if ( end == 0 )
3967       return theEmptyString; // no word found
3968     beg = end - 1;
3969     char endChar = theString.Value( end );
3970     if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3971       char begChar = ( endChar == ']' ) ? '[' : endChar;
3972       // beg is at the corresponding quoting mark
3973       while ( beg > 1 &&
3974               ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3975         --beg;
3976     }
3977     else {
3978       while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3979         --beg;
3980       ++beg;
3981     }
3982   }
3983   theStartPos = beg;
3984   //cout << theString << " ---- " << beg << " - " << end << endl;
3985   return theString.SubString( beg, end );
3986 }
3987
3988 //================================================================================
3989 /*!
3990  * \brief Returns true if the string looks like a study entry
3991  */
3992 //================================================================================
3993
3994 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3995 {
3996   if ( str.Length() < 5 ) return false;
3997
3998   int nbColons = 0, isColon;
3999   for ( int i = 1; i <= str.Length(); ++i )
4000   {
4001     char c = str.Value(i);
4002     if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4003       return false;
4004     nbColons += isColon;
4005   }
4006   return nbColons > 2 && str.Length()-nbColons > 2;
4007 }
4008
4009 //================================================================================
4010 /*!
4011  * \brief Returns true if the string looks like an object ID but not like a list,
4012  *        string, command etc.
4013  */
4014 //================================================================================
4015
4016 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4017 {
4018   if ( str.Length() < 1 ) return false;
4019
4020   const char* s = str.ToCString();
4021
4022   for ( int i = 0; i < str.Length(); ++i )
4023     if ( !IsIDChar( s[i] ))
4024       return false;
4025
4026   return true;
4027 }
4028
4029 //================================================================================
4030 /*!
4031  * \brief Finds entries in a sting
4032  */
4033 //================================================================================
4034
4035 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4036 {
4037   std::list< _pyID > resList;
4038   int pos = 0;
4039   while ( ++pos <= str.Length() )
4040   {
4041     if ( !isdigit( str.Value( pos ))) continue;
4042     if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4043
4044     int end = pos;
4045     while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4046     _pyID entry = str.SubString( pos, end-1 );
4047     pos = end;
4048     if ( IsStudyEntry( entry ))
4049       resList.push_back( entry );
4050   }
4051   return resList;
4052 }
4053
4054 //================================================================================
4055 /*!
4056  * \brief Look for position where not space char is
4057  *  \param theString - The string
4058  *  \param thePos - The position to search from and which returns result
4059  * \retval bool - false if there are only space after thePos in theString
4060  */
4061 //================================================================================
4062
4063 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4064 {
4065   if ( thePos < 1 || thePos > theString.Length() )
4066     return false;
4067
4068   while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4069     ++thePos;
4070
4071   return thePos <= theString.Length();
4072 }
4073
4074 //================================================================================
4075 /*!
4076  * \brief Modify a part of the command
4077  *  \param thePartIndex - The index of the part
4078  *  \param thePart - The new part string
4079  *  \param theOldPart - The old part
4080  */
4081 //================================================================================
4082
4083 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4084                          TCollection_AsciiString& theOldPart)
4085 {
4086   int pos = GetBegPos( thePartIndex );
4087   if ( pos <= Length() && theOldPart != thePart)
4088   {
4089     TCollection_AsciiString seperator;
4090     if ( pos < 1 ) {
4091       pos = GetBegPos( thePartIndex + 1 );
4092       if ( pos < 1 ) return;
4093       switch ( thePartIndex ) {
4094       case RESULT_IND: seperator = " = "; break;
4095       case OBJECT_IND: seperator = "."; break;
4096       case METHOD_IND: seperator = "()"; break;
4097       default:;
4098       }
4099     }
4100     myString.Remove( pos, theOldPart.Length() );
4101     if ( !seperator.IsEmpty() )
4102       myString.Insert( pos , seperator );
4103     myString.Insert( pos, thePart );
4104     // update starting positions of the following parts
4105     int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4106     for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4107       if ( myBegPos( i ) > 0 )
4108         myBegPos( i ) += posDelta;
4109     }
4110     theOldPart = thePart;
4111   }
4112 }
4113
4114 //================================================================================
4115 /*!
4116  * \brief Set argument
4117  *  \param index - The argument index, it counts from 1
4118  *  \param theArg - The argument string
4119  */
4120 //================================================================================
4121
4122 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4123 {
4124   FindAllArgs();
4125   int argInd = ARG1_IND + index - 1;
4126   int pos = GetBegPos( argInd );
4127   if ( pos < 1 ) // no index-th arg exist, append inexistent args
4128   {
4129     // find a closing parenthesis
4130     if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4131       int lastArgInd = GetNbArgs();
4132       pos = GetBegPos( ARG1_IND + lastArgInd  - 1 ) + GetArg( lastArgInd ).Length();
4133       while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4134         ++pos;
4135     }
4136     else {
4137       pos = Length();
4138       while ( pos > 0 && myString.Value( pos ) != ')' )
4139         --pos;
4140     }
4141     if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4142       myString += "()";
4143       pos = Length();
4144     }
4145     while ( myArgs.Length() < index ) {
4146       if ( myArgs.Length() )
4147         myString.Insert( pos++, "," );
4148       myArgs.Append("None");
4149       myString.Insert( pos, myArgs.Last() );
4150       SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4151       pos += myArgs.Last().Length();
4152     }
4153   }
4154   SetPart( argInd, theArg, myArgs( index ));
4155 }
4156
4157 //================================================================================
4158 /*!
4159  * \brief Empty arg list
4160  */
4161 //================================================================================
4162
4163 void _pyCommand::RemoveArgs()
4164 {
4165   if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4166     myString.Trunc( pos );
4167   myString += ")";
4168   myArgs.Clear();
4169   if ( myBegPos.Length() >= ARG1_IND )
4170     myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4171 }
4172
4173 //================================================================================
4174 /*!
4175  * \brief Comment a python command
4176  */
4177 //================================================================================
4178
4179 void _pyCommand::Comment()
4180 {
4181   if ( IsEmpty() ) return;
4182
4183   int i = 1;
4184   while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4185   if ( i <= Length() )
4186   {
4187     myString.Insert( i, "#" );
4188     for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4189     {
4190       int begPos = GetBegPos( iPart );
4191       if ( begPos != UNKNOWN && begPos != EMPTY )
4192         SetBegPos( iPart, begPos + 1 );
4193     }
4194   }
4195 }
4196
4197 //================================================================================
4198 /*!
4199  * \brief Set dependent commands after this one
4200  */
4201 //================================================================================
4202
4203 bool _pyCommand::SetDependentCmdsAfter() const
4204 {
4205   bool orderChanged = false;
4206   list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4207   for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4208     if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4209       orderChanged = true;
4210       theGen->SetCommandAfter( *cmd, this );
4211       (*cmd)->SetDependentCmdsAfter();
4212     }
4213   }
4214   return orderChanged;
4215 }
4216 //================================================================================
4217 /*!
4218  * \brief Insert accessor method after theObjectID
4219  *  \param theObjectID - id of the accessed object
4220  *  \param theAcsMethod - name of the method giving access to the object
4221  * \retval bool - false if theObjectID is not found in the command string
4222  */
4223 //================================================================================
4224
4225 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4226 {
4227   if ( !theAcsMethod )
4228     return false;
4229   // start object search from the object, i.e. ignore result
4230   GetObject();
4231   int beg = GetBegPos( OBJECT_IND );
4232   if ( beg < 1 || beg > Length() )
4233     return false;
4234   bool added = false;
4235   while (( beg = myString.Location( theObjectID, beg, Length() )))
4236   {
4237     // check that theObjectID is not just a part of a longer ID
4238     int afterEnd = beg + theObjectID.Length();
4239     Standard_Character c = myString.Value( afterEnd );
4240     if ( !IsIDChar( c ))
4241     {
4242       // check if accessor method already present
4243       if ( c != '.' ||
4244            myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4245         // insertion
4246         int oldLen = Length();
4247         myString.Insert( afterEnd, (char*) theAcsMethod );
4248         myString.Insert( afterEnd, "." );
4249         // update starting positions of the parts following the modified one
4250         int posDelta = Length() - oldLen;
4251         for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4252           if ( myBegPos( i ) > afterEnd )
4253             myBegPos( i ) += posDelta;
4254         }
4255         added = true;
4256       }
4257     }
4258     beg = afterEnd; // is a part -> next search
4259   }
4260   return added;
4261 }
4262
4263 //================================================================================
4264 /*!
4265  * \brief Creates pyObject
4266  */
4267 //================================================================================
4268
4269 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4270   : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4271 {
4272   setID( theID );
4273 }
4274
4275 //================================================================================
4276 /*!
4277  * \brief Set up myID and myIsPublished
4278  */
4279 //================================================================================
4280
4281 void _pyObject::setID(const _pyID& theID)
4282 {
4283   myID = theID;
4284   myIsPublished = !theGen->IsNotPublished( GetID() );
4285 }
4286
4287 //================================================================================
4288 /*!
4289  * \brief Clear myCreationCmd and myProcessedCmds
4290  */
4291 //================================================================================
4292
4293 void _pyObject::ClearCommands()
4294 {
4295   if ( !CanClear() )
4296     return;
4297
4298   if ( !myCreationCmd.IsNull() )
4299     myCreationCmd->Clear();
4300
4301   list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4302   for ( ; cmd != myProcessedCmds.end(); ++cmd )
4303     (*cmd)->Clear();
4304 }
4305
4306 //================================================================================
4307 /*!
4308  * \brief Return method name giving access to an interaface object wrapped by python class
4309  * \retval const char* - method name
4310  */
4311 //================================================================================
4312
4313 const char* _pyObject::AccessorMethod() const
4314 {
4315   return 0;
4316 }
4317 //================================================================================
4318 /*!
4319  * \brief Return ID of a father
4320  */
4321 //================================================================================
4322
4323 _pyID _pyObject::FatherID(const _pyID & childID)
4324 {
4325   int colPos = childID.SearchFromEnd(':');
4326   if ( colPos > 0 )
4327     return childID.SubString( 1, colPos-1 );
4328   return "";
4329 }
4330
4331 //================================================================================
4332 /*!
4333  * \brief SelfEraser erases creation command if none of it's commands invoked
4334  *        (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4335  */
4336 //================================================================================
4337
4338 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4339   :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4340 {
4341   myIsPublished = true; // prevent clearing as a not published
4342   theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4343 }
4344
4345 //================================================================================
4346 /*!
4347  * \brief SelfEraser erases creation command if none of it's commands invoked
4348  *        (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4349  */
4350 //================================================================================
4351
4352 bool _pySelfEraser::CanClear()
4353 {
4354   bool toErase = false;
4355   if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4356   {
4357     int nbArgUses = 0;
4358     list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4359     for ( ; cmd != myArgCmds.end(); ++cmd )
4360       nbArgUses += IsAliveCmd( *cmd );
4361
4362     toErase = ( nbArgUses < 1 );
4363   }
4364   else
4365   {
4366     int nbCalls = 0;
4367     std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4368     std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4369     for ( ; cmd != cmds.end();  )
4370       // check of cmd emptiness is not enough as object can change
4371       if (( *cmd )->GetString().Search( GetID() ) > 0 )
4372         ++nbCalls, ++cmd;
4373       else
4374         cmd = cmds.erase( cmd ); // save the cmd from clearing
4375
4376     toErase = ( nbCalls < 1 );
4377   }
4378   return toErase;
4379 }
4380
4381 //================================================================================
4382 /*!
4383  * \brief Check if a command is or can be cleared
4384  */
4385 //================================================================================
4386
4387 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4388 {
4389   if ( theCmd->IsEmpty() )
4390     return false;
4391
4392   if ( !theGen->IsToKeepAllCommands() )
4393   {
4394     const _pyID& objID = theCmd->GetObject();
4395     Handle( _pyObject ) obj = theGen->FindObject( objID );
4396     if ( !obj.IsNull() )
4397       return !obj->CanClear();
4398   }
4399   return true;
4400 }
4401
4402 //================================================================================
4403 /*!
4404  * \brief SelfEraser erases creation command if none of it's commands invoked
4405  *        (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4406  */
4407 //================================================================================
4408
4409 void _pySelfEraser::Flush()
4410 {
4411   if ( CanClear() )
4412   {
4413     myIsPublished = false;
4414     _pyObject::ClearCommands();
4415   }
4416 }
4417
4418 //================================================================================
4419 /*!
4420  * \brief _pySubMesh constructor
4421  */
4422 //================================================================================
4423
4424 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4425   _pyObject(theCreationCmd)
4426 {
4427   myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4428   if ( toKeepAgrCmds )
4429     theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4430 }
4431
4432 //================================================================================
4433 /*!
4434  * \brief Return true if a sub-mesh can be used as argument of the given method
4435  */
4436 //================================================================================
4437
4438 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4439 {
4440   return false;
4441   // names of all methods where a sub-mesh can be used as argument
4442   // static TStringSet methods;
4443   // if ( methods.empty() ) {
4444   //   const char * names[] = {
4445   //     // methods of SMESH_Gen
4446   //     "CopyMesh",
4447   //     // methods of SMESH_Group
4448   //     "AddFrom",
4449   //     // methods of SMESH_Measurements
4450   //     "MinDistance",
4451   //     // methods of SMESH_Mesh
4452   //     "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4453   //     "RemoveSubMesh",
4454   //     // methods of SMESH_MeshEditor
4455   //     "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4456   //     "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4457   //     "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4458   //     "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4459   //     "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4460   //     "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4461   //     "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4462   //     "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4463   //     "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4464   //     "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4465   //     "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4466   //     "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4467   //     "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4468   //     "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4469   //     "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4470   //     "" }; // <- mark of end
4471   //   methods.Insert( names );
4472   // }
4473   // return methods.Contains( theMethodName );
4474 }
4475
4476 //================================================================================
4477 /*!
4478  * \brief count invoked commands
4479  */
4480 //================================================================================
4481
4482 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4483 {
4484   _pyObject::Process(theCommand); // count calls of Process()
4485 }
4486
4487 //================================================================================
4488 /*!
4489  * \brief Move creation command depending on invoked commands
4490  */
4491 //================================================================================
4492
4493 void _pySubMesh::Flush()
4494 {
4495   if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4496     theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4497   else if ( !myCreator.IsNull() )
4498     // move to be just after creator
4499     myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4500
4501   // move sub-mesh usage after creation cmd
4502   list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4503   for ( ; cmd != myArgCmds.end(); ++cmd )
4504     if ( !(*cmd)->IsEmpty() )
4505       GetCreationCmd()->AddDependantCmd( *cmd );
4506 }
4507
4508 //================================================================================
4509 /*!
4510  * \brief Creates _pyGroup
4511  */
4512 //================================================================================
4513
4514 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4515   :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4516 {
4517   if ( !id.IsEmpty() )
4518     setID( id );
4519
4520   myCanClearCreationCmd = true;
4521
4522   const _AString& method = theCreationCmd->GetMethod();
4523   if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4524   {
4525     theCreationCmd->SetMethod( "CreateEmptyGroup" );
4526   }
4527   // ----------------------------------------------------------------------
4528   else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4529   {
4530     _pyID geom = theCreationCmd->GetArg( 3 );
4531     // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4532     // next if(){...} section is commented
4533     //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4534     //  theCreationCmd->SetMethod( "Group" );
4535     //  theCreationCmd->RemoveArgs();
4536     //  theCreationCmd->SetArg( 1, geom );
4537     //}
4538     //else {
4539     // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4540     _pyID type = theCreationCmd->GetArg( 1 );
4541     _pyID name = theCreationCmd->GetArg( 2 );
4542     theCreationCmd->SetMethod( "GroupOnGeom" );
4543     theCreationCmd->RemoveArgs();
4544     theCreationCmd->SetArg( 1, geom );
4545     theCreationCmd->SetArg( 2, name );
4546     theCreationCmd->SetArg( 3, type );
4547     //}
4548   }
4549   else if ( method == "CreateGroupFromFilter" )
4550   {
4551     // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4552     theCreationCmd->SetMethod( "GroupOnFilter" );
4553
4554     _pyID filterID = theCreationCmd->GetArg(3);
4555     Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4556     if ( !filter.IsNull())
4557     {
4558       if ( !filter->GetNewID().IsEmpty() )
4559         theCreationCmd->SetArg( 3, filter->GetNewID() );
4560       //filter->AddUser( this );
4561     }
4562     myFilter = filter;
4563   }
4564   else if ( method == "GetGroups" )
4565   {
4566     myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4567   }
4568   else
4569   {
4570     // theCreationCmd does something else apart from creation of this group
4571     // and thus it can't be cleared if this group is removed
4572     myCanClearCreationCmd = false;
4573   }
4574 }
4575
4576 //================================================================================
4577 /*!
4578  * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command 
4579  *        can be cleared
4580  */
4581 //================================================================================
4582
4583 bool _pyGroup::CanClear()
4584 {
4585   if ( IsInStudy() )
4586     return false;
4587
4588   if ( !myCanClearCreationCmd &&
4589        !myCreationCmd.IsNull() &&
4590        myCreationCmd->GetMethod() == "GetGroups" )
4591   {
4592     TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4593     list< _pyID >          idList = myCreationCmd->GetStudyEntries( grIDs );
4594     list< _pyID >::iterator  grID = idList.begin();
4595     if ( GetID() == *grID )
4596     {
4597       myCanClearCreationCmd = true;
4598       list< Handle(_pyGroup ) > groups;
4599       for ( ; grID != idList.end(); ++grID )
4600       {
4601         Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4602         if ( group.IsNull() ) continue;
4603         groups.push_back( group );
4604         if ( group->IsInStudy() )
4605           myCanClearCreationCmd = false;
4606       }
4607       // set myCanClearCreationCmd == true to all groups
4608       list< Handle(_pyGroup ) >::iterator group = groups.begin();
4609       for ( ; group != groups.end(); ++group )
4610         (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4611     }
4612   }
4613
4614   return myCanClearCreationCmd;
4615 }
4616
4617 //================================================================================
4618 /*!
4619  * \brief set myCanClearCreationCmd = true if the main action of the creation
4620  *        command is discarded
4621  */
4622 //================================================================================
4623
4624 void _pyGroup::RemovedWithContents()
4625 {
4626   // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4627   // via a created group
4628   //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4629   // myCanClearCreationCmd = true;
4630 }
4631
4632 //================================================================================
4633 /*!
4634  * \brief To convert creation of a group by filter
4635  */
4636 //================================================================================
4637
4638 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4639 {
4640   // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4641   // group = mesh.CreateEmptyGroup( elemType, groupName )
4642   // aFilter.SetMesh(mesh)
4643   // nbAdd = group.AddFrom( aFilter )
4644   Handle(_pyFilter) filter;
4645   if ( theCommand->GetMethod() == "AddFrom" )
4646   {
4647     _pyID idSource = theCommand->GetArg(1);
4648     // check if idSource is a filter
4649     filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4650     if ( !filter.IsNull() )
4651     {
4652       // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4653       list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4654       while ( *cmdIt != theCommand ) ++cmdIt;
4655       while ( (*cmdIt)->GetOrderNb() != 1 )
4656       {
4657         const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4658         if ((setMeshCmd->GetObject() == idSource ||
4659              setMeshCmd->GetObject() == filter->GetNewID() )
4660             &&
4661             setMeshCmd->GetMethod() == "SetMesh")
4662         {
4663           setMeshCmd->Clear();
4664           break;
4665         }
4666       }
4667       // replace 3 commands by one
4668       theCommand->Clear();
4669       const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4670       TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4671       if ( !filter->GetNewID().IsEmpty() )
4672         idSource = filter->GetNewID();
4673       makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4674       makeGroupCmd->SetArg( 1, name );
4675       makeGroupCmd->SetArg( 2, idSource );
4676       filter->AddArgCmd( makeGroupCmd );
4677     }
4678   }
4679   else if ( theCommand->GetMethod() == "SetFilter" )
4680   {
4681     // set new name of a filter or clear the command if the same filter is set
4682     _pyID filterID = theCommand->GetArg(1);
4683     filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4684     if ( !myFilter.IsNull() && filter == myFilter )
4685       theCommand->Clear();
4686     else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4687       theCommand->SetArg( 1, filter->GetNewID() );
4688     myFilter = filter;
4689   }
4690   else if ( theCommand->GetMethod() == "GetFilter" )
4691   {
4692     // GetFilter() returns a filter with other ID, make myFilter process
4693     // calls of the returned filter
4694     if ( !myFilter.IsNull() )
4695     {
4696       theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4697       theCommand->Clear();
4698     }
4699   }
4700
4701   // if ( !filter.IsNull() )
4702   //   filter->AddUser( this );
4703
4704   theGen->AddMeshAccessorMethod( theCommand );
4705 }
4706
4707 //================================================================================
4708 /*!
4709  * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4710  */
4711 //================================================================================
4712
4713 void _pyGroup::Flush()
4714 {
4715   if ( !theGen->IsToKeepAllCommands() &&
4716        !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4717   {
4718     myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4719   }
4720 }
4721
4722 //================================================================================
4723 /*!
4724  * \brief Constructor of _pyFilter
4725  */
4726 //================================================================================
4727
4728 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4729   :_pyObject(theCreationCmd), myNewID( newID )
4730 {
4731   //myIsPublished = true; // prevent clearing as a not published
4732   theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4733 }
4734
4735 //================================================================================
4736 /*!
4737  * \brief To convert creation of a filter by criteria and
4738  * to replace an old name by a new one
4739  */
4740 //================================================================================
4741
4742 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4743 {
4744   if ( theCommand->GetObject() == GetID() )
4745     _pyObject::Process(theCommand); // count commands
4746
4747   if ( !myNewID.IsEmpty() )
4748     theCommand->SetObject( myNewID );
4749     
4750   // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4751   // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4752   // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4753   if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4754        theCommand->GetMethod() == "SetCriteria")
4755   {
4756     // aFilter.SetCriteria(aCriteria) ->
4757     // aFilter = smesh.GetFilterFromCriteria(criteria)
4758     if ( myNewID.IsEmpty() )
4759       theCommand->SetResultValue( GetID() );
4760     else
4761       theCommand->SetResultValue( myNewID );
4762     theCommand->SetObject( SMESH_2smeshpy::GenName() );
4763     theCommand->SetMethod( "GetFilterFromCriteria" );
4764
4765     // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4766     GetCreationCmd()->Clear();
4767     GetCreationCmd()->GetString() = theCommand->GetString();
4768     theCommand->Clear();
4769     theCommand->AddDependantCmd( GetCreationCmd() );
4770     // why swap? -- it's needed
4771     //GetCreationCmd()->Clear();
4772   }
4773   else if ( theCommand->GetMethod() == "SetMesh" )
4774   {
4775     if ( myMesh == theCommand->GetArg( 1 ))
4776       theCommand->Clear();
4777     else
4778       myMesh = theCommand->GetArg( 1 );
4779     theGen->AddMeshAccessorMethod( theCommand );
4780   }
4781 }
4782
4783 //================================================================================
4784 /*!
4785  * \brief Set new filter name to the creation command and to myArgCmds
4786  */
4787 //================================================================================
4788
4789 void _pyFilter::Flush()
4790 {
4791   if ( myNewID.IsEmpty() ) return;
4792   
4793   list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4794   for ( ; cmd != myArgCmds.end(); ++cmd )
4795     if ( !(*cmd)->IsEmpty() )
4796     {
4797       _AString cmdStr = (*cmd)->GetString();
4798       _AString id     = GetID();
4799       int pos = cmdStr.Search( id );
4800       if ( pos > 0 )
4801       {
4802         cmdStr.Remove( pos, id.Length() );
4803         cmdStr.Insert( pos, myNewID );
4804       }
4805       (*cmd)->Clear();
4806       (*cmd)->GetString() = cmdStr;
4807     }
4808
4809   if ( !GetCreationCmd()->IsEmpty() )
4810     GetCreationCmd()->SetResultValue( myNewID );
4811 }
4812
4813 //================================================================================
4814 /*!
4815  * \brief Return true if all my users can be cleared
4816  */
4817 //================================================================================
4818
4819 bool _pyObject::CanClear()
4820 {
4821   list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4822   for ( ; cmd != myArgCmds.end(); ++cmd )
4823     if ( !(*cmd)->IsEmpty() )
4824     {
4825       Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4826       if ( !obj.IsNull() && !obj->CanClear() )
4827         return false;
4828     }
4829   return ( !myIsPublished );
4830 }
4831
4832 //================================================================================
4833 /*!
4834  * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4835  */
4836 //================================================================================
4837
4838 _pyHypothesisReader::_pyHypothesisReader()
4839 {
4840   // Read xml files
4841   vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4842   LDOMParser xmlParser;
4843   for ( size_t i = 0; i < xmlPaths.size(); ++i )
4844   {
4845     bool error = xmlParser.parse( xmlPaths[i].c_str() );
4846     if ( error )
4847     {
4848       _AString data;
4849       INFOS( xmlParser.GetError(data) );
4850       continue;
4851     }
4852     // <algorithm type="Regular_1D"
4853     //            label-id="Wire discretisation"
4854     //            ...>
4855     //   <python-wrap>
4856     //     <algo>Regular_1D=Segment()</algo>
4857     //     <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4858     //
4859     LDOM_Document xmlDoc = xmlParser.getDocument();
4860     LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4861     for ( int i = 0; i < algoNodeList.getLength(); ++i )
4862     {
4863       LDOM_Node     algoNode = algoNodeList.item( i );
4864       LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4865       LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4866       if ( pyAlgoNodeList.getLength() < 1 ) continue;
4867
4868       _AString text, algoType, method, arg;
4869       for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4870       {
4871         LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4872         LDOM_Node textNode   = pyAlgoNode.getFirstChild();
4873         text = textNode.getNodeValue();
4874         Handle(_pyCommand) algoCmd = new _pyCommand( text );
4875         algoType = algoCmd->GetResultValue();
4876         method   = algoCmd->GetMethod();
4877         arg      = algoCmd->GetArg(1);
4878         if ( !algoType.IsEmpty() && !method.IsEmpty() )
4879         {
4880           Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4881           algo->SetConvMethodAndType( method, algoType );
4882           if ( !arg.IsEmpty() )
4883             algo->setCreationArg( 1, arg );
4884
4885           myType2Hyp[ algoType ] = algo;
4886           break;
4887         }
4888       }
4889       if ( algoType.IsEmpty() ) continue;
4890
4891       LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4892       _AString hypType;
4893       Handle( _pyHypothesis ) hyp;
4894       for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4895       {
4896         LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4897         LDOM_Node textNode   = pyHypoNode.getFirstChild();
4898         text = textNode.getNodeValue();
4899         Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4900         hypType = hypoCmd->GetResultValue();
4901         method  = hypoCmd->GetMethod();
4902         if ( !hypType.IsEmpty() && !method.IsEmpty() )
4903         {
4904           map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4905           if ( type2hyp == myType2Hyp.end() )
4906             hyp = new _pyHypothesis( hypoCmd );
4907           else
4908             hyp = type2hyp->second;
4909           hyp->SetConvMethodAndType( method, algoType );
4910           for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4911           {
4912             _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4913             _AString argMethod = argCmd.GetMethod();
4914             _AString argNbText = argCmd.GetArg( 1 );
4915             if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4916               hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4917             else
4918               hyp->AddArgMethod( argMethod,
4919                                  argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4920           }
4921           myType2Hyp[ hypType ] = hyp;
4922         }
4923       }
4924     }
4925     // <hypothesis type="BLSURF_Parameters"
4926     //          ...
4927     //          dim="2">
4928     //   <python-wrap>
4929     //     <accumulative-methods> 
4930     //       SetEnforcedVertex,
4931     //       SetEnforcedVertexNamed
4932     //     </accumulative-methods>
4933     //   </python-wrap>
4934     // </hypothesis>
4935     //
4936     LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4937     for ( int i = 0; i < hypNodeList.getLength(); ++i )
4938     {
4939       LDOM_Node     hypNode      = hypNodeList.item( i );
4940       LDOM_Element& hypElem      = (LDOM_Element&) hypNode;
4941       _AString      hypType      = hypElem.getAttribute("type");
4942       LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4943       if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4944
4945       map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4946       if ( type2hyp == myType2Hyp.end() ) continue;
4947
4948       LDOM_Node methNode = methNodeList.item( 0 );
4949       LDOM_Node textNode = methNode.getFirstChild();
4950       _AString      text = textNode.getNodeValue();
4951       _AString method;
4952       int pos = 1;
4953       do {
4954         method = _pyCommand::GetWord( text, pos, /*forward= */true );
4955         pos += method.Length();
4956         type2hyp->second->AddAccumulativeMethod( method );
4957       }
4958       while ( !method.IsEmpty() );
4959     }
4960
4961   } // loop on xmlPaths
4962 }
4963
4964 //================================================================================
4965 /*!
4966  * \brief Returns a new hypothesis initialized according to the read information
4967  */
4968 //================================================================================
4969
4970 Handle(_pyHypothesis)
4971 _pyHypothesisReader::GetHypothesis(const _AString&           hypType,
4972                                    const Handle(_pyCommand)& creationCmd) const
4973 {
4974   Handle(_pyHypothesis) resHyp, sampleHyp;
4975
4976   map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4977   if ( type2hyp != myType2Hyp.end() )
4978     sampleHyp = type2hyp->second;
4979
4980   if ( sampleHyp.IsNull() )
4981   {
4982     resHyp = new _pyHypothesis(creationCmd);
4983   }
4984   else
4985   {
4986     if ( sampleHyp->IsAlgo() )
4987       resHyp = new _pyAlgorithm( creationCmd );
4988     else
4989       resHyp = new _pyHypothesis(creationCmd);
4990     resHyp->Assign( sampleHyp, _pyID() );
4991   }
4992   return resHyp;
4993 }
4994
4995 //================================================================================
4996 /*!
4997  * \brief Adds an object ID to some family of IDs with a common prefix
4998  *  \param [in] str - the object ID
4999  *  \return bool - \c false if \a str does not have the same prefix as \a this family
5000  *          (for internal usage)
5001  */
5002 //================================================================================
5003
5004 bool _pyStringFamily::Add( const char* str )
5005 {
5006   if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5007     return false; // expected prefix is missing
5008
5009   str += _prefix.Length(); // skip _prefix
5010
5011   // try to add to some of child falimies
5012   std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5013   for ( ; itSub != _subFams.end(); ++itSub )
5014     if ( itSub->Add( str ))
5015       return true;
5016
5017   // no suitable family found - add str to _strings or create a new child family
5018
5019   // look for a proper place within sorted _strings
5020   std::list< _AString >::iterator itStr = _strings.begin();
5021   while ( itStr != _strings.end() && itStr->IsLess( str ))
5022     ++itStr;
5023   if ( itStr != _strings.end() && itStr->IsEqual( str ))
5024     return true; // same ID already kept
5025
5026   const int minPrefixSize = 4;
5027
5028   // count "smaller" strings with the same prefix
5029   std::list< _AString >::iterator itLess = itStr; --itLess;
5030   int nbLess = 0;
5031   for ( ; itLess != _strings.end(); --itLess )
5032     if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5033       ++nbLess;
5034     else
5035       break;
5036   ++itLess;
5037   // count "greater" strings with the same prefix
5038   std::list< _AString >::iterator itMore = itStr;
5039   int nbMore = 0;
5040   for ( ; itMore != _strings.end(); ++itMore )
5041     if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5042       ++nbMore;
5043     else
5044       break;
5045   --itMore;
5046   if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5047   {
5048     // look for a maximal prefix length
5049     // int lessPrefSize = 3, morePrefSize = 3;
5050     // if ( nbLess > 0 )
5051     //   while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ]  )
5052     //     ++lessPrefSize;
5053     // if ( nbMore > 0 )
5054     //   while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
5055     //     ++morePrefSize;
5056     // int prefixSize = 3;
5057     // if ( nbLess == 0 )
5058     //   prefixSize = morePrefSize;
5059     // else if ( nbMore == 0 )
5060     //   prefixSize = lessPrefSize;
5061     // else
5062     //   prefixSize = Min( lessPrefSize, morePrefSize );
5063     int prefixSize = minPrefixSize;
5064     _AString newPrefix ( str, prefixSize );
5065
5066     // look for a proper place within _subFams sorted by _prefix
5067     for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5068       if ( !itSub->_prefix.IsLess( newPrefix ))
5069         break;
5070
5071     // add the new _pyStringFamily
5072     itSub = _subFams.insert( itSub, _pyStringFamily());
5073     _pyStringFamily& newSubFam = *itSub;
5074     newSubFam._prefix = newPrefix;
5075
5076     // pass this->_strings to newSubFam._strings
5077     for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5078       newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5079     newSubFam._strings.push_back( str + prefixSize );
5080     for ( ; nbMore > 0; --nbMore, ++itStr )
5081       newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5082
5083     _strings.erase( itLess, ++itMore );
5084   }
5085   else // too few string to make a family for them
5086   {
5087     _strings.insert( itStr, str );
5088   }
5089   return true;
5090 }
5091
5092 //================================================================================
5093 /*!
5094  * \brief Finds an object ID in the command
5095  *  \param [in] longStr - the command string
5096  *  \param [out] subStr - the found object ID
5097  *  \return bool - \c true if the object ID found
5098  */
5099 //================================================================================
5100
5101 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5102 {
5103   const _AString& longStr = cmd->GetString();
5104   const char*           s = longStr.ToCString();
5105
5106   // look in _subFams
5107   std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5108   int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5109   if ( argBeg < 4 || argBeg > longStr.Length() )
5110     return false;
5111   for ( ; itSub != _subFams.end(); ++itSub )
5112   {
5113     from = argBeg;
5114     while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5115       if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5116       {
5117         subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5118         from = pos + len + itSub->_prefix.Length();
5119         nbFound++;
5120       }
5121       else
5122       {
5123         from += itSub->_prefix.Length();
5124       }
5125   }
5126   // look among _strings
5127   std::list< _AString >::iterator itStr = _strings.begin();
5128   for ( ; itStr != _strings.end(); ++itStr )
5129     if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5130       // check that object ID does not continue after len
5131       if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5132       {
5133         subStr.push_back( *itStr );
5134         nbFound++;
5135       }
5136   return nbFound;
5137 }
5138
5139 //================================================================================
5140 /*!
5141  * \brief Return remainder length of the object ID after my _prefix
5142  *  \param [in] str - remainder of the command after my _prefix
5143  *  \return int - length of the object ID or -1 if not found
5144  */
5145 //================================================================================
5146
5147 int _pyStringFamily::isIn( const char* str )
5148 {
5149   std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5150   int len = -1;
5151   for ( ; itSub != _subFams.end(); ++itSub )
5152   {
5153     int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5154     if ( cmp == 0 )
5155     {
5156       if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5157         return itSub->_prefix.Length() + len;
5158     }
5159     else if ( cmp < 0 )
5160       break;
5161   }
5162   if ( !_strings.empty() )
5163   {
5164     std::list< _AString >::iterator itStr = _strings.begin();
5165     bool firstEmpty = itStr->IsEmpty();
5166     if ( firstEmpty )
5167       ++itStr, len = 0;
5168     for ( ; itStr != _strings.end(); ++itStr )
5169     {
5170       int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5171       if ( cmp == 0 )
5172       {
5173         len = itStr->Length();
5174         break;
5175       }
5176       else if ( cmp < 0 )
5177       {
5178         break;
5179       }
5180     }
5181
5182     // check that object ID does not continue after len
5183     if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5184       len = -1;
5185   }
5186
5187   return len;
5188 }
5189
5190 //================================================================================
5191 /*!
5192  * \brief DEBUG
5193  */
5194 //================================================================================
5195
5196 void _pyStringFamily::Print( int level )
5197 {
5198   cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5199   std::list< _AString >::iterator itStr = _strings.begin();
5200   for ( ; itStr != _strings.end(); ++itStr )
5201     cout << *itStr << " | ";
5202   cout << endl;
5203   std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5204   for ( ; itSub != _subFams.end(); ++itSub )
5205     itSub->Print( level + 1 );
5206   if ( level == 0 )
5207     cout << string( 70, '-' ) << endl;
5208 }
5209