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