Salome HOME
22635: EDF 8345 - Creation of group based on groups
[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 sub-meshes 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             method == "CreateDimGroup" )
1899   {
1900     Handle(_pyGroup) group = new _pyGroup( theCommand );
1901     myGroups.push_back( group );
1902     theGen->AddObject( group );
1903   }
1904   // ----------------------------------------------------------------------
1905   // update list of groups
1906   else if ( method == "GetGroups" )
1907   {
1908     bool allGroupsRemoved = true;
1909     TCollection_AsciiString grIDs = theCommand->GetResultValue();
1910     list< _pyID >          idList = theCommand->GetStudyEntries( grIDs );
1911     list< _pyID >::iterator  grID = idList.begin();
1912     const int nbGroupsBefore = myGroups.size();
1913     Handle(_pyObject) obj;
1914     for ( ; grID != idList.end(); ++grID )
1915     {
1916       obj = theGen->FindObject( *grID );
1917       if ( obj.IsNull() )
1918       {
1919         Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1920         theGen->AddObject( group );
1921         myGroups.push_back( group );
1922         obj = group;
1923       }
1924       if ( !obj->CanClear() )
1925         allGroupsRemoved = false;
1926     }
1927     if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1928       obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1929
1930     if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1931     {
1932       // check if the preceding command is Compute();
1933       // if GetGroups() is just after Compute(), this can mean that the groups
1934       // were created by some algorithm and hence Compute() should not be discarded
1935       std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1936       std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1937       while ( (*cmd)->GetMethod() == "GetGroups" )
1938         ++cmd;
1939       if ( myLastComputeCmd == (*cmd))
1940         // protect last Compute() from clearing by the next Compute()
1941         myLastComputeCmd.Nullify();
1942     }
1943   }
1944   // ----------------------------------------------------------------------
1945   // notify a group about full removal
1946   else if ( method == "RemoveGroupWithContents" ||
1947             method == "RemoveGroup")
1948   {
1949     if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1950       const _pyID groupID = theCommand->GetArg( 1 );
1951       Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1952       if ( !grp.IsNull() )
1953       {
1954         if ( method == "RemoveGroupWithContents" )
1955           grp->RemovedWithContents();
1956         // to clear RemoveGroup() if the group creation is cleared
1957         grp->AddProcessedCmd( theCommand );
1958       }
1959     }
1960   }
1961   // ----------------------------------------------------------------------
1962   else if ( theCommand->MethodStartsFrom( "Export" ))
1963   {
1964     if ( method == "ExportToMED" ||  // ExportToMED()  --> ExportMED()
1965          method == "ExportToMEDX" )  // ExportToMEDX() --> ExportMED()
1966     {
1967       theCommand->SetMethod( "ExportMED" );
1968       if ( theCommand->GetNbArgs() == 5 )
1969       {
1970         // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1971         _AString autoDimension = theCommand->GetArg( 5 );
1972         theCommand->SetArg( 5, "None" );
1973         theCommand->SetArg( 6, autoDimension );
1974       }
1975     }
1976     else if ( method == "ExportCGNS" )
1977     { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1978       _pyID partID = theCommand->GetArg( 1 );
1979       int nbArgs = theCommand->GetNbArgs();
1980       for ( int i = 2; i <= nbArgs; ++i )
1981         theCommand->SetArg( i-1, theCommand->GetArg( i ));
1982       theCommand->SetArg( nbArgs, partID );
1983     }
1984     else if ( method == "ExportGMF" )
1985     { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1986       _pyID partID  = theCommand->GetArg( 1 );
1987       _AString file = theCommand->GetArg( 2 );
1988       theCommand->RemoveArgs();
1989       theCommand->SetArg( 1, file );
1990       theCommand->SetArg( 2, partID );
1991     }
1992     else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1993     { // ExportPartTo*(part, ...) -> Export*(..., part)
1994       //
1995       // remove "PartTo" from the method
1996       TCollection_AsciiString newMethod = method;
1997       newMethod.Remove( /*where=*/7, /*howmany=*/6 );
1998       theCommand->SetMethod( newMethod );
1999       // make the 1st arg be the last one (or last but three for ExportMED())
2000       _pyID partID = theCommand->GetArg( 1 );
2001       int nbArgs = theCommand->GetNbArgs() - 3 * (newMethod == "ExportMED");
2002       for ( int i = 2; i <= nbArgs; ++i )
2003         theCommand->SetArg( i-1, theCommand->GetArg( i ));
2004       theCommand->SetArg( nbArgs, partID );
2005     }
2006     // remember file name
2007     theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2008                              ExportedMeshData( this, myLastComputeCmd ));
2009   }
2010   // ----------------------------------------------------------------------
2011   else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2012   {
2013     _pyID hypID  = theCommand->GetArg( 2 );
2014     _pyID geomID = theCommand->GetArg( 1 );
2015     bool isLocal = ( geomID != GetGeom() );
2016
2017     // check if this mesh still has corresponding addition command
2018     Handle(_pyCommand) addCmd;
2019     list< Handle(_pyCommand) >::iterator cmd;
2020     list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2021     for ( int i = 0; i < 2; ++i )
2022     {
2023       list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2024       for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2025       {
2026         bool sameHyp = true;
2027         if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2028           sameHyp = false; // other hyp
2029         if ( (*cmd)->GetNbArgs() == 2 &&
2030              geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2031           sameHyp = false; // other geom
2032         if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2033           sameHyp = false; // other geom
2034         if ( sameHyp )
2035         {
2036           addCmd = *cmd;
2037           cmd    = addHypCmds.erase( cmd );
2038           if ( !theGen->IsToKeepAllCommands() && CanClear() ) {
2039             addCmd->Clear();
2040             theCommand->Clear();
2041           }
2042           else
2043           {
2044             // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2045             addCmd->RemoveArgs();
2046             addCmd->SetArg( 1, hypID );
2047             if ( isLocal )
2048               addCmd->SetArg( 2, geomID );
2049           }
2050         }
2051         else
2052         {
2053           ++cmd;
2054         }
2055       }
2056     }
2057     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2058     if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2059       // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2060       _pyID geom = theCommand->GetArg( 1 );
2061       theCommand->RemoveArgs();
2062       theCommand->SetArg( 1, hypID );
2063       if ( geom != GetGeom() )
2064         theCommand->SetArg( 2, geom );
2065     }
2066     // remove hyp from myHypos
2067     myHypos.remove( hyp );
2068   }
2069   // check for SubMesh order commands
2070   else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2071   {
2072     // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2073     // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2074     // commands are moved at the end of the script
2075     TCollection_AsciiString subIDs =
2076       ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2077     list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2078     list< _pyID >::iterator subID = idList.begin();
2079     for ( ; subID != idList.end(); ++subID )
2080     {
2081       Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2082       if ( !subMesh.IsNull() )
2083         subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2084     }
2085   }
2086   // add accessor method if necessary
2087   else
2088   {
2089     if ( NeedMeshAccess( theCommand ))
2090       // apply theCommand to the mesh wrapped by smeshpy mesh
2091       AddMeshAccess( theCommand );
2092   }
2093 }
2094
2095 //================================================================================
2096 /*!
2097  * \brief Return True if addition of accesor method is needed
2098  */
2099 //================================================================================
2100
2101 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2102 {
2103   // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2104   // so no conversion is needed for them at all:
2105   static TStringSet sameMethods;
2106   if ( sameMethods.empty() ) {
2107     const char * names[] =
2108       { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2109         "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2110         "ClearLog","GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2111         "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2112         "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2113         "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2114         "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2115         "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2116         "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2117         "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2118         "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2119         "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2120         "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2121         "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2122         ,"" }; // <- mark of end
2123     sameMethods.Insert( names );
2124   }
2125
2126   return !sameMethods.Contains( theCommand->GetMethod() );
2127 }
2128
2129 //================================================================================
2130 /*!
2131  * \brief Convert creation and addition of all algos and hypos
2132  */
2133 //================================================================================
2134
2135 void _pyMesh::Flush()
2136 {
2137   {
2138     // get the meshes this mesh depends on via hypotheses
2139     list< Handle(_pyMesh) > fatherMeshes;
2140     list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2141     for ( ; hyp != myHypos.end(); ++hyp )
2142       if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2143         myGeomNotInStudy = true;
2144
2145     list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2146     for ( ; m != fatherMeshes.end(); ++m )
2147       addFatherMesh( *m );
2148     // if ( removedGeom )
2149     //     SetRemovedFromStudy(); // as reffered geometry not in study
2150   }
2151   if ( myGeomNotInStudy )
2152     return;
2153
2154   list < Handle(_pyCommand) >::iterator cmd;
2155
2156   // try to convert algo addition like this:
2157   // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2158   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2159   {
2160     Handle(_pyCommand) addCmd = *cmd;
2161
2162     _pyID algoID = addCmd->GetArg( 2 );
2163     Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2164     if ( algo.IsNull() || !algo->IsAlgo() )
2165       continue;
2166
2167     // check and create new algorithm instance if it is already wrapped
2168     if ( algo->IsWrapped() ) {
2169       _pyID localAlgoID = theGen->GenerateNewID( algoID );
2170       TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2171         TCollection_AsciiString( " = " ) + theGen->GetID() +
2172         TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2173         TCollection_AsciiString( "\" )" );
2174
2175       Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2176       Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2177       if ( !newAlgo.IsNull() ) {
2178         newAlgo->Assign( algo, this->GetID() );
2179         newAlgo->SetCreationCmd( newCmd );
2180         algo = newAlgo;
2181         // set algorithm creation
2182         theGen->SetCommandBefore( newCmd, addCmd );
2183         myHypos.push_back( newAlgo );
2184         if ( !myLastComputeCmd.IsNull() &&
2185              newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2186           newAlgo->MeshComputed( myLastComputeCmd );
2187       }
2188       else
2189         newCmd->Clear();
2190     }
2191     _pyID geom = addCmd->GetArg( 1 );
2192     bool isLocalAlgo = ( geom != GetGeom() );
2193
2194     // try to convert
2195     if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2196     {
2197       // wrapped algo is created after mesh creation
2198       GetCreationCmd()->AddDependantCmd( addCmd );
2199
2200       if ( isLocalAlgo ) {
2201         // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2202         addCmd->SetArg( addCmd->GetNbArgs() + 1,
2203                         TCollection_AsciiString( "geom=" ) + geom );
2204         // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2205         list < Handle(_pySubMesh) >::iterator smIt;
2206         for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2207           Handle(_pySubMesh) subMesh = *smIt;
2208           Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2209           if ( geom == subCmd->GetArg( 1 )) {
2210             subCmd->SetObject( algo->GetID() );
2211             subCmd->RemoveArgs();
2212             subMesh->SetCreator( algo );
2213           }
2214         }
2215       }
2216     }
2217     else // KO - ALGO was already created
2218     {
2219       // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2220       addCmd->RemoveArgs();
2221       addCmd->SetArg( 1, algoID );
2222       if ( isLocalAlgo )
2223         addCmd->SetArg( 2, geom );
2224       myNotConvertedAddHypCmds.push_back( addCmd );
2225     }
2226   }
2227
2228   // try to convert hypo addition like this:
2229   // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2230   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2231   {
2232     Handle(_pyCommand) addCmd = *cmd;
2233     _pyID hypID = addCmd->GetArg( 2 );
2234     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2235     if ( hyp.IsNull() || hyp->IsAlgo() )
2236       continue;
2237     bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2238     if ( !converted ) {
2239       // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2240       _pyID geom = addCmd->GetArg( 1 );
2241       addCmd->RemoveArgs();
2242       addCmd->SetArg( 1, hypID );
2243       if ( geom != GetGeom() )
2244         addCmd->SetArg( 2, geom );
2245       myNotConvertedAddHypCmds.push_back( addCmd );
2246     }
2247   }
2248
2249   myAddHypCmds.clear();
2250   mySubmeshes.clear();
2251
2252   // flush hypotheses
2253   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2254   for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2255     (*hyp)->Flush();
2256 }
2257
2258 //================================================================================
2259 /*!
2260  * \brief Sets myIsPublished of me and of all objects depending on me.
2261  */
2262 //================================================================================
2263
2264 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2265 {
2266   _pyObject::SetRemovedFromStudy(isRemoved);
2267
2268   list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2269   for ( ; sm != mySubmeshes.end(); ++sm )
2270     (*sm)->SetRemovedFromStudy(isRemoved);
2271
2272   list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2273   for ( ; gr != myGroups.end(); ++gr )
2274     (*gr)->SetRemovedFromStudy(isRemoved);
2275
2276   list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2277   for ( ; m != myChildMeshes.end(); ++m )
2278     (*m)->SetRemovedFromStudy(isRemoved);
2279
2280   list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2281   for ( ; e != myEditors.end(); ++e )
2282     (*e)->SetRemovedFromStudy(isRemoved);
2283 }
2284
2285 //================================================================================
2286 /*!
2287  * \brief Return true if none of myChildMeshes is in study
2288  */
2289 //================================================================================
2290
2291 bool _pyMesh::CanClear()
2292 {
2293   if ( IsInStudy() )
2294     return false;
2295
2296   list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2297   for ( ; m != myChildMeshes.end(); ++m )
2298     if ( !(*m)->CanClear() )
2299       return false;
2300
2301   return true;
2302 }
2303
2304 //================================================================================
2305 /*!
2306  * \brief Clear my commands and commands of mesh editor
2307  */
2308 //================================================================================
2309
2310 void _pyMesh::ClearCommands()
2311 {
2312   if ( !CanClear() )
2313   {
2314     if ( !IsInStudy() )
2315     {
2316       // mark all sub-objects as not removed, except child meshes
2317       list< Handle(_pyMesh) > children;
2318       children.swap( myChildMeshes );
2319       SetRemovedFromStudy( false );
2320       children.swap( myChildMeshes );
2321     }
2322     return;
2323   }
2324   _pyObject::ClearCommands();
2325
2326   list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2327   for ( ; sm != mySubmeshes.end(); ++sm )
2328     (*sm)->ClearCommands();
2329   
2330   list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2331   for ( ; gr != myGroups.end(); ++gr )
2332     (*gr)->ClearCommands();
2333
2334   list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2335   for ( ; e != myEditors.end(); ++e )
2336     (*e)->ClearCommands();
2337 }
2338
2339 //================================================================================
2340 /*!
2341  * \brief Add a father mesh by ID
2342  */
2343 //================================================================================
2344
2345 void _pyMesh::addFatherMesh( const _pyID& meshID )
2346 {
2347   if ( !meshID.IsEmpty() && meshID != GetID() )
2348     addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2349 }
2350
2351 //================================================================================
2352 /*!
2353  * \brief Add a father mesh
2354  */
2355 //================================================================================
2356
2357 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2358 {
2359   if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2360   {
2361     //myFatherMeshes.push_back( mesh );
2362     mesh->myChildMeshes.push_back( this );
2363
2364     // protect last Compute() from clearing by the next Compute()
2365     mesh->myLastComputeCmd.Nullify();
2366   }
2367 }
2368
2369 //================================================================================
2370 /*!
2371  * \brief MeshEditor convert its commands to ones of mesh
2372  */
2373 //================================================================================
2374
2375 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2376   _pyObject( theCreationCmd )
2377 {
2378   myMesh = theCreationCmd->GetObject();
2379   myCreationCmdStr = theCreationCmd->GetString();
2380   theCreationCmd->Clear();
2381
2382   Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2383   if ( !mesh.IsNull() )
2384     mesh->AddEditor( this );
2385 }
2386
2387 //================================================================================
2388 /*!
2389  * \brief convert its commands to ones of mesh
2390  */
2391 //================================================================================
2392
2393 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2394 {
2395   // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2396   // commands calling these methods are converted to calls of Mesh methods without
2397   // additional modifs, only object is changed from MeshEditor to Mesh.
2398   static TStringSet sameMethods;
2399   if ( sameMethods.empty() ) {
2400     const char * names[] = {
2401       "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2402       "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2403       "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2404       "MoveNode", "MoveClosestNodeToPoint",
2405       "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2406       "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2407       "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2408       "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2409       "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2410       "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2411       "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2412       "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2413       "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2414       "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2415       "FindCoincidentNodes","MergeNodes","FindEqualElements",
2416       "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2417       "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2418       "GetLastCreatedElems",
2419       "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2420       "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2421       "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2422       "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2423       "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2424       "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2425       "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2426       ,"" }; // <- mark of the end
2427     sameMethods.Insert( names );
2428   }
2429
2430   // names of SMESH_MeshEditor commands in which only a method name must be replaced
2431   TStringMap diffMethods;
2432   if ( diffMethods.empty() ) {
2433     const char * orig2newName[] = {
2434       // original name --------------> new name
2435       "ExtrusionAlongPathObjX"      , "ExtrusionAlongPathX",
2436       "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2437       "ConvertToQuadraticObject"    , "ConvertToQuadratic",
2438       "ConvertFromQuadraticObject"  , "ConvertFromQuadratic",
2439       "Create0DElementsOnAllNodes"  , "Add0DElementsToAllNodes",
2440       ""};// <- mark of the end
2441     diffMethods.Insert( orig2newName );
2442   }
2443
2444   // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2445   // only by last two arguments
2446   static TStringSet diffLastTwoArgsMethods;
2447   if (diffLastTwoArgsMethods.empty() ) {
2448     const char * names[] = {
2449       "MirrorMakeGroups","MirrorObjectMakeGroups",
2450       "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2451       "RotateMakeGroups","RotateObjectMakeGroups",
2452       ""};// <- mark of the end
2453     diffLastTwoArgsMethods.Insert( names );
2454   }
2455
2456   // only a method name is to change?
2457   const TCollection_AsciiString & method = theCommand->GetMethod();
2458   bool isPyMeshMethod = sameMethods.Contains( method );
2459   if ( !isPyMeshMethod )
2460   {
2461     TCollection_AsciiString newMethod = diffMethods.Value( method );
2462     if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2463       theCommand->SetMethod( newMethod );
2464   }
2465   // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2466   if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2467   {
2468     isPyMeshMethod = true;
2469     theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2470     theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2471   }
2472
2473   if ( !isPyMeshMethod )
2474   {
2475     // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2476     // functions with the flag "theMakeGroups = True" like:
2477     // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2478     int pos = method.Search("MakeGroups");
2479     if( pos != -1)
2480     {
2481       isPyMeshMethod = true;
2482       bool is0DmethId  = ( method == "ExtrusionSweepMakeGroups0D" );
2483       bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2484
2485       // 1. Remove "MakeGroups" from the Command
2486       TCollection_AsciiString aMethod = theCommand->GetMethod();
2487       int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2488       
2489       if(is0DmethObj)
2490         pos = pos-2;  //Remove "0D" from the Command too
2491       aMethod.Trunc(pos-1);
2492       theCommand->SetMethod(aMethod);
2493
2494       // 2. And add last "True" argument(s)
2495       while(nbArgsToAdd--)
2496         theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2497       if( is0DmethId || is0DmethObj )
2498         theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2499     }
2500   }
2501
2502   // ExtrusionSweep0D()       -> ExtrusionSweep()
2503   // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2504   if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D"  ||
2505                             method == "ExtrusionSweepObject0D" ))
2506   {
2507     isPyMeshMethod = true;
2508     theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2509     theCommand->SetArg(theCommand->GetNbArgs()+1,"False");  //sets flag "MakeGroups = False"
2510     theCommand->SetArg(theCommand->GetNbArgs()+1,"True");  //sets flag "IsNode = True"
2511   }
2512
2513   // DoubleNode...New(...) -> DoubleNode...(...,True)
2514   if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew"  ||
2515                             method == "DoubleNodeElemGroupsNew" ||
2516                             method == "DoubleNodeGroupNew"      ||
2517                             method == "DoubleNodeGroupsNew"     ||
2518                             method == "DoubleNodeElemGroup2New" ||
2519                             method == "DoubleNodeElemGroups2New"))
2520   {
2521     isPyMeshMethod = true;
2522     const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2523     theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2524     if ( excessLen == 3 )
2525     {
2526       theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2527     }
2528     else if ( theCommand->GetArg(4) == "0" ||
2529               theCommand->GetArg(5) == "0" )
2530     {
2531       // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2532       // Group = DoubleNodeGroup2New(,,,False, True)
2533       _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2534       theCommand->SetResultValue( groupID );
2535     }
2536   }
2537   // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2538   // FindElementsByPoint(x, y, z, elementType, meshPart)
2539   if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2540   {
2541     isPyMeshMethod = true;
2542     theCommand->SetMethod( "FindElementsByPoint" );
2543     // make the 1st arg be the last one
2544     _pyID partID = theCommand->GetArg( 1 );
2545     int nbArgs = theCommand->GetNbArgs();
2546     for ( int i = 2; i <= nbArgs; ++i )
2547       theCommand->SetArg( i-1, theCommand->GetArg( i ));
2548     theCommand->SetArg( nbArgs, partID );
2549   }
2550   // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2551   if ( !isPyMeshMethod && method == "Reorient2D" )
2552   {
2553     isPyMeshMethod = true;
2554     _AString mesh  = theCommand->GetArg( 1 );
2555     _AString dir   = theCommand->GetArg( 2 );
2556     _AString face  = theCommand->GetArg( 3 );
2557     _AString point = theCommand->GetArg( 4 );
2558     theCommand->RemoveArgs();
2559     theCommand->SetArg( 1, mesh );
2560     theCommand->SetArg( 2, dir );
2561     if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2562       theCommand->SetArg( 3, point );
2563     else
2564       theCommand->SetArg( 3, face );
2565   }
2566
2567   if ( method == "QuadToTri" || method == "QuadToTriObject" )
2568   {
2569     isPyMeshMethod = true;
2570     int crit_arg = theCommand->GetNbArgs();
2571     const _AString& crit = theCommand->GetArg(crit_arg);
2572     if (crit.Search("MaxElementLength2D") != -1)
2573       theCommand->SetArg(crit_arg, "");
2574   }
2575
2576   if ( isPyMeshMethod )
2577   {
2578     theCommand->SetObject( myMesh );
2579   }
2580   else
2581   {
2582     // editor creation command is needed only if any editor function is called
2583     theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2584     if ( !myCreationCmdStr.IsEmpty() ) {
2585       GetCreationCmd()->GetString() = myCreationCmdStr;
2586       myCreationCmdStr.Clear();
2587     }
2588   }
2589 }
2590
2591 //================================================================================
2592 /*!
2593  * \brief Return true if my mesh can be removed
2594  */
2595 //================================================================================
2596
2597 bool _pyMeshEditor::CanClear()
2598 {
2599   Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2600   return mesh.IsNull() ? true : mesh->CanClear();
2601 }
2602
2603 //================================================================================
2604 /*!
2605  * \brief _pyHypothesis constructor
2606   * \param theCreationCmd -
2607  */
2608 //================================================================================
2609
2610 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2611   _pyObject( theCreationCmd ), myCurCrMethod(0)
2612 {
2613   myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2614 }
2615
2616 //================================================================================
2617 /*!
2618  * \brief Creates algorithm or hypothesis
2619   * \param theCreationCmd - The engine command creating a hypothesis
2620   * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2621  */
2622 //================================================================================
2623
2624 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2625 {
2626   // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2627   ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2628
2629   Handle(_pyHypothesis) hyp, algo;
2630
2631   // "theHypType"
2632   const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2633   if ( hypTypeQuoted.IsEmpty() )
2634     return hyp;
2635   // theHypType
2636   TCollection_AsciiString  hypType =
2637     hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2638
2639   algo = new _pyAlgorithm( theCreationCmd );
2640   hyp  = new _pyHypothesis( theCreationCmd );
2641
2642   if ( hypType == "NumberOfSegments" ) {
2643     hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2644     hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2645     // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2646     hyp->AddArgMethod( "SetNumberOfSegments" );
2647     // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2648     hyp->AddArgMethod( "SetScaleFactor" );
2649     hyp->AddArgMethod( "SetReversedEdges" );
2650     // same for ""CompositeSegment_1D:
2651     hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2652     hyp->AddArgMethod( "SetNumberOfSegments" );
2653     hyp->AddArgMethod( "SetScaleFactor" );
2654     hyp->AddArgMethod( "SetReversedEdges" );
2655   }
2656   else if ( hypType == "SegmentLengthAroundVertex" ) {
2657     hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2658     hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2659     hyp->AddArgMethod( "SetLength" );
2660     // same for ""CompositeSegment_1D:
2661     hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2662     hyp->AddArgMethod( "SetLength" );
2663   }
2664   else if ( hypType == "LayerDistribution2D" ) {
2665     hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2666     hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2667   }
2668   else if ( hypType == "LayerDistribution" ) {
2669     hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2670     hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2671   }
2672   else if ( hypType == "CartesianParameters3D" ) {
2673     hyp = new _pyComplexParamHypo( theCreationCmd );
2674     hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2675     for ( int iArg = 0; iArg < 4; ++iArg )
2676       hyp->setCreationArg( iArg+1, "[]");
2677     hyp->AddAccumulativeMethod( "SetGrid" );
2678     hyp->AddAccumulativeMethod( "SetGridSpacing" );
2679   }
2680   else
2681   {
2682     hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2683   }
2684
2685   return algo->IsValid() ? algo : hyp;
2686 }
2687
2688 //================================================================================
2689 /*!
2690  * \brief Returns true if addition of this hypothesis to a given mesh can be
2691  *        wrapped into hypothesis creation
2692  */
2693 //================================================================================
2694
2695 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2696 {
2697   if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2698   {
2699     Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2700     if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2701       return true;
2702   }
2703   return false;
2704 }
2705
2706 //================================================================================
2707 /*!
2708  * \brief Convert the command adding a hypothesis to mesh into a smesh command
2709   * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2710   * \param theAlgo - The algo that can create this hypo
2711   * \retval bool - false if the command cant be converted
2712  */
2713 //================================================================================
2714
2715 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2716                                        const _pyID&              theMesh)
2717 {
2718   ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2719
2720   if ( !IsWrappable( theMesh ))
2721     return false;
2722
2723   myGeom = theCmd->GetArg( 1 );
2724
2725   Handle(_pyHypothesis) algo;
2726   if ( !IsAlgo() ) {
2727     // find algo created on myGeom in theMesh
2728     algo = theGen->FindAlgo( myGeom, theMesh, this );
2729     if ( algo.IsNull() )
2730       return false;
2731     // attach hypothesis creation command to be after algo creation command
2732     // because it can be new created instance of algorithm
2733     algo->GetCreationCmd()->AddDependantCmd( theCmd );
2734   }
2735   myIsWrapped = true;
2736
2737   // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2738   theCmd->SetResultValue( GetID() );
2739   theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2740   theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2741   // set args (geom will be set by _pyMesh calling this method)
2742   theCmd->RemoveArgs();
2743   for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2744     if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2745       theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2746     else
2747       theCmd->SetArg( i+1, "[]");
2748   }
2749   // set a new creation command
2750   GetCreationCmd()->Clear();
2751   // replace creation command by wrapped instance
2752   // please note, that hypothesis attaches to algo creation command (see upper)
2753   SetCreationCmd( theCmd );
2754
2755
2756   // clear commands setting arg values
2757   list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2758   for ( ; argCmd != myArgCommands.end(); ++argCmd )
2759     (*argCmd)->Clear();
2760
2761   // set unknown arg commands after hypo creation
2762   Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2763   list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2764   for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2765     afterCmd->AddDependantCmd( *cmd );
2766   }
2767
2768   return myIsWrapped;
2769 }
2770
2771 //================================================================================
2772 /*!
2773  * \brief Remember hypothesis parameter values
2774  * \param theCommand - The called hypothesis method
2775  */
2776 //================================================================================
2777
2778 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2779 {
2780   ASSERT( !myIsAlgo );
2781   if ( !theGen->IsToKeepAllCommands() )
2782     rememberCmdOfParameter( theCommand );
2783   // set args
2784   bool usedCommand = false;
2785   TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2786   for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2787   {
2788     CreationMethod& crMethod = type2meth->second;
2789     for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2790       if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2791         if ( !usedCommand )
2792           myArgCommands.push_back( theCommand );
2793         usedCommand = true;
2794         while ( crMethod.myArgs.size() < i+1 )
2795           crMethod.myArgs.push_back( "None" );
2796         crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2797       }
2798     }
2799   }
2800   if ( !usedCommand )
2801     myUnusedCommands.push_back( theCommand );
2802 }
2803
2804 //================================================================================
2805 /*!
2806  * \brief Finish conversion
2807  */
2808 //================================================================================
2809
2810 void _pyHypothesis::Flush()
2811 {
2812   if ( !IsAlgo() )
2813   {
2814     list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2815     for ( ; cmd != myArgCommands.end(); ++cmd ) {
2816       // Add access to a wrapped mesh
2817       theGen->AddMeshAccessorMethod( *cmd );
2818       // Add access to a wrapped algorithm
2819       theGen->AddAlgoAccessorMethod( *cmd );
2820     }
2821     cmd = myUnusedCommands.begin();
2822     for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2823       // Add access to a wrapped mesh
2824       theGen->AddMeshAccessorMethod( *cmd );
2825       // Add access to a wrapped algorithm
2826       theGen->AddAlgoAccessorMethod( *cmd );
2827     }
2828   }
2829   // forget previous hypothesis modifications
2830   myArgCommands.clear();
2831   myUnusedCommands.clear();
2832 }
2833
2834 //================================================================================
2835 /*!
2836  * \brief clear creation, arg and unkown commands
2837  */
2838 //================================================================================
2839
2840 void _pyHypothesis::ClearAllCommands()
2841 {
2842   GetCreationCmd()->Clear();
2843   list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2844   for ( ; cmd != myArgCommands.end(); ++cmd )
2845     ( *cmd )->Clear();
2846   cmd = myUnusedCommands.begin();
2847   for ( ; cmd != myUnusedCommands.end(); ++cmd )
2848     ( *cmd )->Clear();
2849 }
2850
2851
2852 //================================================================================
2853 /*!
2854  * \brief Assign fields of theOther to me except myIsWrapped
2855  */
2856 //================================================================================
2857
2858 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2859                             const _pyID&                 theMesh )
2860 {
2861   // myCreationCmd = theOther->myCreationCmd;
2862   myIsAlgo                  = theOther->myIsAlgo;
2863   myIsWrapped               = false;
2864   myGeom                    = theOther->myGeom;
2865   myMesh                    = theMesh;
2866   myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2867   myAccumulativeMethods     = theOther->myAccumulativeMethods;
2868   //myUnusedCommands          = theOther->myUnusedCommands;
2869   // init myCurCrMethod
2870   GetCreationMethod( theOther->GetAlgoType() );
2871 }
2872
2873 //================================================================================
2874 /*!
2875  * \brief Analyze my erasability depending on myReferredObjs
2876  */
2877 //================================================================================
2878
2879 bool _pyHypothesis::CanClear()
2880 {
2881   if ( IsInStudy() )
2882   {
2883     list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2884     for ( ; obj != myReferredObjs.end(); ++obj )
2885       if ( (*obj)->CanClear() )
2886         return true;
2887     return false;
2888   }
2889   return true;
2890 }
2891
2892 //================================================================================
2893 /*!
2894  * \brief Clear my commands depending on usage by meshes
2895  */
2896 //================================================================================
2897
2898 void _pyHypothesis::ClearCommands()
2899 {
2900   // if ( !theGen->IsToKeepAllCommands() )
2901   // {
2902   //   bool isUsed = false;
2903   //   int lastComputeOrder = 0;
2904   //   list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2905   //   for ( ; cmd != myComputeCmds.end(); ++cmd )
2906   //     if ( ! (*cmd)->IsEmpty() )
2907   //     {
2908   //       isUsed = true;
2909   //       if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2910   //         lastComputeOrder = (*cmd)->GetOrderNb();
2911   //     }
2912   //   if ( !isUsed )
2913   //   {
2914   //     SetRemovedFromStudy( true );
2915   //   }
2916   //   else
2917   //   {
2918   //     // clear my commands invoked after lastComputeOrder
2919   //     // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2920   //     // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2921   //     // {
2922   //     //   list< Handle(_pyCommand)> & cmds = m2c->second;
2923   //     //   if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2924   //     //     cmds.back()->Clear();
2925   //     // }
2926   //   }
2927   // }
2928   _pyObject::ClearCommands();
2929 }
2930
2931 //================================================================================
2932 /*!
2933  * \brief Find arguments that are objects like mesh, group, geometry
2934  *  \param meshes - referred meshes (directly or indirrectly)
2935  *  \retval bool - false if a referred geometry is not in the study
2936  */
2937 //================================================================================
2938
2939 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2940 {
2941   if ( IsAlgo() ) return true;
2942
2943   bool geomPublished = true;
2944   vector< _AString > args;
2945   TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2946   for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2947   {
2948     CreationMethod& crMethod = type2meth->second;
2949     args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2950   }
2951   list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2952   for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2953     for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2954       args.push_back( (*cmd)->GetArg( nb ));
2955   }
2956
2957   for ( size_t i = 0; i < args.size(); ++i )
2958   {
2959     list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2960     if ( idList.empty() && !args[ i ].IsEmpty() )
2961       idList.push_back( args[ i ]);
2962     list< _pyID >::iterator id = idList.begin();
2963     for ( ; id != idList.end(); ++id )
2964     {
2965       Handle(_pyObject)   obj = theGen->FindObject( *id );
2966       if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2967       if ( obj.IsNull() )
2968       {
2969         if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2970           geomPublished = false;
2971       }
2972       else
2973       {
2974         myReferredObjs.push_back( obj );
2975         Handle(_pyMesh) mesh = ObjectToMesh( obj );
2976         if ( !mesh.IsNull() )
2977           meshes.push_back( mesh );
2978         // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2979         else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2980           obj->SetRemovedFromStudy( false );
2981       }
2982     }
2983   }
2984   return geomPublished;
2985 }
2986
2987 //================================================================================
2988 /*!
2989  * \brief Remember theCommand setting a parameter
2990  */
2991 //================================================================================
2992
2993 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2994 {
2995   // parameters are discriminated by method name
2996   _AString method = theCommand->GetMethod();
2997   if ( myAccumulativeMethods.count( method ))
2998     return; // this method adds values and not override the previus value
2999
3000   // discriminate commands setting different parameters via one method
3001   // by passing parameter names like e.g. SetOption("size", "0.2")
3002   if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3003        theCommand->GetNbArgs() > 1 )
3004   {
3005     // mangle method by appending a 1st textual arg
3006     for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3007     {
3008       const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3009       if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3010       if ( !isalpha( arg.Value(2))) continue;
3011       method += arg;
3012       break;
3013     }
3014   }
3015   // parameters are discriminated by method name
3016   list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3017   if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3018   {
3019     cmds.back()->Clear(); // previous parameter value has not been used
3020     cmds.back() = theCommand;
3021   }
3022   else
3023   {
3024     cmds.push_back( theCommand );
3025   }
3026 }
3027
3028 //================================================================================
3029 /*!
3030  * \brief Return true if a setting parameter command ha been used to compute mesh
3031  */
3032 //================================================================================
3033
3034 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3035                                          _pyCommand::TAddr          avoidComputeAddr ) const
3036 {
3037   bool isUsed = false;
3038   map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3039     myComputeAddr2Cmds.begin();
3040   for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3041   {
3042     if ( addr2cmds->first == avoidComputeAddr ) continue;
3043     const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3044     isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3045   }
3046   return isUsed;
3047 }
3048
3049 //================================================================================
3050 /*!
3051  * \brief Save commands setting parameters as they are used for a mesh computation
3052  */
3053 //================================================================================
3054
3055 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3056 {
3057   myComputeCmds.push_back( theComputeCmd );
3058   list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3059
3060   map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3061   for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3062     savedCmds.push_back( m2c->second.back() );
3063 }
3064
3065 //================================================================================
3066 /*!
3067  * \brief Clear commands setting parameters as a mesh computed using them is cleared
3068  */
3069 //================================================================================
3070
3071 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3072 {
3073   list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3074
3075   list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3076   for ( ; cmd != savedCmds.end(); ++cmd )
3077   {
3078     // check if a cmd has been used to compute another mesh
3079     if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3080       continue;
3081     // check if a cmd is a sole command setting its parameter;
3082     // don't use method name for search as it can change
3083     map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3084       m2cmds = myMeth2Commands.begin();
3085     for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3086     {
3087       list< Handle(_pyCommand)>& cmds = m2cmds->second;
3088       list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3089       if ( cmdIt != cmds.end() )
3090       {
3091         if ( cmds.back() != *cmd )
3092         {
3093           cmds.erase( cmdIt );
3094           (*cmd)->Clear();
3095         }
3096         break;
3097       }
3098     }
3099   }
3100   myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3101 }
3102
3103 //================================================================================
3104 /*!
3105  * \brief Sets an argNb-th argument of current creation command
3106  *  \param argNb - argument index countered from 1
3107  */
3108 //================================================================================
3109
3110 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3111 {
3112   if ( myCurCrMethod )
3113   {
3114     while ( myCurCrMethod->myArgs.size() < argNb )
3115       myCurCrMethod->myArgs.push_back( "None" );
3116     if ( arg.IsEmpty() )
3117       myCurCrMethod->myArgs[ argNb-1 ] = "None";
3118     else
3119       myCurCrMethod->myArgs[ argNb-1 ] = arg;
3120   }
3121 }
3122
3123
3124 //================================================================================
3125 /*!
3126  * \brief Remember hypothesis parameter values
3127  * \param theCommand - The called hypothesis method
3128  */
3129 //================================================================================
3130
3131 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3132 {
3133   if ( GetAlgoType() == "Cartesian_3D" )
3134   {
3135     // CartesianParameters3D hyp
3136
3137     if ( theCommand->GetMethod() == "SetSizeThreshold"  ||
3138          theCommand->GetMethod() == "SetToAddEdges" )
3139     {
3140       int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3141       setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3142       myArgCommands.push_back( theCommand );
3143       return;
3144     }
3145     if ( theCommand->GetMethod() == "SetGrid" ||
3146          theCommand->GetMethod() == "SetGridSpacing" )
3147     {
3148       TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3149       int iArg = axis.Value(1) - '0';
3150       if ( theCommand->GetMethod() == "SetGrid" )
3151       {
3152         setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3153       }
3154       else
3155       {
3156         myCurCrMethod->myArgs[ iArg ] = "[ ";
3157         myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3158         myCurCrMethod->myArgs[ iArg ] += ", ";
3159         myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3160         myCurCrMethod->myArgs[ iArg ] += "]";
3161       }
3162       myArgCommands.push_back( theCommand );
3163       //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3164       //                                  accumulative, else, if the creation
3165       //                 is not converted, commands for axes 1 and 2 are lost
3166       return;
3167     }
3168   }
3169
3170   if( theCommand->GetMethod() == "SetLength" )
3171   {
3172     // NOW it is OBSOLETE
3173     // ex: hyp.SetLength(start, 1)
3174     //     hyp.SetLength(end,   0)
3175     ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3176     int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3177     TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3178     for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3179     {
3180       CreationMethod& crMethod = type2meth->second;
3181         while ( crMethod.myArgs.size() < i+1 )
3182           crMethod.myArgs.push_back( "[]" );
3183         crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3184     }
3185     myArgCommands.push_back( theCommand );
3186   }
3187   else
3188   {
3189     _pyHypothesis::Process( theCommand );
3190   }
3191 }
3192 //================================================================================
3193 /*!
3194  * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3195  */
3196 //================================================================================
3197
3198 void _pyComplexParamHypo::Flush()
3199 {
3200   list < Handle(_pyCommand) >::iterator cmd;
3201   if ( IsWrapped() )
3202   {
3203     for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3204       if ((*cmd)->GetMethod() == "SetObjectEntry" )
3205         (*cmd)->Clear();
3206   }
3207
3208   // if ( GetAlgoType() == "Cartesian_3D" )
3209   // {
3210   //   _pyID algo = myCreationCmd->GetObject();
3211   //   for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3212   //   {
3213   //     if ( IsWrapped() )
3214   //     {
3215   //       StructToList( *cmd, /*checkMethod=*/false );
3216   //       const _AString & method = (*cmd)->GetMethod();
3217   //       if ( method == "SetFixedPoint" )
3218   //         (*cmd)->SetObject( algo );
3219   //     }
3220   //   }
3221   // }
3222 }
3223
3224 //================================================================================
3225 /*!
3226  * \brief Convert methods of 1D hypotheses to my own methods
3227  * \param theCommand - The called hypothesis method
3228  */
3229 //================================================================================
3230
3231 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3232 {
3233   if ( theCommand->GetMethod() != "SetLayerDistribution" )
3234     return;
3235
3236   const _pyID& hyp1dID = theCommand->GetArg( 1 );
3237   // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3238   // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3239   // {
3240   //   TCollection_AsciiString cmd =
3241   //     my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3242   //   Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3243   //   theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3244   //   hyp1d = my1dHyp;
3245   // }
3246   // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3247   // {
3248   //   // 1D hypo is already set, so distribution changes and the old
3249   //   // 1D hypo is thrown away
3250   //   my1dHyp->ClearAllCommands();
3251   // }
3252   // my1dHyp = hyp1d;
3253   // //my1dHyp->SetRemovedFromStudy( false );
3254
3255   // if ( !myArgCommands.empty() )
3256   //   myArgCommands.back()->Clear();
3257   myCurCrMethod->myArgs.push_back( hyp1dID );
3258   myArgCommands.push_back( theCommand );
3259 }
3260
3261 //================================================================================
3262 /*!
3263  * \brief
3264   * \param theAdditionCmd - command to be converted
3265   * \param theMesh - mesh instance
3266   * \retval bool - status
3267  */
3268 //================================================================================
3269
3270 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3271                                                   const _pyID&              theMesh)
3272 {
3273   myIsWrapped = false;
3274
3275   if ( my1dHyp.IsNull() )
3276     return false;
3277
3278   // set "SetLayerDistribution()" after addition cmd
3279   theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3280
3281   _pyID geom = theAdditionCmd->GetArg( 1 );
3282
3283   Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3284   if ( !algo.IsNull() )
3285   {
3286     my1dHyp->SetMesh( theMesh );
3287     my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3288                                   algo->GetAlgoType().ToCString());
3289     if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3290       return false;
3291
3292     // clear "SetLayerDistribution()" cmd
3293     myArgCommands.back()->Clear();
3294
3295     // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3296
3297     // find RadialPrism algo created on <geom> for theMesh
3298     GetCreationCmd()->SetObject( algo->GetID() );
3299     GetCreationCmd()->SetMethod( myAlgoMethod );
3300     GetCreationCmd()->RemoveArgs();
3301     theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3302     myIsWrapped = true;
3303   }
3304   return myIsWrapped;
3305 }
3306
3307 //================================================================================
3308 /*!
3309  * \brief
3310  */
3311 //================================================================================
3312
3313 void _pyLayerDistributionHypo::Flush()
3314 {
3315   // as creation of 1D hyp was written later then it's edition,
3316   // we need to find all it's edition calls and process them
3317   list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3318   _pyID prevNewName;
3319   for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3320   {    
3321     const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3322     if ( hyp1dID.IsEmpty() ) continue;
3323
3324     Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3325
3326     // make a new name for 1D hyp = "HypType" + "_Distribution"
3327     _pyID newName;
3328     if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3329     {
3330       if ( prevNewName.IsEmpty() ) continue;
3331       newName = prevNewName;
3332     }
3333     else
3334     {
3335       if ( hyp1d->IsWrapped() ) {
3336         newName = hyp1d->GetCreationCmd()->GetMethod();
3337       }
3338       else {
3339         TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3340         newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3341       }
3342       newName += "_Distribution";
3343       prevNewName = newName;
3344     
3345       hyp1d->GetCreationCmd()->SetResultValue( newName );
3346     }
3347     list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3348     list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3349     for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3350       const _pyID& objID = (*cmdIt)->GetObject();
3351       if ( objID == hyp1dID ) {
3352         if ( !hyp1d.IsNull() )
3353         {
3354           hyp1d->Process( *cmdIt );
3355           hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3356         }
3357         ( *cmdIt )->SetObject( newName );
3358       }
3359     }
3360     // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3361     (*cmd)->SetArg( 1, newName );
3362   }
3363 }
3364
3365 //================================================================================
3366 /*!
3367  * \brief additionally to Addition2Creation, clears SetDistrType() command
3368   * \param theCmd - AddHypothesis() command
3369   * \param theMesh - mesh to which a hypothesis is added
3370   * \retval bool - convertion result
3371  */
3372 //================================================================================
3373
3374 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3375                                                 const _pyID&              theMesh)
3376 {
3377   if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3378     // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3379     bool scaleDistrType = false;
3380     list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3381     for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3382       if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3383         if ( (*cmd)->GetArg( 1 ) == "1" ) {
3384           scaleDistrType = true;
3385           (*cmd)->Clear();
3386         }
3387         else if ( !scaleDistrType ) {
3388           // distribution type changed: remove scale factor from args
3389           TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3390           for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3391           {
3392             CreationMethod& crMethod = type2meth->second;
3393             if ( crMethod.myArgs.size() == 2 )
3394               crMethod.myArgs.pop_back();
3395           }
3396           break;
3397         }
3398       }
3399     }
3400   }
3401   return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3402 }
3403
3404 //================================================================================
3405 /*!
3406  * \brief remove repeated commands defining distribution
3407  */
3408 //================================================================================
3409
3410 void _pyNumberOfSegmentsHyp::Flush()
3411 {
3412   // find number of the last SetDistrType() command
3413   list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3414   int distrTypeNb = 0;
3415   for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3416     if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3417       if ( cmd != myUnusedCommands.rbegin() )
3418         distrTypeNb = (*cmd)->GetOrderNb();
3419     }
3420     else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3421       (*cmd)->Clear();
3422     }
3423   // clear commands before the last SetDistrType()
3424   list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3425   set< int > treatedCmdNbs; // avoid treating same cmd twice
3426   for ( int i = 0; i < 2; ++i ) {
3427     set<TCollection_AsciiString> uniqueMethods;
3428     list<Handle(_pyCommand)> & cmdList = *cmds[i];
3429     for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3430     {
3431       if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3432         continue;// avoid treating same cmd twice
3433       bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3434       const TCollection_AsciiString& method = (*cmd)->GetMethod();
3435       if ( !clear || method == "SetNumberOfSegments" ) {
3436         bool isNewInSet = uniqueMethods.insert( method ).second;
3437         clear = !isNewInSet;
3438       }
3439       if ( clear )
3440         (*cmd)->Clear();
3441     }
3442     cmdList.clear();
3443   }
3444 }
3445
3446 //================================================================================
3447 /*!
3448  * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3449  * into regular1D.LengthNearVertex( length, vertex )
3450   * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3451   * \param theMesh - The mesh needing this hypo
3452   * \retval bool - false if the command cant be converted
3453  */
3454 //================================================================================
3455
3456 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3457                                                          const _pyID&              theMeshID)
3458 {
3459   if ( IsWrappable( theMeshID )) {
3460
3461     _pyID vertex = theCmd->GetArg( 1 );
3462
3463     // the problem here is that segment algo will not be found
3464     // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3465     // geometry where segment algorithm is assigned
3466     Handle(_pyHypothesis) algo;
3467     _pyID geom = vertex;
3468     while ( algo.IsNull() && !geom.IsEmpty()) {
3469       // try to find geom as a father of <vertex>
3470       geom = FatherID( geom );
3471       algo = theGen->FindAlgo( geom, theMeshID, this );
3472     }
3473     if ( algo.IsNull() )
3474       return false; // also possible to find geom as brother of veretex...
3475     // set geom instead of vertex
3476     theCmd->SetArg( 1, geom );
3477
3478     // set vertex as a second arg
3479     if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3480     setCreationArg( 2, vertex );
3481
3482     // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3483     // theMeshID.LengthNearVertex( length, vertex )
3484     return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3485   }
3486   return false;
3487 }
3488
3489 //================================================================================
3490 /*!
3491  * \brief _pyAlgorithm constructor
3492  * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3493  */
3494 //================================================================================
3495
3496 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3497   : _pyHypothesis( theCreationCmd )
3498 {
3499   myIsAlgo = true;
3500 }
3501
3502 //================================================================================
3503 /*!
3504  * \brief Convert the command adding an algorithm to mesh
3505   * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3506   * \param theMesh - The mesh needing this algo
3507   * \retval bool - false if the command cant be converted
3508  */
3509 //================================================================================
3510
3511 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3512                                       const _pyID&              theMeshID)
3513 {
3514   // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3515   if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3516     theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3517     return true;
3518   }
3519   return false;
3520 }
3521
3522 //================================================================================
3523 /*!
3524  * \brief Return starting position of a part of python command
3525   * \param thePartIndex - The index of command part
3526   * \retval int - Part position
3527  */
3528 //================================================================================
3529
3530 int _pyCommand::GetBegPos( int thePartIndex ) const
3531 {
3532   if ( IsEmpty() )
3533     return EMPTY;
3534   if ( myBegPos.Length() < thePartIndex )
3535     return UNKNOWN;
3536   ASSERT( thePartIndex > 0 );
3537   return myBegPos( thePartIndex );
3538 }
3539
3540 //================================================================================
3541 /*!
3542  * \brief Store starting position of a part of python command
3543   * \param thePartIndex - The index of command part
3544   * \param thePosition - Part position
3545  */
3546 //================================================================================
3547
3548 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3549 {
3550   while ( myBegPos.Length() < thePartIndex )
3551     myBegPos.Append( UNKNOWN );
3552   ASSERT( thePartIndex > 0 );
3553   myBegPos( thePartIndex ) = thePosition;
3554 }
3555
3556 //================================================================================
3557 /*!
3558  * \brief Returns whitespace symbols at the line beginning
3559   * \retval TCollection_AsciiString - result
3560  */
3561 //================================================================================
3562
3563 TCollection_AsciiString _pyCommand::GetIndentation()
3564 {
3565   int end = 1;
3566   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3567     GetWord( myString, end, true );
3568   else
3569     end = GetBegPos( RESULT_IND );
3570   return myString.SubString( 1, Max( end - 1, 1 ));
3571 }
3572
3573 //================================================================================
3574 /*!
3575  * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3576   * \retval const TCollection_AsciiString & - ResultValue substring
3577  */
3578 //================================================================================
3579
3580 const TCollection_AsciiString & _pyCommand::GetResultValue()
3581 {
3582   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3583   {
3584     SetBegPos( RESULT_IND, EMPTY );
3585     int begPos, endPos = myString.Location( "=", 1, Length() );
3586     if ( endPos )
3587     {
3588       begPos = 1;
3589       while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3590       if ( begPos < endPos )
3591       {
3592         SetBegPos( RESULT_IND, begPos );
3593         --endPos;
3594         while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3595         myRes = myString.SubString( begPos, endPos );
3596       }
3597     }
3598   }
3599   return myRes;
3600 }
3601
3602 //================================================================================
3603 /*!
3604  * \brief Return number of python command result value ResultValue = Obj.Meth()
3605  */
3606 //================================================================================
3607
3608 int _pyCommand::GetNbResultValues()
3609 {
3610   GetResultValue(1);
3611   return myResults.Length();
3612 }
3613
3614
3615 //================================================================================
3616 /*!
3617  * \brief Return substring of python command looking like
3618  *  ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3619  * \retval const TCollection_AsciiString & - ResultValue with res index substring
3620  */
3621 //================================================================================
3622 const _AString& _pyCommand::GetResultValue(int res)
3623 {
3624   if ( GetResultValue().IsEmpty() )
3625     return theEmptyString;
3626
3627   if ( myResults.IsEmpty() )
3628   {
3629     int begPos = 1;
3630     if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3631       ++begPos; // skip [, else the whole list is returned
3632     while ( begPos < myRes.Length() ) {
3633       _AString result = GetWord( myRes, begPos, true );
3634       begPos += result.Length();
3635       // if(res == Nb) {
3636       //   result.RemoveAll('[');
3637       //   result.RemoveAll(']');
3638       //   return result;
3639       // }
3640       // if(Nb>res)
3641       //   break;
3642       myResults.Append( result );
3643     }
3644   }
3645   if ( res > 0 && res <= myResults.Length() )
3646     return myResults( res );
3647   return theEmptyString;
3648 }
3649
3650 //================================================================================
3651 /*!
3652  * \brief Return substring of python command looking like ResVal = Object.Meth()
3653  * \retval const TCollection_AsciiString & - Object substring
3654  */
3655 //================================================================================
3656
3657 const TCollection_AsciiString & _pyCommand::GetObject()
3658 {
3659   if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3660   {
3661     // beginning
3662     int begPos = GetBegPos( RESULT_IND );
3663     if ( begPos < 1 ) {
3664       begPos = myString.Location( "=", 1, Length() ) + 1;
3665       // is '=' in the string argument (for example, name) or not
3666       int nb1 = 0; // number of ' character at the left of =
3667       int nb2 = 0; // number of " character at the left of =
3668       for ( int i = 1; i < begPos-1; i++ ) {
3669         if ( myString.Value( i )=='\'' )
3670           nb1 += 1;
3671         else if ( myString.Value( i )=='"' )
3672           nb2 += 1;
3673       }
3674       // if number of ' or " is not divisible by 2,
3675       // then get an object at the start of the command
3676       if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3677         begPos = 1;
3678     }
3679     else {
3680       begPos += myRes.Length();
3681     }
3682     myObj = GetWord( myString, begPos, true );
3683     if ( begPos != EMPTY )
3684     {
3685       // check if object is complex,
3686       // so far consider case like "smesh.Method()"
3687       if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3688         //if ( bracketPos==0 ) bracketPos = Length();
3689         int dotPos = begPos+myObj.Length();
3690         while ( dotPos+1 < bracketPos ) {
3691           if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3692             dotPos = pos;
3693           else
3694             break;
3695         }
3696         if ( dotPos > begPos+myObj.Length() )
3697           myObj = myString.SubString( begPos, dotPos-1 );
3698       }
3699     }
3700     // 1st word after '=' is an object
3701     // else // no method -> no object
3702     // {
3703     //   myObj.Clear();
3704     //   begPos = EMPTY;
3705     // }
3706     // store
3707     SetBegPos( OBJECT_IND, begPos );
3708   }
3709   //SCRUTE(myObj);
3710   return myObj;
3711 }
3712
3713 //================================================================================
3714 /*!
3715  * \brief Return substring of python command looking like ResVal = Obj.Method()
3716   * \retval const TCollection_AsciiString & - Method substring
3717  */
3718 //================================================================================
3719
3720 const TCollection_AsciiString & _pyCommand::GetMethod()
3721 {
3722   if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3723   {
3724     // beginning
3725     int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3726     bool forward = true;
3727     if ( begPos < 1 ) {
3728       begPos = myString.Location( "(", 1, Length() ) - 1;
3729       forward = false;
3730     }
3731     // store
3732     myMeth = GetWord( myString, begPos, forward );
3733     SetBegPos( METHOD_IND, begPos );
3734   }
3735   //SCRUTE(myMeth);
3736   return myMeth;
3737 }
3738
3739 //================================================================================
3740 /*!
3741  * \brief Returns true if there are brackets after the method
3742  */
3743 //================================================================================
3744
3745 bool _pyCommand::IsMethodCall()
3746 {
3747   if ( GetMethod().IsEmpty() )
3748     return false;
3749   const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3750   return ( s[0] == '(' || s[1] == '(' );
3751 }
3752
3753 //================================================================================
3754 /*!
3755  * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3756   * \retval const TCollection_AsciiString & - Arg<index> substring
3757  */
3758 //================================================================================
3759
3760 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3761 {
3762   if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3763   {
3764     // Find all args
3765
3766     int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3767     if ( pos < 1 )
3768       pos = myString.Location( "(", 1, Length() );
3769     else
3770       --pos;
3771
3772     // we are at or before '(', skip it if present
3773     if ( pos > 0 ) {
3774       while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3775       if ( pos > Length() )
3776         pos = 0;
3777     }
3778     if ( pos < 1 ) {
3779       SetBegPos( ARG1_IND, 0 ); // even no '('
3780       return theEmptyString;
3781     }
3782     ++pos;
3783
3784     list< TCollection_AsciiString > separatorStack( 1, ",)");
3785     bool ignoreNesting = false;
3786     int prevPos = pos;
3787     while ( pos <= Length() )
3788     {
3789       const char chr = myString.Value( pos );
3790
3791       if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3792       {
3793         if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3794         {
3795           while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3796             ++prevPos;
3797           TCollection_AsciiString arg;
3798           if ( pos-1 >= prevPos ) {
3799             arg = myString.SubString( prevPos, pos-1 );
3800             arg.RightAdjust(); // remove spaces
3801             arg.LeftAdjust();
3802           }
3803           if ( !arg.IsEmpty() || chr == ',' )
3804           {
3805             SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3806             myArgs.Append( arg );
3807           }
3808           if ( chr == ')' )
3809             break;
3810           prevPos = pos+1;
3811         }
3812         else // end of nesting args found
3813         {
3814           separatorStack.pop_back();
3815           ignoreNesting = false;
3816         }
3817       }
3818       else if ( !ignoreNesting )
3819       {
3820         switch ( chr ) {
3821         case '(' : separatorStack.push_back(")"); break;
3822         case '[' : separatorStack.push_back("]"); break;
3823         case '\'': separatorStack.push_back("'");  ignoreNesting=true; break;
3824         case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3825         default:;
3826         }
3827       }
3828       ++pos;
3829     }
3830   }
3831   if ( myArgs.Length() < index )
3832     return theEmptyString;
3833   return myArgs( index );
3834 }
3835
3836 //================================================================================
3837 /*!
3838  * \brief Return position where arguments begin
3839  */
3840 //================================================================================
3841
3842 int _pyCommand::GetArgBeginning() const
3843 {
3844   int pos = GetBegPos( ARG1_IND );
3845   if ( pos == UNKNOWN )
3846   {
3847     pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3848     if ( pos < 1 )
3849       pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3850   }
3851   return pos;
3852 }
3853
3854 //================================================================================
3855 /*!
3856  * \brief Check if char is a word part
3857   * \param c - The character to check
3858   * \retval bool - The check result
3859  */
3860 //================================================================================
3861
3862 static inline bool isWord(const char c, const bool dotIsWord)
3863 {
3864   return
3865     !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3866 }
3867
3868 //================================================================================
3869 /*!
3870  * \brief Looks for a word in the string and returns word's beginning
3871   * \param theString - The input string
3872   * \param theStartPos - The position to start the search, returning word's beginning
3873   * \param theForward - The search direction
3874   * \retval TCollection_AsciiString - The found word
3875  */
3876 //================================================================================
3877
3878 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3879                                              int &            theStartPos,
3880                                              const bool       theForward,
3881                                              const bool       dotIsWord )
3882 {
3883   int beg = theStartPos, end = theStartPos;
3884   theStartPos = EMPTY;
3885   if ( beg < 1 || beg > theString.Length() )
3886     return theEmptyString;
3887
3888   if ( theForward ) { // search forward
3889     // beg
3890     while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3891       ++beg;
3892     if ( beg > theString.Length() )
3893       return theEmptyString; // no word found
3894     // end
3895     end = beg + 1;
3896     char begChar = theString.Value( beg );
3897     if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3898       char endChar = ( begChar == '[' ) ? ']' : begChar;
3899       // end is at the corresponding quoting mark or bracket
3900       while ( end < theString.Length() &&
3901               ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3902         ++end;
3903     }
3904     else {
3905       while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3906         ++end;
3907       --end;
3908     }
3909   }
3910   else {  // search backward
3911     // end
3912     while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3913       --end;
3914     if ( end == 0 )
3915       return theEmptyString; // no word found
3916     beg = end - 1;
3917     char endChar = theString.Value( end );
3918     if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3919       char begChar = ( endChar == ']' ) ? '[' : endChar;
3920       // beg is at the corresponding quoting mark
3921       while ( beg > 1 &&
3922               ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3923         --beg;
3924     }
3925     else {
3926       while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3927         --beg;
3928       ++beg;
3929     }
3930   }
3931   theStartPos = beg;
3932   //cout << theString << " ---- " << beg << " - " << end << endl;
3933   return theString.SubString( beg, end );
3934 }
3935
3936 //================================================================================
3937 /*!
3938  * \brief Returns true if the string looks like a study entry
3939  */
3940 //================================================================================
3941
3942 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3943 {
3944   if ( str.Length() < 5 ) return false;
3945
3946   int nbColons = 0, isColon;
3947   for ( int i = 1; i <= str.Length(); ++i )
3948   {
3949     char c = str.Value(i);
3950     if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3951       return false;
3952     nbColons += isColon;
3953   }
3954   return nbColons > 2 && str.Length()-nbColons > 2;
3955 }
3956
3957 //================================================================================
3958 /*!
3959  * \brief Returns true if the string looks like an object ID but not like a list,
3960  *        string, command etc.
3961  */
3962 //================================================================================
3963
3964 bool _pyCommand::IsID( const TCollection_AsciiString& str )
3965 {
3966   if ( str.Length() < 1 ) return false;
3967
3968   const char* s = str.ToCString();
3969
3970   for ( int i = 0; i < str.Length(); ++i )
3971     if ( !IsIDChar( s[i] ))
3972       return false;
3973
3974   return true;
3975 }
3976
3977 //================================================================================
3978 /*!
3979  * \brief Finds entries in a sting
3980  */
3981 //================================================================================
3982
3983 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3984 {
3985   std::list< _pyID > resList;
3986   int pos = 0;
3987   while ( ++pos <= str.Length() )
3988   {
3989     if ( !isdigit( str.Value( pos ))) continue;
3990     if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3991
3992     int end = pos;
3993     while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3994     _pyID entry = str.SubString( pos, end-1 );
3995     pos = end;
3996     if ( IsStudyEntry( entry ))
3997       resList.push_back( entry );
3998   }
3999   return resList;
4000 }
4001
4002 //================================================================================
4003 /*!
4004  * \brief Look for position where not space char is
4005   * \param theString - The string
4006   * \param thePos - The position to search from and which returns result
4007   * \retval bool - false if there are only space after thePos in theString
4008  */
4009 //================================================================================
4010
4011 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4012 {
4013   if ( thePos < 1 || thePos > theString.Length() )
4014     return false;
4015
4016   while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4017     ++thePos;
4018
4019   return thePos <= theString.Length();
4020 }
4021
4022 //================================================================================
4023 /*!
4024  * \brief Modify a part of the command
4025   * \param thePartIndex - The index of the part
4026   * \param thePart - The new part string
4027   * \param theOldPart - The old part
4028  */
4029 //================================================================================
4030
4031 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4032                         TCollection_AsciiString& theOldPart)
4033 {
4034   int pos = GetBegPos( thePartIndex );
4035   if ( pos <= Length() && theOldPart != thePart)
4036   {
4037     TCollection_AsciiString seperator;
4038     if ( pos < 1 ) {
4039       pos = GetBegPos( thePartIndex + 1 );
4040       if ( pos < 1 ) return;
4041       switch ( thePartIndex ) {
4042       case RESULT_IND: seperator = " = "; break;
4043       case OBJECT_IND: seperator = "."; break;
4044       case METHOD_IND: seperator = "()"; break;
4045       default:;
4046       }
4047     }
4048     myString.Remove( pos, theOldPart.Length() );
4049     if ( !seperator.IsEmpty() )
4050       myString.Insert( pos , seperator );
4051     myString.Insert( pos, thePart );
4052     // update starting positions of the following parts
4053     int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4054     for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4055       if ( myBegPos( i ) > 0 )
4056         myBegPos( i ) += posDelta;
4057     }
4058     theOldPart = thePart;
4059   }
4060 }
4061
4062 //================================================================================
4063 /*!
4064  * \brief Set agrument
4065   * \param index - The argument index, it counts from 1
4066   * \param theArg - The argument string
4067  */
4068 //================================================================================
4069
4070 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4071 {
4072   FindAllArgs();
4073   int argInd = ARG1_IND + index - 1;
4074   int pos = GetBegPos( argInd );
4075   if ( pos < 1 ) // no index-th arg exist, append inexistent args
4076   {
4077     // find a closing parenthesis
4078     if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4079       int lastArgInd = GetNbArgs();
4080       pos = GetBegPos( ARG1_IND + lastArgInd  - 1 ) + GetArg( lastArgInd ).Length();
4081       while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4082         ++pos;
4083     }
4084     else {
4085       pos = Length();
4086       while ( pos > 0 && myString.Value( pos ) != ')' )
4087         --pos;
4088     }
4089     if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4090       myString += "()";
4091       pos = Length();
4092     }
4093     while ( myArgs.Length() < index ) {
4094       if ( myArgs.Length() )
4095         myString.Insert( pos++, "," );
4096       myArgs.Append("None");
4097       myString.Insert( pos, myArgs.Last() );
4098       SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4099       pos += myArgs.Last().Length();
4100     }
4101   }
4102   SetPart( argInd, theArg, myArgs( index ));
4103 }
4104
4105 //================================================================================
4106 /*!
4107  * \brief Empty arg list
4108  */
4109 //================================================================================
4110
4111 void _pyCommand::RemoveArgs()
4112 {
4113   if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4114     myString.Trunc( pos );
4115   myString += ")";
4116   myArgs.Clear();
4117   if ( myBegPos.Length() >= ARG1_IND )
4118     myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4119 }
4120
4121 //================================================================================
4122 /*!
4123  * \brief Comment a python command
4124  */
4125 //================================================================================
4126
4127 void _pyCommand::Comment()
4128 {
4129   if ( IsEmpty() ) return;
4130
4131   int i = 1;
4132   while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4133   if ( i <= Length() )
4134   {
4135     myString.Insert( i, "#" );
4136     for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4137     {
4138       int begPos = GetBegPos( iPart );
4139       if ( begPos != UNKNOWN && begPos != EMPTY )
4140         SetBegPos( iPart, begPos + 1 );
4141     }
4142   }
4143 }
4144
4145 //================================================================================
4146 /*!
4147  * \brief Set dependent commands after this one
4148  */
4149 //================================================================================
4150
4151 bool _pyCommand::SetDependentCmdsAfter() const
4152 {
4153   bool orderChanged = false;
4154   list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4155   for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4156     if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4157       orderChanged = true;
4158       theGen->SetCommandAfter( *cmd, this );
4159       (*cmd)->SetDependentCmdsAfter();
4160     }
4161   }
4162   return orderChanged;
4163 }
4164 //================================================================================
4165 /*!
4166  * \brief Insert accessor method after theObjectID
4167   * \param theObjectID - id of the accessed object
4168   * \param theAcsMethod - name of the method giving access to the object
4169   * \retval bool - false if theObjectID is not found in the command string
4170  */
4171 //================================================================================
4172
4173 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4174 {
4175   if ( !theAcsMethod )
4176     return false;
4177   // start object search from the object, i.e. ignore result
4178   GetObject();
4179   int beg = GetBegPos( OBJECT_IND );
4180   if ( beg < 1 || beg > Length() )
4181     return false;
4182   bool added = false;
4183   while (( beg = myString.Location( theObjectID, beg, Length() )))
4184   {
4185     // check that theObjectID is not just a part of a longer ID
4186     int afterEnd = beg + theObjectID.Length();
4187     Standard_Character c = myString.Value( afterEnd );
4188     if ( !IsIDChar( c ))
4189     {
4190       // check if accessor method already present
4191       if ( c != '.' ||
4192            myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4193         // insertion
4194         int oldLen = Length();
4195         myString.Insert( afterEnd, (char*) theAcsMethod );
4196         myString.Insert( afterEnd, "." );
4197         // update starting positions of the parts following the modified one
4198         int posDelta = Length() - oldLen;
4199         for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4200           if ( myBegPos( i ) > afterEnd )
4201             myBegPos( i ) += posDelta;
4202         }
4203         added = true;
4204       }
4205     }
4206     beg = afterEnd; // is a part -> next search
4207   }
4208   return added;
4209 }
4210
4211 //================================================================================
4212 /*!
4213  * \brief Creates pyObject
4214  */
4215 //================================================================================
4216
4217 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4218   : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4219 {
4220   setID( theID );
4221 }
4222
4223 //================================================================================
4224 /*!
4225  * \brief Set up myID and myIsPublished
4226  */
4227 //================================================================================
4228
4229 void _pyObject::setID(const _pyID& theID)
4230 {
4231   myID = theID;
4232   myIsPublished = !theGen->IsNotPublished( GetID() );
4233 }
4234
4235 //================================================================================
4236 /*!
4237  * \brief Clear myCreationCmd and myProcessedCmds
4238  */
4239 //================================================================================
4240
4241 void _pyObject::ClearCommands()
4242 {
4243   if ( !CanClear() )
4244     return;
4245
4246   if ( !myCreationCmd.IsNull() )
4247     myCreationCmd->Clear();
4248
4249   list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4250   for ( ; cmd != myProcessedCmds.end(); ++cmd )
4251     (*cmd)->Clear();
4252 }
4253
4254 //================================================================================
4255 /*!
4256  * \brief Return method name giving access to an interaface object wrapped by python class
4257   * \retval const char* - method name
4258  */
4259 //================================================================================
4260
4261 const char* _pyObject::AccessorMethod() const
4262 {
4263   return 0;
4264 }
4265 //================================================================================
4266 /*!
4267  * \brief Return ID of a father
4268  */
4269 //================================================================================
4270
4271 _pyID _pyObject::FatherID(const _pyID & childID)
4272 {
4273   int colPos = childID.SearchFromEnd(':');
4274   if ( colPos > 0 )
4275     return childID.SubString( 1, colPos-1 );
4276   return "";
4277 }
4278
4279 //================================================================================
4280 /*!
4281  * \brief SelfEraser erases creation command if none of it's commands invoked
4282  *        (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4283  */
4284 //================================================================================
4285
4286 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4287   :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4288 {
4289   myIsPublished = true; // prevent clearing as a not published
4290   theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4291 }
4292
4293 //================================================================================
4294 /*!
4295  * \brief SelfEraser erases creation command if none of it's commands invoked
4296  *        (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4297  */
4298 //================================================================================
4299
4300 bool _pySelfEraser::CanClear()
4301 {
4302   bool toErase = false;
4303   if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4304   {
4305     int nbArgUses = 0;
4306     list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4307     for ( ; cmd != myArgCmds.end(); ++cmd )
4308       nbArgUses += IsAliveCmd( *cmd );
4309
4310     toErase = ( nbArgUses < 1 );
4311   }
4312   else
4313   {
4314     int nbCalls = 0;
4315     std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4316     std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4317     for ( ; cmd != cmds.end();  )
4318       // check of cmd emptiness is not enough as object can change
4319       if (( *cmd )->GetString().Search( GetID() ) > 0 )
4320         ++nbCalls, ++cmd;
4321       else
4322         cmd = cmds.erase( cmd ); // save the cmd from clearing
4323
4324     toErase = ( nbCalls < 1 );
4325   }
4326   return toErase;
4327 }
4328
4329 //================================================================================
4330 /*!
4331  * \brief Check if a command is or can be cleared
4332  */
4333 //================================================================================
4334
4335 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4336 {
4337   if ( theCmd->IsEmpty() )
4338     return false;
4339
4340   if ( !theGen->IsToKeepAllCommands() )
4341   {
4342     const _pyID& objID = theCmd->GetObject();
4343     Handle( _pyObject ) obj = theGen->FindObject( objID );
4344     if ( !obj.IsNull() )
4345       return !obj->CanClear();
4346   }
4347   return true;
4348 }
4349
4350 //================================================================================
4351 /*!
4352  * \brief SelfEraser erases creation command if none of it's commands invoked
4353  *        (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4354  */
4355 //================================================================================
4356
4357 void _pySelfEraser::Flush()
4358 {
4359   if ( CanClear() )
4360   {
4361     myIsPublished = false;
4362     _pyObject::ClearCommands();
4363   }
4364 }
4365
4366 //================================================================================
4367 /*!
4368  * \brief _pySubMesh constructor
4369  */
4370 //================================================================================
4371
4372 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4373   _pyObject(theCreationCmd)
4374 {
4375   myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4376   if ( toKeepAgrCmds )
4377     theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4378 }
4379
4380 //================================================================================
4381 /*!
4382  * \brief Return true if a sub-mesh can be used as argument of the given method
4383  */
4384 //================================================================================
4385
4386 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4387 {
4388   return false;
4389 //   // names of all methods where a sub-mesh can be used as argument
4390 //   static TStringSet methods;
4391 //   if ( methods.empty() ) {
4392 //     const char * names[] = {
4393 //       // methods of SMESH_Gen
4394 //       "CopyMesh",
4395 //       // methods of SMESH_Group
4396 //       "AddFrom",
4397 //       // methods of SMESH_Measurements
4398 //       "MinDistance",
4399 //       // methods of SMESH_Mesh
4400 //       "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4401 //       "RemoveSubMesh",
4402 //       // methods of SMESH_MeshEditor
4403 //       "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4404 //       "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4405 //       "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4406 //       "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4407 //       "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4408 //       "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4409 //       "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4410 //       "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4411 //       "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4412 //       "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4413 //       "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4414 //       "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4415 //       "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4416 //       "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4417 //       "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4418 //       "" }; // <- mark of end
4419 //     methods.Insert( names );
4420 //   }
4421 //   return methods.Contains( theMethodName );
4422 }
4423
4424 //================================================================================
4425 /*!
4426  * \brief count invoked commands
4427  */
4428 //================================================================================
4429
4430 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4431 {
4432   _pyObject::Process(theCommand); // count calls of Process()
4433 }
4434
4435 //================================================================================
4436 /*!
4437  * \brief Move creation command depending on invoked commands
4438  */
4439 //================================================================================
4440
4441 void _pySubMesh::Flush()
4442 {
4443   if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4444     theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4445   else if ( !myCreator.IsNull() )
4446     // move to be just after creator
4447     myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4448
4449   // move sub-mesh usage after creation cmd
4450   list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4451   for ( ; cmd != myArgCmds.end(); ++cmd )
4452     if ( !(*cmd)->IsEmpty() )
4453       GetCreationCmd()->AddDependantCmd( *cmd );
4454 }
4455
4456 //================================================================================
4457 /*!
4458  * \brief Creates _pyGroup
4459  */
4460 //================================================================================
4461
4462 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4463   :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4464 {
4465   if ( !id.IsEmpty() )
4466     setID( id );
4467
4468   myCanClearCreationCmd = true;
4469
4470   const _AString& method = theCreationCmd->GetMethod();
4471   if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4472   {
4473     theCreationCmd->SetMethod( "CreateEmptyGroup" );
4474   }
4475   // ----------------------------------------------------------------------
4476   else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4477   {
4478     _pyID geom = theCreationCmd->GetArg( 3 );
4479     // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4480     // next if(){...} section is commented
4481     //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4482     //  theCreationCmd->SetMethod( "Group" );
4483     //  theCreationCmd->RemoveArgs();
4484     //  theCreationCmd->SetArg( 1, geom );
4485     //}
4486     //else {
4487     // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4488       _pyID type = theCreationCmd->GetArg( 1 );
4489       _pyID name = theCreationCmd->GetArg( 2 );
4490       theCreationCmd->SetMethod( "GroupOnGeom" );
4491       theCreationCmd->RemoveArgs();
4492       theCreationCmd->SetArg( 1, geom );
4493       theCreationCmd->SetArg( 2, name );
4494       theCreationCmd->SetArg( 3, type );
4495     //}
4496   }
4497   else if ( method == "CreateGroupFromFilter" )
4498   {
4499     // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4500     theCreationCmd->SetMethod( "GroupOnFilter" );
4501
4502     _pyID filterID = theCreationCmd->GetArg(3);
4503     Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4504     if ( !filter.IsNull())
4505     {
4506       if ( !filter->GetNewID().IsEmpty() )
4507         theCreationCmd->SetArg( 3, filter->GetNewID() );
4508       //filter->AddUser( this );
4509     }
4510     myFilter = filter;
4511   }
4512   else if ( method == "GetGroups" )
4513   {
4514     myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4515   }
4516   else
4517   {
4518     // theCreationCmd does something else apart from creation of this group
4519     // and thus it can't be cleared if this group is removed
4520     myCanClearCreationCmd = false;
4521   }
4522 }
4523
4524 //================================================================================
4525 /*!
4526  * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command 
4527  *        can be cleared
4528  */
4529 //================================================================================
4530
4531 bool _pyGroup::CanClear()
4532 {
4533   if ( IsInStudy() )
4534     return false;
4535
4536   if ( !myCanClearCreationCmd &&
4537        !myCreationCmd.IsNull() &&
4538        myCreationCmd->GetMethod() == "GetGroups" )
4539   {
4540     TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4541     list< _pyID >          idList = myCreationCmd->GetStudyEntries( grIDs );
4542     list< _pyID >::iterator  grID = idList.begin();
4543     if ( GetID() == *grID )
4544     {
4545       myCanClearCreationCmd = true;
4546       list< Handle(_pyGroup ) > groups;
4547       for ( ; grID != idList.end(); ++grID )
4548       {
4549         Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4550         if ( group.IsNull() ) continue;
4551         groups.push_back( group );
4552         if ( group->IsInStudy() )
4553           myCanClearCreationCmd = false;
4554       }
4555       // set myCanClearCreationCmd == true to all groups
4556       list< Handle(_pyGroup ) >::iterator group = groups.begin();
4557       for ( ; group != groups.end(); ++group )
4558         (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4559     }
4560   }
4561
4562   return myCanClearCreationCmd;
4563 }
4564
4565 //================================================================================
4566 /*!
4567  * \brief set myCanClearCreationCmd = true if the main action of the creation
4568  *        command is discarded
4569  */
4570 //================================================================================
4571
4572 void _pyGroup::RemovedWithContents()
4573 {
4574   // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4575   // via a created group
4576   //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4577   // myCanClearCreationCmd = true;
4578 }
4579
4580 //================================================================================
4581 /*!
4582  * \brief To convert creation of a group by filter
4583  */
4584 //================================================================================
4585
4586 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4587 {
4588   // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4589   // group = mesh.CreateEmptyGroup( elemType, groupName )
4590   // aFilter.SetMesh(mesh)
4591   // nbAdd = group.AddFrom( aFilter )
4592   Handle(_pyFilter) filter;
4593   if ( theCommand->GetMethod() == "AddFrom" )
4594   {
4595     _pyID idSource = theCommand->GetArg(1);
4596     // check if idSource is a filter
4597     filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4598     if ( !filter.IsNull() )
4599     {
4600       // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4601       list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4602       while ( *cmdIt != theCommand ) ++cmdIt;
4603       while ( (*cmdIt)->GetOrderNb() != 1 )
4604       {
4605         const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4606         if ((setMeshCmd->GetObject() == idSource ||
4607              setMeshCmd->GetObject() == filter->GetNewID() )
4608             &&
4609             setMeshCmd->GetMethod() == "SetMesh")
4610         {
4611           setMeshCmd->Clear();
4612           break;
4613         }
4614       }
4615       // replace 3 commands by one
4616       theCommand->Clear();
4617       const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4618       TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4619       if ( !filter->GetNewID().IsEmpty() )
4620         idSource = filter->GetNewID();
4621       makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4622       makeGroupCmd->SetArg( 1, name );
4623       makeGroupCmd->SetArg( 2, idSource );
4624       filter->AddArgCmd( makeGroupCmd );
4625     }
4626   }
4627   else if ( theCommand->GetMethod() == "SetFilter" )
4628   {
4629     // set new name of a filter or clear the command if the same filter is set
4630     _pyID filterID = theCommand->GetArg(1);
4631     filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4632     if ( !myFilter.IsNull() && filter == myFilter )
4633       theCommand->Clear();
4634     else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4635       theCommand->SetArg( 1, filter->GetNewID() );
4636     myFilter = filter;
4637   }
4638   else if ( theCommand->GetMethod() == "GetFilter" )
4639   {
4640     // GetFilter() returns a filter with other ID, make myFilter process
4641     // calls of the returned filter
4642     if ( !myFilter.IsNull() )
4643     {
4644       theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4645       theCommand->Clear();
4646     }
4647   }
4648
4649   // if ( !filter.IsNull() )
4650   //   filter->AddUser( this );
4651
4652   theGen->AddMeshAccessorMethod( theCommand );
4653 }
4654
4655 //================================================================================
4656 /*!
4657  * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4658  */
4659 //================================================================================
4660
4661 void _pyGroup::Flush()
4662 {
4663   if ( !theGen->IsToKeepAllCommands() &&
4664        !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4665   {
4666     myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4667   }
4668 }
4669
4670 //================================================================================
4671 /*!
4672  * \brief Constructor of _pyFilter
4673  */
4674 //================================================================================
4675
4676 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4677   :_pyObject(theCreationCmd), myNewID( newID )
4678 {
4679   //myIsPublished = true; // prevent clearing as a not published
4680   theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4681 }
4682
4683 //================================================================================
4684 /*!
4685  * \brief To convert creation of a filter by criteria and
4686  * to replace an old name by a new one
4687  */
4688 //================================================================================
4689
4690 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4691 {
4692   if ( theCommand->GetObject() == GetID() )
4693     _pyObject::Process(theCommand); // count commands
4694
4695   if ( !myNewID.IsEmpty() )
4696     theCommand->SetObject( myNewID );
4697     
4698   // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4699   // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4700   // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4701   if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4702        theCommand->GetMethod() == "SetCriteria")
4703   {
4704     // aFilter.SetCriteria(aCriteria) ->
4705     // aFilter = smesh.GetFilterFromCriteria(criteria)
4706     if ( myNewID.IsEmpty() )
4707       theCommand->SetResultValue( GetID() );
4708     else
4709       theCommand->SetResultValue( myNewID );
4710     theCommand->SetObject( SMESH_2smeshpy::GenName() );
4711     theCommand->SetMethod( "GetFilterFromCriteria" );
4712
4713     // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4714     GetCreationCmd()->Clear();
4715     GetCreationCmd()->GetString() = theCommand->GetString();
4716     theCommand->Clear();
4717     theCommand->AddDependantCmd( GetCreationCmd() );
4718     // why swap? -- it's needed
4719     //GetCreationCmd()->Clear();
4720   }
4721   else if ( theCommand->GetMethod() == "SetMesh" )
4722   {
4723     if ( myMesh == theCommand->GetArg( 1 ))
4724       theCommand->Clear();
4725     else
4726       myMesh = theCommand->GetArg( 1 );
4727     theGen->AddMeshAccessorMethod( theCommand );
4728   }
4729 }
4730
4731 //================================================================================
4732 /*!
4733  * \brief Set new filter name to the creation command and to myArgCmds
4734  */
4735 //================================================================================
4736
4737 void _pyFilter::Flush()
4738 {
4739   if ( myNewID.IsEmpty() ) return;
4740   
4741   list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4742   for ( ; cmd != myArgCmds.end(); ++cmd )
4743     if ( !(*cmd)->IsEmpty() )
4744     {
4745       _AString cmdStr = (*cmd)->GetString();
4746       _AString id     = GetID();
4747       int pos = cmdStr.Search( id );
4748       if ( pos > 0 )
4749       {
4750         cmdStr.Remove( pos, id.Length() );
4751         cmdStr.Insert( pos, myNewID );
4752       }
4753       (*cmd)->Clear();
4754       (*cmd)->GetString() = cmdStr;
4755     }
4756
4757   if ( !GetCreationCmd()->IsEmpty() )
4758     GetCreationCmd()->SetResultValue( myNewID );
4759 }
4760
4761 //================================================================================
4762 /*!
4763  * \brief Return true if all my users can be cleared
4764  */
4765 //================================================================================
4766
4767 bool _pyObject::CanClear()
4768 {
4769   list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4770   for ( ; cmd != myArgCmds.end(); ++cmd )
4771     if ( !(*cmd)->IsEmpty() )
4772     {
4773       Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4774       if ( !obj.IsNull() && !obj->CanClear() )
4775         return false;
4776     }
4777   return ( !myIsPublished );
4778 }
4779
4780 //================================================================================
4781 /*!
4782  * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4783  */
4784 //================================================================================
4785
4786 _pyHypothesisReader::_pyHypothesisReader()
4787 {
4788   // Read xml files
4789   vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4790   LDOMParser xmlParser;
4791   for ( size_t i = 0; i < xmlPaths.size(); ++i )
4792   {
4793     bool error = xmlParser.parse( xmlPaths[i].c_str() );
4794     if ( error )
4795     {
4796       _AString data;
4797       INFOS( xmlParser.GetError(data) );
4798       continue;
4799     }
4800     // <algorithm type="Regular_1D"
4801     //            label-id="Wire discretisation"
4802     //            ...>
4803     //   <python-wrap>
4804     //     <algo>Regular_1D=Segment()</algo>
4805     //     <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4806     //
4807     LDOM_Document xmlDoc = xmlParser.getDocument();
4808     LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4809     for ( int i = 0; i < algoNodeList.getLength(); ++i )
4810     {
4811       LDOM_Node     algoNode = algoNodeList.item( i );
4812       LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4813       LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4814       if ( pyAlgoNodeList.getLength() < 1 ) continue;
4815
4816       _AString text, algoType, method, arg;
4817       for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4818       {
4819         LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4820         LDOM_Node textNode   = pyAlgoNode.getFirstChild();
4821         text = textNode.getNodeValue();
4822         Handle(_pyCommand) algoCmd = new _pyCommand( text );
4823         algoType = algoCmd->GetResultValue();
4824         method   = algoCmd->GetMethod();
4825         arg      = algoCmd->GetArg(1);
4826         if ( !algoType.IsEmpty() && !method.IsEmpty() )
4827         {
4828           Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4829           algo->SetConvMethodAndType( method, algoType );
4830           if ( !arg.IsEmpty() )
4831             algo->setCreationArg( 1, arg );
4832
4833           myType2Hyp[ algoType ] = algo;
4834           break;
4835         }
4836       }
4837       if ( algoType.IsEmpty() ) continue;
4838
4839       LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4840       _AString hypType;
4841       Handle( _pyHypothesis ) hyp;
4842       for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4843       {
4844         LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4845         LDOM_Node textNode   = pyHypoNode.getFirstChild();
4846         text = textNode.getNodeValue();
4847         Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4848         hypType = hypoCmd->GetResultValue();
4849         method  = hypoCmd->GetMethod();
4850         if ( !hypType.IsEmpty() && !method.IsEmpty() )
4851         {
4852           map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4853           if ( type2hyp == myType2Hyp.end() )
4854             hyp = new _pyHypothesis( hypoCmd );
4855           else
4856             hyp = type2hyp->second;
4857           hyp->SetConvMethodAndType( method, algoType );
4858           for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4859           {
4860             _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4861             _AString argMethod = argCmd.GetMethod();
4862             _AString argNbText = argCmd.GetArg( 1 );
4863             if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4864               hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4865             else
4866               hyp->AddArgMethod( argMethod,
4867                                  argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4868           }
4869           myType2Hyp[ hypType ] = hyp;
4870         }
4871       }
4872     }
4873     // <hypothesis type="BLSURF_Parameters"
4874     //          ...
4875     //          dim="2">
4876     //   <python-wrap>
4877     //     <accumulative-methods> 
4878     //       SetEnforcedVertex,
4879     //       SetEnforcedVertexNamed
4880     //     </accumulative-methods>
4881     //   </python-wrap>
4882     // </hypothesis>
4883     //
4884     LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4885     for ( int i = 0; i < hypNodeList.getLength(); ++i )
4886     {
4887       LDOM_Node     hypNode      = hypNodeList.item( i );
4888       LDOM_Element& hypElem      = (LDOM_Element&) hypNode;
4889       _AString      hypType      = hypElem.getAttribute("type");
4890       LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4891       if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4892
4893       map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4894       if ( type2hyp == myType2Hyp.end() ) continue;
4895
4896       LDOM_Node methNode = methNodeList.item( 0 );
4897       LDOM_Node textNode = methNode.getFirstChild();
4898       _AString      text = textNode.getNodeValue();
4899       _AString method;
4900       int pos = 1;
4901       do {
4902         method = _pyCommand::GetWord( text, pos, /*forward= */true );
4903         pos += method.Length();
4904         type2hyp->second->AddAccumulativeMethod( method );
4905       }
4906       while ( !method.IsEmpty() );
4907     }
4908
4909   } // loop on xmlPaths
4910 }
4911
4912 //================================================================================
4913 /*!
4914  * \brief Returns a new hypothesis initialized according to the read information
4915  */
4916 //================================================================================
4917
4918 Handle(_pyHypothesis)
4919 _pyHypothesisReader::GetHypothesis(const _AString&           hypType,
4920                                    const Handle(_pyCommand)& creationCmd) const
4921 {
4922   Handle(_pyHypothesis) resHyp, sampleHyp;
4923
4924   map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4925   if ( type2hyp != myType2Hyp.end() )
4926     sampleHyp = type2hyp->second;
4927
4928   if ( sampleHyp.IsNull() )
4929   {
4930     resHyp = new _pyHypothesis(creationCmd);
4931   }
4932   else
4933   {
4934     if ( sampleHyp->IsAlgo() )
4935       resHyp = new _pyAlgorithm( creationCmd );
4936     else
4937       resHyp = new _pyHypothesis(creationCmd);
4938     resHyp->Assign( sampleHyp, _pyID() );
4939   }
4940   return resHyp;
4941 }
4942
4943 //================================================================================
4944 /*!
4945  * \brief Adds an object ID to some family of IDs with a common prefix
4946  *  \param [in] str - the object ID
4947  *  \return bool - \c false if \a str does not have the same prefix as \a this family
4948  *          (for internal usage)
4949  */
4950 //================================================================================
4951
4952 bool _pyStringFamily::Add( const char* str )
4953 {
4954   if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
4955     return false; // expected prefix is missing
4956
4957   str += _prefix.Length(); // skip _prefix
4958
4959   // try to add to some of child falimies
4960   std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4961   for ( ; itSub != _subFams.end(); ++itSub )
4962     if ( itSub->Add( str ))
4963       return true;
4964
4965   // no suitable family found - add str to _strings or create a new child family
4966
4967   // look for a proper place within sorted _strings
4968   std::list< _AString >::iterator itStr = _strings.begin();
4969   while ( itStr != _strings.end() && itStr->IsLess( str ))
4970     ++itStr;
4971   if ( itStr != _strings.end() && itStr->IsEqual( str ))
4972     return true; // same ID already kept
4973
4974   const int minPrefixSize = 4;
4975
4976   // count "smaller" strings with the same prefix
4977   std::list< _AString >::iterator itLess = itStr; --itLess;
4978   int nbLess = 0;
4979   for ( ; itLess != _strings.end(); --itLess )
4980     if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
4981       ++nbLess;
4982     else
4983       break;
4984   ++itLess;
4985   // count "greater" strings with the same prefix
4986   std::list< _AString >::iterator itMore = itStr;
4987   int nbMore = 0;
4988   for ( ; itMore != _strings.end(); ++itMore )
4989     if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
4990       ++nbMore;
4991     else
4992       break;
4993   --itMore;
4994   if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
4995   {
4996     // look for a maximal prefix length
4997     // int lessPrefSize = 3, morePrefSize = 3;
4998     // if ( nbLess > 0 )
4999     //   while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ]  )
5000     //     ++lessPrefSize;
5001     // if ( nbMore > 0 )
5002     //   while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
5003     //     ++morePrefSize;
5004     // int prefixSize = 3;
5005     // if ( nbLess == 0 )
5006     //   prefixSize = morePrefSize;
5007     // else if ( nbMore == 0 )
5008     //   prefixSize = lessPrefSize;
5009     // else
5010     //   prefixSize = Min( lessPrefSize, morePrefSize );
5011     int prefixSize = minPrefixSize;
5012     _AString newPrefix ( str, prefixSize );
5013
5014     // look for a proper place within _subFams sorted by _prefix
5015     for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5016       if ( !itSub->_prefix.IsLess( newPrefix ))
5017         break;
5018
5019     // add the new _pyStringFamily
5020     itSub = _subFams.insert( itSub, _pyStringFamily());
5021     _pyStringFamily& newSubFam = *itSub;
5022     newSubFam._prefix = newPrefix;
5023
5024     // pass this->_strings to newSubFam._strings
5025     for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5026       newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5027     newSubFam._strings.push_back( str + prefixSize );
5028     for ( ; nbMore > 0; --nbMore, ++itStr )
5029       newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5030
5031     _strings.erase( itLess, ++itMore );
5032   }
5033   else // to few string to make a family fot them
5034   {
5035     _strings.insert( itStr, str );
5036   }
5037   return true;
5038 }
5039
5040 //================================================================================
5041 /*!
5042  * \brief Finds an object ID in the command
5043  *  \param [in] longStr - the command string
5044  *  \param [out] subStr - the found object ID
5045  *  \return bool - \c true if the object ID found
5046  */
5047 //================================================================================
5048
5049 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5050 {
5051   const _AString& longStr = cmd->GetString();
5052   const char*           s = longStr.ToCString();
5053
5054   // look in _subFams
5055   std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5056   int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5057   if ( argBeg < 4 || argBeg > longStr.Length() )
5058     return false;
5059   for ( ; itSub != _subFams.end(); ++itSub )
5060   {
5061     from = argBeg;
5062     while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5063       if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5064       {
5065         subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5066         from = pos + len + itSub->_prefix.Length();
5067         nbFound++;
5068       }
5069       else
5070       {
5071         from += itSub->_prefix.Length();
5072       }
5073   }
5074   // look among _strings
5075   std::list< _AString >::iterator itStr = _strings.begin();
5076   for ( ; itStr != _strings.end(); ++itStr )
5077     if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5078       // check that object ID does not continue after len
5079       if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5080       {
5081         subStr.push_back( *itStr );
5082         nbFound++;
5083       }
5084   return nbFound;
5085 }
5086
5087 //================================================================================
5088 /*!
5089  * \brief Return remainder length of the object ID after my _prefix
5090  *  \param [in] str - remainder of the command after my _prefix
5091  *  \return int - length of the object ID or -1 if not found
5092  */
5093 //================================================================================
5094
5095 int _pyStringFamily::isIn( const char* str )
5096 {
5097   std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5098   int len = -1;
5099   for ( ; itSub != _subFams.end(); ++itSub )
5100   {
5101     int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5102     if ( cmp == 0 )
5103     {
5104       if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5105         return itSub->_prefix.Length() + len;
5106     }
5107     else if ( cmp > 0 )
5108       break;
5109   }
5110   if ( !_strings.empty() )
5111   {
5112     std::list< _AString >::iterator itStr = _strings.begin();
5113     bool firstEmpty = itStr->IsEmpty();
5114     if ( firstEmpty )
5115       ++itStr, len = 0;
5116     for ( ; itStr != _strings.end(); ++itStr )
5117     {
5118       int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5119       if ( cmp == 0 )
5120       {
5121         len = itStr->Length();
5122         break;
5123       }
5124       else if ( cmp < 0 )
5125       {
5126         break;
5127       }
5128     }
5129
5130     // check that object ID does not continue after len
5131     if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5132       len = -1;
5133   }
5134
5135   return len;
5136 }
5137
5138 //================================================================================
5139 /*!
5140  * \brief DEBUG
5141  */
5142 //================================================================================
5143
5144 void _pyStringFamily::Print( int level )
5145 {
5146   cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5147   std::list< _AString >::iterator itStr = _strings.begin();
5148   for ( ; itStr != _strings.end(); ++itStr )
5149     cout << *itStr << " | ";
5150   cout << endl;
5151   std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5152   for ( ; itSub != _subFams.end(); ++itSub )
5153     itSub->Print( level + 1 );
5154   if ( level == 0 )
5155     cout << string( 70, '-' ) << endl;
5156 }
5157