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