Salome HOME
Merge from V6_main 01/04/2013
[modules/smesh.git] / src / SMESH_I / SMESH_2smeshpy.cxx
1 // Copyright (C) 2007-2013  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 <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
35
36 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
38
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41  * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42  * that declare methods named GetObject - to apply the same rules of GetObject renaming
43  * and thus to avoid mess with GetObject symbol on Windows */
44
45 #include <LDOMParser.hxx>
46
47 #ifdef WNT
48 #include <windows.h>
49 #else
50 #include <unistd.h>
51 #endif
52
53
54 IMPLEMENT_STANDARD_HANDLE (_pyObject          ,Standard_Transient);
55 IMPLEMENT_STANDARD_HANDLE (_pyCommand         ,Standard_Transient);
56 IMPLEMENT_STANDARD_HANDLE (_pyHypothesisReader,Standard_Transient);
57 IMPLEMENT_STANDARD_HANDLE (_pyGen             ,_pyObject);
58 IMPLEMENT_STANDARD_HANDLE (_pyMesh            ,_pyObject);
59 IMPLEMENT_STANDARD_HANDLE (_pySubMesh         ,_pyObject);
60 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor      ,_pyObject);
61 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis      ,_pyObject);
62 IMPLEMENT_STANDARD_HANDLE (_pySelfEraser      ,_pyObject);
63 IMPLEMENT_STANDARD_HANDLE (_pyGroup           ,_pyObject);
64 IMPLEMENT_STANDARD_HANDLE (_pyFilter          ,_pyObject);
65 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm       ,_pyHypothesis);
66 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
67 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
68
69 IMPLEMENT_STANDARD_RTTIEXT(_pyObject          ,Standard_Transient);
70 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand         ,Standard_Transient);
71 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
72 IMPLEMENT_STANDARD_RTTIEXT(_pyGen             ,_pyObject);
73 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh            ,_pyObject);
74 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh         ,_pyObject);
75 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor      ,_pyObject);
76 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis      ,_pyObject);
77 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser      ,_pyObject);
78 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup           ,_pyObject);
79 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter          ,_pyObject);
80 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm       ,_pyHypothesis);
81 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
82 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
83 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
84 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
85
86 using namespace std;
87 using SMESH::TPythonDump;
88
89 /*!
90  * \brief Container of commands into which the initial script is split.
91  *        It also contains data coresponding to SMESH_Gen contents
92  */
93 static Handle(_pyGen) theGen;
94
95 static TCollection_AsciiString theEmptyString;
96
97 //#define DUMP_CONVERSION
98
99 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
100 #undef DUMP_CONVERSION
101 #endif
102
103
104 namespace {
105
106   //================================================================================
107   /*!
108    * \brief Set of TCollection_AsciiString initialized by C array of C strings
109    */
110   //================================================================================
111
112   struct TStringSet: public set<TCollection_AsciiString>
113   {
114     /*!
115      * \brief Filling. The last string must be ""
116      */
117     void Insert(const char* names[]) {
118       for ( int i = 0; names[i][0] ; ++i )
119         insert( (char*) names[i] );
120     }
121     /*!
122      * \brief Check if a string is in
123      */
124     bool Contains(const TCollection_AsciiString& name ) {
125       return find( name ) != end();
126     }
127   };
128
129   //================================================================================
130   /*!
131    * \brief Map of TCollection_AsciiString initialized by C array of C strings.
132    *        Odd items of the C array are map keys, and even items are values
133    */
134   //================================================================================
135
136   struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
137   {
138     /*!
139      * \brief Filling. The last string must be ""
140      */
141     void Insert(const char* names_values[]) {
142       for ( int i = 0; names_values[i][0] ; i += 2 )
143         insert( make_pair( (char*) names_values[i], names_values[i+1] ));
144     }
145     /*!
146      * \brief Check if a string is in
147      */
148     TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
149       map< _AString, _AString >::iterator it = find( name );
150       return it == end() ? "" : it->second;
151     }
152   };
153
154   //================================================================================
155   /*!
156    * \brief Returns a mesh by object
157    */
158   //================================================================================
159
160   Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
161   {
162     if ( !obj.IsNull() )
163     {
164       if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
165         return Handle(_pyMesh)::DownCast( obj );
166       else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
167         return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
168       else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
169         return Handle(_pyGroup)::DownCast( obj )->GetMesh();
170     }
171     return Handle(_pyMesh)();
172   }
173
174   //================================================================================
175   /*!
176    * \brief Check if objects used as args have been created by previous commands
177    */
178   //================================================================================
179
180   void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
181   {
182     // either comment or erase a command including NotPublishedObjectName()
183     if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
184     {
185       bool isResultPublished = false;
186       for ( int i = 0; i < cmd->GetNbResultValues(); i++ )
187       {
188         _pyID objID = cmd->GetResultValue( i+1 );
189         if ( cmd->IsStudyEntry( objID ))
190           isResultPublished = (! theGen->IsNotPublished( objID ));
191         theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
192       }
193       if ( isResultPublished )
194         cmd->Comment();
195       else
196         cmd->Clear();
197       return;
198     }
199     // comment a command having not created args
200     for ( int iArg = cmd->GetNbArgs(); iArg; --iArg )
201     {
202       const _pyID& arg = cmd->GetArg( iArg );
203       if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
204         continue;
205       list< _pyID > idList = cmd->GetStudyEntries( arg );
206       list< _pyID >::iterator id = idList.begin();
207       for ( ; id != idList.end(); ++id )
208         if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
209         {
210           cmd->Comment();
211           cmd->GetString() += " ### " ;
212           cmd->GetString() += *id + " has not been yet created";
213           for ( int i = 0; i < cmd->GetNbResultValues(); i++ ) {
214             _pyID objID = cmd->GetResultValue( i+1 );
215             theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
216           }
217           return;
218         }
219     }
220     // comment a command having not created Object
221     const _pyID& obj = cmd->GetObject();
222     if ( !obj.IsEmpty() && cmd->IsStudyEntry( obj ) && !presentObjects.count( obj ))
223     {
224       cmd->Comment();
225       cmd->GetString() += " ### not created object" ;
226       for ( int i = 0; i < cmd->GetNbResultValues(); i++ ) {
227         _pyID objID = cmd->GetResultValue( i+1 );
228         theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
229       }
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_wrap 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_wrap 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       if ( cmd != myUnusedCommands.rbegin() )
3056         distrTypeNb = (*cmd)->GetOrderNb();
3057     }
3058     else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3059       (*cmd)->Clear();
3060     }
3061   // clear commands before the last SetDistrType()
3062   list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3063   set< int > treatedCmdNbs; // avoid treating same cmd twice
3064   for ( int i = 0; i < 2; ++i ) {
3065     set<TCollection_AsciiString> uniqueMethods;
3066     list<Handle(_pyCommand)> & cmdList = *cmds[i];
3067     for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3068     {
3069       if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3070         continue;// avoid treating same cmd twice
3071       bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3072       const TCollection_AsciiString& method = (*cmd)->GetMethod();
3073       if ( !clear || method == "SetNumberOfSegments" ) {
3074         bool isNewInSet = uniqueMethods.insert( method ).second;
3075         clear = !isNewInSet;
3076       }
3077       if ( clear )
3078         (*cmd)->Clear();
3079     }
3080     cmdList.clear();
3081   }
3082 }
3083
3084 //================================================================================
3085 /*!
3086  * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3087  * into regular1D.LengthNearVertex( length, vertex )
3088   * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3089   * \param theMesh - The mesh needing this hypo
3090   * \retval bool - false if the command cant be converted
3091  */
3092 //================================================================================
3093
3094 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3095                                                          const _pyID&              theMeshID)
3096 {
3097   if ( IsWrappable( theMeshID )) {
3098
3099     _pyID vertex = theCmd->GetArg( 1 );
3100
3101     // the problem here is that segment algo will not be found
3102     // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3103     // geometry where segment algorithm is assigned
3104     Handle(_pyHypothesis) algo;
3105     _pyID geom = vertex;
3106     while ( algo.IsNull() && !geom.IsEmpty()) {
3107       // try to find geom as a father of <vertex>
3108       geom = FatherID( geom );
3109       algo = theGen->FindAlgo( geom, theMeshID, this );
3110     }
3111     if ( algo.IsNull() )
3112       return false; // also possible to find geom as brother of veretex...
3113     // set geom instead of vertex
3114     theCmd->SetArg( 1, geom );
3115
3116     // set vertex as a second arg
3117     if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3118     setCreationArg( 2, vertex );
3119
3120     // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3121     // theMeshID.LengthNearVertex( length, vertex )
3122     return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3123   }
3124   return false;
3125 }
3126
3127 //================================================================================
3128 /*!
3129  * \brief _pyAlgorithm constructor
3130  * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3131  */
3132 //================================================================================
3133
3134 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3135   : _pyHypothesis( theCreationCmd )
3136 {
3137   myIsAlgo = true;
3138 }
3139
3140 //================================================================================
3141 /*!
3142  * \brief Convert the command adding an algorithm to mesh
3143   * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3144   * \param theMesh - The mesh needing this algo
3145   * \retval bool - false if the command cant be converted
3146  */
3147 //================================================================================
3148
3149 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3150                                       const _pyID&              theMeshID)
3151 {
3152   // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3153   if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3154     theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3155     return true;
3156   }
3157   return false;
3158 }
3159
3160 //================================================================================
3161 /*!
3162  * \brief Return starting position of a part of python command
3163   * \param thePartIndex - The index of command part
3164   * \retval int - Part position
3165  */
3166 //================================================================================
3167
3168 int _pyCommand::GetBegPos( int thePartIndex )
3169 {
3170   if ( IsEmpty() )
3171     return EMPTY;
3172   if ( myBegPos.Length() < thePartIndex )
3173     return UNKNOWN;
3174   return myBegPos( thePartIndex );
3175 }
3176
3177 //================================================================================
3178 /*!
3179  * \brief Store starting position of a part of python command
3180   * \param thePartIndex - The index of command part
3181   * \param thePosition - Part position
3182  */
3183 //================================================================================
3184
3185 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3186 {
3187   while ( myBegPos.Length() < thePartIndex )
3188     myBegPos.Append( UNKNOWN );
3189   myBegPos( thePartIndex ) = thePosition;
3190 }
3191
3192 //================================================================================
3193 /*!
3194  * \brief Returns whitespace symbols at the line beginning
3195   * \retval TCollection_AsciiString - result
3196  */
3197 //================================================================================
3198
3199 TCollection_AsciiString _pyCommand::GetIndentation()
3200 {
3201   int end = 1;
3202   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3203     GetWord( myString, end, true );
3204   else
3205     end = GetBegPos( RESULT_IND );
3206   return myString.SubString( 1, end - 1 );
3207 }
3208
3209 //================================================================================
3210 /*!
3211  * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3212   * \retval const TCollection_AsciiString & - ResultValue substring
3213  */
3214 //================================================================================
3215
3216 const TCollection_AsciiString & _pyCommand::GetResultValue()
3217 {
3218   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3219   {
3220     SetBegPos( RESULT_IND, EMPTY );
3221     int begPos, endPos = myString.Location( "=", 1, Length() );
3222     if ( endPos )
3223     {
3224       begPos = 1;
3225       while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3226       if ( begPos < endPos )
3227       {
3228         SetBegPos( RESULT_IND, begPos );
3229         --endPos;
3230         while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3231         myRes = myString.SubString( begPos, endPos );
3232       }
3233     }
3234   }
3235   return myRes;
3236 }
3237
3238 //================================================================================
3239 /*!
3240  * \brief Return number of python command result value ResultValue = Obj.Meth()
3241  */
3242 //================================================================================
3243
3244 int _pyCommand::GetNbResultValues()
3245 {
3246   int nb     = 0;
3247   int begPos = 1;
3248   int endPos = myString.Location( "=", 1, Length() );
3249   while ( begPos < endPos )
3250   {
3251     _AString str = GetWord( myString, begPos, true );
3252     begPos = begPos+ str.Length();
3253     nb++;
3254   }
3255   return (nb-1);
3256 }
3257
3258
3259 //================================================================================
3260 /*!
3261  * \brief Return substring of python command looking like
3262  *  ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3263  * \retval const TCollection_AsciiString & - ResultValue with res index substring
3264  */
3265 //================================================================================
3266 TCollection_AsciiString _pyCommand::GetResultValue(int res)
3267 {
3268   int begPos = 1;
3269   if ( SkipSpaces( myString, begPos ) && myString.Value( begPos ) == '[' )
3270     ++begPos; // skip [, else the whole list is returned
3271   int endPos = myString.Location( "=", 1, Length() );
3272   int Nb=0;
3273   while ( begPos < endPos) {
3274     _AString result = GetWord( myString, begPos, true );
3275     begPos = begPos + result.Length();
3276     Nb++;
3277     if(res == Nb) {
3278       result.RemoveAll('[');
3279       result.RemoveAll(']');
3280       return result;
3281     }
3282     if(Nb>res)
3283       break;
3284   }
3285   return theEmptyString;
3286 }
3287
3288 //================================================================================
3289 /*!
3290  * \brief Return substring of python command looking like ResVal = Object.Meth()
3291   * \retval const TCollection_AsciiString & - Object substring
3292  */
3293 //================================================================================
3294
3295 const TCollection_AsciiString & _pyCommand::GetObject()
3296 {
3297   if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3298   {
3299     // beginning
3300     int begPos = GetBegPos( RESULT_IND ) + myRes.Length();
3301     if ( begPos < 1 ) {
3302       begPos = myString.Location( "=", 1, Length() ) + 1;
3303       // is '=' in the string argument (for example, name) or not
3304       int nb1 = 0; // number of ' character at the left of =
3305       int nb2 = 0; // number of " character at the left of =
3306       for ( int i = 1; i < begPos-1; i++ ) {
3307         if ( myString.Value( i )=='\'' )
3308           nb1 += 1;
3309         else if ( myString.Value( i )=='"' )
3310           nb2 += 1;
3311       }
3312       // if number of ' or " is not divisible by 2,
3313       // then get an object at the start of the command
3314       if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3315         begPos = 1;
3316     }
3317     myObj = GetWord( myString, begPos, true );
3318     // check if object is complex,
3319     // so far consider case like "smesh.smesh.Method()"
3320     if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3321       //if ( bracketPos==0 ) bracketPos = Length();
3322       int dotPos = begPos+myObj.Length();
3323       while ( dotPos+1 < bracketPos ) {
3324         if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3325           dotPos = pos;
3326         else
3327           break;
3328       }
3329       if ( dotPos > begPos+myObj.Length() )
3330         myObj = myString.SubString( begPos, dotPos-1 );
3331     }
3332     // 1st word after '=' is an object
3333     // else // no method -> no object
3334     // {
3335     //   myObj.Clear();
3336     //   begPos = EMPTY;
3337     // }
3338     // store
3339     SetBegPos( OBJECT_IND, begPos );
3340   }
3341   //SCRUTE(myObj);
3342   return myObj;
3343 }
3344
3345 //================================================================================
3346 /*!
3347  * \brief Return substring of python command looking like ResVal = Obj.Method()
3348   * \retval const TCollection_AsciiString & - Method substring
3349  */
3350 //================================================================================
3351
3352 const TCollection_AsciiString & _pyCommand::GetMethod()
3353 {
3354   if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3355   {
3356     // beginning
3357     int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3358     bool forward = true;
3359     if ( begPos < 1 ) {
3360       begPos = myString.Location( "(", 1, Length() ) - 1;
3361       forward = false;
3362     }
3363     // store
3364     myMeth = GetWord( myString, begPos, forward );
3365     SetBegPos( METHOD_IND, begPos );
3366   }
3367   //SCRUTE(myMeth);
3368   return myMeth;
3369 }
3370
3371 //================================================================================
3372 /*!
3373  * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3374   * \retval const TCollection_AsciiString & - Arg<index> substring
3375  */
3376 //================================================================================
3377
3378 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3379 {
3380   if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3381   {
3382     // Find all args
3383
3384     int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3385     if ( pos < 1 )
3386       pos = myString.Location( "(", 1, Length() );
3387     else
3388       --pos;
3389
3390     // we are at or before '(', skip it if present
3391     if ( pos > 0 ) {
3392       while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3393       if ( pos > Length() )
3394         pos = 0;
3395     }
3396     if ( pos < 1 ) {
3397       SetBegPos( ARG1_IND, 0 ); // even no '('
3398       return theEmptyString;
3399     }
3400     ++pos;
3401
3402     list< TCollection_AsciiString > separatorStack( 1, ",)");
3403     bool ignoreNesting = false;
3404     int prevPos = pos;
3405     while ( pos <= Length() )
3406     {
3407       const char chr = myString.Value( pos );
3408
3409       if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3410       {
3411         if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3412         {
3413           while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3414             ++prevPos;
3415           TCollection_AsciiString arg;
3416           if ( pos-1 >= prevPos ) {
3417             arg = myString.SubString( prevPos, pos-1 );
3418             arg.RightAdjust(); // remove spaces
3419             arg.LeftAdjust();
3420           }
3421           if ( !arg.IsEmpty() || chr == ',' )
3422           {
3423             SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3424             myArgs.Append( arg );
3425           }
3426           if ( chr == ')' )
3427             break;
3428           prevPos = pos+1;
3429         }
3430         else // end of nesting args found
3431         {
3432           separatorStack.pop_back();
3433           ignoreNesting = false;
3434         }
3435       }
3436       else if ( !ignoreNesting )
3437       {
3438         switch ( chr ) {
3439         case '(' : separatorStack.push_back(")"); break;
3440         case '[' : separatorStack.push_back("]"); break;
3441         case '\'': separatorStack.push_back("'");  ignoreNesting=true; break;
3442         case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3443         default:;
3444         }
3445       }
3446       ++pos;
3447     }
3448   }
3449   if ( myArgs.Length() < index )
3450     return theEmptyString;
3451   return myArgs( index );
3452 }
3453
3454 //================================================================================
3455 /*!
3456  * \brief Check if char is a word part
3457   * \param c - The character to check
3458   * \retval bool - The check result
3459  */
3460 //================================================================================
3461
3462 static inline bool isWord(const char c, const bool dotIsWord)
3463 {
3464   return
3465     !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3466 }
3467
3468 //================================================================================
3469 /*!
3470  * \brief Looks for a word in the string and returns word's beginning
3471   * \param theString - The input string
3472   * \param theStartPos - The position to start the search, returning word's beginning
3473   * \param theForward - The search direction
3474   * \retval TCollection_AsciiString - The found word
3475  */
3476 //================================================================================
3477
3478 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3479                                              int &            theStartPos,
3480                                              const bool       theForward,
3481                                              const bool       dotIsWord )
3482 {
3483   int beg = theStartPos, end = theStartPos;
3484   theStartPos = EMPTY;
3485   if ( beg < 1 || beg > theString.Length() )
3486     return theEmptyString;
3487
3488   if ( theForward ) { // search forward
3489     // beg
3490     while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3491       ++beg;
3492     if ( beg > theString.Length() )
3493       return theEmptyString; // no word found
3494     // end
3495     end = beg + 1;
3496     char begChar = theString.Value( beg );
3497     if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3498       char endChar = ( begChar == '[' ) ? ']' : begChar;
3499       // end is at the corresponding quoting mark or bracket
3500       while ( end < theString.Length() &&
3501               ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3502         ++end;
3503     }
3504     else {
3505       while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3506         ++end;
3507       --end;
3508     }
3509   }
3510   else {  // search backward
3511     // end
3512     while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3513       --end;
3514     if ( end == 0 )
3515       return theEmptyString; // no word found
3516     beg = end - 1;
3517     char endChar = theString.Value( end );
3518     if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3519       char begChar = ( endChar == ']' ) ? '[' : endChar;
3520       // beg is at the corresponding quoting mark
3521       while ( beg > 1 &&
3522               ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3523         --beg;
3524     }
3525     else {
3526       while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3527         --beg;
3528       ++beg;
3529     }
3530   }
3531   theStartPos = beg;
3532   //cout << theString << " ---- " << beg << " - " << end << endl;
3533   return theString.SubString( beg, end );
3534 }
3535
3536 //================================================================================
3537 /*!
3538  * \brief Returns true if the string looks like a study entry
3539  */
3540 //================================================================================
3541
3542 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3543 {
3544   if ( str.Length() < 5 ) return false;
3545
3546   int nbColons = 0, isColon;
3547   for ( int i = 1; i <= str.Length(); ++i )
3548   {
3549     char c = str.Value(i);
3550     if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3551       return false;
3552     nbColons += isColon;
3553   }
3554   return nbColons > 2 && str.Length()-nbColons > 2;
3555 }
3556
3557 //================================================================================
3558 /*!
3559  * \brief Finds entries in a sting
3560  */
3561 //================================================================================
3562
3563 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3564 {
3565   std::list< _pyID > resList;
3566   int pos = 0;
3567   while ( ++pos <= str.Length() )
3568   {
3569     if ( !isdigit( str.Value( pos ))) continue;
3570     if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3571
3572     int end = pos;
3573     while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3574     _pyID entry = str.SubString( pos, end-1 );
3575     pos = end;
3576     if ( IsStudyEntry( entry ))
3577       resList.push_back( entry );
3578   }
3579   return resList;
3580 }
3581
3582 //================================================================================
3583 /*!
3584  * \brief Look for position where not space char is
3585   * \param theString - The string
3586   * \param thePos - The position to search from and which returns result
3587   * \retval bool - false if there are only space after thePos in theString
3588  */
3589 //================================================================================
3590
3591 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
3592 {
3593   if ( thePos < 1 || thePos > theString.Length() )
3594     return false;
3595
3596   while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
3597     ++thePos;
3598
3599   return thePos <= theString.Length();
3600 }
3601
3602 //================================================================================
3603 /*!
3604  * \brief Modify a part of the command
3605   * \param thePartIndex - The index of the part
3606   * \param thePart - The new part string
3607   * \param theOldPart - The old part
3608  */
3609 //================================================================================
3610
3611 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
3612                         TCollection_AsciiString& theOldPart)
3613 {
3614   int pos = GetBegPos( thePartIndex );
3615   if ( pos <= Length() && theOldPart != thePart)
3616   {
3617     TCollection_AsciiString seperator;
3618     if ( pos < 1 ) {
3619       pos = GetBegPos( thePartIndex + 1 );
3620       if ( pos < 1 ) return;
3621       switch ( thePartIndex ) {
3622       case RESULT_IND: seperator = " = "; break;
3623       case OBJECT_IND: seperator = "."; break;
3624       case METHOD_IND: seperator = "()"; break;
3625       default:;
3626       }
3627     }
3628     myString.Remove( pos, theOldPart.Length() );
3629     if ( !seperator.IsEmpty() )
3630       myString.Insert( pos , seperator );
3631     myString.Insert( pos, thePart );
3632     // update starting positions of the following parts
3633     int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
3634     for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
3635       if ( myBegPos( i ) > 0 )
3636         myBegPos( i ) += posDelta;
3637     }
3638     theOldPart = thePart;
3639   }
3640 }
3641
3642 //================================================================================
3643 /*!
3644  * \brief Set agrument
3645   * \param index - The argument index, it counts from 1
3646   * \param theArg - The argument string
3647  */
3648 //================================================================================
3649
3650 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
3651 {
3652   FindAllArgs();
3653   int argInd = ARG1_IND + index - 1;
3654   int pos = GetBegPos( argInd );
3655   if ( pos < 1 ) // no index-th arg exist, append inexistent args
3656   {
3657     // find a closing parenthesis
3658     if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
3659       int lastArgInd = GetNbArgs();
3660       pos = GetBegPos( ARG1_IND + lastArgInd  - 1 ) + GetArg( lastArgInd ).Length();
3661       while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
3662         ++pos;
3663     }
3664     else {
3665       pos = Length();
3666       while ( pos > 0 && myString.Value( pos ) != ')' )
3667         --pos;
3668     }
3669     if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
3670       myString += "()";
3671       pos = Length();
3672     }
3673     while ( myArgs.Length() < index ) {
3674       if ( myArgs.Length() )
3675         myString.Insert( pos++, "," );
3676       myArgs.Append("None");
3677       myString.Insert( pos, myArgs.Last() );
3678       SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
3679       pos += myArgs.Last().Length();
3680     }
3681   }
3682   SetPart( argInd, theArg, myArgs( index ));
3683 }
3684
3685 //================================================================================
3686 /*!
3687  * \brief Empty arg list
3688  */
3689 //================================================================================
3690
3691 void _pyCommand::RemoveArgs()
3692 {
3693   if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
3694     myString.Trunc( pos );
3695   myString += ")";
3696   myArgs.Clear();
3697   if ( myBegPos.Length() >= ARG1_IND )
3698     myBegPos.Remove( ARG1_IND, myBegPos.Length() );
3699 }
3700
3701 //================================================================================
3702 /*!
3703  * \brief Comment a python command
3704  */
3705 //================================================================================
3706
3707 void _pyCommand::Comment()
3708 {
3709   if ( IsEmpty() ) return;
3710
3711   int i = 1;
3712   while ( i <= Length() && isspace( myString.Value(i) )) ++i;
3713   if ( i <= Length() )
3714   {
3715     myString.Insert( i, "#" );
3716     for ( int iPart = 0; iPart < myBegPos.Length(); ++iPart )
3717     {
3718       int begPos = GetBegPos( iPart );
3719       if ( begPos != UNKNOWN )
3720         SetBegPos( iPart, begPos + 1 );
3721     }
3722   }
3723 }
3724
3725 //================================================================================
3726 /*!
3727  * \brief Set dependent commands after this one
3728  */
3729 //================================================================================
3730
3731 bool _pyCommand::SetDependentCmdsAfter() const
3732 {
3733   bool orderChanged = false;
3734   list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
3735   for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
3736     if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
3737       orderChanged = true;
3738       theGen->SetCommandAfter( *cmd, this );
3739       (*cmd)->SetDependentCmdsAfter();
3740     }
3741   }
3742   return orderChanged;
3743 }
3744 //================================================================================
3745 /*!
3746  * \brief Insert accessor method after theObjectID
3747   * \param theObjectID - id of the accessed object
3748   * \param theAcsMethod - name of the method giving access to the object
3749   * \retval bool - false if theObjectID is not found in the command string
3750  */
3751 //================================================================================
3752
3753 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
3754 {
3755   if ( !theAcsMethod )
3756     return false;
3757   // start object search from the object, i.e. ignore result
3758   GetObject();
3759   int beg = GetBegPos( OBJECT_IND );
3760   if ( beg < 1 || beg > Length() )
3761     return false;
3762   bool added = false;
3763   while (( beg = myString.Location( theObjectID, beg, Length() )))
3764   {
3765     // check that theObjectID is not just a part of a longer ID
3766     int afterEnd = beg + theObjectID.Length();
3767     Standard_Character c = myString.Value( afterEnd );
3768     if ( !isalnum( c ) && c != ':' ) {
3769       // check if accessor method already present
3770       if ( c != '.' ||
3771            myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
3772         // insertion
3773         int oldLen = Length();
3774         myString.Insert( afterEnd, (char*) theAcsMethod );
3775         myString.Insert( afterEnd, "." );
3776         // update starting positions of the parts following the modified one
3777         int posDelta = Length() - oldLen;
3778         for ( int i = 1; i <= myBegPos.Length(); ++i ) {
3779           if ( myBegPos( i ) > afterEnd )
3780             myBegPos( i ) += posDelta;
3781         }
3782         added = true;
3783       }
3784     }
3785     beg = afterEnd; // is a part - next search
3786   }
3787   return added;
3788 }
3789
3790 //================================================================================
3791 /*!
3792  * \brief Creates pyObject
3793  */
3794 //================================================================================
3795
3796 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
3797   : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
3798 {
3799   setID( theID );
3800 }
3801
3802 //================================================================================
3803 /*!
3804  * \brief Set up myID and myIsPublished
3805  */
3806 //================================================================================
3807
3808 void _pyObject::setID(const _pyID& theID)
3809 {
3810   myID = theID;
3811   myIsPublished = !theGen->IsNotPublished( GetID() );
3812 }
3813
3814 //================================================================================
3815 /*!
3816  * \brief Clear myCreationCmd and myProcessedCmds
3817  */
3818 //================================================================================
3819
3820 void _pyObject::ClearCommands()
3821 {
3822   if ( !CanClear() )
3823     return;
3824
3825   if ( !myCreationCmd.IsNull() )
3826     myCreationCmd->Clear();
3827
3828   list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
3829   for ( ; cmd != myProcessedCmds.end(); ++cmd )
3830     (*cmd)->Clear();
3831 }
3832
3833 //================================================================================
3834 /*!
3835  * \brief Return method name giving access to an interaface object wrapped by python class
3836   * \retval const char* - method name
3837  */
3838 //================================================================================
3839
3840 const char* _pyObject::AccessorMethod() const
3841 {
3842   return 0;
3843 }
3844 //================================================================================
3845 /*!
3846  * \brief Return ID of a father
3847  */
3848 //================================================================================
3849
3850 _pyID _pyObject::FatherID(const _pyID & childID)
3851 {
3852   int colPos = childID.SearchFromEnd(':');
3853   if ( colPos > 0 )
3854     return childID.SubString( 1, colPos-1 );
3855   return "";
3856 }
3857
3858 //================================================================================
3859 /*!
3860  * \brief SelfEraser erases creation command if no more it's commands invoked
3861  */
3862 //================================================================================
3863
3864 void _pySelfEraser::Flush()
3865 {
3866   if ( GetNbCalls() == 0 )
3867     GetCreationCmd()->Clear();
3868 }
3869
3870 //================================================================================
3871 /*!
3872  * \brief _pySubMesh constructor
3873  */
3874 //================================================================================
3875
3876 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd):
3877   _pyObject(theCreationCmd)
3878 {
3879   myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
3880 }
3881
3882 //================================================================================
3883 /*!
3884  * \brief Return true if a sub-mesh can be used as argument of the given method
3885  */
3886 //================================================================================
3887
3888 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
3889 {
3890   // names of all methods where a sub-mesh can be used as argument
3891   static TStringSet methods;
3892   if ( methods.empty() ) {
3893     const char * names[] = {
3894       // methods of SMESH_Gen
3895       "CopyMesh",
3896       // methods of SMESH_Group
3897       "AddFrom",
3898       // methods of SMESH_Measurements
3899       "MinDistance",
3900       // methods of SMESH_Mesh
3901       "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
3902       "RemoveSubMesh",
3903       // methods of SMESH_MeshEditor
3904       "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
3905       "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
3906       "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
3907       "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
3908       "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
3909       "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
3910       "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
3911       "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
3912       "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
3913       "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
3914       "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
3915       "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
3916       "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
3917       "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
3918       "MakeBoundaryMesh","Create0DElementsOnAllNodes",
3919       "" }; // <- mark of end
3920     methods.Insert( names );
3921   }
3922   return methods.Contains( theMethodName );
3923 }
3924
3925 //================================================================================
3926 /*!
3927  * \brief count invoked commands
3928  */
3929 //================================================================================
3930
3931 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
3932 {
3933   _pyObject::Process(theCommand); // count calls of Process()
3934   GetCreationCmd()->AddDependantCmd( theCommand );
3935 }
3936
3937 //================================================================================
3938 /*!
3939  * \brief Move creation command depending on invoked commands
3940  */
3941 //================================================================================
3942
3943 void _pySubMesh::Flush()
3944 {
3945   if ( GetNbCalls() == 0 ) // move to the end of all commands
3946     theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
3947   else if ( !myCreator.IsNull() )
3948     // move to be just after creator
3949     myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
3950 }
3951
3952 //================================================================================
3953 /*!
3954  * \brief Creates _pyGroup
3955  */
3956 //================================================================================
3957
3958 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
3959   :_pySubMesh(theCreationCmd)
3960 {
3961   if ( !id.IsEmpty() )
3962     setID( id );
3963
3964   myCanClearCreationCmd = true;
3965
3966   const _AString& method = theCreationCmd->GetMethod();
3967   if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
3968   {
3969     theCreationCmd->SetMethod( "CreateEmptyGroup" );
3970   }
3971   // ----------------------------------------------------------------------
3972   else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
3973   {
3974     _pyID geom = theCreationCmd->GetArg( 3 );
3975     // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
3976     // next if(){...} section is commented
3977     //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
3978     //  theCreationCmd->SetMethod( "Group" );
3979     //  theCreationCmd->RemoveArgs();
3980     //  theCreationCmd->SetArg( 1, geom );
3981     //}
3982     //else {
3983     // ------------------------->>>>> GroupOnGeom( geom, name, typ )
3984       _pyID type = theCreationCmd->GetArg( 1 );
3985       _pyID name = theCreationCmd->GetArg( 2 );
3986       theCreationCmd->SetMethod( "GroupOnGeom" );
3987       theCreationCmd->RemoveArgs();
3988       theCreationCmd->SetArg( 1, geom );
3989       theCreationCmd->SetArg( 2, name );
3990       theCreationCmd->SetArg( 3, type );
3991     //}
3992   }
3993   else if ( method == "CreateGroupFromFilter" )
3994   {
3995     // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
3996     theCreationCmd->SetMethod( "GroupOnFilter" );
3997
3998     _pyID filterID = theCreationCmd->GetArg(3);
3999     Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4000     if ( !filter.IsNull())
4001     {
4002       if ( !filter->GetNewID().IsEmpty() )
4003         theCreationCmd->SetArg( 3, filter->GetNewID() );
4004       filter->AddUser( this );
4005     }
4006     myFilter = filter;
4007   }
4008   else
4009   {
4010     // theCreationCmd does something else apart from creation of this group
4011     // and thus it can't be cleared if this group is removed
4012     myCanClearCreationCmd = false;
4013   }
4014 }
4015
4016 //================================================================================
4017 /*!
4018  * \brief set myCanClearCreationCmd = true if the main action of the creation
4019  *        command is discarded
4020  */
4021 //================================================================================
4022
4023 void _pyGroup::RemovedWithContents()
4024 {
4025   // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4026   // via a created group
4027   //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4028   // myCanClearCreationCmd = true;
4029 }
4030
4031 //================================================================================
4032 /*!
4033  * \brief To convert creation of a group by filter
4034  */
4035 //================================================================================
4036
4037 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4038 {
4039   // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4040   // group = mesh.CreateEmptyGroup( elemType, groupName )
4041   // aFilter.SetMesh(mesh)
4042   // nbAdd = group.AddFrom( aFilter )
4043   Handle(_pyFilter) filter;
4044   if ( theCommand->GetMethod() == "AddFrom" )
4045   {
4046     _pyID idSource = theCommand->GetArg(1);
4047     // check if idSource is a filter
4048     filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4049     if ( !filter.IsNull() )
4050     {
4051       // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4052       list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4053       while ( *cmdIt != theCommand ) ++cmdIt;
4054       while ( (*cmdIt)->GetOrderNb() != 1 )
4055       {
4056         const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4057         if ((setMeshCmd->GetObject() == idSource ||
4058              setMeshCmd->GetObject() == filter->GetNewID() )
4059             &&
4060             setMeshCmd->GetMethod() == "SetMesh")
4061         {
4062           setMeshCmd->Clear();
4063           break;
4064         }
4065       }
4066       // replace 3 commands by one
4067       theCommand->Clear();
4068       const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4069       TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4070       if ( !filter->GetNewID().IsEmpty() )
4071         idSource = filter->GetNewID();
4072       makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4073       makeGroupCmd->SetArg( 1, name );
4074       makeGroupCmd->SetArg( 2, idSource );
4075     }
4076   }
4077   else if ( theCommand->GetMethod() == "SetFilter" )
4078   {
4079     // set new name of a filter or clear the command if the same filter is set
4080     _pyID filterID = theCommand->GetArg(1);
4081     filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4082     if ( !myFilter.IsNull() && filter == myFilter )
4083       theCommand->Clear();
4084     else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4085       theCommand->SetArg( 1, filter->GetNewID() );
4086     myFilter = filter;
4087   }
4088   else if ( theCommand->GetMethod() == "GetFilter" )
4089   {
4090     // GetFilter() returns a filter with other ID, make myFilter process
4091     // calls of the returned filter
4092     if ( !myFilter.IsNull() )
4093     {
4094       theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4095       theCommand->Clear();
4096     }
4097   }
4098
4099   if ( !filter.IsNull() )
4100     filter->AddUser( this );
4101
4102   theGen->AddMeshAccessorMethod( theCommand );
4103 }
4104
4105 //================================================================================
4106 /*!
4107  * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4108  */
4109 //================================================================================
4110
4111 void _pyGroup::Flush()
4112 {
4113   if ( !theGen->IsToKeepAllCommands() &&
4114        myCreationCmd && !myCanClearCreationCmd )
4115   {
4116     myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4117   }
4118 }
4119
4120 //================================================================================
4121 /*!
4122  * \brief Constructor of _pyFilter
4123  */
4124 //================================================================================
4125
4126 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4127   :_pyObject(theCreationCmd), myNewID( newID )
4128 {
4129 }
4130
4131 //================================================================================
4132 /*!
4133  * \brief To convert creation of a filter by criteria and
4134  * to replace an old name by a new one
4135  */
4136 //================================================================================
4137
4138 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4139 {
4140   if ( theCommand->GetObject() == GetID() )
4141     _pyObject::Process(theCommand); // count commands
4142
4143   if ( !myNewID.IsEmpty() )
4144     theCommand->SetObject( myNewID );
4145     
4146   // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4147   // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4148   // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4149   if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4150        theCommand->GetMethod() == "SetCriteria")
4151   {
4152     // aFilter.SetCriteria(aCriteria) ->
4153     // aFilter = smesh.GetFilterFromCriteria(criteria)
4154     if ( myNewID.IsEmpty() )
4155       theCommand->SetResultValue( GetID() );
4156     else
4157       theCommand->SetResultValue( myNewID );
4158     theCommand->SetObject( SMESH_2smeshpy::GenName() );
4159     theCommand->SetMethod( "GetFilterFromCriteria" );
4160
4161     // Clear aFilterManager.CreateFilter()
4162     GetCreationCmd()->Clear();
4163   }
4164   else if ( theCommand->GetMethod() == "SetMesh" )
4165   {
4166     if ( myMesh == theCommand->GetArg( 1 ))
4167       theCommand->Clear();
4168     else
4169       myMesh = theCommand->GetArg( 1 );
4170     theGen->AddMeshAccessorMethod( theCommand );
4171   }
4172 }
4173
4174 //================================================================================
4175 /*!
4176  * \brief Set new filter name to the creation command
4177  */
4178 //================================================================================
4179
4180 void _pyFilter::Flush()
4181 {
4182   if ( !myNewID.IsEmpty() && !GetCreationCmd()->IsEmpty() )
4183     GetCreationCmd()->SetResultValue( myNewID );
4184 }
4185
4186 //================================================================================
4187 /*!
4188  * \brief Return true if all my users can be cleared
4189  */
4190 //================================================================================
4191
4192 bool _pyFilter::CanClear()
4193 {
4194   list< Handle(_pyObject) >::iterator obj = myUsers.begin();
4195   for ( ; obj != myUsers.end(); ++obj )
4196     if ( !(*obj)->CanClear() )
4197       return false;
4198
4199   return true;
4200 }
4201
4202 //================================================================================
4203 /*!
4204  * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4205  */
4206 //================================================================================
4207
4208 _pyHypothesisReader::_pyHypothesisReader()
4209 {
4210   // Read xml files
4211   vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4212   LDOMParser xmlParser;
4213   for ( size_t i = 0; i < xmlPaths.size(); ++i )
4214   {
4215     bool error = xmlParser.parse( xmlPaths[i].c_str() );
4216     if ( error )
4217     {
4218       _AString data;
4219       INFOS( xmlParser.GetError(data) );
4220       continue;
4221     }
4222     // <algorithm type="Regular_1D"
4223     //            label-id="Wire discretisation"
4224     //            ...>
4225     //   <python-wrap>
4226     //     <algo>Regular_1D=Segment()</algo>
4227     //     <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4228     //
4229     LDOM_Document xmlDoc = xmlParser.getDocument();
4230     LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4231     for ( int i = 0; i < algoNodeList.getLength(); ++i )
4232     {
4233       LDOM_Node     algoNode = algoNodeList.item( i );
4234       LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4235       LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4236       if ( pyAlgoNodeList.getLength() < 1 ) continue;
4237
4238       _AString text, algoType, method, arg;
4239       for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4240       {
4241         LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4242         LDOM_Node textNode   = pyAlgoNode.getFirstChild();
4243         text = textNode.getNodeValue();
4244         Handle(_pyCommand) algoCmd = new _pyCommand( text );
4245         algoType = algoCmd->GetResultValue();
4246         method   = algoCmd->GetMethod();
4247         arg      = algoCmd->GetArg(1);
4248         if ( !algoType.IsEmpty() && !method.IsEmpty() )
4249         {
4250           Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4251           algo->SetConvMethodAndType( method, algoType );
4252           if ( !arg.IsEmpty() )
4253             algo->setCreationArg( 1, arg );
4254
4255           myType2Hyp[ algoType ] = algo;
4256           break;
4257         }
4258       }
4259       if ( algoType.IsEmpty() ) continue;
4260
4261       LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4262       _AString hypType;
4263       Handle( _pyHypothesis ) hyp;
4264       for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4265       {
4266         LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4267         LDOM_Node textNode   = pyHypoNode.getFirstChild();
4268         text = textNode.getNodeValue();
4269         Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4270         hypType = hypoCmd->GetResultValue();
4271         method  = hypoCmd->GetMethod();
4272         if ( !hypType.IsEmpty() && !method.IsEmpty() )
4273         {
4274           map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4275           if ( type2hyp == myType2Hyp.end() )
4276             hyp = new _pyHypothesis( hypoCmd );
4277           else
4278             hyp = type2hyp->second;
4279           hyp->SetConvMethodAndType( method, algoType );
4280           for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4281           {
4282             _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4283             _AString argMethod = argCmd.GetMethod();
4284             _AString argNbText = argCmd.GetArg( 1 );
4285             if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4286               hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4287             else
4288               hyp->AddArgMethod( argMethod,
4289                                  argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4290           }
4291           myType2Hyp[ hypType ] = hyp;
4292         }
4293       }
4294     }
4295     // <hypothesis type="BLSURF_Parameters"
4296     //          ...
4297     //          dim="2">
4298     //   <python-wrap>
4299     //     <accumulative-methods> 
4300     //       SetEnforcedVertex,
4301     //       SetEnforcedVertexNamed
4302     //     </accumulative-methods>
4303     //   </python-wrap>
4304     // </hypothesis>
4305     //
4306     LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4307     for ( int i = 0; i < hypNodeList.getLength(); ++i )
4308     {
4309       LDOM_Node     hypNode      = hypNodeList.item( i );
4310       LDOM_Element& hypElem      = (LDOM_Element&) hypNode;
4311       _AString      hypType      = hypElem.getAttribute("type");
4312       LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4313       if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4314
4315       map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4316       if ( type2hyp == myType2Hyp.end() ) continue;
4317
4318       LDOM_Node methNode = methNodeList.item( 0 );
4319       LDOM_Node textNode = methNode.getFirstChild();
4320       _AString      text = textNode.getNodeValue();
4321       _AString method;
4322       int pos = 1;
4323       do {
4324         method = _pyCommand::GetWord( text, pos, /*forward= */true );
4325         pos += method.Length();
4326         type2hyp->second->AddAccumulativeMethod( method );
4327       }
4328       while ( !method.IsEmpty() );
4329     }
4330
4331   } // loop on xmlPaths
4332 }
4333
4334 //================================================================================
4335 /*!
4336  * \brief Returns a new hypothesis initialized according to the read information
4337  */
4338 //================================================================================
4339
4340 Handle(_pyHypothesis)
4341 _pyHypothesisReader::GetHypothesis(const _AString&           hypType,
4342                                    const Handle(_pyCommand)& creationCmd) const
4343 {
4344   Handle(_pyHypothesis) resHyp, sampleHyp;
4345
4346   map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4347   if ( type2hyp != myType2Hyp.end() )
4348     sampleHyp = type2hyp->second;
4349
4350   if ( sampleHyp.IsNull() )
4351   {
4352     resHyp = new _pyHypothesis(creationCmd);
4353   }
4354   else
4355   {
4356     if ( sampleHyp->IsAlgo() )
4357       resHyp = new _pyAlgorithm( creationCmd );
4358     else
4359       resHyp = new _pyHypothesis(creationCmd);
4360     resHyp->Assign( sampleHyp, _pyID() );
4361   }
4362   return resHyp;
4363 }