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