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