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