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