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