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