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