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