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