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