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