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