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