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