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