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