Salome HOME
0022100: EDF 2413 SMESH: Take into account TRIA7
[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 Remove object name from myObjectNames 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   // update list of groups
1620   else if ( method == "GetGroups" )
1621   {
1622     TCollection_AsciiString grIDs = theCommand->GetResultValue();
1623     list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1624     list< _pyID >::iterator grID = idList.begin();
1625     for ( ; grID != idList.end(); ++grID )
1626     {
1627       Handle(_pyObject) obj = theGen->FindObject( *grID );
1628       if ( obj.IsNull() )
1629       {
1630         Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1631         theGen->AddObject( group );
1632         myGroups.push_back( group );
1633       }
1634     }
1635   }
1636   // notify a group about full removal
1637   else if ( method == "RemoveGroupWithContents" )
1638   {
1639     if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1640       const _pyID groupID = theCommand->GetArg( 1 );
1641       Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1642       if ( !grp.IsNull() )
1643         grp->RemovedWithContents();
1644     }
1645   }
1646   // ----------------------------------------------------------------------
1647   else if ( theCommand->MethodStartsFrom( "Export" ))
1648   {
1649     if ( method == "ExportToMED" ||   // ExportToMED()  --> ExportMED()
1650          method == "ExportToMEDX" ) { // ExportToMEDX() --> ExportMED()
1651       theCommand->SetMethod( "ExportMED" );
1652     }
1653     else if ( method == "ExportCGNS" )
1654     { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1655       _pyID partID = theCommand->GetArg( 1 );
1656       int nbArgs = theCommand->GetNbArgs();
1657       for ( int i = 2; i <= nbArgs; ++i )
1658         theCommand->SetArg( i-1, theCommand->GetArg( i ));
1659       theCommand->SetArg( nbArgs, partID );
1660     }
1661     else if ( method == "ExportGMF" )
1662     { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1663       _pyID partID  = theCommand->GetArg( 1 );
1664       _AString file = theCommand->GetArg( 2 );
1665       theCommand->RemoveArgs();
1666       theCommand->SetArg( 1, file );
1667       theCommand->SetArg( 2, partID );
1668     }
1669     else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1670     { // ExportPartTo*(part, ...) -> Export*(..., part)
1671       //
1672       // remove "PartTo" from the method
1673       TCollection_AsciiString newMethod = method;
1674       newMethod.Remove( 7, 6 );
1675       theCommand->SetMethod( newMethod );
1676       // make the 1st arg be the last one
1677       _pyID partID = theCommand->GetArg( 1 );
1678       int nbArgs = theCommand->GetNbArgs();
1679       for ( int i = 2; i <= nbArgs; ++i )
1680         theCommand->SetArg( i-1, theCommand->GetArg( i ));
1681       theCommand->SetArg( nbArgs, partID );
1682     }
1683     // remember file name
1684     theGen->AddExportedMesh( theCommand->GetArg( 1 ),
1685                              ExportedMeshData( this, myLastComputeCmd ));
1686   }
1687   // ----------------------------------------------------------------------
1688   else if ( method == "RemoveHypothesis" ) // (geom, hyp)
1689   {
1690     _pyID hypID  = theCommand->GetArg( 2 );
1691     _pyID geomID = theCommand->GetArg( 1 );
1692     bool isLocal = ( geomID != GetGeom() );
1693
1694     // check if this mesh still has corresponding addition command
1695     Handle(_pyCommand) addCmd;
1696     list< Handle(_pyCommand) >::iterator cmd;
1697     list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
1698     for ( int i = 0; i < 2; ++i )
1699     {
1700       list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
1701       for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
1702       {
1703         bool sameHyp = true;
1704         if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
1705           sameHyp = false; // other hyp
1706         if ( (*cmd)->GetNbArgs() == 2 &&
1707              geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
1708           sameHyp = false; // other geom
1709         if ( (*cmd)->GetNbArgs() == 1 && isLocal )
1710           sameHyp = false; // other geom
1711         if ( sameHyp )
1712         {
1713           addCmd = *cmd;
1714           cmd    = addHypCmds.erase( cmd );
1715           if ( !theGen->IsToKeepAllCommands() ) {
1716             addCmd->Clear();
1717             theCommand->Clear();
1718           }
1719         }
1720         else
1721         {
1722           ++cmd;
1723         }
1724       }
1725     }
1726     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1727     if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
1728       // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
1729       _pyID geom = theCommand->GetArg( 1 );
1730       theCommand->RemoveArgs();
1731       theCommand->SetArg( 1, hypID );
1732       if ( geom != GetGeom() )
1733         theCommand->SetArg( 2, geom );
1734     }
1735     // remove hyp from myHypos
1736     myHypos.remove( hyp );
1737   }
1738   // check for SubMesh order commands
1739   else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
1740   {
1741     // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
1742     // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
1743     // commands are moved at the end of the script
1744     TCollection_AsciiString subIDs =
1745       ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
1746     list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
1747     list< _pyID >::iterator subID = idList.begin();
1748     for ( ; subID != idList.end(); ++subID )
1749     {
1750       Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
1751       if ( !subMesh.IsNull() )
1752         subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
1753     }
1754   }
1755   // add accessor method if necessary
1756   else
1757   {
1758     if ( NeedMeshAccess( theCommand ))
1759       // apply theCommand to the mesh wrapped by smeshpy mesh
1760       AddMeshAccess( theCommand );
1761   }
1762 }
1763
1764 //================================================================================
1765 /*!
1766  * \brief Return True if addition of accesor method is needed
1767  */
1768 //================================================================================
1769
1770 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
1771 {
1772   // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
1773   // so no conversion is needed for them at all:
1774   static TStringSet sameMethods;
1775   if ( sameMethods.empty() ) {
1776     const char * names[] =
1777       { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
1778         "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
1779         "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
1780         "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
1781         "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
1782         "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
1783         "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
1784         "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
1785         "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
1786         "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
1787         "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
1788         "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
1789         "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
1790         ,"" }; // <- mark of end
1791     sameMethods.Insert( names );
1792   }
1793
1794   return !sameMethods.Contains( theCommand->GetMethod() );
1795 }
1796
1797 //================================================================================
1798 /*!
1799  * \brief Convert creation and addition of all algos and hypos
1800  */
1801 //================================================================================
1802
1803 void _pyMesh::Flush()
1804 {
1805   {
1806     // get the meshes this mesh depends on via hypotheses
1807     list< Handle(_pyMesh) > fatherMeshes;
1808     list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1809     for ( ; hyp != myHypos.end(); ++hyp )
1810       if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
1811         myGeomNotInStudy = true;
1812
1813     list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
1814     for ( ; m != fatherMeshes.end(); ++m )
1815       addFatherMesh( *m );
1816     // if ( removedGeom )
1817     //     SetRemovedFromStudy(); // as reffered geometry not in study
1818   }
1819   if ( myGeomNotInStudy )
1820     return;
1821
1822   list < Handle(_pyCommand) >::iterator cmd;
1823
1824   // try to convert algo addition like this:
1825   // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
1826   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
1827   {
1828     Handle(_pyCommand) addCmd = *cmd;
1829
1830     _pyID algoID = addCmd->GetArg( 2 );
1831     Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
1832     if ( algo.IsNull() || !algo->IsAlgo() )
1833       continue;
1834
1835     // check and create new algorithm instance if it is already wrapped
1836     if ( algo->IsWrapped() ) {
1837       _pyID localAlgoID = theGen->GenerateNewID( algoID );
1838       TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
1839         TCollection_AsciiString( " = " ) + theGen->GetID() +
1840         TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
1841         TCollection_AsciiString( "\" )" );
1842
1843       Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
1844       Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
1845       if ( !newAlgo.IsNull() ) {
1846         newAlgo->Assign( algo, this->GetID() );
1847         newAlgo->SetCreationCmd( newCmd );
1848         algo = newAlgo;
1849         // set algorithm creation
1850         theGen->SetCommandBefore( newCmd, addCmd );
1851         myHypos.push_back( newAlgo );
1852         if ( !myLastComputeCmd.IsNull() &&
1853              newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
1854           newAlgo->MeshComputed( myLastComputeCmd );
1855       }
1856       else
1857         newCmd->Clear();
1858     }
1859     _pyID geom = addCmd->GetArg( 1 );
1860     bool isLocalAlgo = ( geom != GetGeom() );
1861
1862     // try to convert
1863     if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
1864     {
1865       // wrapped algo is created after mesh creation
1866       GetCreationCmd()->AddDependantCmd( addCmd );
1867
1868       if ( isLocalAlgo ) {
1869         // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
1870         addCmd->SetArg( addCmd->GetNbArgs() + 1,
1871                         TCollection_AsciiString( "geom=" ) + geom );
1872         // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
1873         list < Handle(_pySubMesh) >::iterator smIt;
1874         for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
1875           Handle(_pySubMesh) subMesh = *smIt;
1876           Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
1877           if ( geom == subCmd->GetArg( 1 )) {
1878             subCmd->SetObject( algo->GetID() );
1879             subCmd->RemoveArgs();
1880             subMesh->SetCreator( algo );
1881           }
1882         }
1883       }
1884     }
1885     else // KO - ALGO was already created
1886     {
1887       // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
1888       addCmd->RemoveArgs();
1889       addCmd->SetArg( 1, algoID );
1890       if ( isLocalAlgo )
1891         addCmd->SetArg( 2, geom );
1892       myNotConvertedAddHypCmds.push_back( addCmd );
1893     }
1894   }
1895
1896   // try to convert hypo addition like this:
1897   // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
1898   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
1899   {
1900     Handle(_pyCommand) addCmd = *cmd;
1901     _pyID hypID = addCmd->GetArg( 2 );
1902     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1903     if ( hyp.IsNull() || hyp->IsAlgo() )
1904       continue;
1905     bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
1906     if ( !converted ) {
1907       // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
1908       _pyID geom = addCmd->GetArg( 1 );
1909       addCmd->RemoveArgs();
1910       addCmd->SetArg( 1, hypID );
1911       if ( geom != GetGeom() )
1912         addCmd->SetArg( 2, geom );
1913       myNotConvertedAddHypCmds.push_back( addCmd );
1914     }
1915   }
1916
1917   myAddHypCmds.clear();
1918   mySubmeshes.clear();
1919
1920   // flush hypotheses
1921   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1922   for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1923     (*hyp)->Flush();
1924 }
1925
1926 //================================================================================
1927 /*!
1928  * \brief Sets myIsPublished of me and of all objects depending on me.
1929  */
1930 //================================================================================
1931
1932 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
1933 {
1934   _pyObject::SetRemovedFromStudy(isRemoved);
1935
1936   list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
1937   for ( ; sm != mySubmeshes.end(); ++sm )
1938     (*sm)->SetRemovedFromStudy(isRemoved);
1939
1940   list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
1941   for ( ; gr != myGroups.end(); ++gr )
1942     (*gr)->SetRemovedFromStudy(isRemoved);
1943
1944   list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
1945   for ( ; m != myChildMeshes.end(); ++m )
1946     (*m)->SetRemovedFromStudy(isRemoved);
1947
1948   list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1949   for ( ; e != myEditors.end(); ++e )
1950     (*e)->SetRemovedFromStudy(isRemoved);
1951 }
1952
1953 //================================================================================
1954 /*!
1955  * \brief Return true if none of myChildMeshes is in study
1956  */
1957 //================================================================================
1958
1959 bool _pyMesh::CanClear()
1960 {
1961   if ( IsInStudy() )
1962     return false;
1963
1964   list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
1965   for ( ; m != myChildMeshes.end(); ++m )
1966     if ( !(*m)->CanClear() )
1967       return false;
1968
1969   return true;
1970 }
1971
1972 //================================================================================
1973 /*!
1974  * \brief Clear my commands and commands of mesh editor
1975  */
1976 //================================================================================
1977
1978 void _pyMesh::ClearCommands()
1979 {
1980   if ( !CanClear() )
1981   {
1982     if ( !IsInStudy() )
1983     {
1984       // mark all sub-objects as not removed, except child meshes
1985       list< Handle(_pyMesh) > children;
1986       children.swap( myChildMeshes );
1987       SetRemovedFromStudy( false );
1988       children.swap( myChildMeshes );
1989     }
1990     return;
1991   }
1992   _pyObject::ClearCommands();
1993
1994   list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
1995   for ( ; sm != mySubmeshes.end(); ++sm )
1996     (*sm)->ClearCommands();
1997   
1998   list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
1999   for ( ; gr != myGroups.end(); ++gr )
2000     (*gr)->ClearCommands();
2001
2002   list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2003   for ( ; e != myEditors.end(); ++e )
2004     (*e)->ClearCommands();
2005 }
2006
2007 //================================================================================
2008 /*!
2009  * \brief Add a father mesh by ID
2010  */
2011 //================================================================================
2012
2013 void _pyMesh::addFatherMesh( const _pyID& meshID )
2014 {
2015   if ( !meshID.IsEmpty() && meshID != GetID() )
2016     addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2017 }
2018
2019 //================================================================================
2020 /*!
2021  * \brief Add a father mesh
2022  */
2023 //================================================================================
2024
2025 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2026 {
2027   if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2028   {
2029     //myFatherMeshes.push_back( mesh );
2030     mesh->myChildMeshes.push_back( this );
2031
2032     // protect last Compute() from clearing by the next Compute()
2033     mesh->myLastComputeCmd.Nullify();
2034   }
2035 }
2036
2037 //================================================================================
2038 /*!
2039  * \brief MeshEditor convert its commands to ones of mesh
2040  */
2041 //================================================================================
2042
2043 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2044   _pyObject( theCreationCmd )
2045 {
2046   myMesh = theCreationCmd->GetObject();
2047   myCreationCmdStr = theCreationCmd->GetString();
2048   theCreationCmd->Clear();
2049
2050   Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2051   if ( !mesh.IsNull() )
2052     mesh->AddEditor( this );
2053 }
2054
2055 //================================================================================
2056 /*!
2057  * \brief convert its commands to ones of mesh
2058  */
2059 //================================================================================
2060
2061 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2062 {
2063   // names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2064   // commands calling this methods are converted to calls of Mesh methods
2065   static TStringSet sameMethods;
2066   if ( sameMethods.empty() ) {
2067     const char * names[] = {
2068       "RemoveElements","RemoveNodes","RemoveOrphanNodes","AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2069       "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces","MoveNode", "MoveClosestNodeToPoint",
2070       "InverseDiag","DeleteDiag","Reorient","ReorientObject",
2071       "TriToQuad","TriToQuadObject", "SplitQuad","SplitQuadObject",
2072       "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2073       "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2074       "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2075       "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
2076       "ExtrusionAlongPath","ExtrusionAlongPathObject","ExtrusionAlongPathX",
2077       "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2078       "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2079       "FindCoincidentNodes",/*"FindCoincidentNodesOnPart",*/"MergeNodes","FindEqualElements",
2080       "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2081       "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2082       "GetLastCreatedElems",
2083       "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh",
2084       "TranslateObjectMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2085       "MakeBoundaryElements", "SplitVolumesIntoTetra"
2086       ,"" }; // <- mark of the end
2087     sameMethods.Insert( names );
2088   }
2089
2090   // names of SMESH_MeshEditor commands in which only a method name must be replaced
2091   TStringMap diffMethods;
2092   if ( diffMethods.empty() ) {
2093     const char * orig2newName[] = {
2094       // original name --------------> new name
2095       "ExtrusionAlongPathObjX"      , "ExtrusionAlongPathX",
2096       "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2097       "ConvertToQuadraticObject"    , "ConvertToQuadratic",
2098       "ConvertFromQuadraticObject"  , "ConvertFromQuadratic",
2099       "Create0DElementsOnAllNodes"  , "Add0DElementsToAllNodes",
2100       ""};// <- mark of the end
2101     diffMethods.Insert( orig2newName );
2102   }
2103
2104   // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2105   // only by last two arguments
2106   static TStringSet diffLastTwoArgsMethods;
2107   if (diffLastTwoArgsMethods.empty() ) {
2108     const char * names[] = {
2109       "MirrorMakeGroups","MirrorObjectMakeGroups",
2110       "TranslateMakeGroups","TranslateObjectMakeGroups",
2111       "RotateMakeGroups","RotateObjectMakeGroups",
2112       ""};// <- mark of the end
2113     diffLastTwoArgsMethods.Insert( names );
2114   }
2115
2116   // only a method name is to change?
2117   const TCollection_AsciiString & method = theCommand->GetMethod();
2118   bool isPyMeshMethod = sameMethods.Contains( method );
2119   if ( !isPyMeshMethod )
2120   {
2121     TCollection_AsciiString newMethod = diffMethods.Value( method );
2122     if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2123       theCommand->SetMethod( newMethod );
2124   }
2125   // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2126   if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2127   {
2128     isPyMeshMethod = true;
2129     theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2130     theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2131   }
2132
2133   if ( !isPyMeshMethod )
2134   {
2135     // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2136     // functions with the flag "theMakeGroups = True" like:
2137     // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2138     int pos = method.Search("MakeGroups");
2139     if( pos != -1)
2140     {
2141       isPyMeshMethod = true;
2142       bool is0DmethId  = ( method == "ExtrusionSweepMakeGroups0D" );
2143       bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2144
2145       // 1. Remove "MakeGroups" from the Command
2146       TCollection_AsciiString aMethod = theCommand->GetMethod();
2147       int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2148       
2149       if(is0DmethObj)
2150         pos = pos-2;  //Remove "0D" from the Command too
2151       aMethod.Trunc(pos-1);
2152       theCommand->SetMethod(aMethod);
2153
2154       // 2. And add last "True" argument(s)
2155       while(nbArgsToAdd--)
2156         theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2157       if( is0DmethId || is0DmethObj )
2158         theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2159     }
2160   }
2161
2162   // ExtrusionSweep0D()       -> ExtrusionSweep()
2163   // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2164   if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D"  ||
2165                             method == "ExtrusionSweepObject0D" ))
2166   {
2167     isPyMeshMethod = true;
2168     theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2169     theCommand->SetArg(theCommand->GetNbArgs()+1,"False");  //sets flag "MakeGroups = False"
2170     theCommand->SetArg(theCommand->GetNbArgs()+1,"True");  //sets flag "IsNode = True"
2171   }
2172
2173   // DoubleNode...New(...) -> DoubleNode...(...,True)
2174   if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew"  ||
2175                             method == "DoubleNodeElemGroupsNew" ||
2176                             method == "DoubleNodeGroupNew"      ||
2177                             method == "DoubleNodeGroupsNew"     ||
2178                             method == "DoubleNodeElemGroup2New" ||
2179                             method == "DoubleNodeElemGroups2New"))
2180   {
2181     isPyMeshMethod = true;
2182     const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2183     theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2184     if ( excessLen == 3 )
2185     {
2186       theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2187     }
2188     else if ( theCommand->GetArg(4) == "0" ||
2189               theCommand->GetArg(5) == "0" )
2190     {
2191       // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2192       // Group = DoubleNodeGroup2New(,,,False, True)
2193       _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2194       theCommand->SetResultValue( groupID );
2195     }
2196   }
2197   // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2198   // FindElementsByPoint(x, y, z, elementType, meshPart)
2199   if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2200   {
2201     isPyMeshMethod = true;
2202     theCommand->SetMethod( "FindElementsByPoint" );
2203     // make the 1st arg be the last one
2204     _pyID partID = theCommand->GetArg( 1 );
2205     int nbArgs = theCommand->GetNbArgs();
2206     for ( int i = 2; i <= nbArgs; ++i )
2207       theCommand->SetArg( i-1, theCommand->GetArg( i ));
2208     theCommand->SetArg( nbArgs, partID );
2209   }
2210   // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2211   if ( !isPyMeshMethod && method == "Reorient2D" )
2212   {
2213     isPyMeshMethod = true;
2214     _AString mesh  = theCommand->GetArg( 1 );
2215     _AString dir   = theCommand->GetArg( 2 );
2216     _AString face  = theCommand->GetArg( 3 );
2217     _AString point = theCommand->GetArg( 4 );
2218     theCommand->RemoveArgs();
2219     theCommand->SetArg( 1, mesh );
2220     theCommand->SetArg( 2, dir );
2221     if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2222       theCommand->SetArg( 3, point );
2223     else
2224       theCommand->SetArg( 3, face );
2225   }
2226
2227   if ( method == "QuadToTri" || method == "QuadToTriObject" )
2228   {
2229     isPyMeshMethod = true;
2230     int crit_arg = theCommand->GetNbArgs();
2231     const _AString& crit = theCommand->GetArg(crit_arg);
2232     if (crit.Search("MaxElementLength2D") != -1)
2233       theCommand->SetArg(crit_arg, "");
2234   }
2235
2236   if ( isPyMeshMethod )
2237   {
2238     theCommand->SetObject( myMesh );
2239   }
2240   else
2241   {
2242     // editor creation command is needed only if any editor function is called
2243     theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2244     if ( !myCreationCmdStr.IsEmpty() ) {
2245       GetCreationCmd()->GetString() = myCreationCmdStr;
2246       myCreationCmdStr.Clear();
2247     }
2248   }
2249 }
2250
2251 //================================================================================
2252 /*!
2253  * \brief Return true if my mesh can be removed
2254  */
2255 //================================================================================
2256
2257 bool _pyMeshEditor::CanClear()
2258 {
2259   Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2260   return mesh.IsNull() ? true : mesh->CanClear();
2261 }
2262
2263 //================================================================================
2264 /*!
2265  * \brief _pyHypothesis constructor
2266   * \param theCreationCmd -
2267  */
2268 //================================================================================
2269
2270 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2271   _pyObject( theCreationCmd ), myCurCrMethod(0)
2272 {
2273   myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2274 }
2275
2276 //================================================================================
2277 /*!
2278  * \brief Creates algorithm or hypothesis
2279   * \param theCreationCmd - The engine command creating a hypothesis
2280   * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2281  */
2282 //================================================================================
2283
2284 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2285 {
2286   // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2287   ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2288
2289   Handle(_pyHypothesis) hyp, algo;
2290
2291   // "theHypType"
2292   const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2293   if ( hypTypeQuoted.IsEmpty() )
2294     return hyp;
2295   // theHypType
2296   TCollection_AsciiString  hypType =
2297     hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2298
2299   algo = new _pyAlgorithm( theCreationCmd );
2300   hyp  = new _pyHypothesis( theCreationCmd );
2301
2302   if ( hypType == "NumberOfSegments" ) {
2303     hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2304     hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2305     // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2306     hyp->AddArgMethod( "SetNumberOfSegments" );
2307     // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2308     hyp->AddArgMethod( "SetScaleFactor" );
2309     hyp->AddArgMethod( "SetReversedEdges" );
2310     // same for ""CompositeSegment_1D:
2311     hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2312     hyp->AddArgMethod( "SetNumberOfSegments" );
2313     hyp->AddArgMethod( "SetScaleFactor" );
2314     hyp->AddArgMethod( "SetReversedEdges" );
2315   }
2316   else if ( hypType == "SegmentLengthAroundVertex" ) {
2317     hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2318     hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2319     hyp->AddArgMethod( "SetLength" );
2320     // same for ""CompositeSegment_1D:
2321     hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2322     hyp->AddArgMethod( "SetLength" );
2323   }
2324   else if ( hypType == "LayerDistribution2D" ) {
2325     hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2326     hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2327   }
2328   else if ( hypType == "LayerDistribution" ) {
2329     hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2330     hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2331   }
2332   else if ( hypType == "CartesianParameters3D" ) {
2333     hyp = new _pyComplexParamHypo( theCreationCmd );
2334     hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2335     for ( int iArg = 0; iArg < 4; ++iArg )
2336       hyp->setCreationArg( iArg+1, "[]");
2337   }
2338   else
2339   {
2340     hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2341   }
2342
2343   return algo->IsValid() ? algo : hyp;
2344 }
2345
2346 //================================================================================
2347 /*!
2348  * \brief Returns true if addition of this hypothesis to a given mesh can be
2349  *        wrapped into hypothesis creation
2350  */
2351 //================================================================================
2352
2353 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2354 {
2355   if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2356   {
2357     Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2358     if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2359       return true;
2360   }
2361   return false;
2362 }
2363
2364 //================================================================================
2365 /*!
2366  * \brief Convert the command adding a hypothesis to mesh into a smesh command
2367   * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2368   * \param theAlgo - The algo that can create this hypo
2369   * \retval bool - false if the command cant be converted
2370  */
2371 //================================================================================
2372
2373 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2374                                        const _pyID&              theMesh)
2375 {
2376   ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2377
2378   if ( !IsWrappable( theMesh ))
2379     return false;
2380
2381   myGeom = theCmd->GetArg( 1 );
2382
2383   Handle(_pyHypothesis) algo;
2384   if ( !IsAlgo() ) {
2385     // find algo created on myGeom in theMesh
2386     algo = theGen->FindAlgo( myGeom, theMesh, this );
2387     if ( algo.IsNull() )
2388       return false;
2389     // attach hypothesis creation command to be after algo creation command
2390     // because it can be new created instance of algorithm
2391     algo->GetCreationCmd()->AddDependantCmd( theCmd );
2392   }
2393   myIsWrapped = true;
2394
2395   // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2396   theCmd->SetResultValue( GetID() );
2397   theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2398   theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2399   // set args (geom will be set by _pyMesh calling this method)
2400   theCmd->RemoveArgs();
2401   for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2402     if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2403       theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2404     else
2405       theCmd->SetArg( i+1, "[]");
2406   }
2407   // set a new creation command
2408   GetCreationCmd()->Clear();
2409   // replace creation command by wrapped instance
2410   // please note, that hypothesis attaches to algo creation command (see upper)
2411   SetCreationCmd( theCmd );
2412
2413
2414   // clear commands setting arg values
2415   list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2416   for ( ; argCmd != myArgCommands.end(); ++argCmd )
2417     (*argCmd)->Clear();
2418
2419   // set unknown arg commands after hypo creation
2420   Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2421   list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2422   for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2423     afterCmd->AddDependantCmd( *cmd );
2424   }
2425
2426   return myIsWrapped;
2427 }
2428
2429 //================================================================================
2430 /*!
2431  * \brief Remember hypothesis parameter values
2432  * \param theCommand - The called hypothesis method
2433  */
2434 //================================================================================
2435
2436 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2437 {
2438   ASSERT( !myIsAlgo );
2439   if ( !theGen->IsToKeepAllCommands() )
2440     rememberCmdOfParameter( theCommand );
2441   // set args
2442   bool usedCommand = false;
2443   TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2444   for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2445   {
2446     CreationMethod& crMethod = type2meth->second;
2447     for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2448       if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2449         if ( !usedCommand )
2450           myArgCommands.push_back( theCommand );
2451         usedCommand = true;
2452         while ( crMethod.myArgs.size() < i+1 )
2453           crMethod.myArgs.push_back( "[]" );
2454         crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2455       }
2456     }
2457   }
2458   if ( !usedCommand )
2459     myUnusedCommands.push_back( theCommand );
2460 }
2461
2462 //================================================================================
2463 /*!
2464  * \brief Finish conversion
2465  */
2466 //================================================================================
2467
2468 void _pyHypothesis::Flush()
2469 {
2470   if ( !IsAlgo() )
2471   {
2472     list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2473     for ( ; cmd != myArgCommands.end(); ++cmd ) {
2474       // Add access to a wrapped mesh
2475       theGen->AddMeshAccessorMethod( *cmd );
2476       // Add access to a wrapped algorithm
2477       theGen->AddAlgoAccessorMethod( *cmd );
2478     }
2479     cmd = myUnusedCommands.begin();
2480     for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2481       // Add access to a wrapped mesh
2482       theGen->AddMeshAccessorMethod( *cmd );
2483       // Add access to a wrapped algorithm
2484       theGen->AddAlgoAccessorMethod( *cmd );
2485     }
2486   }
2487   // forget previous hypothesis modifications
2488   myArgCommands.clear();
2489   myUnusedCommands.clear();
2490 }
2491
2492 //================================================================================
2493 /*!
2494  * \brief clear creation, arg and unkown commands
2495  */
2496 //================================================================================
2497
2498 void _pyHypothesis::ClearAllCommands()
2499 {
2500   GetCreationCmd()->Clear();
2501   list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2502   for ( ; cmd != myArgCommands.end(); ++cmd )
2503     ( *cmd )->Clear();
2504   cmd = myUnusedCommands.begin();
2505   for ( ; cmd != myUnusedCommands.end(); ++cmd )
2506     ( *cmd )->Clear();
2507 }
2508
2509
2510 //================================================================================
2511 /*!
2512  * \brief Assign fields of theOther to me except myIsWrapped
2513  */
2514 //================================================================================
2515
2516 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2517                             const _pyID&                 theMesh )
2518 {
2519   // myCreationCmd = theOther->myCreationCmd;
2520   myIsAlgo                  = theOther->myIsAlgo;
2521   myIsWrapped               = false;
2522   myGeom                    = theOther->myGeom;
2523   myMesh                    = theMesh;
2524   myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2525   myAccumulativeMethods     = theOther->myAccumulativeMethods;
2526   //myUnusedCommands          = theOther->myUnusedCommands;
2527   // init myCurCrMethod
2528   GetCreationMethod( theOther->GetAlgoType() );
2529 }
2530
2531 //================================================================================
2532 /*!
2533  * \brief Analyze my erasability depending on myReferredObjs
2534  */
2535 //================================================================================
2536
2537 bool _pyHypothesis::CanClear()
2538 {
2539   if ( IsInStudy() )
2540   {
2541     list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2542     for ( ; obj != myReferredObjs.end(); ++obj )
2543       if ( (*obj)->CanClear() )
2544         return true;
2545     return false;
2546   }
2547   return true;
2548 }
2549
2550 //================================================================================
2551 /*!
2552  * \brief Clear my commands depending on usage by meshes
2553  */
2554 //================================================================================
2555
2556 void _pyHypothesis::ClearCommands()
2557 {
2558   // if ( !theGen->IsToKeepAllCommands() )
2559   // {
2560   //   bool isUsed = false;
2561   //   int lastComputeOrder = 0;
2562   //   list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2563   //   for ( ; cmd != myComputeCmds.end(); ++cmd )
2564   //     if ( ! (*cmd)->IsEmpty() )
2565   //     {
2566   //       isUsed = true;
2567   //       if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2568   //         lastComputeOrder = (*cmd)->GetOrderNb();
2569   //     }
2570   //   if ( !isUsed )
2571   //   {
2572   //     SetRemovedFromStudy( true );
2573   //   }
2574   //   else
2575   //   {
2576   //     // clear my commands invoked after lastComputeOrder
2577   //     // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2578   //     // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2579   //     // {
2580   //     //   list< Handle(_pyCommand)> & cmds = m2c->second;
2581   //     //   if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2582   //     //     cmds.back()->Clear();
2583   //     // }
2584   //   }
2585   // }
2586   _pyObject::ClearCommands();
2587 }
2588
2589 //================================================================================
2590 /*!
2591  * \brief Find arguments that are objects like mesh, group, geometry
2592  *  \param meshes - referred meshes (directly or indirrectly)
2593  *  \retval bool - false if a referred geometry is not in the study
2594  */
2595 //================================================================================
2596
2597 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2598 {
2599   if ( IsAlgo() ) return true;
2600
2601   bool geomPublished = true;
2602   vector< _AString > args;
2603   TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2604   for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2605   {
2606     CreationMethod& crMethod = type2meth->second;
2607     args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2608   }
2609   list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2610   for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2611     for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2612       args.push_back( (*cmd)->GetArg( nb ));
2613   }
2614
2615   for ( size_t i = 0; i < args.size(); ++i )
2616   {
2617     list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2618     if ( idList.empty() && !args[ i ].IsEmpty() )
2619       idList.push_back( args[ i ]);
2620     list< _pyID >::iterator id = idList.begin();
2621     for ( ; id != idList.end(); ++id )
2622     {
2623       Handle(_pyObject)   obj = theGen->FindObject( *id );
2624       if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2625       if ( obj.IsNull() )
2626       {
2627         if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2628           geomPublished = false;
2629       }
2630       else
2631       {
2632         myReferredObjs.push_back( obj );
2633         Handle(_pyMesh) mesh = ObjectToMesh( obj );
2634         if ( !mesh.IsNull() )
2635           meshes.push_back( mesh );
2636         // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2637         else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2638           obj->SetRemovedFromStudy( false );
2639       }
2640     }
2641   }
2642   return geomPublished;
2643 }
2644
2645 //================================================================================
2646 /*!
2647  * \brief Remember theCommand setting a parameter
2648  */
2649 //================================================================================
2650
2651 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2652 {
2653   // parameters are discriminated by method name
2654   _AString method = theCommand->GetMethod();
2655   if ( myAccumulativeMethods.count( method ))
2656     return; // this method adds values and not override the previus value
2657
2658   // discriminate commands setting different parameters via one method
2659   // by passing parameter names like e.g. SetOption("size", "0.2")
2660   if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
2661        theCommand->GetNbArgs() > 1 )
2662   {
2663     // mangle method by appending a 1st textual arg
2664     for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
2665     {
2666       const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
2667       if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
2668       if ( !isalpha( arg.Value(2))) continue;
2669       method += arg;
2670       break;
2671     }
2672   }
2673   // parameters are discriminated by method name
2674   list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
2675   if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
2676   {
2677     cmds.back()->Clear(); // previous parameter value has not been used
2678     cmds.back() = theCommand;
2679   }
2680   else
2681   {
2682     cmds.push_back( theCommand );
2683   }
2684 }
2685
2686 //================================================================================
2687 /*!
2688  * \brief Return true if a setting parameter command ha been used to compute mesh
2689  */
2690 //================================================================================
2691
2692 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
2693                                          _pyCommand::TAddr          avoidComputeAddr ) const
2694 {
2695   bool isUsed = false;
2696   map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
2697     myComputeAddr2Cmds.begin();
2698   for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
2699   {
2700     if ( addr2cmds->first == avoidComputeAddr ) continue;
2701     const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
2702     isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
2703   }
2704   return isUsed;
2705 }
2706
2707 //================================================================================
2708 /*!
2709  * \brief Save commands setting parameters as they are used for a mesh computation
2710  */
2711 //================================================================================
2712
2713 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
2714 {
2715   myComputeCmds.push_back( theComputeCmd );
2716   list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2717
2718   map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2719   for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2720     savedCmds.push_back( m2c->second.back() );
2721 }
2722
2723 //================================================================================
2724 /*!
2725  * \brief Clear commands setting parameters as a mesh computed using them is cleared
2726  */
2727 //================================================================================
2728
2729 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
2730 {
2731   list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2732
2733   list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
2734   for ( ; cmd != savedCmds.end(); ++cmd )
2735   {
2736     // check if a cmd has been used to compute another mesh
2737     if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
2738       continue;
2739     // check if a cmd is a sole command setting its parameter;
2740     // don't use method name for search as it can change
2741     map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
2742       m2cmds = myMeth2Commands.begin();
2743     for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
2744     {
2745       list< Handle(_pyCommand)>& cmds = m2cmds->second;
2746       list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
2747       if ( cmdIt != cmds.end() )
2748       {
2749         if ( cmds.back() != *cmd )
2750         {
2751           cmds.erase( cmdIt );
2752           (*cmd)->Clear();
2753         }
2754         break;
2755       }
2756     }
2757   }
2758   myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
2759 }
2760
2761 //================================================================================
2762 /*!
2763  * \brief Sets an argNb-th argument of current creation command
2764  *  \param argNb - argument index countered from 1
2765  */
2766 //================================================================================
2767
2768 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
2769 {
2770   if ( myCurCrMethod )
2771   {
2772     while ( myCurCrMethod->myArgs.size() < argNb )
2773       myCurCrMethod->myArgs.push_back( "None" );
2774     if ( arg.IsEmpty() )
2775       myCurCrMethod->myArgs[ argNb-1 ] = "None";
2776     else
2777       myCurCrMethod->myArgs[ argNb-1 ] = arg;
2778   }
2779 }
2780
2781
2782 //================================================================================
2783 /*!
2784  * \brief Remember hypothesis parameter values
2785  * \param theCommand - The called hypothesis method
2786  */
2787 //================================================================================
2788
2789 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
2790 {
2791   if ( GetAlgoType() == "Cartesian_3D" )
2792   {
2793     // CartesianParameters3D hyp
2794
2795     if ( theCommand->GetMethod() == "SetSizeThreshold" )
2796     {
2797       setCreationArg( 4, theCommand->GetArg( 1 ));
2798       myArgCommands.push_back( theCommand );
2799       return;
2800     }
2801     if ( theCommand->GetMethod() == "SetGrid" ||
2802          theCommand->GetMethod() == "SetGridSpacing" )
2803     {
2804       TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
2805       int iArg = axis.Value(1) - '0';
2806       if ( theCommand->GetMethod() == "SetGrid" )
2807       {
2808         setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
2809       }
2810       else
2811       {
2812         myCurCrMethod->myArgs[ iArg ] = "[ ";
2813         myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
2814         myCurCrMethod->myArgs[ iArg ] += ", ";
2815         myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
2816         myCurCrMethod->myArgs[ iArg ] += "]";
2817       }
2818       myArgCommands.push_back( theCommand );
2819       rememberCmdOfParameter( theCommand );
2820       return;
2821     }
2822   }
2823
2824   if( theCommand->GetMethod() == "SetLength" )
2825   {
2826     // NOW it is OBSOLETE
2827     // ex: hyp.SetLength(start, 1)
2828     //     hyp.SetLength(end,   0)
2829     ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
2830     int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
2831     TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2832     for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2833     {
2834       CreationMethod& crMethod = type2meth->second;
2835         while ( crMethod.myArgs.size() < i+1 )
2836           crMethod.myArgs.push_back( "[]" );
2837         crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
2838     }
2839     myArgCommands.push_back( theCommand );
2840   }
2841   else
2842   {
2843     _pyHypothesis::Process( theCommand );
2844   }
2845 }
2846 //================================================================================
2847 /*!
2848  * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
2849  */
2850 //================================================================================
2851
2852 void _pyComplexParamHypo::Flush()
2853 {
2854   if ( IsWrapped() )
2855   {
2856     list < Handle(_pyCommand) >::iterator cmd = myUnusedCommands.begin();
2857     for ( ; cmd != myUnusedCommands.end(); ++cmd )
2858       if ((*cmd)->GetMethod() == "SetObjectEntry" )
2859         (*cmd)->Clear();
2860   }
2861 }
2862
2863 //================================================================================
2864 /*!
2865  * \brief Convert methods of 1D hypotheses to my own methods
2866   * \param theCommand - The called hypothesis method
2867  */
2868 //================================================================================
2869
2870 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
2871 {
2872   if ( theCommand->GetMethod() != "SetLayerDistribution" )
2873     return;
2874
2875   const _pyID& hyp1dID = theCommand->GetArg( 1 );
2876   // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
2877   // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
2878   // {
2879   //   TCollection_AsciiString cmd =
2880   //     my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
2881   //   Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
2882   //   theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
2883   //   hyp1d = my1dHyp;
2884   // }
2885   // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
2886   // {
2887   //   // 1D hypo is already set, so distribution changes and the old
2888   //   // 1D hypo is thrown away
2889   //   my1dHyp->ClearAllCommands();
2890   // }
2891   // my1dHyp = hyp1d;
2892   // //my1dHyp->SetRemovedFromStudy( false );
2893
2894   // if ( !myArgCommands.empty() )
2895   //   myArgCommands.back()->Clear();
2896   myCurCrMethod->myArgs.push_back( hyp1dID );
2897   myArgCommands.push_back( theCommand );
2898 }
2899
2900 //================================================================================
2901 /*!
2902  * \brief
2903   * \param theAdditionCmd - command to be converted
2904   * \param theMesh - mesh instance
2905   * \retval bool - status
2906  */
2907 //================================================================================
2908
2909 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
2910                                                   const _pyID&              theMesh)
2911 {
2912   myIsWrapped = false;
2913
2914   if ( my1dHyp.IsNull() )
2915     return false;
2916
2917   // set "SetLayerDistribution()" after addition cmd
2918   theAdditionCmd->AddDependantCmd( myArgCommands.front() );
2919
2920   _pyID geom = theAdditionCmd->GetArg( 1 );
2921
2922   Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
2923   if ( !algo.IsNull() )
2924   {
2925     my1dHyp->SetMesh( theMesh );
2926     my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
2927                                   algo->GetAlgoType().ToCString());
2928     if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
2929       return false;
2930
2931     // clear "SetLayerDistribution()" cmd
2932     myArgCommands.back()->Clear();
2933
2934     // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
2935
2936     // find RadialPrism algo created on <geom> for theMesh
2937     GetCreationCmd()->SetObject( algo->GetID() );
2938     GetCreationCmd()->SetMethod( myAlgoMethod );
2939     GetCreationCmd()->RemoveArgs();
2940     theAdditionCmd->AddDependantCmd( GetCreationCmd() );
2941     myIsWrapped = true;
2942   }
2943   return myIsWrapped;
2944 }
2945
2946 //================================================================================
2947 /*!
2948  * \brief
2949  */
2950 //================================================================================
2951
2952 void _pyLayerDistributionHypo::Flush()
2953 {
2954   // as creation of 1D hyp was written later then it's edition,
2955   // we need to find all it's edition calls and process them
2956   list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2957   _pyID prevNewName;
2958   for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
2959   {    
2960     const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
2961     if ( hyp1dID.IsEmpty() ) continue;
2962
2963     Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
2964
2965     // make a new name for 1D hyp = "HypType" + "_Distribution"
2966     _pyID newName;
2967     if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
2968     {
2969       if ( prevNewName.IsEmpty() ) continue;
2970       newName = prevNewName;
2971     }
2972     else
2973     {
2974       if ( hyp1d->IsWrapped() ) {
2975         newName = hyp1d->GetCreationCmd()->GetMethod();
2976       }
2977       else {
2978         TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
2979         newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2980       }
2981       newName += "_Distribution";
2982       prevNewName = newName;
2983     
2984       hyp1d->GetCreationCmd()->SetResultValue( newName );
2985     }
2986     list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
2987     list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
2988     for ( ; cmdIt != cmds.end(); ++cmdIt ) {
2989       const _pyID& objID = (*cmdIt)->GetObject();
2990       if ( objID == hyp1dID ) {
2991         if ( !hyp1d.IsNull() )
2992         {
2993           hyp1d->Process( *cmdIt );
2994           hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
2995         }
2996         ( *cmdIt )->SetObject( newName );
2997       }
2998     }
2999     // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3000     (*cmd)->SetArg( 1, newName );
3001   }
3002 }
3003
3004 //================================================================================
3005 /*!
3006  * \brief additionally to Addition2Creation, clears SetDistrType() command
3007   * \param theCmd - AddHypothesis() command
3008   * \param theMesh - mesh to which a hypothesis is added
3009   * \retval bool - convertion result
3010  */
3011 //================================================================================
3012
3013 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3014                                                 const _pyID&              theMesh)
3015 {
3016   if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3017     // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3018     bool scaleDistrType = false;
3019     list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3020     for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3021       if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3022         if ( (*cmd)->GetArg( 1 ) == "1" ) {
3023           scaleDistrType = true;
3024           (*cmd)->Clear();
3025         }
3026         else if ( !scaleDistrType ) {
3027           // distribution type changed: remove scale factor from args
3028           TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3029           for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3030           {
3031             CreationMethod& crMethod = type2meth->second;
3032             if ( crMethod.myArgs.size() == 2 )
3033               crMethod.myArgs.pop_back();
3034           }
3035           break;
3036         }
3037       }
3038     }
3039   }
3040   return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3041 }
3042
3043 //================================================================================
3044 /*!
3045  * \brief remove repeated commands defining distribution
3046  */
3047 //================================================================================
3048
3049 void _pyNumberOfSegmentsHyp::Flush()
3050 {
3051   // find number of the last SetDistrType() command
3052   list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3053   int distrTypeNb = 0;
3054   for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3055     if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3056       if ( cmd != myUnusedCommands.rbegin() )
3057         distrTypeNb = (*cmd)->GetOrderNb();
3058     }
3059     else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3060       (*cmd)->Clear();
3061     }
3062   // clear commands before the last SetDistrType()
3063   list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3064   set< int > treatedCmdNbs; // avoid treating same cmd twice
3065   for ( int i = 0; i < 2; ++i ) {
3066     set<TCollection_AsciiString> uniqueMethods;
3067     list<Handle(_pyCommand)> & cmdList = *cmds[i];
3068     for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3069     {
3070       if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3071         continue;// avoid treating same cmd twice
3072       bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3073       const TCollection_AsciiString& method = (*cmd)->GetMethod();
3074       if ( !clear || method == "SetNumberOfSegments" ) {
3075         bool isNewInSet = uniqueMethods.insert( method ).second;
3076         clear = !isNewInSet;
3077       }
3078       if ( clear )
3079         (*cmd)->Clear();
3080     }
3081     cmdList.clear();
3082   }
3083 }
3084
3085 //================================================================================
3086 /*!
3087  * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3088  * into regular1D.LengthNearVertex( length, vertex )
3089   * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3090   * \param theMesh - The mesh needing this hypo
3091   * \retval bool - false if the command cant be converted
3092  */
3093 //================================================================================
3094
3095 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3096                                                          const _pyID&              theMeshID)
3097 {
3098   if ( IsWrappable( theMeshID )) {
3099
3100     _pyID vertex = theCmd->GetArg( 1 );
3101
3102     // the problem here is that segment algo will not be found
3103     // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3104     // geometry where segment algorithm is assigned
3105     Handle(_pyHypothesis) algo;
3106     _pyID geom = vertex;
3107     while ( algo.IsNull() && !geom.IsEmpty()) {
3108       // try to find geom as a father of <vertex>
3109       geom = FatherID( geom );
3110       algo = theGen->FindAlgo( geom, theMeshID, this );
3111     }
3112     if ( algo.IsNull() )
3113       return false; // also possible to find geom as brother of veretex...
3114     // set geom instead of vertex
3115     theCmd->SetArg( 1, geom );
3116
3117     // set vertex as a second arg
3118     if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3119     setCreationArg( 2, vertex );
3120
3121     // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3122     // theMeshID.LengthNearVertex( length, vertex )
3123     return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3124   }
3125   return false;
3126 }
3127
3128 //================================================================================
3129 /*!
3130  * \brief _pyAlgorithm constructor
3131  * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3132  */
3133 //================================================================================
3134
3135 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3136   : _pyHypothesis( theCreationCmd )
3137 {
3138   myIsAlgo = true;
3139 }
3140
3141 //================================================================================
3142 /*!
3143  * \brief Convert the command adding an algorithm to mesh
3144   * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3145   * \param theMesh - The mesh needing this algo
3146   * \retval bool - false if the command cant be converted
3147  */
3148 //================================================================================
3149
3150 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3151                                       const _pyID&              theMeshID)
3152 {
3153   // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3154   if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3155     theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3156     return true;
3157   }
3158   return false;
3159 }
3160
3161 //================================================================================
3162 /*!
3163  * \brief Return starting position of a part of python command
3164   * \param thePartIndex - The index of command part
3165   * \retval int - Part position
3166  */
3167 //================================================================================
3168
3169 int _pyCommand::GetBegPos( int thePartIndex )
3170 {
3171   if ( IsEmpty() )
3172     return EMPTY;
3173   if ( myBegPos.Length() < thePartIndex )
3174     return UNKNOWN;
3175   return myBegPos( thePartIndex );
3176 }
3177
3178 //================================================================================
3179 /*!
3180  * \brief Store starting position of a part of python command
3181   * \param thePartIndex - The index of command part
3182   * \param thePosition - Part position
3183  */
3184 //================================================================================
3185
3186 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3187 {
3188   while ( myBegPos.Length() < thePartIndex )
3189     myBegPos.Append( UNKNOWN );
3190   myBegPos( thePartIndex ) = thePosition;
3191 }
3192
3193 //================================================================================
3194 /*!
3195  * \brief Returns whitespace symbols at the line beginning
3196   * \retval TCollection_AsciiString - result
3197  */
3198 //================================================================================
3199
3200 TCollection_AsciiString _pyCommand::GetIndentation()
3201 {
3202   int end = 1;
3203   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3204     GetWord( myString, end, true );
3205   else
3206     end = GetBegPos( RESULT_IND );
3207   return myString.SubString( 1, end - 1 );
3208 }
3209
3210 //================================================================================
3211 /*!
3212  * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3213   * \retval const TCollection_AsciiString & - ResultValue substring
3214  */
3215 //================================================================================
3216
3217 const TCollection_AsciiString & _pyCommand::GetResultValue()
3218 {
3219   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3220   {
3221     SetBegPos( RESULT_IND, EMPTY );
3222     int begPos, endPos = myString.Location( "=", 1, Length() );
3223     if ( endPos )
3224     {
3225       begPos = 1;
3226       while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3227       if ( begPos < endPos )
3228       {
3229         SetBegPos( RESULT_IND, begPos );
3230         --endPos;
3231         while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3232         myRes = myString.SubString( begPos, endPos );
3233       }
3234     }
3235   }
3236   return myRes;
3237 }
3238
3239 //================================================================================
3240 /*!
3241  * \brief Return number of python command result value ResultValue = Obj.Meth()
3242  */
3243 //================================================================================
3244
3245 int _pyCommand::GetNbResultValues()
3246 {
3247   int nb     = 0;
3248   int begPos = 1;
3249   int endPos = myString.Location( "=", 1, Length() );
3250   while ( begPos < endPos )
3251   {
3252     _AString str = GetWord( myString, begPos, true );
3253     begPos = begPos+ str.Length();
3254     nb++;
3255   }
3256   return (nb-1);
3257 }
3258
3259
3260 //================================================================================
3261 /*!
3262  * \brief Return substring of python command looking like
3263  *  ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3264  * \retval const TCollection_AsciiString & - ResultValue with res index substring
3265  */
3266 //================================================================================
3267 TCollection_AsciiString _pyCommand::GetResultValue(int res)
3268 {
3269   int begPos = 1;
3270   if ( SkipSpaces( myString, begPos ) && myString.Value( begPos ) == '[' )
3271     ++begPos; // skip [, else the whole list is returned
3272   int endPos = myString.Location( "=", 1, Length() );
3273   int Nb=0;
3274   while ( begPos < endPos) {
3275     _AString result = GetWord( myString, begPos, true );
3276     begPos = begPos + result.Length();
3277     Nb++;
3278     if(res == Nb) {
3279       result.RemoveAll('[');
3280       result.RemoveAll(']');
3281       return result;
3282     }
3283     if(Nb>res)
3284       break;
3285   }
3286   return theEmptyString;
3287 }
3288
3289 //================================================================================
3290 /*!
3291  * \brief Return substring of python command looking like ResVal = Object.Meth()
3292   * \retval const TCollection_AsciiString & - Object substring
3293  */
3294 //================================================================================
3295
3296 const TCollection_AsciiString & _pyCommand::GetObject()
3297 {
3298   if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3299   {
3300     // beginning
3301     int begPos = GetBegPos( RESULT_IND ) + myRes.Length();
3302     if ( begPos < 1 ) {
3303       begPos = myString.Location( "=", 1, Length() ) + 1;
3304       // is '=' in the string argument (for example, name) or not
3305       int nb1 = 0; // number of ' character at the left of =
3306       int nb2 = 0; // number of " character at the left of =
3307       for ( int i = 1; i < begPos-1; i++ ) {
3308         if ( myString.Value( i )=='\'' )
3309           nb1 += 1;
3310         else if ( myString.Value( i )=='"' )
3311           nb2 += 1;
3312       }
3313       // if number of ' or " is not divisible by 2,
3314       // then get an object at the start of the command
3315       if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3316         begPos = 1;
3317     }
3318     myObj = GetWord( myString, begPos, true );
3319     if ( begPos != EMPTY )
3320     {
3321       // check if object is complex,
3322       // so far consider case like "smesh.Method()"
3323       if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3324         //if ( bracketPos==0 ) bracketPos = Length();
3325         int dotPos = begPos+myObj.Length();
3326         while ( dotPos+1 < bracketPos ) {
3327           if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3328             dotPos = pos;
3329           else
3330             break;
3331         }
3332         if ( dotPos > begPos+myObj.Length() )
3333           myObj = myString.SubString( begPos, dotPos-1 );
3334       }
3335     }
3336     // 1st word after '=' is an object
3337     // else // no method -> no object
3338     // {
3339     //   myObj.Clear();
3340     //   begPos = EMPTY;
3341     // }
3342     // store
3343     SetBegPos( OBJECT_IND, begPos );
3344   }
3345   //SCRUTE(myObj);
3346   return myObj;
3347 }
3348
3349 //================================================================================
3350 /*!
3351  * \brief Return substring of python command looking like ResVal = Obj.Method()
3352   * \retval const TCollection_AsciiString & - Method substring
3353  */
3354 //================================================================================
3355
3356 const TCollection_AsciiString & _pyCommand::GetMethod()
3357 {
3358   if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3359   {
3360     // beginning
3361     int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3362     bool forward = true;
3363     if ( begPos < 1 ) {
3364       begPos = myString.Location( "(", 1, Length() ) - 1;
3365       forward = false;
3366     }
3367     // store
3368     myMeth = GetWord( myString, begPos, forward );
3369     SetBegPos( METHOD_IND, begPos );
3370   }
3371   //SCRUTE(myMeth);
3372   return myMeth;
3373 }
3374
3375 //================================================================================
3376 /*!
3377  * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3378   * \retval const TCollection_AsciiString & - Arg<index> substring
3379  */
3380 //================================================================================
3381
3382 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3383 {
3384   if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3385   {
3386     // Find all args
3387
3388     int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3389     if ( pos < 1 )
3390       pos = myString.Location( "(", 1, Length() );
3391     else
3392       --pos;
3393
3394     // we are at or before '(', skip it if present
3395     if ( pos > 0 ) {
3396       while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3397       if ( pos > Length() )
3398         pos = 0;
3399     }
3400     if ( pos < 1 ) {
3401       SetBegPos( ARG1_IND, 0 ); // even no '('
3402       return theEmptyString;
3403     }
3404     ++pos;
3405
3406     list< TCollection_AsciiString > separatorStack( 1, ",)");
3407     bool ignoreNesting = false;
3408     int prevPos = pos;
3409     while ( pos <= Length() )
3410     {
3411       const char chr = myString.Value( pos );
3412
3413       if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3414       {
3415         if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3416         {
3417           while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3418             ++prevPos;
3419           TCollection_AsciiString arg;
3420           if ( pos-1 >= prevPos ) {
3421             arg = myString.SubString( prevPos, pos-1 );
3422             arg.RightAdjust(); // remove spaces
3423             arg.LeftAdjust();
3424           }
3425           if ( !arg.IsEmpty() || chr == ',' )
3426           {
3427             SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3428             myArgs.Append( arg );
3429           }
3430           if ( chr == ')' )
3431             break;
3432           prevPos = pos+1;
3433         }
3434         else // end of nesting args found
3435         {
3436           separatorStack.pop_back();
3437           ignoreNesting = false;
3438         }
3439       }
3440       else if ( !ignoreNesting )
3441       {
3442         switch ( chr ) {
3443         case '(' : separatorStack.push_back(")"); break;
3444         case '[' : separatorStack.push_back("]"); break;
3445         case '\'': separatorStack.push_back("'");  ignoreNesting=true; break;
3446         case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3447         default:;
3448         }
3449       }
3450       ++pos;
3451     }
3452   }
3453   if ( myArgs.Length() < index )
3454     return theEmptyString;
3455   return myArgs( index );
3456 }
3457
3458 //================================================================================
3459 /*!
3460  * \brief Check if char is a word part
3461   * \param c - The character to check
3462   * \retval bool - The check result
3463  */
3464 //================================================================================
3465
3466 static inline bool isWord(const char c, const bool dotIsWord)
3467 {
3468   return
3469     !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3470 }
3471
3472 //================================================================================
3473 /*!
3474  * \brief Looks for a word in the string and returns word's beginning
3475   * \param theString - The input string
3476   * \param theStartPos - The position to start the search, returning word's beginning
3477   * \param theForward - The search direction
3478   * \retval TCollection_AsciiString - The found word
3479  */
3480 //================================================================================
3481
3482 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3483                                              int &            theStartPos,
3484                                              const bool       theForward,
3485                                              const bool       dotIsWord )
3486 {
3487   int beg = theStartPos, end = theStartPos;
3488   theStartPos = EMPTY;
3489   if ( beg < 1 || beg > theString.Length() )
3490     return theEmptyString;
3491
3492   if ( theForward ) { // search forward
3493     // beg
3494     while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3495       ++beg;
3496     if ( beg > theString.Length() )
3497       return theEmptyString; // no word found
3498     // end
3499     end = beg + 1;
3500     char begChar = theString.Value( beg );
3501     if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3502       char endChar = ( begChar == '[' ) ? ']' : begChar;
3503       // end is at the corresponding quoting mark or bracket
3504       while ( end < theString.Length() &&
3505               ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3506         ++end;
3507     }
3508     else {
3509       while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3510         ++end;
3511       --end;
3512     }
3513   }
3514   else {  // search backward
3515     // end
3516     while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3517       --end;
3518     if ( end == 0 )
3519       return theEmptyString; // no word found
3520     beg = end - 1;
3521     char endChar = theString.Value( end );
3522     if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3523       char begChar = ( endChar == ']' ) ? '[' : endChar;
3524       // beg is at the corresponding quoting mark
3525       while ( beg > 1 &&
3526               ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3527         --beg;
3528     }
3529     else {
3530       while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3531         --beg;
3532       ++beg;
3533     }
3534   }
3535   theStartPos = beg;
3536   //cout << theString << " ---- " << beg << " - " << end << endl;
3537   return theString.SubString( beg, end );
3538 }
3539
3540 //================================================================================
3541 /*!
3542  * \brief Returns true if the string looks like a study entry
3543  */
3544 //================================================================================
3545
3546 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3547 {
3548   if ( str.Length() < 5 ) return false;
3549
3550   int nbColons = 0, isColon;
3551   for ( int i = 1; i <= str.Length(); ++i )
3552   {
3553     char c = str.Value(i);
3554     if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3555       return false;
3556     nbColons += isColon;
3557   }
3558   return nbColons > 2 && str.Length()-nbColons > 2;
3559 }
3560
3561 //================================================================================
3562 /*!
3563  * \brief Finds entries in a sting
3564  */
3565 //================================================================================
3566
3567 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3568 {
3569   std::list< _pyID > resList;
3570   int pos = 0;
3571   while ( ++pos <= str.Length() )
3572   {
3573     if ( !isdigit( str.Value( pos ))) continue;
3574     if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3575
3576     int end = pos;
3577     while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3578     _pyID entry = str.SubString( pos, end-1 );
3579     pos = end;
3580     if ( IsStudyEntry( entry ))
3581       resList.push_back( entry );
3582   }
3583   return resList;
3584 }
3585
3586 //================================================================================
3587 /*!
3588  * \brief Look for position where not space char is
3589   * \param theString - The string
3590   * \param thePos - The position to search from and which returns result
3591   * \retval bool - false if there are only space after thePos in theString
3592  */
3593 //================================================================================
3594
3595 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
3596 {
3597   if ( thePos < 1 || thePos > theString.Length() )
3598     return false;
3599
3600   while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
3601     ++thePos;
3602
3603   return thePos <= theString.Length();
3604 }
3605
3606 //================================================================================
3607 /*!
3608  * \brief Modify a part of the command
3609   * \param thePartIndex - The index of the part
3610   * \param thePart - The new part string
3611   * \param theOldPart - The old part
3612  */
3613 //================================================================================
3614
3615 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
3616                         TCollection_AsciiString& theOldPart)
3617 {
3618   int pos = GetBegPos( thePartIndex );
3619   if ( pos <= Length() && theOldPart != thePart)
3620   {
3621     TCollection_AsciiString seperator;
3622     if ( pos < 1 ) {
3623       pos = GetBegPos( thePartIndex + 1 );
3624       if ( pos < 1 ) return;
3625       switch ( thePartIndex ) {
3626       case RESULT_IND: seperator = " = "; break;
3627       case OBJECT_IND: seperator = "."; break;
3628       case METHOD_IND: seperator = "()"; break;
3629       default:;
3630       }
3631     }
3632     myString.Remove( pos, theOldPart.Length() );
3633     if ( !seperator.IsEmpty() )
3634       myString.Insert( pos , seperator );
3635     myString.Insert( pos, thePart );
3636     // update starting positions of the following parts
3637     int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
3638     for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
3639       if ( myBegPos( i ) > 0 )
3640         myBegPos( i ) += posDelta;
3641     }
3642     theOldPart = thePart;
3643   }
3644 }
3645
3646 //================================================================================
3647 /*!
3648  * \brief Set agrument
3649   * \param index - The argument index, it counts from 1
3650   * \param theArg - The argument string
3651  */
3652 //================================================================================
3653
3654 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
3655 {
3656   FindAllArgs();
3657   int argInd = ARG1_IND + index - 1;
3658   int pos = GetBegPos( argInd );
3659   if ( pos < 1 ) // no index-th arg exist, append inexistent args
3660   {
3661     // find a closing parenthesis
3662     if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
3663       int lastArgInd = GetNbArgs();
3664       pos = GetBegPos( ARG1_IND + lastArgInd  - 1 ) + GetArg( lastArgInd ).Length();
3665       while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
3666         ++pos;
3667     }
3668     else {
3669       pos = Length();
3670       while ( pos > 0 && myString.Value( pos ) != ')' )
3671         --pos;
3672     }
3673     if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
3674       myString += "()";
3675       pos = Length();
3676     }
3677     while ( myArgs.Length() < index ) {
3678       if ( myArgs.Length() )
3679         myString.Insert( pos++, "," );
3680       myArgs.Append("None");
3681       myString.Insert( pos, myArgs.Last() );
3682       SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
3683       pos += myArgs.Last().Length();
3684     }
3685   }
3686   SetPart( argInd, theArg, myArgs( index ));
3687 }
3688
3689 //================================================================================
3690 /*!
3691  * \brief Empty arg list
3692  */
3693 //================================================================================
3694
3695 void _pyCommand::RemoveArgs()
3696 {
3697   if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
3698     myString.Trunc( pos );
3699   myString += ")";
3700   myArgs.Clear();
3701   if ( myBegPos.Length() >= ARG1_IND )
3702     myBegPos.Remove( ARG1_IND, myBegPos.Length() );
3703 }
3704
3705 //================================================================================
3706 /*!
3707  * \brief Comment a python command
3708  */
3709 //================================================================================
3710
3711 void _pyCommand::Comment()
3712 {
3713   if ( IsEmpty() ) return;
3714
3715   int i = 1;
3716   while ( i <= Length() && isspace( myString.Value(i) )) ++i;
3717   if ( i <= Length() )
3718   {
3719     myString.Insert( i, "#" );
3720     for ( int iPart = 0; iPart < myBegPos.Length(); ++iPart )
3721     {
3722       int begPos = GetBegPos( iPart + 1 );
3723       if ( begPos != UNKNOWN )
3724         SetBegPos( iPart + 1, begPos + 1 );
3725     }
3726   }
3727 }
3728
3729 //================================================================================
3730 /*!
3731  * \brief Set dependent commands after this one
3732  */
3733 //================================================================================
3734
3735 bool _pyCommand::SetDependentCmdsAfter() const
3736 {
3737   bool orderChanged = false;
3738   list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
3739   for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
3740     if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
3741       orderChanged = true;
3742       theGen->SetCommandAfter( *cmd, this );
3743       (*cmd)->SetDependentCmdsAfter();
3744     }
3745   }
3746   return orderChanged;
3747 }
3748 //================================================================================
3749 /*!
3750  * \brief Insert accessor method after theObjectID
3751   * \param theObjectID - id of the accessed object
3752   * \param theAcsMethod - name of the method giving access to the object
3753   * \retval bool - false if theObjectID is not found in the command string
3754  */
3755 //================================================================================
3756
3757 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
3758 {
3759   if ( !theAcsMethod )
3760     return false;
3761   // start object search from the object, i.e. ignore result
3762   GetObject();
3763   int beg = GetBegPos( OBJECT_IND );
3764   if ( beg < 1 || beg > Length() )
3765     return false;
3766   bool added = false;
3767   while (( beg = myString.Location( theObjectID, beg, Length() )))
3768   {
3769     // check that theObjectID is not just a part of a longer ID
3770     int afterEnd = beg + theObjectID.Length();
3771     Standard_Character c = myString.Value( afterEnd );
3772     if ( !isalnum( c ) && c != ':' ) {
3773       // check if accessor method already present
3774       if ( c != '.' ||
3775            myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
3776         // insertion
3777         int oldLen = Length();
3778         myString.Insert( afterEnd, (char*) theAcsMethod );
3779         myString.Insert( afterEnd, "." );
3780         // update starting positions of the parts following the modified one
3781         int posDelta = Length() - oldLen;
3782         for ( int i = 1; i <= myBegPos.Length(); ++i ) {
3783           if ( myBegPos( i ) > afterEnd )
3784             myBegPos( i ) += posDelta;
3785         }
3786         added = true;
3787       }
3788     }
3789     beg = afterEnd; // is a part - next search
3790   }
3791   return added;
3792 }
3793
3794 //================================================================================
3795 /*!
3796  * \brief Creates pyObject
3797  */
3798 //================================================================================
3799
3800 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
3801   : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
3802 {
3803   setID( theID );
3804 }
3805
3806 //================================================================================
3807 /*!
3808  * \brief Set up myID and myIsPublished
3809  */
3810 //================================================================================
3811
3812 void _pyObject::setID(const _pyID& theID)
3813 {
3814   myID = theID;
3815   myIsPublished = !theGen->IsNotPublished( GetID() );
3816 }
3817
3818 //================================================================================
3819 /*!
3820  * \brief Clear myCreationCmd and myProcessedCmds
3821  */
3822 //================================================================================
3823
3824 void _pyObject::ClearCommands()
3825 {
3826   if ( !CanClear() )
3827     return;
3828
3829   if ( !myCreationCmd.IsNull() )
3830     myCreationCmd->Clear();
3831
3832   list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
3833   for ( ; cmd != myProcessedCmds.end(); ++cmd )
3834     (*cmd)->Clear();
3835 }
3836
3837 //================================================================================
3838 /*!
3839  * \brief Return method name giving access to an interaface object wrapped by python class
3840   * \retval const char* - method name
3841  */
3842 //================================================================================
3843
3844 const char* _pyObject::AccessorMethod() const
3845 {
3846   return 0;
3847 }
3848 //================================================================================
3849 /*!
3850  * \brief Return ID of a father
3851  */
3852 //================================================================================
3853
3854 _pyID _pyObject::FatherID(const _pyID & childID)
3855 {
3856   int colPos = childID.SearchFromEnd(':');
3857   if ( colPos > 0 )
3858     return childID.SubString( 1, colPos-1 );
3859   return "";
3860 }
3861
3862 //================================================================================
3863 /*!
3864  * \brief SelfEraser erases creation command if no more it's commands invoked
3865  */
3866 //================================================================================
3867
3868 void _pySelfEraser::Flush()
3869 {
3870   int nbCalls = GetNbCalls();
3871   if ( nbCalls > 0 )
3872   {
3873     // ignore cleared commands
3874     std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
3875     std::list< Handle(_pyCommand) >::const_iterator cmd = cmds.begin();
3876     for ( ; cmd != cmds.end(); ++cmd )
3877       nbCalls -= (*cmd)->IsEmpty();
3878   }
3879   if ( nbCalls < 1 )
3880     GetCreationCmd()->Clear();
3881 }
3882
3883 //================================================================================
3884 /*!
3885  * \brief _pySubMesh constructor
3886  */
3887 //================================================================================
3888
3889 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd):
3890   _pyObject(theCreationCmd)
3891 {
3892   myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
3893 }
3894
3895 //================================================================================
3896 /*!
3897  * \brief Return true if a sub-mesh can be used as argument of the given method
3898  */
3899 //================================================================================
3900
3901 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
3902 {
3903   // names of all methods where a sub-mesh can be used as argument
3904   static TStringSet methods;
3905   if ( methods.empty() ) {
3906     const char * names[] = {
3907       // methods of SMESH_Gen
3908       "CopyMesh",
3909       // methods of SMESH_Group
3910       "AddFrom",
3911       // methods of SMESH_Measurements
3912       "MinDistance",
3913       // methods of SMESH_Mesh
3914       "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
3915       "RemoveSubMesh",
3916       // methods of SMESH_MeshEditor
3917       "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
3918       "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
3919       "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
3920       "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
3921       "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
3922       "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
3923       "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
3924       "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
3925       "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
3926       "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
3927       "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
3928       "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
3929       "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
3930       "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
3931       "MakeBoundaryMesh","Create0DElementsOnAllNodes",
3932       "" }; // <- mark of end
3933     methods.Insert( names );
3934   }
3935   return methods.Contains( theMethodName );
3936 }
3937
3938 //================================================================================
3939 /*!
3940  * \brief count invoked commands
3941  */
3942 //================================================================================
3943
3944 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
3945 {
3946   _pyObject::Process(theCommand); // count calls of Process()
3947   GetCreationCmd()->AddDependantCmd( theCommand );
3948 }
3949
3950 //================================================================================
3951 /*!
3952  * \brief Move creation command depending on invoked commands
3953  */
3954 //================================================================================
3955
3956 void _pySubMesh::Flush()
3957 {
3958   if ( GetNbCalls() == 0 ) // move to the end of all commands
3959     theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
3960   else if ( !myCreator.IsNull() )
3961     // move to be just after creator
3962     myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
3963 }
3964
3965 //================================================================================
3966 /*!
3967  * \brief Creates _pyGroup
3968  */
3969 //================================================================================
3970
3971 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
3972   :_pySubMesh(theCreationCmd)
3973 {
3974   if ( !id.IsEmpty() )
3975     setID( id );
3976
3977   myCanClearCreationCmd = true;
3978
3979   const _AString& method = theCreationCmd->GetMethod();
3980   if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
3981   {
3982     theCreationCmd->SetMethod( "CreateEmptyGroup" );
3983   }
3984   // ----------------------------------------------------------------------
3985   else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
3986   {
3987     _pyID geom = theCreationCmd->GetArg( 3 );
3988     // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
3989     // next if(){...} section is commented
3990     //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
3991     //  theCreationCmd->SetMethod( "Group" );
3992     //  theCreationCmd->RemoveArgs();
3993     //  theCreationCmd->SetArg( 1, geom );
3994     //}
3995     //else {
3996     // ------------------------->>>>> GroupOnGeom( geom, name, typ )
3997       _pyID type = theCreationCmd->GetArg( 1 );
3998       _pyID name = theCreationCmd->GetArg( 2 );
3999       theCreationCmd->SetMethod( "GroupOnGeom" );
4000       theCreationCmd->RemoveArgs();
4001       theCreationCmd->SetArg( 1, geom );
4002       theCreationCmd->SetArg( 2, name );
4003       theCreationCmd->SetArg( 3, type );
4004     //}
4005   }
4006   else if ( method == "CreateGroupFromFilter" )
4007   {
4008     // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4009     theCreationCmd->SetMethod( "GroupOnFilter" );
4010
4011     _pyID filterID = theCreationCmd->GetArg(3);
4012     Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4013     if ( !filter.IsNull())
4014     {
4015       if ( !filter->GetNewID().IsEmpty() )
4016         theCreationCmd->SetArg( 3, filter->GetNewID() );
4017       filter->AddUser( this );
4018     }
4019     myFilter = filter;
4020   }
4021   else
4022   {
4023     // theCreationCmd does something else apart from creation of this group
4024     // and thus it can't be cleared if this group is removed
4025     myCanClearCreationCmd = false;
4026   }
4027 }
4028
4029 //================================================================================
4030 /*!
4031  * \brief set myCanClearCreationCmd = true if the main action of the creation
4032  *        command is discarded
4033  */
4034 //================================================================================
4035
4036 void _pyGroup::RemovedWithContents()
4037 {
4038   // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4039   // via a created group
4040   //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4041   // myCanClearCreationCmd = true;
4042 }
4043
4044 //================================================================================
4045 /*!
4046  * \brief To convert creation of a group by filter
4047  */
4048 //================================================================================
4049
4050 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4051 {
4052   // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4053   // group = mesh.CreateEmptyGroup( elemType, groupName )
4054   // aFilter.SetMesh(mesh)
4055   // nbAdd = group.AddFrom( aFilter )
4056   Handle(_pyFilter) filter;
4057   if ( theCommand->GetMethod() == "AddFrom" )
4058   {
4059     _pyID idSource = theCommand->GetArg(1);
4060     // check if idSource is a filter
4061     filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4062     if ( !filter.IsNull() )
4063     {
4064       // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4065       list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4066       while ( *cmdIt != theCommand ) ++cmdIt;
4067       while ( (*cmdIt)->GetOrderNb() != 1 )
4068       {
4069         const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4070         if ((setMeshCmd->GetObject() == idSource ||
4071              setMeshCmd->GetObject() == filter->GetNewID() )
4072             &&
4073             setMeshCmd->GetMethod() == "SetMesh")
4074         {
4075           setMeshCmd->Clear();
4076           break;
4077         }
4078       }
4079       // replace 3 commands by one
4080       theCommand->Clear();
4081       const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4082       TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4083       if ( !filter->GetNewID().IsEmpty() )
4084         idSource = filter->GetNewID();
4085       makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4086       makeGroupCmd->SetArg( 1, name );
4087       makeGroupCmd->SetArg( 2, idSource );
4088     }
4089   }
4090   else if ( theCommand->GetMethod() == "SetFilter" )
4091   {
4092     // set new name of a filter or clear the command if the same filter is set
4093     _pyID filterID = theCommand->GetArg(1);
4094     filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4095     if ( !myFilter.IsNull() && filter == myFilter )
4096       theCommand->Clear();
4097     else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4098       theCommand->SetArg( 1, filter->GetNewID() );
4099     myFilter = filter;
4100   }
4101   else if ( theCommand->GetMethod() == "GetFilter" )
4102   {
4103     // GetFilter() returns a filter with other ID, make myFilter process
4104     // calls of the returned filter
4105     if ( !myFilter.IsNull() )
4106     {
4107       theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4108       theCommand->Clear();
4109     }
4110   }
4111
4112   if ( !filter.IsNull() )
4113     filter->AddUser( this );
4114
4115   theGen->AddMeshAccessorMethod( theCommand );
4116 }
4117
4118 //================================================================================
4119 /*!
4120  * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4121  */
4122 //================================================================================
4123
4124 void _pyGroup::Flush()
4125 {
4126   if ( !theGen->IsToKeepAllCommands() &&
4127        myCreationCmd && !myCanClearCreationCmd )
4128   {
4129     myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4130   }
4131 }
4132
4133 //================================================================================
4134 /*!
4135  * \brief Constructor of _pyFilter
4136  */
4137 //================================================================================
4138
4139 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4140   :_pyObject(theCreationCmd), myNewID( newID )
4141 {
4142 }
4143
4144 //================================================================================
4145 /*!
4146  * \brief To convert creation of a filter by criteria and
4147  * to replace an old name by a new one
4148  */
4149 //================================================================================
4150
4151 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4152 {
4153   if ( theCommand->GetObject() == GetID() )
4154     _pyObject::Process(theCommand); // count commands
4155
4156   if ( !myNewID.IsEmpty() )
4157     theCommand->SetObject( myNewID );
4158     
4159   // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4160   // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4161   // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4162   if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4163        theCommand->GetMethod() == "SetCriteria")
4164   {
4165     // aFilter.SetCriteria(aCriteria) ->
4166     // aFilter = smesh.GetFilterFromCriteria(criteria)
4167     if ( myNewID.IsEmpty() )
4168       theCommand->SetResultValue( GetID() );
4169     else
4170       theCommand->SetResultValue( myNewID );
4171     theCommand->SetObject( SMESH_2smeshpy::GenName() );
4172     theCommand->SetMethod( "GetFilterFromCriteria" );
4173
4174     // Clear aFilterManager.CreateFilter()
4175     GetCreationCmd()->Clear();
4176   }
4177   else if ( theCommand->GetMethod() == "SetMesh" )
4178   {
4179     if ( myMesh == theCommand->GetArg( 1 ))
4180       theCommand->Clear();
4181     else
4182       myMesh = theCommand->GetArg( 1 );
4183     theGen->AddMeshAccessorMethod( theCommand );
4184   }
4185 }
4186
4187 //================================================================================
4188 /*!
4189  * \brief Set new filter name to the creation command
4190  */
4191 //================================================================================
4192
4193 void _pyFilter::Flush()
4194 {
4195   if ( !myNewID.IsEmpty() && !GetCreationCmd()->IsEmpty() )
4196     GetCreationCmd()->SetResultValue( myNewID );
4197 }
4198
4199 //================================================================================
4200 /*!
4201  * \brief Return true if all my users can be cleared
4202  */
4203 //================================================================================
4204
4205 bool _pyFilter::CanClear()
4206 {
4207   list< Handle(_pyObject) >::iterator obj = myUsers.begin();
4208   for ( ; obj != myUsers.end(); ++obj )
4209     if ( !(*obj)->CanClear() )
4210       return false;
4211
4212   return true;
4213 }
4214
4215 //================================================================================
4216 /*!
4217  * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4218  */
4219 //================================================================================
4220
4221 _pyHypothesisReader::_pyHypothesisReader()
4222 {
4223   // Read xml files
4224   vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4225   LDOMParser xmlParser;
4226   for ( size_t i = 0; i < xmlPaths.size(); ++i )
4227   {
4228     bool error = xmlParser.parse( xmlPaths[i].c_str() );
4229     if ( error )
4230     {
4231       _AString data;
4232       INFOS( xmlParser.GetError(data) );
4233       continue;
4234     }
4235     // <algorithm type="Regular_1D"
4236     //            label-id="Wire discretisation"
4237     //            ...>
4238     //   <python-wrap>
4239     //     <algo>Regular_1D=Segment()</algo>
4240     //     <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4241     //
4242     LDOM_Document xmlDoc = xmlParser.getDocument();
4243     LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4244     for ( int i = 0; i < algoNodeList.getLength(); ++i )
4245     {
4246       LDOM_Node     algoNode = algoNodeList.item( i );
4247       LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4248       LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4249       if ( pyAlgoNodeList.getLength() < 1 ) continue;
4250
4251       _AString text, algoType, method, arg;
4252       for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4253       {
4254         LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4255         LDOM_Node textNode   = pyAlgoNode.getFirstChild();
4256         text = textNode.getNodeValue();
4257         Handle(_pyCommand) algoCmd = new _pyCommand( text );
4258         algoType = algoCmd->GetResultValue();
4259         method   = algoCmd->GetMethod();
4260         arg      = algoCmd->GetArg(1);
4261         if ( !algoType.IsEmpty() && !method.IsEmpty() )
4262         {
4263           Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4264           algo->SetConvMethodAndType( method, algoType );
4265           if ( !arg.IsEmpty() )
4266             algo->setCreationArg( 1, arg );
4267
4268           myType2Hyp[ algoType ] = algo;
4269           break;
4270         }
4271       }
4272       if ( algoType.IsEmpty() ) continue;
4273
4274       LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4275       _AString hypType;
4276       Handle( _pyHypothesis ) hyp;
4277       for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4278       {
4279         LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4280         LDOM_Node textNode   = pyHypoNode.getFirstChild();
4281         text = textNode.getNodeValue();
4282         Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4283         hypType = hypoCmd->GetResultValue();
4284         method  = hypoCmd->GetMethod();
4285         if ( !hypType.IsEmpty() && !method.IsEmpty() )
4286         {
4287           map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4288           if ( type2hyp == myType2Hyp.end() )
4289             hyp = new _pyHypothesis( hypoCmd );
4290           else
4291             hyp = type2hyp->second;
4292           hyp->SetConvMethodAndType( method, algoType );
4293           for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4294           {
4295             _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4296             _AString argMethod = argCmd.GetMethod();
4297             _AString argNbText = argCmd.GetArg( 1 );
4298             if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4299               hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4300             else
4301               hyp->AddArgMethod( argMethod,
4302                                  argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4303           }
4304           myType2Hyp[ hypType ] = hyp;
4305         }
4306       }
4307     }
4308     // <hypothesis type="BLSURF_Parameters"
4309     //          ...
4310     //          dim="2">
4311     //   <python-wrap>
4312     //     <accumulative-methods> 
4313     //       SetEnforcedVertex,
4314     //       SetEnforcedVertexNamed
4315     //     </accumulative-methods>
4316     //   </python-wrap>
4317     // </hypothesis>
4318     //
4319     LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4320     for ( int i = 0; i < hypNodeList.getLength(); ++i )
4321     {
4322       LDOM_Node     hypNode      = hypNodeList.item( i );
4323       LDOM_Element& hypElem      = (LDOM_Element&) hypNode;
4324       _AString      hypType      = hypElem.getAttribute("type");
4325       LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4326       if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4327
4328       map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4329       if ( type2hyp == myType2Hyp.end() ) continue;
4330
4331       LDOM_Node methNode = methNodeList.item( 0 );
4332       LDOM_Node textNode = methNode.getFirstChild();
4333       _AString      text = textNode.getNodeValue();
4334       _AString method;
4335       int pos = 1;
4336       do {
4337         method = _pyCommand::GetWord( text, pos, /*forward= */true );
4338         pos += method.Length();
4339         type2hyp->second->AddAccumulativeMethod( method );
4340       }
4341       while ( !method.IsEmpty() );
4342     }
4343
4344   } // loop on xmlPaths
4345 }
4346
4347 //================================================================================
4348 /*!
4349  * \brief Returns a new hypothesis initialized according to the read information
4350  */
4351 //================================================================================
4352
4353 Handle(_pyHypothesis)
4354 _pyHypothesisReader::GetHypothesis(const _AString&           hypType,
4355                                    const Handle(_pyCommand)& creationCmd) const
4356 {
4357   Handle(_pyHypothesis) resHyp, sampleHyp;
4358
4359   map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4360   if ( type2hyp != myType2Hyp.end() )
4361     sampleHyp = type2hyp->second;
4362
4363   if ( sampleHyp.IsNull() )
4364   {
4365     resHyp = new _pyHypothesis(creationCmd);
4366   }
4367   else
4368   {
4369     if ( sampleHyp->IsAlgo() )
4370       resHyp = new _pyAlgorithm( creationCmd );
4371     else
4372       resHyp = new _pyHypothesis(creationCmd);
4373     resHyp->Assign( sampleHyp, _pyID() );
4374   }
4375   return resHyp;
4376 }