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