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