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