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