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