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