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