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