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