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