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