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