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