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