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