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