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