Salome HOME
2437efbd32cee8957f1e55c981f82d2454755801
[modules/smesh.git] / src / SMESH_I / SMESH_2smeshpy.cxx
1 // Copyright (C) 2007-2011  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 //  SMESH SMESH_I : idl implementation based on 'SMESH' unit's calsses
24 // File      : SMESH_2smeshpy.cxx
25 // Created   : Fri Nov 18 13:20:10 2005
26 // Author    : Edward AGAPOV (eap)
27 //
28 #include "SMESH_2smeshpy.hxx"
29
30 #include "utilities.h"
31 #include "SMESH_PythonDump.hxx"
32 #include "SMESH_NoteBook.hxx"
33 #include "SMESH_Filter_i.hxx"
34
35 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
36
37 #include "SMESH_Gen_i.hxx"
38 /* SALOME headers that include CORBA headers that include windows.h
39  * that defines GetObject symbol as GetObjectA should stand before SALOME headers
40  * that declare methods named GetObject - to apply the same rules of GetObject renaming
41  * and thus to avoid mess with GetObject symbol on Windows */
42
43 IMPLEMENT_STANDARD_HANDLE (_pyObject          ,Standard_Transient);
44 IMPLEMENT_STANDARD_HANDLE (_pyCommand         ,Standard_Transient);
45 IMPLEMENT_STANDARD_HANDLE (_pyGen             ,_pyObject);
46 IMPLEMENT_STANDARD_HANDLE (_pyMesh            ,_pyObject);
47 IMPLEMENT_STANDARD_HANDLE (_pySubMesh         ,_pyObject);
48 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor      ,_pyObject);
49 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis      ,_pyObject);
50 IMPLEMENT_STANDARD_HANDLE (_pySelfEraser      ,_pyObject);
51 IMPLEMENT_STANDARD_HANDLE (_pyGroup           ,_pyObject);
52 IMPLEMENT_STANDARD_HANDLE (_pyFilter          ,_pyObject);
53 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm       ,_pyHypothesis);
54 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
55 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
56
57 IMPLEMENT_STANDARD_RTTIEXT(_pyObject          ,Standard_Transient);
58 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand         ,Standard_Transient);
59 IMPLEMENT_STANDARD_RTTIEXT(_pyGen             ,_pyObject);
60 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh            ,_pyObject);
61 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh         ,_pyObject);
62 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor      ,_pyObject);
63 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis      ,_pyObject);
64 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser      ,_pyObject);
65 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup           ,_pyObject);
66 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter          ,_pyObject);
67 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm       ,_pyHypothesis);
68 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
69 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
70 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
71 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
72
73 using namespace std;
74 using SMESH::TPythonDump;
75
76 /*!
77  * \brief Container of commands into which the initial script is split.
78  *        It also contains data coresponding to SMESH_Gen contents
79  */
80 static Handle(_pyGen) theGen;
81
82 static TCollection_AsciiString theEmptyString;
83
84 //#define DUMP_CONVERSION
85
86 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
87 #undef DUMP_CONVERSION
88 #endif
89
90
91 namespace {
92
93   //================================================================================
94   /*!
95    * \brief Set of TCollection_AsciiString initialized by C array of C strings
96    */
97   //================================================================================
98
99   struct TStringSet: public set<TCollection_AsciiString>
100   {
101     /*!
102      * \brief Filling. The last string must be ""
103      */
104     void Insert(const char* names[]) {
105       for ( int i = 0; names[i][0] ; ++i )
106         insert( (char*) names[i] );
107     }
108     /*!
109      * \brief Check if a string is in
110      */
111     bool Contains(const TCollection_AsciiString& name ) {
112       return find( name ) != end();
113     }
114   };
115 }
116
117 //================================================================================
118 /*!
119  * \brief Convert python script using commands of smesh.py
120   * \param theScript - Input script
121   * \retval TCollection_AsciiString - Convertion result
122   *
123   * Class SMESH_2smeshpy declared in SMESH_PythonDump.hxx
124  */
125 //================================================================================
126
127 TCollection_AsciiString
128 SMESH_2smeshpy::ConvertScript(const TCollection_AsciiString& theScript,
129                               Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
130                               Resource_DataMapOfAsciiStringAsciiString& theObjectNames)
131 {
132   theGen = new _pyGen( theEntry2AccessorMethod, theObjectNames );
133
134   // split theScript into separate commands
135
136   SMESH_NoteBook * aNoteBook = new SMESH_NoteBook();
137
138   int from = 1, end = theScript.Length(), to;
139   while ( from < end && ( to = theScript.Location( "\n", from, end )))
140   {
141     if ( to != from )
142         // cut out and store a command
143         aNoteBook->AddCommand( theScript.SubString( from, to - 1 ));
144       from = to + 1;
145   }
146
147   aNoteBook->ReplaceVariables();
148
149   TCollection_AsciiString aNoteScript = aNoteBook->GetResultScript();
150   delete aNoteBook;
151   aNoteBook = 0;
152
153   // split theScript into separate commands
154   from = 1, end = aNoteScript.Length();
155   while ( from < end && ( to = aNoteScript.Location( "\n", from, end )))
156   {
157     if ( to != from )
158       // cut out and store a command
159       theGen->AddCommand( aNoteScript.SubString( from, to - 1 ));
160     from = to + 1;
161   }
162
163   // finish conversion
164   theGen->Flush();
165 #ifdef DUMP_CONVERSION
166   MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
167 #endif
168
169   // reorder commands after conversion
170   list< Handle(_pyCommand) >::iterator cmd;
171   bool orderChanges;
172   do {
173     orderChanges = false;
174     for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
175       if ( (*cmd)->SetDependentCmdsAfter() )
176         orderChanges = true;
177   } while ( orderChanges );
178
179   // concat commands back into a script
180   TCollection_AsciiString aScript;
181   for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
182   {
183 #ifdef DUMP_CONVERSION
184     MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
185 #endif
186     if ( !(*cmd)->IsEmpty() ) {
187       aScript += "\n";
188       aScript += (*cmd)->GetString();
189     }
190   }
191   aScript += "\n";
192
193   theGen.Nullify();
194
195   return aScript;
196 }
197
198 //================================================================================
199 /*!
200  * \brief _pyGen constructor
201  */
202 //================================================================================
203
204 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
205                Resource_DataMapOfAsciiStringAsciiString& theObjectNames)
206   : _pyObject( new _pyCommand( "", 0 )),
207     myNbCommands( 0 ),
208     myID2AccessorMethod( theEntry2AccessorMethod ),
209     myObjectNames( theObjectNames ),
210     myNbFilters( 0 )
211 {
212   // make that GetID() to return TPythonDump::SMESHGenName()
213   GetCreationCmd()->Clear();
214   GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
215   GetCreationCmd()->GetString() += "=";
216 }
217
218 //================================================================================
219 /*!
220  * \brief name of SMESH_Gen in smesh.py
221  */
222 //================================================================================
223
224 const char* _pyGen::AccessorMethod() const
225 {
226   return SMESH_2smeshpy::GenName();
227 }
228
229 //================================================================================
230 /*!
231  * \brief Convert a command using a specific converter
232   * \param theCommand - the command to convert
233  */
234 //================================================================================
235
236 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
237 {
238   // store theCommand in the sequence
239   myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
240
241   Handle(_pyCommand) aCommand = myCommands.back();
242 #ifdef DUMP_CONVERSION
243   MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
244 #endif
245
246   _pyID objID = aCommand->GetObject();
247
248   if ( objID.IsEmpty() )
249     return aCommand;
250
251   // Find an object to process theCommand
252
253   // SMESH_Gen method?
254   if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName()) {
255     this->Process( aCommand );
256     return aCommand;
257   }
258
259   // SMESH_Mesh method?
260   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
261   if ( id_mesh != myMeshes.end() )
262   {
263     id_mesh->second->AddProcessedCmd( aCommand );
264
265     // check for mesh editor object
266     if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
267       _pyID editorID = aCommand->GetResultValue();
268       Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
269       myMeshEditors.insert( make_pair( editorID, editor ));
270       return aCommand;
271     }
272     // check for SubMesh objects
273     else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
274       _pyID subMeshID = aCommand->GetResultValue();
275       Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
276       myObjects.insert( make_pair( subMeshID, subMesh ));
277     }
278
279     id_mesh->second->Process( aCommand );
280     return aCommand;
281   }
282
283   // SMESH_MeshEditor method?
284   map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
285   if ( id_editor != myMeshEditors.end() )
286   {
287     id_editor->second->Process( aCommand );
288     id_editor->second->AddProcessedCmd( aCommand );
289     TCollection_AsciiString processedCommand = aCommand->GetString();
290
291     // some commands of SMESH_MeshEditor create meshes
292     if ( aCommand->GetMethod().Search("MakeMesh") != -1 ) {
293       _pyID meshID = aCommand->GetResultValue();
294       Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
295       aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
296       myMeshes.insert( make_pair( meshID, mesh ));
297     }
298     if ( aCommand->GetMethod() == "MakeBoundaryMesh") {
299       _pyID meshID = aCommand->GetResultValue(0);
300       if ( !myMeshes.count( meshID ) )
301       {
302         Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
303         aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
304         myMeshes.insert( make_pair( meshID, mesh ));
305       }
306     }
307     return aCommand;
308   }
309   // SMESH_Hypothesis method?
310   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
311   for ( ; hyp != myHypos.end(); ++hyp )
312     if ( !(*hyp)->IsAlgo() && objID == (*hyp)->GetID() ) {
313       (*hyp)->Process( aCommand );
314       (*hyp)->AddProcessedCmd( aCommand );
315       return aCommand;
316     }
317
318   // aFilterManager.CreateFilter() ?
319   if ( aCommand->GetMethod() == "CreateFilter" )
320   {
321     // Set a more human readable name to a filter
322     // aFilter0x7fbf6c71cfb0 -> aFilter_nb
323     _pyID newID, filterID = aCommand->GetResultValue();
324     int pos = filterID.Search( "0x" );
325     if ( pos > 1 )
326       newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
327
328     Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
329     AddObject( filter );
330   }
331
332   // other object method?
333   map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
334   if ( id_obj != myObjects.end() ) {
335     id_obj->second->Process( aCommand );
336     id_obj->second->AddProcessedCmd( aCommand );
337     return aCommand;
338   }
339
340   // Add access to a wrapped mesh
341   AddMeshAccessorMethod( aCommand );
342
343   // Add access to a wrapped algorithm
344   //  AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
345
346   // PAL12227. PythonDump was not updated at proper time; result is
347   //     aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
348   // TypeError: __init__() takes exactly 11 arguments (10 given)
349   const char wrongCommand[] = "SMESH.Filter.Criterion(";
350   if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
351   {
352     _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
353     // there must be 10 arguments, 5-th arg ThresholdID is missing,
354     const int wrongNbArgs = 9, missingArg = 5;
355     if ( tmpCmd.GetNbArgs() == wrongNbArgs )
356     {
357       for ( int i = wrongNbArgs; i > missingArg; --i )
358         tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
359       tmpCmd.SetArg(  missingArg, "''");
360       aCommand->GetString().Trunc( beg - 1 );
361       aCommand->GetString() += tmpCmd.GetString();
362     }
363     // IMP issue 0021014
364     // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
365     //                  1           2        3       4        5       6        7
366     // instead of "SMESH.Filter.Criterion(
367     // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
368     // 1    2       3         4            5           6       7        8         9             10
369     // in order to avoid the problem of type mismatch of long and FunctorType
370     const TCollection_AsciiString
371       SMESH("SMESH."), dfltFunctor = "SMESH.FT_Undefined", dftlTol = "1e-07", dftlPreci = "-1";
372     TCollection_AsciiString
373       Type          = aCommand->GetArg(1),  // long
374       Compare       = aCommand->GetArg(2),  // long
375       Threshold     = aCommand->GetArg(3),  // double
376       ThresholdStr  = aCommand->GetArg(4),  // string
377       ThresholdID   = aCommand->GetArg(5),  // string
378       UnaryOp       = aCommand->GetArg(6),  // long
379       BinaryOp      = aCommand->GetArg(7),  // long
380       Tolerance     = aCommand->GetArg(8),  // double
381       TypeOfElement = aCommand->GetArg(9),  // ElementType
382       Precision     = aCommand->GetArg(10); // long
383     Type     = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
384     Compare  = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
385     UnaryOp  = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
386     BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
387
388     aCommand->RemoveArgs();
389     aCommand->SetObject( SMESH_2smeshpy::GenName() );
390     aCommand->SetMethod( "GetCriterion" );
391
392     aCommand->SetArg( 1, TypeOfElement );
393     aCommand->SetArg( 2, Type );
394     aCommand->SetArg( 3, Compare );
395
396     if ( Type == "SMESH.FT_ElemGeomType" && Threshold.IsIntegerValue() )
397     {
398       // set SMESH.GeometryType instead of a numerical Threshold
399       const char* types[SMESH::Geom_POLYHEDRA+1] = {
400         "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
401         "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
402         "Geom_POLYHEDRA"
403       };
404       int iGeom = Threshold.IntegerValue();
405       if ( -1 < iGeom && iGeom < SMESH::Geom_POLYHEDRA+1 )
406         Threshold = SMESH + types[ iGeom ];
407     }
408     if ( ThresholdStr.Length() != 2 ) // not '' or ""
409       aCommand->SetArg( 4, ThresholdStr );
410     else if ( ThresholdID.Length() != 2 )
411       aCommand->SetArg( 4, ThresholdID );
412     else
413       aCommand->SetArg( 4, Threshold );
414     // find the last not default arg
415     int lastDefault = 8;
416     if ( Tolerance == dftlTol ) {
417       lastDefault = 7;
418       if ( BinaryOp == dfltFunctor ) {
419         lastDefault = 6;
420         if ( UnaryOp == dfltFunctor )
421           lastDefault = 5;
422       }
423     }
424     if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
425     if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
426     if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
427     if ( Precision != dftlPreci )
428     {
429       TCollection_AsciiString crit = aCommand->GetResultValue();
430       aCommand->GetString() += "; ";
431       aCommand->GetString() += crit + ".Precision = " + Precision;
432     }
433   }
434   return aCommand;
435 }
436
437 //================================================================================
438 /*!
439  * \brief Convert the command or remember it for later conversion
440   * \param theCommand - The python command calling a method of SMESH_Gen
441  */
442 //================================================================================
443
444 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
445 {
446   // there are methods to convert:
447   // CreateMesh( shape )
448   // Concatenate( [mesh1, ...], ... )
449   // CreateHypothesis( theHypType, theLibName )
450   // Compute( mesh, geom )
451   // Evaluate( mesh, geom )
452   // mesh creation
453   TCollection_AsciiString method = theCommand->GetMethod();
454
455   if ( method == "CreateMesh" || method == "CreateEmptyMesh")
456   {
457     Handle(_pyMesh) mesh = new _pyMesh( theCommand );
458     myMeshes.insert( make_pair( mesh->GetID(), mesh ));
459     return;
460   }
461   if ( method == "CreateMeshesFromUNV" ||
462        method == "CreateMeshesFromSTL" ||
463        method == "CreateMeshesFromCGNS" ||
464        method == "CopyMesh" )
465   {
466     Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
467     myMeshes.insert( make_pair( mesh->GetID(), mesh ));
468     return;
469   }
470   if( method == "CreateMeshesFromMED" || method == "CreateMeshesFromSAUV")
471   {
472     for(int ind = 0;ind<theCommand->GetNbResultValues();ind++)
473     {
474       Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue(ind));
475       myMeshes.insert( make_pair( theCommand->GetResultValue(ind), mesh ));
476     }
477   }
478
479   // CreateHypothesis()
480   if ( method == "CreateHypothesis" )
481   {
482     // issue 199929, remove standard library name (default parameter)
483     const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
484     if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
485       // keep first argument
486       TCollection_AsciiString arg = theCommand->GetArg( 1 );
487       theCommand->RemoveArgs();
488       theCommand->SetArg( 1, arg );
489     }
490
491     myHypos.push_back( _pyHypothesis::NewHypothesis( theCommand ));
492     return;
493   }
494
495   // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
496   if ( method == "Compute" )
497   {
498     const _pyID& meshID = theCommand->GetArg( 1 );
499     map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
500     if ( id_mesh != myMeshes.end() ) {
501       theCommand->SetObject( meshID );
502       theCommand->RemoveArgs();
503       id_mesh->second->Flush();
504       return;
505     }
506   }
507
508   // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
509   if ( method == "Evaluate" )
510   {
511     const _pyID& meshID = theCommand->GetArg( 1 );
512     map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
513     if ( id_mesh != myMeshes.end() ) {
514       theCommand->SetObject( meshID );
515       _pyID geom = theCommand->GetArg( 2 );
516       theCommand->RemoveArgs();
517       theCommand->SetArg( 1, geom );
518       return;
519     }
520   }
521
522   // objects erasing creation command if no more it's commands invoked:
523   // SMESH_Pattern, FilterManager
524   if ( method == "GetPattern" ||
525        method == "CreateFilterManager" ||
526        method == "CreateMeasurements" ) {
527     Handle(_pyObject) obj = new _pySelfEraser( theCommand );
528     if ( !myObjects.insert( make_pair( obj->GetID(), obj )).second )
529       theCommand->Clear(); // already created
530   }
531
532   // Concatenate( [mesh1, ...], ... )
533   if ( method == "Concatenate" || method == "ConcatenateWithGroups")
534   {
535     if ( method == "ConcatenateWithGroups" ) {
536       theCommand->SetMethod( "Concatenate" );
537       theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
538     }
539     Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
540     myMeshes.insert( make_pair( mesh->GetID(), mesh ));
541     AddMeshAccessorMethod( theCommand );
542   }
543
544   // Replace name of SMESH_Gen
545
546   // names of SMESH_Gen methods fully equal to methods defined in smesh.py
547   static TStringSet smeshpyMethods;
548   if ( smeshpyMethods.empty() ) {
549     const char * names[] =
550       { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
551         "GetPattern","GetSubShapesId",
552         "" }; // <- mark of array end
553     smeshpyMethods.Insert( names );
554   }
555   if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
556     // smeshgen.Method() --> smesh.Method()
557     theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
558   else
559     // smeshgen.Method() --> smesh.smesh.Method()
560     theCommand->SetObject( SMESH_2smeshpy::GenName() );
561 }
562
563 //================================================================================
564 /*!
565  * \brief Convert the remembered commands
566  */
567 //================================================================================
568
569 void _pyGen::Flush()
570 {
571   // create empty command
572   myLastCommand = new _pyCommand();
573
574   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
575   for ( ; id_mesh != myMeshes.end(); ++id_mesh )
576     if ( ! id_mesh->second.IsNull() )
577       id_mesh->second->Flush();
578
579   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
580   for ( ; hyp != myHypos.end(); ++hyp )
581     if ( !hyp->IsNull() ) {
582       (*hyp)->Flush();
583       // smeshgen.CreateHypothesis() --> smesh.smesh.CreateHypothesis()
584       if ( !(*hyp)->IsWrapped() )
585         (*hyp)->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
586     }
587
588   map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
589   for ( ; id_obj != myObjects.end(); ++id_obj )
590     if ( ! id_obj->second.IsNull() )
591       id_obj->second->Flush();
592
593   myLastCommand->SetOrderNb( ++myNbCommands );
594   myCommands.push_back( myLastCommand );
595 }
596
597 //================================================================================
598 /*!
599  * \brief Add access method to mesh that is an argument
600   * \param theCmd - command to add access method
601   * \retval bool - true if added
602  */
603 //================================================================================
604
605 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
606 {
607   bool added = false;
608   map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
609   for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
610     if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
611       added = true;
612   }
613   return added;
614 }
615
616 //================================================================================
617 /*!
618  * \brief Add access method to algo that is an object or an argument
619   * \param theCmd - command to add access method
620   * \retval bool - true if added
621  */
622 //================================================================================
623
624 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
625 {
626   bool added = false;
627   list< Handle(_pyHypothesis) >::const_iterator hyp = myHypos.begin();
628   for ( ; hyp != myHypos.end(); ++hyp ) {
629     if ( (*hyp)->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
630          theCmd->AddAccessorMethod( (*hyp)->GetID(), (*hyp)->AccessorMethod() ))
631       added = true;
632   }
633   return added;
634 }
635
636 //================================================================================
637 /*!
638  * \brief Find hypothesis by ID (entry)
639   * \param theHypID - The hypothesis ID
640   * \retval Handle(_pyHypothesis) - The found hypothesis
641  */
642 //================================================================================
643
644 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
645 {
646   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
647   for ( ; hyp != myHypos.end(); ++hyp )
648     if ( !hyp->IsNull() && theHypID == (*hyp)->GetID() )
649       return *hyp;
650   return Handle(_pyHypothesis)();
651 }
652
653 //================================================================================
654 /*!
655  * \brief Find algorithm the created algorithm
656   * \param theGeom - The shape ID the algorithm was created on
657   * \param theMesh - The mesh ID that created the algorithm
658   * \param dim - The algo dimension
659   * \retval Handle(_pyHypothesis) - The found algo
660  */
661 //================================================================================
662
663 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
664                                         const Handle(_pyHypothesis)& theHypothesis )
665 {
666   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
667   for ( ; hyp != myHypos.end(); ++hyp )
668     if ( !hyp->IsNull() &&
669          (*hyp)->IsAlgo() &&
670          theHypothesis->CanBeCreatedBy( (*hyp)->GetAlgoType() ) &&
671          (*hyp)->GetGeom() == theGeom &&
672          (*hyp)->GetMesh() == theMesh )
673       return *hyp;
674   return 0;
675 }
676
677 //================================================================================
678 /*!
679  * \brief Find subMesh by ID (entry)
680   * \param theSubMeshID - The subMesh ID
681   * \retval Handle(_pySubMesh) - The found subMesh
682  */
683 //================================================================================
684
685 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
686 {
687   map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
688   if ( id_subMesh != myObjects.end() )
689     return Handle(_pySubMesh)::DownCast( id_subMesh->second );
690   return Handle(_pySubMesh)();
691 }
692
693
694 //================================================================================
695 /*!
696  * \brief Change order of commands in the script
697   * \param theCmd1 - One command
698   * \param theCmd2 - Another command
699  */
700 //================================================================================
701
702 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
703 {
704   list< Handle(_pyCommand) >::iterator pos1, pos2;
705   pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
706   pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
707   myCommands.insert( pos1, theCmd2 );
708   myCommands.insert( pos2, theCmd1 );
709   myCommands.erase( pos1 );
710   myCommands.erase( pos2 );
711
712   int nb1 = theCmd1->GetOrderNb();
713   theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
714   theCmd2->SetOrderNb( nb1 );
715 //   cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
716 //        << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
717 }
718
719 //================================================================================
720 /*!
721  * \brief Set one command after the other
722   * \param theCmd - Command to move
723   * \param theAfterCmd - Command ater which to insert the first one
724  */
725 //================================================================================
726
727 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
728 {
729   setNeighbourCommand( theCmd, theAfterCmd, true );
730 }
731
732 //================================================================================
733 /*!
734  * \brief Set one command before the other
735   * \param theCmd - Command to move
736   * \param theBeforeCmd - Command before which to insert the first one
737  */
738 //================================================================================
739
740 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
741 {
742   setNeighbourCommand( theCmd, theBeforeCmd, false );
743 }
744
745 //================================================================================
746 /*!
747  * \brief Set one command before or after the other
748   * \param theCmd - Command to move
749   * \param theOtherCmd - Command ater or before which to insert the first one
750  */
751 //================================================================================
752
753 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
754                                   Handle(_pyCommand)& theOtherCmd,
755                                   const bool theIsAfter )
756 {
757   list< Handle(_pyCommand) >::iterator pos;
758   pos = find( myCommands.begin(), myCommands.end(), theCmd );
759   myCommands.erase( pos );
760   pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
761   myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
762
763   int i = 1;
764   for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
765     (*pos)->SetOrderNb( i++ );
766 }
767
768 //================================================================================
769 /*!
770  * \brief Set command be last in list of commands
771   * \param theCmd - Command to be last
772  */
773 //================================================================================
774
775 Handle(_pyCommand)& _pyGen::GetLastCommand()
776 {
777   return myLastCommand;
778 }
779
780 //================================================================================
781 /*!
782  * \brief Set method to access to object wrapped with python class
783   * \param theID - The wrapped object entry
784   * \param theMethod - The accessor method
785  */
786 //================================================================================
787
788 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
789 {
790   myID2AccessorMethod.Bind( theID, (char*) theMethod );
791 }
792
793 //================================================================================
794 /*!
795  * \brief Generated new ID for object and assign with existing name
796   * \param theID - ID of existing object
797  */
798 //================================================================================
799
800 _pyID _pyGen::GenerateNewID( const _pyID& theID )
801 {
802   int index = 1;
803   _pyID aNewID;
804   do {
805     aNewID = theID + _pyID( ":" ) + _pyID( index++ );
806   }
807   while ( myObjectNames.IsBound( aNewID ) );
808
809   myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
810                       ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
811                       : _pyID( "A" ) + aNewID );
812   return aNewID;
813 }
814
815 //================================================================================
816 /*!
817  * \brief Stores theObj in myObjects
818  */
819 //================================================================================
820
821 void _pyGen::AddObject( Handle(_pyObject)& theObj )
822 {
823   myObjects.insert( make_pair( theObj->GetID(), theObj ));
824 }
825
826 //================================================================================
827 /*!
828  * \brief Finds a _pyObject by ID
829  */
830 //================================================================================
831
832 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID )  const
833 {
834   std::map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
835   return ( id_obj == myObjects.end() ) ? Handle(_pyObject)() : id_obj->second;
836 }
837
838 //================================================================================
839 /*!
840  * \brief Returns true if an object is removed from study
841  */
842 //================================================================================
843
844 bool _pyGen::IsDead(const _pyID& theObjID) const
845 {
846   if ( theObjID.IsEmpty() ) return false;
847   const bool hasStudyName = myObjectNames.IsBound( theObjID );
848   return !hasStudyName;
849 }
850
851 //================================================================================
852 /*!
853  * \brief Find out type of geom group
854   * \param grpID - The geom group entry
855   * \retval int - The type
856  */
857 //================================================================================
858
859 // static bool sameGroupType( const _pyID&                   grpID,
860 //                            const TCollection_AsciiString& theType)
861 // {
862 //   // define group type as smesh.Mesh.Group() does
863 //   int type = -1;
864 //   SALOMEDS::Study_var study = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
865 //   SALOMEDS::SObject_var aSObj = study->FindObjectID( grpID.ToCString() );
866 //   if ( !aSObj->_is_nil() ) {
867 //     GEOM::GEOM_Object_var aGeomObj = GEOM::GEOM_Object::_narrow( aSObj->GetObject() );
868 //     if ( !aGeomObj->_is_nil() ) {
869 //       switch ( aGeomObj->GetShapeType() ) {
870 //       case GEOM::VERTEX: type = SMESH::NODE; break;
871 //       case GEOM::EDGE:   type = SMESH::EDGE; break;
872 //       case GEOM::FACE:   type = SMESH::FACE; break;
873 //       case GEOM::SOLID:
874 //       case GEOM::SHELL:  type = SMESH::VOLUME; break;
875 //       case GEOM::COMPOUND: {
876 //         GEOM::GEOM_Gen_ptr aGeomGen = SMESH_Gen_i::GetSMESHGen()->GetGeomEngine();
877 //         if ( !aGeomGen->_is_nil() ) {
878 //           GEOM::GEOM_IGroupOperations_var aGrpOp =
879 //             aGeomGen->GetIGroupOperations( study->StudyId() );
880 //           if ( !aGrpOp->_is_nil() ) {
881 //             switch ( aGrpOp->GetType( aGeomObj )) {
882 //             case TopAbs_VERTEX: type = SMESH::NODE; break;
883 //             case TopAbs_EDGE:   type = SMESH::EDGE; break;
884 //             case TopAbs_FACE:   type = SMESH::FACE; break;
885 //             case TopAbs_SOLID:  type = SMESH::VOLUME; break;
886 //             default:;
887 //             }
888 //           }
889 //         }
890 //       }
891 //       default:;
892 //       }
893 //     }
894 //   }
895 //   if ( type < 0 ) {
896 //     MESSAGE("Type of the group " << grpID << " not found");
897 //     return false;
898 //   }
899 //   if ( theType.IsIntegerValue() )
900 //     return type == theType.IntegerValue();
901
902 //   switch ( type ) {
903 //   case SMESH::NODE:   return theType.Location( "NODE", 1, theType.Length() );
904 //   case SMESH::EDGE:   return theType.Location( "EDGE", 1, theType.Length() );
905 //   case SMESH::FACE:   return theType.Location( "FACE", 1, theType.Length() );
906 //   case SMESH::VOLUME: return theType.Location( "VOLUME", 1, theType.Length() );
907 //   default:;
908 //   }
909 //   return false;
910 // }
911
912 //================================================================================
913 /*!
914  * \brief
915   * \param theCreationCmd -
916  */
917 //================================================================================
918
919 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
920   : _pyObject(theCreationCmd), myHasEditor(false)
921 {
922   // convert my creation command
923   Handle(_pyCommand) creationCmd = GetCreationCmd();
924   //TCollection_AsciiString str = creationCmd->GetMethod();
925 //   if(str != "CreateMeshesFromUNV" &&
926 //      str != "CreateMeshesFromMED" &&
927 //      str != "CreateMeshesFromSTL")
928   creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
929   creationCmd->SetMethod( "Mesh" );
930
931   theGen->SetAccessorMethod( GetID(), "GetMesh()" );
932 }
933
934 //================================================================================
935 /*!
936  * \brief
937   * \param theCreationCmd -
938  */
939 //================================================================================
940 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const TCollection_AsciiString& id):
941   _pyObject(theCreationCmd), myHasEditor(false)
942 {
943   // convert my creation command
944   Handle(_pyCommand) creationCmd = GetCreationCmd();
945   creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
946   theGen->SetAccessorMethod( id, "GetMesh()" );
947 }
948
949 //================================================================================
950 /*!
951  * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
952   * \param theCommand - Engine method called for this mesh
953  */
954 //================================================================================
955
956 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
957 {
958   // some methods of SMESH_Mesh interface needs special conversion
959   // to methods of Mesh python class
960   //
961   // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
962   //     --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
963   // 2. AddHypothesis(geom, hyp)
964   //     --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
965   // 3. CreateGroupFromGEOM(type, name, grp)
966   //     --> in Mesh.Group(grp, name="")
967   // 4. ExportToMED(f, auto_groups, version)
968   //     --> in Mesh.ExportMED( f, auto_groups, version )
969   // 5. etc
970
971   const TCollection_AsciiString method = theCommand->GetMethod();
972   // ----------------------------------------------------------------------
973   if ( method == "GetSubMesh" ) { // collect submeshes of the mesh
974     Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
975     if ( !subMesh.IsNull() ) {
976       subMesh->SetCreator( this );
977       mySubmeshes.push_back( subMesh );
978     }
979   }
980   // ----------------------------------------------------------------------
981   else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
982     myAddHypCmds.push_back( theCommand );
983     // set mesh to hypo
984     const _pyID& hypID = theCommand->GetArg( 2 );
985     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
986     if ( !hyp.IsNull() ) {
987       myHypos.push_back( hyp );
988       if ( hyp->GetMesh().IsEmpty() )
989         hyp->SetMesh( this->GetID() );
990     }
991   }
992   // ----------------------------------------------------------------------
993   else if ( method == "CreateGroupFromGEOM" ) {// (type, name, grp)
994     _pyID grp = theCommand->GetArg( 3 );
995     // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
996     // next if(){...} section is commented
997     //if ( sameGroupType( grp, theCommand->GetArg( 1 )) ) { // --> Group(grp)
998     //  theCommand->SetMethod( "Group" );
999     //  theCommand->RemoveArgs();
1000     //  theCommand->SetArg( 1, grp );
1001     //}
1002     //else {
1003     // ------------------------->>>>> GroupOnGeom( grp, name, typ )
1004       _pyID type = theCommand->GetArg( 1 );
1005       _pyID name = theCommand->GetArg( 2 );
1006       theCommand->SetMethod( "GroupOnGeom" );
1007       theCommand->RemoveArgs();
1008       theCommand->SetArg( 1, grp );
1009       theCommand->SetArg( 2, name );
1010       theCommand->SetArg( 3, type );
1011     //}
1012   }
1013   // ----------------------------------------------------------------------
1014   else if ( method == "CreateGroupFromFilter" ) // --> GroupOnFilter()
1015   {
1016     theCommand->SetMethod( "GroupOnFilter" );
1017     Handle(_pyGroup) group = new _pyGroup( theCommand );
1018     theGen->AddObject( group );
1019
1020     // GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
1021     _pyID filterID = theCommand->GetArg(3);
1022     Handle(_pyObject) filter = theGen->FindObject( filterID );
1023     if ( !filter.IsNull() && filter->IsKind(STANDARD_TYPE(_pyFilter)))
1024       filter->Process( theCommand );
1025   }
1026   // ----------------------------------------------------------------------
1027   else if ( method == "GetIdsFromFilter" )
1028   {
1029     // GetIdsFromFilter( aFilter0x4743dc0) -> GetIdsFromFilter( aFilter_1)
1030     _pyID filterID = theCommand->GetArg(1);
1031     Handle(_pyObject) filter = theGen->FindObject( filterID );
1032     if ( !filter.IsNull() && filter->IsKind(STANDARD_TYPE(_pyFilter)))
1033       filter->Process( theCommand );
1034   }
1035   // ----------------------------------------------------------------------
1036   else if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
1037   {
1038     theCommand->SetMethod( "CreateEmptyGroup" );
1039     Handle(_pyGroup) group = new _pyGroup( theCommand );
1040     theGen->AddObject( group );
1041   }
1042   // ----------------------------------------------------------------------
1043   else if ( method == "ExportToMED" ||   // ExportToMED()  --> ExportMED()
1044             method == "ExportToMEDX" ) { // ExportToMEDX() --> ExportMED()
1045     theCommand->SetMethod( "ExportMED" );
1046   }
1047   // ----------------------------------------------------------------------
1048   else if ( method == "ExportCGNS" )
1049   { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1050     _pyID partID = theCommand->GetArg( 1 );
1051     int nbArgs = theCommand->GetNbArgs();
1052     for ( int i = 2; i <= nbArgs; ++i )
1053       theCommand->SetArg( i-1, theCommand->GetArg( i ));
1054     theCommand->SetArg( nbArgs, partID );
1055   }
1056   // ----------------------------------------------------------------------
1057   else if ( method.Location( "ExportPartTo", 1, method.Length() ) == 1 )
1058   { // ExportPartTo*(part, ...) -> Export*(..., part)
1059     //
1060     // remove "PartTo" from the method
1061     TCollection_AsciiString newMethod = method;
1062     newMethod.Remove( 7, 6 );
1063     theCommand->SetMethod( newMethod );
1064     // make the 1st arg be the last one
1065     _pyID partID = theCommand->GetArg( 1 );
1066     int nbArgs = theCommand->GetNbArgs();
1067     for ( int i = 2; i <= nbArgs; ++i )
1068       theCommand->SetArg( i-1, theCommand->GetArg( i ));
1069     theCommand->SetArg( nbArgs, partID );
1070   }
1071   // ----------------------------------------------------------------------
1072   else if ( method == "RemoveHypothesis" ) // (geom, hyp)
1073   {
1074     _pyID hypID = theCommand->GetArg( 2 );
1075
1076     // check if this mesh still has corresponding addition command
1077     bool hasAddCmd = false;
1078     list< Handle(_pyCommand) >::iterator cmd = myAddHypCmds.begin();
1079     while ( cmd != myAddHypCmds.end() )
1080     {
1081       // AddHypothesis(geom, hyp)
1082       if ( hypID == (*cmd)->GetArg( 2 )) { // erase both (add and remove) commands
1083         theCommand->Clear();
1084         (*cmd)->Clear();
1085         cmd = myAddHypCmds.erase( cmd );
1086         hasAddCmd = true;
1087       }
1088       else {
1089         ++cmd;
1090       }
1091     }
1092     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1093     if ( ! hasAddCmd && hypID.Length() != 0 ) { // hypo addition already wrapped
1094       // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
1095       _pyID geom = theCommand->GetArg( 1 );
1096       theCommand->RemoveArgs();
1097       theCommand->SetArg( 1, hypID );
1098       if ( geom != GetGeom() )
1099         theCommand->SetArg( 2, geom );
1100     }
1101     // remove hyp from myHypos
1102     myHypos.remove( hyp );
1103   }
1104   // check for SubMesh order commands
1105   else if ( theCommand->GetMethod() == "GetMeshOrder" ||
1106             theCommand->GetMethod() == "SetMeshOrder" )
1107   {
1108     // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
1109     // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
1110     // commands are moved at the end of the script
1111     const bool isArg = theCommand->GetMethod() == "SetMeshOrder";
1112     const TCollection_AsciiString& cmdStr = theCommand->GetString();
1113     int begPos = (/*isArg ? cmdStr.Search( "(" ) :*/ cmdStr.Search( "[" )) + 1;
1114     int endPos = (isArg ? cmdStr.Search( ")" ) : cmdStr.Search( "=" )) - 1;
1115     if ( begPos != -1 && begPos < endPos && endPos <= cmdStr.Length() ) {
1116       TCollection_AsciiString aSubStr = cmdStr.SubString( begPos, endPos );
1117       Standard_Integer index = 1;
1118       TCollection_AsciiString anIDStr = aSubStr.Token("\t ,[]", index++);
1119       while ( !anIDStr.IsEmpty() ) {
1120         Handle(_pySubMesh) subMesh = theGen->FindSubMesh( anIDStr );
1121         if ( !subMesh.IsNull() )
1122           subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
1123         anIDStr = aSubStr.Token("\t ,[]", index++);
1124       }
1125     }
1126   }
1127   // add accessor method if necessary
1128   else
1129   {
1130     if ( NeedMeshAccess( theCommand ))
1131       // apply theCommand to the mesh wrapped by smeshpy mesh
1132       AddMeshAccess( theCommand );
1133   }
1134 }
1135
1136 //================================================================================
1137 /*!
1138  * \brief Return True if addition of accesor method is needed
1139  */
1140 //================================================================================
1141
1142 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
1143 {
1144   // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
1145   // so no conversion is needed for them at all:
1146   static TStringSet sameMethods;
1147   if ( sameMethods.empty() ) {
1148     const char * names[] =
1149       { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
1150         "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
1151         "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
1152         "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
1153         "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
1154         "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
1155         "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
1156         "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
1157         "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
1158         "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
1159         "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
1160         "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
1161         "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
1162         ,"" }; // <- mark of end
1163     sameMethods.Insert( names );
1164   }
1165
1166   return !sameMethods.Contains( theCommand->GetMethod() );
1167 }
1168
1169 //================================================================================
1170 /*!
1171  * \brief Convert creation and addition of all algos and hypos
1172  */
1173 //================================================================================
1174
1175 void _pyMesh::Flush()
1176 {
1177   list < Handle(_pyCommand) >::iterator cmd;
1178
1179   // try to convert algo addition like this:
1180   // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
1181   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
1182   {
1183     Handle(_pyCommand) addCmd = *cmd;
1184
1185     _pyID algoID = addCmd->GetArg( 2 );
1186     Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
1187     if ( algo.IsNull() || !algo->IsAlgo() )
1188       continue;
1189
1190     // check and create new algorithm instance if it is already wrapped
1191     if ( algo->IsWrapped() ) {
1192       _pyID localAlgoID = theGen->GenerateNewID( algoID );
1193       TCollection_AsciiString aNewCmdStr = localAlgoID +
1194         TCollection_AsciiString( " = " ) + theGen->GetID() +
1195         TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
1196         TCollection_AsciiString( "\" )" );
1197
1198       Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
1199       Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
1200       if ( !newAlgo.IsNull() ) {
1201         newAlgo->Assign( algo, this->GetID() );
1202         newAlgo->SetCreationCmd( newCmd );
1203         algo = newAlgo;
1204         // set algorithm creation
1205         theGen->SetCommandBefore( newCmd, addCmd );
1206       }
1207       else
1208         newCmd->Clear();
1209     }
1210     _pyID geom = addCmd->GetArg( 1 );
1211     bool isLocalAlgo = ( geom != GetGeom() );
1212
1213     // try to convert
1214     if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
1215     {
1216       // wrapped algo is created after mesh creation
1217       GetCreationCmd()->AddDependantCmd( addCmd );
1218
1219       if ( isLocalAlgo ) {
1220         // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
1221         addCmd->SetArg( addCmd->GetNbArgs() + 1,
1222                         TCollection_AsciiString( "geom=" ) + geom );
1223         // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
1224         list < Handle(_pySubMesh) >::iterator smIt;
1225         for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
1226           Handle(_pySubMesh) subMesh = *smIt;
1227           Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
1228           if ( geom == subCmd->GetArg( 1 )) {
1229             subCmd->SetObject( algo->GetID() );
1230             subCmd->RemoveArgs();
1231             subMesh->SetCreator( algo );
1232           }
1233         }
1234       }
1235     }
1236     else // KO - ALGO was already created
1237     {
1238       // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
1239       addCmd->RemoveArgs();
1240       addCmd->SetArg( 1, algoID );
1241       if ( isLocalAlgo )
1242         addCmd->SetArg( 2, geom );
1243     }
1244   }
1245
1246   // try to convert hypo addition like this:
1247   // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
1248   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
1249   {
1250     Handle(_pyCommand) addCmd = *cmd;
1251     _pyID hypID = addCmd->GetArg( 2 );
1252     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1253     if ( hyp.IsNull() || hyp->IsAlgo() )
1254       continue;
1255     bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
1256     if ( !converted ) {
1257       // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
1258       _pyID geom = addCmd->GetArg( 1 );
1259       addCmd->RemoveArgs();
1260       addCmd->SetArg( 1, hypID );
1261       if ( geom != GetGeom() )
1262         addCmd->SetArg( 2, geom );
1263     }
1264   }
1265
1266   // sm = mesh.GetSubMesh(geom, name) --> sm = mesh.GetMesh().GetSubMesh(geom, name)
1267 //   for ( cmd = mySubmeshes.begin(); cmd != mySubmeshes.end(); ++cmd ) {
1268 //     Handle(_pyCommand) subCmd = *cmd;
1269 //     if ( subCmd->GetNbArgs() > 0 )
1270 //       AddMeshAccess( subCmd );
1271 //   }
1272   myAddHypCmds.clear();
1273   mySubmeshes.clear();
1274
1275   // flush hypotheses
1276   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1277   for ( ; hyp != myHypos.end(); ++hyp )
1278     (*hyp)->Flush();
1279 }
1280
1281 //================================================================================
1282 /*!
1283  * \brief MeshEditor convert its commands to ones of mesh
1284  */
1285 //================================================================================
1286
1287 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
1288   _pyObject( theCreationCmd )
1289 {
1290   myMesh = theCreationCmd->GetObject();
1291   myCreationCmdStr = theCreationCmd->GetString();
1292   theCreationCmd->Clear();
1293 }
1294
1295 //================================================================================
1296 /*!
1297  * \brief convert its commands to ones of mesh
1298  */
1299 //================================================================================
1300
1301 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
1302 {
1303   // names of SMESH_MeshEditor methods fully equal to methods of python class Mesh, so
1304   // commands calling this methods are converted to calls of methods of Mesh
1305   static TStringSet sameMethods;
1306   if ( sameMethods.empty() ) {
1307     const char * names[] = {
1308       "RemoveElements","RemoveNodes","RemoveOrphanNodes","AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace",
1309       "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces","MoveNode", "MoveClosestNodeToPoint",
1310       "InverseDiag","DeleteDiag","Reorient","ReorientObject","TriToQuad","SplitQuad","SplitQuadObject",
1311       "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
1312       "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
1313       "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
1314       "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
1315       "ExtrusionAlongPath","ExtrusionAlongPathObject","ExtrusionAlongPathX",
1316       "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
1317       "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
1318       "FindCoincidentNodes",/*"FindCoincidentNodesOnPart",*/"MergeNodes","FindEqualElements",
1319       "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
1320       "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
1321       "GetLastCreatedElems",
1322       "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh",
1323       "TranslateObjectMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
1324       "MakeBoundaryElements"
1325       ,"" }; // <- mark of the end
1326     sameMethods.Insert( names );
1327   }
1328
1329   // names of SMESH_MeshEditor methods which differ from methods of class Mesh
1330   // only by last two arguments
1331   static TStringSet diffLastTwoArgsMethods;
1332   if (diffLastTwoArgsMethods.empty() ) {
1333     const char * names[] = {
1334       "MirrorMakeGroups","MirrorObjectMakeGroups",
1335       "TranslateMakeGroups","TranslateObjectMakeGroups",
1336       "RotateMakeGroups","RotateObjectMakeGroups",
1337       ""};// <- mark of the end
1338     diffLastTwoArgsMethods.Insert( names );
1339   }
1340
1341   const TCollection_AsciiString & method = theCommand->GetMethod();
1342   bool isPyMeshMethod = sameMethods.Contains( method );
1343   if ( !isPyMeshMethod )
1344   {
1345     //Replace SMESH_MeshEditor "MakeGroups" functions by the Mesh
1346     //functions with the flag "theMakeGroups = True" like:
1347     //SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
1348     int pos = method.Search("MakeGroups");
1349     if( pos != -1)
1350     {
1351       isPyMeshMethod = true;
1352
1353       // 1. Remove "MakeGroups" from the Command
1354       TCollection_AsciiString aMethod = theCommand->GetMethod();
1355       int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
1356       aMethod.Trunc(pos-1);
1357       theCommand->SetMethod(aMethod);
1358
1359       // 2. And add last "True" argument(s)
1360       while(nbArgsToAdd--)
1361         theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
1362     }
1363   }
1364
1365   // set "ExtrusionAlongPathX()" instead of "ExtrusionAlongPathObjX()"
1366   if ( !isPyMeshMethod && method == "ExtrusionAlongPathObjX")
1367   {
1368     isPyMeshMethod=true;
1369     theCommand->SetMethod("ExtrusionAlongPathX");
1370   }
1371
1372   // set "FindCoincidentNodesOnPart()" instead of "FindCoincidentNodesOnPartBut()"
1373   if ( !isPyMeshMethod && method == "FindCoincidentNodesOnPartBut")
1374   {
1375     isPyMeshMethod=true;
1376     theCommand->SetMethod("FindCoincidentNodesOnPart");
1377   }
1378   // DoubleNodeElemGroupNew() -> DoubleNodeElemGroup()
1379   // DoubleNodeGroupNew() -> DoubleNodeGroup()
1380   // DoubleNodeGroupsNew() -> DoubleNodeGroups()
1381   // DoubleNodeElemGroupsNew() -> DoubleNodeElemGroups()
1382   if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew"  ||
1383                             method == "DoubleNodeElemGroupsNew" ||
1384                             method == "DoubleNodeGroupNew"      ||
1385                             method == "DoubleNodeGroupsNew"))
1386   {
1387     isPyMeshMethod=true;
1388     theCommand->SetMethod( method.SubString( 1, method.Length()-3));
1389     theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
1390   }
1391   // ConvertToQuadraticObject(bool,obj) -> ConvertToQuadratic(bool,obj)
1392   // ConvertFromQuadraticObject(obj) -> ConvertFromQuadratic(obj)
1393   if ( !isPyMeshMethod && ( method == "ConvertToQuadraticObject" ||
1394                             method == "ConvertFromQuadraticObject" ))
1395   {
1396     isPyMeshMethod=true;
1397     theCommand->SetMethod( method.SubString( 1, method.Length()-6));
1398     // prevent moving creation of the converted sub-mesh to the end of the script
1399     bool isFromQua = ( method.Value( 8 ) == 'F' );
1400     Handle(_pySubMesh) sm = theGen->FindSubMesh( theCommand->GetArg( isFromQua ? 1 : 2 ));
1401     if ( !sm.IsNull() )
1402       sm->Process( theCommand );
1403   }
1404   // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
1405   // FindElementsByPoint(x, y, z, elementType, meshPart)
1406   if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
1407   {
1408     isPyMeshMethod=true;
1409     theCommand->SetMethod( "FindElementsByPoint" );
1410     // make the 1st arg be the last one
1411     _pyID partID = theCommand->GetArg( 1 );
1412     int nbArgs = theCommand->GetNbArgs();
1413     for ( int i = 2; i <= nbArgs; ++i )
1414       theCommand->SetArg( i-1, theCommand->GetArg( i ));
1415     theCommand->SetArg( nbArgs, partID );
1416   }
1417
1418   // meshes made by *MakeMesh() methods are not wrapped by _pyMesh,
1419   // so let _pyMesh care of it (TMP?)
1420   //     if ( theCommand->GetMethod().Search("MakeMesh") != -1 )
1421   //       _pyMesh( new _pyCommand( theCommand->GetString(), 0 )); // for theGen->SetAccessorMethod()
1422   if ( isPyMeshMethod )
1423   {
1424     theCommand->SetObject( myMesh );
1425   }
1426   else
1427   {
1428     // editor creation command is needed only if any editor function is called
1429     theGen->AddMeshAccessorMethod( theCommand ); // for *Object()
1430     if ( !myCreationCmdStr.IsEmpty() ) {
1431       GetCreationCmd()->GetString() = myCreationCmdStr;
1432       myCreationCmdStr.Clear();
1433     }
1434   }
1435 }
1436
1437 //================================================================================
1438 /*!
1439  * \brief _pyHypothesis constructor
1440   * \param theCreationCmd -
1441  */
1442 //================================================================================
1443
1444 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
1445   _pyObject( theCreationCmd )
1446 {
1447   myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
1448 }
1449
1450 //================================================================================
1451 /*!
1452  * \brief Creates algorithm or hypothesis
1453   * \param theCreationCmd - The engine command creating a hypothesis
1454   * \retval Handle(_pyHypothesis) - Result _pyHypothesis
1455  */
1456 //================================================================================
1457
1458 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
1459 {
1460   // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
1461   ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
1462
1463   Handle(_pyHypothesis) hyp, algo;
1464
1465   // "theHypType"
1466   const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
1467   if ( hypTypeQuoted.IsEmpty() )
1468     return hyp;
1469   // theHypType
1470   TCollection_AsciiString  hypType =
1471     hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
1472
1473   algo = new _pyAlgorithm( theCreationCmd );
1474   hyp  = new _pyHypothesis( theCreationCmd );
1475
1476   // 1D Regular_1D ----------
1477   if ( hypType == "Regular_1D" ) {
1478     // set mesh's method creating algo,
1479     // i.e. convertion result will be "regular1d = Mesh.Segment()",
1480     // and set hypType by which algo creating a hypothesis is searched for
1481     algo->SetConvMethodAndType("Segment", hypType.ToCString());
1482   }
1483   else if ( hypType == "CompositeSegment_1D" ) {
1484     algo->SetConvMethodAndType("Segment", "Regular_1D");
1485     algo->myArgs.Append( "algo=smesh.COMPOSITE");
1486   }
1487   else if ( hypType == "LocalLength" ) {
1488     // set algo's method creating hyp, and algo type
1489     hyp->SetConvMethodAndType( "LocalLength", "Regular_1D");
1490     // set method whose 1 arg will become the 1-st arg of hyp creation command
1491     // i.e. convertion result will be "locallength = regular1d.LocalLength(<arg of SetLength()>)"
1492     hyp->AddArgMethod( "SetLength" );
1493   }
1494   else if ( hypType == "MaxLength" ) {
1495     // set algo's method creating hyp, and algo type
1496     hyp->SetConvMethodAndType( "MaxSize", "Regular_1D");
1497     // set method whose 1 arg will become the 1-st arg of hyp creation command
1498     // i.e. convertion result will be "maxsize = regular1d.MaxSize(<arg of SetLength()>)"
1499     hyp->AddArgMethod( "SetLength" );
1500   }
1501   else if ( hypType == "NumberOfSegments" ) {
1502     hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
1503     hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
1504     // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
1505     hyp->AddArgMethod( "SetNumberOfSegments" );
1506     // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
1507     hyp->AddArgMethod( "SetScaleFactor" );
1508     hyp->AddArgMethod( "SetReversedEdges" );
1509   }
1510   else if ( hypType == "Arithmetic1D" ) {
1511     hyp = new _pyComplexParamHypo( theCreationCmd );
1512     hyp->SetConvMethodAndType( "Arithmetic1D", "Regular_1D");
1513     hyp->AddArgMethod( "SetStartLength" );
1514     hyp->AddArgMethod( "SetEndLength" );
1515     hyp->AddArgMethod( "SetReversedEdges" );
1516   }
1517   else if ( hypType == "StartEndLength" ) {
1518     hyp = new _pyComplexParamHypo( theCreationCmd );
1519     hyp->SetConvMethodAndType( "StartEndLength", "Regular_1D");
1520     hyp->AddArgMethod( "SetStartLength" );
1521     hyp->AddArgMethod( "SetEndLength" );
1522     hyp->AddArgMethod( "SetReversedEdges" );
1523   }
1524   else if ( hypType == "Deflection1D" ) {
1525     hyp->SetConvMethodAndType( "Deflection1D", "Regular_1D");
1526     hyp->AddArgMethod( "SetDeflection" );
1527   }
1528   else if ( hypType == "Propagation" ) {
1529     hyp->SetConvMethodAndType( "Propagation", "Regular_1D");
1530   }
1531   else if ( hypType == "QuadraticMesh" ) {
1532     hyp->SetConvMethodAndType( "QuadraticMesh", "Regular_1D");
1533   }
1534   else if ( hypType == "AutomaticLength" ) {
1535     hyp->SetConvMethodAndType( "AutomaticLength", "Regular_1D");
1536     hyp->AddArgMethod( "SetFineness");
1537   }
1538   else if ( hypType == "SegmentLengthAroundVertex" ) {
1539     hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
1540     hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
1541     hyp->AddArgMethod( "SetLength" );
1542   }
1543   // 1D Python_1D ----------
1544   else if ( hypType == "Python_1D" ) {
1545     algo->SetConvMethodAndType( "Segment", hypType.ToCString());
1546     algo->myArgs.Append( "algo=smesh.PYTHON");
1547   }
1548   else if ( hypType == "PythonSplit1D" ) {
1549     hyp->SetConvMethodAndType( "PythonSplit1D", "Python_1D");
1550     hyp->AddArgMethod( "SetNumberOfSegments");
1551     hyp->AddArgMethod( "SetPythonLog10RatioFunction");
1552   }
1553   // MEFISTO_2D ----------
1554   else if ( hypType == "MEFISTO_2D" ) { // MEFISTO_2D
1555     algo->SetConvMethodAndType( "Triangle", hypType.ToCString());
1556   }
1557   else if ( hypType == "MaxElementArea" ) {
1558     hyp->SetConvMethodAndType( "MaxElementArea", "MEFISTO_2D");
1559     hyp->SetConvMethodAndType( "MaxElementArea", "NETGEN_2D_ONLY");
1560     hyp->AddArgMethod( "SetMaxElementArea");
1561   }
1562   else if ( hypType == "LengthFromEdges" ) {
1563     hyp->SetConvMethodAndType( "LengthFromEdges", "MEFISTO_2D");
1564     hyp->SetConvMethodAndType( "LengthFromEdges", "NETGEN_2D_ONLY");
1565   }
1566   // Quadrangle_2D ----------
1567   else if ( hypType == "Quadrangle_2D" ) {
1568     algo->SetConvMethodAndType( "Quadrangle" , hypType.ToCString());
1569   }
1570   else if ( hypType == "QuadranglePreference" ) {
1571     hyp->SetConvMethodAndType( "QuadranglePreference", "Quadrangle_2D");
1572     hyp->SetConvMethodAndType( "SetQuadAllowed", "NETGEN_2D_ONLY");
1573   }
1574   else if ( hypType == "TrianglePreference" ) {
1575     hyp->SetConvMethodAndType( "TrianglePreference", "Quadrangle_2D");
1576   }
1577   // RadialQuadrangle_1D2D ----------
1578   else if ( hypType == "RadialQuadrangle_1D2D" ) {
1579     algo->SetConvMethodAndType( "Quadrangle" , hypType.ToCString());
1580     algo->myArgs.Append( "algo=smesh.RADIAL_QUAD" );
1581   }
1582   else if ( hypType == "NumberOfLayers2D" ) {
1583     hyp->SetConvMethodAndType( "NumberOfLayers", "RadialQuadrangle_1D2D");
1584     hyp->AddArgMethod( "SetNumberOfLayers" );
1585   }
1586   else if ( hypType == "LayerDistribution2D" ) {
1587     hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
1588     hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
1589   }
1590   // BLSURF ----------
1591   else if ( hypType == "BLSURF" ) {
1592     algo->SetConvMethodAndType( "Triangle", hypType.ToCString());
1593     algo->myArgs.Append( "algo=smesh.BLSURF" );
1594   }
1595   else if ( hypType == "BLSURF_Parameters") {
1596     hyp->SetConvMethodAndType( "Parameters", "BLSURF");
1597   }
1598   // NETGEN ----------
1599   else if ( hypType == "NETGEN_2D") { // 1D-2D
1600     algo->SetConvMethodAndType( "Triangle" , hypType.ToCString());
1601     algo->myArgs.Append( "algo=smesh.NETGEN" );
1602   }
1603   else if ( hypType == "NETGEN_Parameters_2D") {
1604     hyp->SetConvMethodAndType( "Parameters", "NETGEN_2D");
1605   }
1606   else if ( hypType == "NETGEN_SimpleParameters_2D") {
1607     hyp->SetConvMethodAndType( "Parameters", "NETGEN_2D");
1608     hyp->myArgs.Append( "which=smesh.SIMPLE" );
1609   }
1610   else if ( hypType == "NETGEN_2D3D") { // 1D-2D-3D
1611     algo->SetConvMethodAndType( "Tetrahedron" , hypType.ToCString());
1612     algo->myArgs.Append( "algo=smesh.FULL_NETGEN" );
1613   }
1614   else if ( hypType == "NETGEN_Parameters") {
1615     hyp->SetConvMethodAndType( "Parameters", "NETGEN_2D3D");
1616   }
1617   else if ( hypType == "NETGEN_SimpleParameters_3D") {
1618     hyp->SetConvMethodAndType( "Parameters", "NETGEN_2D3D");
1619     hyp->myArgs.Append( "which=smesh.SIMPLE" );
1620   }
1621   else if ( hypType == "NETGEN_2D_ONLY") { // 2D
1622     algo->SetConvMethodAndType( "Triangle" , hypType.ToCString());
1623     algo->myArgs.Append( "algo=smesh.NETGEN_2D" );
1624   }
1625   else if ( hypType == "NETGEN_3D") { // 3D
1626     algo->SetConvMethodAndType( "Tetrahedron" , hypType.ToCString());
1627     algo->myArgs.Append( "algo=smesh.NETGEN" );
1628   }
1629   else if ( hypType == "MaxElementVolume") {
1630     hyp->SetConvMethodAndType( "MaxElementVolume", "NETGEN_3D");
1631     hyp->AddArgMethod( "SetMaxElementVolume" );
1632   }
1633   // GHS3D_3D ----------
1634   else if ( hypType == "GHS3D_3D" ) {
1635     algo->SetConvMethodAndType( "Tetrahedron", hypType.ToCString());
1636     algo->myArgs.Append( "algo=smesh.GHS3D" );
1637   }
1638   else if ( hypType == "GHS3D_Parameters") {
1639     hyp->SetConvMethodAndType( "Parameters", "GHS3D_3D");
1640   }
1641   // Hexa_3D ---------
1642   else if ( hypType == "BLSURF" ) {
1643     algo->SetConvMethodAndType( "Hexahedron", hypType.ToCString());
1644   }
1645   // Repetitive Projection_1D ---------
1646   else if ( hypType == "Projection_1D" ) {
1647     algo->SetConvMethodAndType( "Projection1D", hypType.ToCString());
1648   }
1649   else if ( hypType == "ProjectionSource1D" ) {
1650     hyp->SetConvMethodAndType( "SourceEdge", "Projection_1D");
1651     hyp->AddArgMethod( "SetSourceEdge");
1652     hyp->AddArgMethod( "SetSourceMesh");
1653     // 2 args of SetVertexAssociation() will become the 3-th and 4-th args of hyp creation command
1654     hyp->AddArgMethod( "SetVertexAssociation", 2 );
1655   }
1656   // Projection_2D ---------
1657   else if ( hypType == "Projection_2D" ) {
1658     algo->SetConvMethodAndType( "Projection2D", hypType.ToCString());
1659   }
1660   else if ( hypType == "Projection_1D2D" ) {
1661     algo->SetConvMethodAndType( "Projection1D2D", hypType.ToCString());
1662   }
1663   else if ( hypType == "ProjectionSource2D" ) {
1664     hyp->SetConvMethodAndType( "SourceFace", "Projection_2D");
1665     hyp->AddArgMethod( "SetSourceFace");
1666     hyp->AddArgMethod( "SetSourceMesh");
1667     hyp->AddArgMethod( "SetVertexAssociation", 4 );
1668   }
1669   // Projection_3D ---------
1670   else if ( hypType == "Projection_3D" ) {
1671     algo->SetConvMethodAndType( "Projection3D", hypType.ToCString());
1672   }
1673   else if ( hypType == "ProjectionSource3D" ) {
1674     hyp->SetConvMethodAndType( "SourceShape3D", "Projection_3D");
1675     hyp->AddArgMethod( "SetSource3DShape");
1676     hyp->AddArgMethod( "SetSourceMesh");
1677     hyp->AddArgMethod( "SetVertexAssociation", 4 );
1678   }
1679   // Prism_3D ---------
1680   else if ( hypType == "Prism_3D" ) {
1681     algo->SetConvMethodAndType( "Prism", hypType.ToCString());
1682   }
1683   // RadialPrism_3D ---------
1684   else if ( hypType == "RadialPrism_3D" ) {
1685     algo->SetConvMethodAndType( "Prism", hypType.ToCString());
1686   }
1687   else if ( hypType == "NumberOfLayers" ) {
1688     hyp->SetConvMethodAndType( "NumberOfLayers", "RadialPrism_3D");
1689     hyp->AddArgMethod( "SetNumberOfLayers" );
1690   }
1691   else if ( hypType == "LayerDistribution" ) {
1692     hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
1693     hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
1694   }
1695   // Cartesian 3D ---------
1696   else if ( hypType == "Cartesian_3D" ) {
1697     algo->SetConvMethodAndType( "BodyFitted", hypType.ToCString());
1698   }
1699   else if ( hypType == "CartesianParameters3D" ) {
1700     hyp = new _pyComplexParamHypo( theCreationCmd );
1701     hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
1702     for ( int iArg = 0; iArg < 4; ++iArg )
1703       hyp->myArgs.Append("[]");
1704   }
1705
1706   return algo->IsValid() ? algo : hyp;
1707 }
1708
1709 //================================================================================
1710 /*!
1711  * \brief Returns true if addition of this hypothesis to a given mesh can be
1712  *        wrapped into hypothesis creation
1713  */
1714 //================================================================================
1715
1716 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
1717 {
1718   if ( !myIsWrapped && myMesh == theMesh && !IsRemovedFromStudy() )
1719   {
1720     Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
1721     if ( !pyMesh.IsNull() && !pyMesh->IsRemovedFromStudy() )
1722       return true;
1723   }
1724   return false;
1725 }
1726
1727 //================================================================================
1728 /*!
1729  * \brief Convert the command adding a hypothesis to mesh into a smesh command
1730   * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
1731   * \param theAlgo - The algo that can create this hypo
1732   * \retval bool - false if the command cant be converted
1733  */
1734 //================================================================================
1735
1736 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
1737                                        const _pyID&              theMesh)
1738 {
1739   ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
1740
1741   if ( !IsWrappable( theMesh ))
1742     return false;
1743
1744   myGeom = theCmd->GetArg( 1 );
1745
1746   Handle(_pyHypothesis) algo;
1747   if ( !IsAlgo() ) {
1748     // find algo created on myGeom in theMesh
1749     algo = theGen->FindAlgo( myGeom, theMesh, this );
1750     if ( algo.IsNull() )
1751       return false;
1752     // attach hypothesis creation command to be after algo creation command
1753     // because it can be new created instance of algorithm
1754     algo->GetCreationCmd()->AddDependantCmd( theCmd );
1755   }
1756   myIsWrapped = true;
1757
1758   // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
1759   theCmd->SetResultValue( GetID() );
1760   theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
1761   theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
1762   // set args
1763   theCmd->RemoveArgs();
1764   for ( int i = 1; i <= myArgs.Length(); ++i ) {
1765     if ( !myArgs( i ).IsEmpty() )
1766       theCmd->SetArg( i, myArgs( i ));
1767     else
1768       theCmd->SetArg( i, "[]");
1769   }
1770   // set a new creation command
1771   GetCreationCmd()->Clear();
1772   // replace creation command by wrapped instance
1773   // please note, that hypothesis attaches to algo creation command (see upper)
1774   SetCreationCmd( theCmd );
1775
1776
1777   // clear commands setting arg values
1778   list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
1779   for ( ; argCmd != myArgCommands.end(); ++argCmd )
1780     (*argCmd)->Clear();
1781
1782   // set unknown arg commands after hypo creation
1783   Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
1784   list<Handle(_pyCommand)>::iterator cmd = myUnknownCommands.begin();
1785   for ( ; cmd != myUnknownCommands.end(); ++cmd ) {
1786     afterCmd->AddDependantCmd( *cmd );
1787   }
1788
1789   return myIsWrapped;
1790 }
1791
1792 //================================================================================
1793 /*!
1794  * \brief Remember hypothesis parameter values
1795  * \param theCommand - The called hypothesis method
1796  */
1797 //================================================================================
1798
1799 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
1800 {
1801   ASSERT( !myIsAlgo );
1802   // set args
1803   int nbArgs = 0;
1804   for ( int i = 1; i <= myArgMethods.Length(); ++i ) {
1805     if ( myArgMethods( i ) == theCommand->GetMethod() ) {
1806       while ( myArgs.Length() < nbArgs + myNbArgsByMethod( i ))
1807         myArgs.Append( "[]" );
1808       for ( int iArg = 1; iArg <= myNbArgsByMethod( i ); ++iArg )
1809         myArgs( nbArgs + iArg ) = theCommand->GetArg( iArg ); // arg value
1810       myArgCommands.push_back( theCommand );
1811       return;
1812     }
1813     nbArgs += myNbArgsByMethod( i );
1814   }
1815   myUnknownCommands.push_back( theCommand );
1816 }
1817
1818 //================================================================================
1819 /*!
1820  * \brief Finish conversion
1821  */
1822 //================================================================================
1823
1824 void _pyHypothesis::Flush()
1825 {
1826   if ( IsWrapped() ) {
1827   }
1828   else {
1829     list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
1830     for ( ; cmd != myArgCommands.end(); ++cmd ) {
1831       // Add access to a wrapped mesh
1832       theGen->AddMeshAccessorMethod( *cmd );
1833       // Add access to a wrapped algorithm
1834       theGen->AddAlgoAccessorMethod( *cmd );
1835     }
1836     cmd = myUnknownCommands.begin();
1837     for ( ; cmd != myUnknownCommands.end(); ++cmd ) {
1838       // Add access to a wrapped mesh
1839       theGen->AddMeshAccessorMethod( *cmd );
1840       // Add access to a wrapped algorithm
1841       theGen->AddAlgoAccessorMethod( *cmd );
1842     }
1843   }
1844   // forget previous hypothesis modifications
1845   myArgCommands.clear();
1846   myUnknownCommands.clear();
1847 }
1848
1849 //================================================================================
1850 /*!
1851  * \brief clear creation, arg and unkown commands
1852  */
1853 //================================================================================
1854
1855 void _pyHypothesis::ClearAllCommands()
1856 {
1857   GetCreationCmd()->Clear();
1858   list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
1859   for ( ; cmd != myArgCommands.end(); ++cmd )
1860     ( *cmd )->Clear();
1861   cmd = myUnknownCommands.begin();
1862   for ( ; cmd != myUnknownCommands.end(); ++cmd )
1863     ( *cmd )->Clear();
1864 }
1865
1866
1867 //================================================================================
1868 /*!
1869  * \brief Assign fields of theOther to me except myIsWrapped
1870  */
1871 //================================================================================
1872
1873 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
1874                             const _pyID&                 theMesh )
1875 {
1876   myIsWrapped = false;
1877   myMesh = theMesh;
1878
1879   // myCreationCmd = theOther->myCreationCmd;
1880   myIsAlgo = theOther->myIsAlgo;
1881   myGeom = theOther->myGeom;
1882   myType2CreationMethod = theOther->myType2CreationMethod;
1883   myArgs = theOther->myArgs;
1884   myArgMethods = theOther->myArgMethods;
1885   myNbArgsByMethod = theOther->myNbArgsByMethod;
1886   myArgCommands = theOther->myArgCommands;
1887   myUnknownCommands = theOther->myUnknownCommands;
1888 }
1889
1890 //================================================================================
1891 /*!
1892  * \brief Remember hypothesis parameter values
1893  * \param theCommand - The called hypothesis method
1894  */
1895 //================================================================================
1896
1897 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
1898 {
1899   if ( GetAlgoType() == "Cartesian_3D" )
1900   {
1901     // CartesianParameters3D hyp
1902
1903     if ( theCommand->GetMethod() == "SetSizeThreshold" )
1904     {
1905       myArgs( 4 ) = theCommand->GetArg( 1 );
1906       myArgCommands.push_back( theCommand );
1907       return;
1908     }
1909     if ( theCommand->GetMethod() == "SetGrid" ||
1910          theCommand->GetMethod() == "SetGridSpacing" )
1911     {
1912       TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
1913       int iArg = 1 + ( axis.Value(1) - '0' );
1914       if ( theCommand->GetMethod() == "SetGrid" )
1915       {
1916         myArgs( iArg ) = theCommand->GetArg( 1 );
1917       }
1918       else
1919       {
1920         myArgs( iArg ) = "[ ";
1921         myArgs( iArg ) += theCommand->GetArg( 1 );
1922         myArgs( iArg ) += ", ";
1923         myArgs( iArg ) += theCommand->GetArg( 2 );
1924         myArgs( iArg ) += "]";
1925       }
1926       myArgCommands.push_back( theCommand );
1927       return;
1928     }
1929   }
1930
1931   if( theCommand->GetMethod() == "SetLength" )
1932   {
1933     // NOW it is OBSOLETE
1934     // ex: hyp.SetLength(start, 1)
1935     //     hyp.SetLength(end,   0)
1936     ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
1937     int i = 2 - theCommand->GetArg( 2 ).IntegerValue();
1938     while ( myArgs.Length() < i )
1939       myArgs.Append( "[]" );
1940     myArgs( i ) = theCommand->GetArg( 1 ); // arg value
1941     myArgCommands.push_back( theCommand );
1942   }
1943   else
1944   {
1945     _pyHypothesis::Process( theCommand );
1946   }
1947 }
1948 //================================================================================
1949 /*!
1950  * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
1951  */
1952 //================================================================================
1953
1954 void _pyComplexParamHypo::Flush()
1955 {
1956   if ( IsWrapped() )
1957   {
1958     list < Handle(_pyCommand) >::iterator cmd = myUnknownCommands.begin();
1959     for ( ; cmd != myUnknownCommands.end(); ++cmd )
1960       if ((*cmd)->GetMethod() == "SetObjectEntry" )
1961         (*cmd)->Clear();
1962   }
1963 }
1964
1965 //================================================================================
1966 /*!
1967  * \brief Convert methods of 1D hypotheses to my own methods
1968   * \param theCommand - The called hypothesis method
1969  */
1970 //================================================================================
1971
1972 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
1973 {
1974   if ( theCommand->GetMethod() != "SetLayerDistribution" )
1975     return;
1976
1977   _pyID newName; // name for 1D hyp = "HypType" + "_Distribution"
1978
1979   const _pyID& hyp1dID = theCommand->GetArg( 1 );
1980   Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
1981   if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
1982     hyp1d = my1dHyp;
1983   else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() ) {
1984     // 1D hypo is already set, so distribution changes and the old
1985     // 1D hypo is thrown away
1986     my1dHyp->ClearAllCommands();
1987   }
1988   my1dHyp = hyp1d;
1989
1990   if ( !myArgCommands.empty() )
1991     myArgCommands.front()->Clear();
1992   myArgCommands.push_back( theCommand );
1993 }
1994
1995 //================================================================================
1996 /*!
1997  * \brief
1998   * \param theAdditionCmd - command to be converted
1999   * \param theMesh - mesh instance
2000   * \retval bool - status
2001  */
2002 //================================================================================
2003
2004 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
2005                                                   const _pyID&              theMesh)
2006 {
2007   myIsWrapped = false;
2008
2009   if ( my1dHyp.IsNull() )
2010     return false;
2011
2012   // set "SetLayerDistribution()" after addition cmd
2013   theAdditionCmd->AddDependantCmd( myArgCommands.front() );
2014
2015   _pyID geom = theAdditionCmd->GetArg( 1 );
2016
2017   Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
2018   if ( !algo.IsNull() )
2019   {
2020     my1dHyp->SetMesh( theMesh );
2021     my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
2022                                   algo->GetAlgoType().ToCString());
2023     if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
2024       return false;
2025
2026     // clear "SetLayerDistribution()" cmd
2027     myArgCommands.back()->Clear();
2028
2029     // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
2030
2031     // find RadialPrism algo created on <geom> for theMesh
2032     GetCreationCmd()->SetObject( algo->GetID() );
2033     GetCreationCmd()->SetMethod( myAlgoMethod );
2034     GetCreationCmd()->RemoveArgs();
2035     theAdditionCmd->AddDependantCmd( GetCreationCmd() );
2036     myIsWrapped = true;
2037   }
2038   return myIsWrapped;
2039 }
2040
2041 //================================================================================
2042 /*!
2043  * \brief
2044  */
2045 //================================================================================
2046
2047 void _pyLayerDistributionHypo::Flush()
2048 {
2049   // as creation of 1D hyp was written later then it's edition,
2050   // we need to find all it's edition calls and process them
2051   if ( !my1dHyp.IsNull() )
2052   {
2053     _pyID hyp1dID = my1dHyp->GetCreationCmd()->GetResultValue();
2054
2055     // make a new name for 1D hyp = "HypType" + "_Distribution"
2056     _pyID newName;
2057     if ( my1dHyp->IsWrapped() ) {
2058       newName = my1dHyp->GetCreationCmd()->GetMethod();
2059     }
2060     else {
2061       TCollection_AsciiString hypTypeQuoted = my1dHyp->GetCreationCmd()->GetArg(1);
2062       newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2063     }
2064     newName += "_Distribution";
2065     my1dHyp->GetCreationCmd()->SetResultValue( newName );
2066
2067     list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
2068     list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
2069     for ( ; cmdIt != cmds.end(); ++cmdIt ) {
2070       const _pyID& objID = (*cmdIt)->GetObject();
2071       if ( objID == hyp1dID ) {
2072         my1dHyp->Process( *cmdIt );
2073         my1dHyp->GetCreationCmd()->AddDependantCmd( *cmdIt );
2074         ( *cmdIt )->SetObject( newName );
2075       }
2076     }
2077     // Set new hyp name to SetLayerDistribution() cmd
2078     if ( !myArgCommands.empty() && !myArgCommands.back()->IsEmpty() )
2079       myArgCommands.back()->SetArg( 1, newName );
2080   }
2081 }
2082
2083 //================================================================================
2084 /*!
2085  * \brief additionally to Addition2Creation, clears SetDistrType() command
2086   * \param theCmd - AddHypothesis() command
2087   * \param theMesh - mesh to which a hypothesis is added
2088   * \retval bool - convertion result
2089  */
2090 //================================================================================
2091
2092 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
2093                                                 const _pyID&              theMesh)
2094 {
2095   if ( IsWrappable( theMesh ) && myArgs.Length() > 1 ) {
2096     // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
2097     bool scaleDistrType = false;
2098     list<Handle(_pyCommand)>::reverse_iterator cmd = myUnknownCommands.rbegin();
2099     for ( ; cmd != myUnknownCommands.rend(); ++cmd ) {
2100       if ( (*cmd)->GetMethod() == "SetDistrType" ) {
2101         if ( (*cmd)->GetArg( 1 ) == "1" ) {
2102           scaleDistrType = true;
2103           (*cmd)->Clear();
2104         }
2105         else if ( !scaleDistrType ) {
2106           // distribution type changed: remove scale factor from args
2107           myArgs.Remove( 2, myArgs.Length() );
2108           break;
2109         }
2110       }
2111     }
2112   }
2113   return _pyHypothesis::Addition2Creation( theCmd, theMesh );
2114 }
2115
2116 //================================================================================
2117 /*!
2118  * \brief remove repeated commands defining distribution
2119  */
2120 //================================================================================
2121
2122 void _pyNumberOfSegmentsHyp::Flush()
2123 {
2124   // find number of the last SetDistrType() command
2125   list<Handle(_pyCommand)>::reverse_iterator cmd = myUnknownCommands.rbegin();
2126   int distrTypeNb = 0;
2127   for ( ; !distrTypeNb && cmd != myUnknownCommands.rend(); ++cmd )
2128     if ( (*cmd)->GetMethod() == "SetDistrType" )
2129       distrTypeNb = (*cmd)->GetOrderNb();
2130     else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" )
2131       (*cmd)->Clear();
2132
2133   // clear commands before the last SetDistrType()
2134   list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnknownCommands };
2135   for ( int i = 0; i < 2; ++i ) {
2136     set<TCollection_AsciiString> uniqueMethods;
2137     list<Handle(_pyCommand)> & cmdList = *cmds[i];
2138     for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
2139     {
2140       bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
2141       const TCollection_AsciiString& method = (*cmd)->GetMethod();
2142       if ( !clear || method == "SetNumberOfSegments" ) {
2143         bool isNewInSet = uniqueMethods.insert( method ).second;
2144         clear = !isNewInSet;
2145       }
2146       if ( clear )
2147         (*cmd)->Clear();
2148     }
2149     cmdList.clear();
2150   }
2151 }
2152
2153 //================================================================================
2154 /*!
2155  * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
2156  * into regular1D.LengthNearVertex( length, vertex )
2157   * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
2158   * \param theMesh - The mesh needing this hypo
2159   * \retval bool - false if the command cant be converted
2160  */
2161 //================================================================================
2162
2163 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
2164                                                          const _pyID&              theMeshID)
2165 {
2166   if ( IsWrappable( theMeshID )) {
2167
2168     _pyID vertex = theCmd->GetArg( 1 );
2169
2170     // the problem here is that segment algo will not be found
2171     // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
2172     // geometry where segment algorithm is assigned
2173     Handle(_pyHypothesis) algo;
2174     _pyID geom = vertex;
2175     while ( algo.IsNull() && !geom.IsEmpty()) {
2176       // try to find geom as a father of <vertex>
2177       geom = FatherID( geom );
2178       algo = theGen->FindAlgo( geom, theMeshID, this );
2179     }
2180     if ( algo.IsNull() )
2181       return false; // also possible to find geom as brother of veretex...
2182     // set geom instead of vertex
2183     theCmd->SetArg( 1, geom );
2184
2185     // set vertex as a second arg
2186     if ( myArgs.Length() < 1) myArgs.Append( "1" ); // :(
2187     myArgs.Append( vertex );
2188
2189     // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
2190     // theMeshID.LengthNearVertex( length, vertex )
2191     return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
2192   }
2193   return false;
2194 }
2195
2196 //================================================================================
2197 /*!
2198  * \brief _pyAlgorithm constructor
2199  * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
2200  */
2201 //================================================================================
2202
2203 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
2204   : _pyHypothesis( theCreationCmd )
2205 {
2206   myIsAlgo = true;
2207 }
2208
2209 //================================================================================
2210 /*!
2211  * \brief Convert the command adding an algorithm to mesh
2212   * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
2213   * \param theMesh - The mesh needing this algo
2214   * \retval bool - false if the command cant be converted
2215  */
2216 //================================================================================
2217
2218 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
2219                                       const _pyID&              theMeshID)
2220 {
2221   // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
2222   if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
2223     theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
2224     return true;
2225   }
2226   return false;
2227 }
2228
2229 //================================================================================
2230 /*!
2231  * \brief Return starting position of a part of python command
2232   * \param thePartIndex - The index of command part
2233   * \retval int - Part position
2234  */
2235 //================================================================================
2236
2237 int _pyCommand::GetBegPos( int thePartIndex )
2238 {
2239   if ( IsEmpty() )
2240     return EMPTY;
2241   if ( myBegPos.Length() < thePartIndex )
2242     return UNKNOWN;
2243   return myBegPos( thePartIndex );
2244 }
2245
2246 //================================================================================
2247 /*!
2248  * \brief Store starting position of a part of python command
2249   * \param thePartIndex - The index of command part
2250   * \param thePosition - Part position
2251  */
2252 //================================================================================
2253
2254 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
2255 {
2256   while ( myBegPos.Length() < thePartIndex )
2257     myBegPos.Append( UNKNOWN );
2258   myBegPos( thePartIndex ) = thePosition;
2259 }
2260
2261 //================================================================================
2262 /*!
2263  * \brief Returns whitespace symbols at the line beginning
2264   * \retval TCollection_AsciiString - result
2265  */
2266 //================================================================================
2267
2268 TCollection_AsciiString _pyCommand::GetIndentation()
2269 {
2270   int end = 1;
2271   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
2272     GetWord( myString, end, true );
2273   else
2274     end = GetBegPos( RESULT_IND );
2275   return myString.SubString( 1, end - 1 );
2276 }
2277
2278 //================================================================================
2279 /*!
2280  * \brief Return substring of python command looking like ResultValue = Obj.Meth()
2281   * \retval const TCollection_AsciiString & - ResultValue substring
2282  */
2283 //================================================================================
2284
2285 const TCollection_AsciiString & _pyCommand::GetResultValue()
2286 {
2287   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
2288   {
2289     int begPos = myString.Location( "=", 1, Length() );
2290     if ( begPos )
2291       myRes = GetWord( myString, begPos, false );
2292     else
2293       begPos = EMPTY;
2294     SetBegPos( RESULT_IND, begPos );
2295   }
2296   return myRes;
2297 }
2298
2299 //================================================================================
2300 /*!
2301  * \brief Return number of python command result value ResultValue = Obj.Meth()
2302   * \retval const int
2303  */
2304 //================================================================================
2305
2306 const int _pyCommand::GetNbResultValues()
2307 {
2308   int begPos = 1;
2309   int Nb=0;
2310   int endPos = myString.Location( "=", 1, Length() );
2311   TCollection_AsciiString str = "";
2312   while ( begPos < endPos) {
2313     str = GetWord( myString, begPos, true );
2314     begPos = begPos+ str.Length();
2315     Nb++;
2316   }
2317   return (Nb-1);
2318 }
2319
2320
2321 //================================================================================
2322 /*!
2323  * \brief Return substring of python command looking like
2324  *  ResultValue1 , ResultValue1,... = Obj.Meth() with res index
2325  * \retval const TCollection_AsciiString & - ResultValue with res index substring
2326  */
2327 //================================================================================
2328 const TCollection_AsciiString & _pyCommand::GetResultValue(int res)
2329 {
2330   int begPos = 1;
2331   int Nb=0;
2332   int endPos = myString.Location( "=", 1, Length() );
2333   while ( begPos < endPos) {
2334     myRes = GetWord( myString, begPos, true );
2335     begPos = begPos + myRes.Length();
2336     Nb++;
2337     if(res == Nb){
2338       myRes.RemoveAll('[');myRes.RemoveAll(']');
2339       return myRes;
2340     }
2341     if(Nb>res)
2342       break;
2343   }
2344   return theEmptyString;
2345 }
2346
2347 //================================================================================
2348 /*!
2349  * \brief Return substring of python command looking like ResVal = Object.Meth()
2350   * \retval const TCollection_AsciiString & - Object substring
2351  */
2352 //================================================================================
2353
2354 const TCollection_AsciiString & _pyCommand::GetObject()
2355 {
2356   if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
2357   {
2358     // beginning
2359     int begPos = GetBegPos( RESULT_IND ) + myRes.Length();
2360     if ( begPos < 1 ) {
2361       begPos = myString.Location( "=", 1, Length() ) + 1;
2362       // is '=' in the string argument (for example, name) or not
2363       int nb1 = 0; // number of ' character at the left of =
2364       int nb2 = 0; // number of " character at the left of =
2365       for ( int i = 1; i < begPos-1; i++ ) {
2366         if ( myString.Value( i )=='\'' )
2367           nb1 += 1;
2368         else if ( myString.Value( i )=='"' )
2369           nb2 += 1;
2370       }
2371       // if number of ' or " is not divisible by 2,
2372       // then get an object at the start of the command
2373       if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
2374         begPos = 1;
2375     }
2376     myObj = GetWord( myString, begPos, true );
2377     // check if object is complex,
2378     // so far consider case like "smesh.smesh.Method()"
2379     if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
2380       //if ( bracketPos==0 ) bracketPos = Length();
2381       int dotPos = begPos+myObj.Length();
2382       while ( dotPos+1 < bracketPos ) {
2383         if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
2384           dotPos = pos;
2385         else
2386           break;
2387       }
2388       if ( dotPos > begPos+myObj.Length() )
2389         myObj = myString.SubString( begPos, dotPos-1 );
2390     }
2391     // store
2392     SetBegPos( OBJECT_IND, begPos );
2393   }
2394   //SCRUTE(myObj);
2395   return myObj;
2396 }
2397
2398 //================================================================================
2399 /*!
2400  * \brief Return substring of python command looking like ResVal = Obj.Method()
2401   * \retval const TCollection_AsciiString & - Method substring
2402  */
2403 //================================================================================
2404
2405 const TCollection_AsciiString & _pyCommand::GetMethod()
2406 {
2407   if ( GetBegPos( METHOD_IND ) == UNKNOWN )
2408   {
2409     // beginning
2410     int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
2411     bool forward = true;
2412     if ( begPos < 1 ) {
2413       begPos = myString.Location( "(", 1, Length() ) - 1;
2414       forward = false;
2415     }
2416     // store
2417     myMeth = GetWord( myString, begPos, forward );
2418     SetBegPos( METHOD_IND, begPos );
2419   }
2420   //SCRUTE(myMeth);
2421   return myMeth;
2422 }
2423
2424 //================================================================================
2425 /*!
2426  * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
2427   * \retval const TCollection_AsciiString & - Arg<index> substring
2428  */
2429 //================================================================================
2430
2431 const TCollection_AsciiString & _pyCommand::GetArg( int index )
2432 {
2433   if ( GetBegPos( ARG1_IND ) == UNKNOWN )
2434   {
2435     // Find all args
2436
2437     int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
2438     if ( pos < 1 )
2439       pos = myString.Location( "(", 1, Length() );
2440     else
2441       --pos;
2442
2443     // we are at or before '(', skip it if present
2444     if ( pos > 0 ) {
2445       while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
2446       if ( myString.Value( pos ) != '(' )
2447         pos = 0;
2448     }
2449     if ( pos < 1 ) {
2450       SetBegPos( ARG1_IND, 0 ); // even no '('
2451       return theEmptyString;
2452     }
2453     ++pos;
2454
2455     list< TCollection_AsciiString > separatorStack( 1, ",)");
2456     bool ignoreNesting = false;
2457     int prevPos = pos;
2458     while ( pos <= Length() )
2459     {
2460       const char chr = myString.Value( pos );
2461
2462       if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
2463       {
2464         if ( separatorStack.size() == 1 ) // ',' dividing args or a terminal ')' found
2465         {
2466           while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
2467             ++prevPos;
2468           if ( pos-1 >= prevPos ) {
2469             TCollection_AsciiString arg = myString.SubString( prevPos, pos-1 );
2470             arg.RightAdjust(); // remove spaces
2471             arg.LeftAdjust();
2472             SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
2473             myArgs.Append( arg );
2474           }
2475           if ( chr == ')' )
2476             break;
2477           prevPos = pos+1;
2478         }
2479         else // end of nesting args found
2480         {
2481           separatorStack.pop_back();
2482           ignoreNesting = false;
2483         }
2484       }
2485       else if ( !ignoreNesting )
2486       {
2487         switch ( chr ) {
2488         case '(' : separatorStack.push_back(")"); break;
2489         case '[' : separatorStack.push_back("]"); break;
2490         case '\'': separatorStack.push_back("'");  ignoreNesting=true; break;
2491         case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
2492         default:;
2493         }
2494       }
2495       ++pos;
2496     }
2497   }
2498   if ( myArgs.Length() < index )
2499     return theEmptyString;
2500   return myArgs( index );
2501 }
2502
2503 //================================================================================
2504 /*!
2505  * \brief Check if char is a word part
2506   * \param c - The character to check
2507   * \retval bool - The check result
2508  */
2509 //================================================================================
2510
2511 static inline bool isWord(const char c, const bool dotIsWord)
2512 {
2513   return
2514     !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
2515 }
2516
2517 //================================================================================
2518 /*!
2519  * \brief Looks for a word in the string and returns word's beginning
2520   * \param theString - The input string
2521   * \param theStartPos - The position to start the search, returning word's beginning
2522   * \param theForward - The search direction
2523   * \retval TCollection_AsciiString - The found word
2524  */
2525 //================================================================================
2526
2527 TCollection_AsciiString _pyCommand::GetWord( const TCollection_AsciiString & theString,
2528                                             int &      theStartPos,
2529                                             const bool theForward,
2530                                             const bool dotIsWord )
2531 {
2532   int beg = theStartPos, end = theStartPos;
2533   theStartPos = EMPTY;
2534   if ( beg < 1 || beg > theString.Length() )
2535     return theEmptyString;
2536
2537   if ( theForward ) { // search forward
2538     // beg
2539     while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
2540       ++beg;
2541     if ( beg > theString.Length() )
2542       return theEmptyString; // no word found
2543     // end
2544     end = beg + 1;
2545     char begChar = theString.Value( beg );
2546     if ( begChar == '"' || begChar == '\'' || begChar == '[') {
2547       char endChar = ( begChar == '[' ) ? ']' : begChar;
2548       // end is at the corresponding quoting mark or bracket
2549       while ( end < theString.Length() &&
2550               ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
2551         ++end;
2552     }
2553     else {
2554       while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
2555         ++end;
2556       --end;
2557     }
2558   }
2559   else {  // search backward
2560     // end
2561     while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
2562       --end;
2563     if ( end == 0 )
2564       return theEmptyString; // no word found
2565     beg = end - 1;
2566     char endChar = theString.Value( end );
2567     if ( endChar == '"' || endChar == '\'' ) {
2568       // beg is at the corresponding quoting mark
2569       while ( beg > 1 &&
2570               ( theString.Value( beg ) != endChar || theString.Value( beg-1 ) == '\\'))
2571         --beg;
2572     }
2573     else {
2574       while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
2575         --beg;
2576       ++beg;
2577     }
2578   }
2579   theStartPos = beg;
2580   //cout << theString << " ---- " << beg << " - " << end << endl;
2581   return theString.SubString( beg, end );
2582 }
2583
2584 //================================================================================
2585 /*!
2586  * \brief Look for position where not space char is
2587   * \param theString - The string
2588   * \param thePos - The position to search from and which returns result
2589   * \retval bool - false if there are only space after thePos in theString
2590  *
2591  *
2592  */
2593 //================================================================================
2594
2595 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
2596 {
2597   if ( thePos < 1 || thePos > theString.Length() )
2598     return false;
2599
2600   while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
2601     ++thePos;
2602
2603   return thePos <= theString.Length();
2604 }
2605
2606 //================================================================================
2607 /*!
2608  * \brief Modify a part of the command
2609   * \param thePartIndex - The index of the part
2610   * \param thePart - The new part string
2611   * \param theOldPart - The old part
2612  */
2613 //================================================================================
2614
2615 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
2616                         TCollection_AsciiString& theOldPart)
2617 {
2618   int pos = GetBegPos( thePartIndex );
2619   if ( pos <= Length() && theOldPart != thePart)
2620   {
2621     TCollection_AsciiString seperator;
2622     if ( pos < 1 ) {
2623       pos = GetBegPos( thePartIndex + 1 );
2624       if ( pos < 1 ) return;
2625       switch ( thePartIndex ) {
2626       case RESULT_IND: seperator = " = "; break;
2627       case OBJECT_IND: seperator = "."; break;
2628       case METHOD_IND: seperator = "()"; break;
2629       default:;
2630       }
2631     }
2632     myString.Remove( pos, theOldPart.Length() );
2633     if ( !seperator.IsEmpty() )
2634       myString.Insert( pos , seperator );
2635     myString.Insert( pos, thePart );
2636     // update starting positions of the following parts
2637     int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
2638     for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
2639       if ( myBegPos( i ) > 0 )
2640         myBegPos( i ) += posDelta;
2641     }
2642     theOldPart = thePart;
2643   }
2644 }
2645
2646 //================================================================================
2647 /*!
2648  * \brief Set agrument
2649   * \param index - The argument index, it counts from 1
2650   * \param theArg - The argument string
2651  */
2652 //================================================================================
2653
2654 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
2655 {
2656   FindAllArgs();
2657   int argInd = ARG1_IND + index - 1;
2658   int pos = GetBegPos( argInd );
2659   if ( pos < 1 ) // no index-th arg exist, append inexistent args
2660   {
2661     // find a closing parenthesis
2662     if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
2663       int lastArgInd = GetNbArgs();
2664       pos = GetBegPos( ARG1_IND + lastArgInd  - 1 ) + GetArg( lastArgInd ).Length();
2665       while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
2666         ++pos;
2667     }
2668     else {
2669       pos = Length();
2670       while ( pos > 0 && myString.Value( pos ) != ')' )
2671         --pos;
2672     }
2673     if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
2674       myString += "()";
2675       pos = Length();
2676     }
2677     while ( myArgs.Length() < index ) {
2678       if ( myArgs.Length() )
2679         myString.Insert( pos++, "," );
2680       myArgs.Append("None");
2681       myString.Insert( pos, myArgs.Last() );
2682       SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
2683       pos += myArgs.Last().Length();
2684     }
2685   }
2686   SetPart( argInd, theArg, myArgs( index ));
2687 }
2688
2689 //================================================================================
2690 /*!
2691  * \brief Empty arg list
2692  */
2693 //================================================================================
2694
2695 void _pyCommand::RemoveArgs()
2696 {
2697   if ( int pos = myString.Location( '(', 1, Length() ))
2698     myString.Trunc( pos );
2699   myString += ")";
2700   myArgs.Clear();
2701   if ( myBegPos.Length() >= ARG1_IND )
2702     myBegPos.Remove( ARG1_IND, myBegPos.Length() );
2703 }
2704
2705 //================================================================================
2706 /*!
2707  * \brief Set dependent commands after this one
2708  */
2709 //================================================================================
2710
2711 bool _pyCommand::SetDependentCmdsAfter() const
2712 {
2713   bool orderChanged = false;
2714   list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
2715   for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
2716     if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
2717       orderChanged = true;
2718       theGen->SetCommandAfter( *cmd, this );
2719       (*cmd)->SetDependentCmdsAfter();
2720     }
2721   }
2722   return orderChanged;
2723 }
2724 //================================================================================
2725 /*!
2726  * \brief Insert accessor method after theObjectID
2727   * \param theObjectID - id of the accessed object
2728   * \param theAcsMethod - name of the method giving access to the object
2729   * \retval bool - false if theObjectID is not found in the command string
2730  */
2731 //================================================================================
2732
2733 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
2734 {
2735   if ( !theAcsMethod )
2736     return false;
2737   // start object search from the object, i.e. ignore result
2738   GetObject();
2739   int beg = GetBegPos( OBJECT_IND );
2740   if ( beg < 1 || beg > Length() )
2741     return false;
2742   bool added = false;
2743   while (( beg = myString.Location( theObjectID, beg, Length() )))
2744   {
2745     // check that theObjectID is not just a part of a longer ID
2746     int afterEnd = beg + theObjectID.Length();
2747     Standard_Character c = myString.Value( afterEnd );
2748     if ( !isalnum( c ) && c != ':' ) {
2749       // check if accessor method already present
2750       if ( c != '.' ||
2751            myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
2752         // insertion
2753         int oldLen = Length();
2754         myString.Insert( afterEnd, (char*) theAcsMethod );
2755         myString.Insert( afterEnd, "." );
2756         // update starting positions of the parts following the modified one
2757         int posDelta = Length() - oldLen;
2758         for ( int i = 1; i <= myBegPos.Length(); ++i ) {
2759           if ( myBegPos( i ) > afterEnd )
2760             myBegPos( i ) += posDelta;
2761         }
2762         added = true;
2763       }
2764     }
2765     beg = afterEnd; // is a part - next search
2766   }
2767   return added;
2768 }
2769
2770 //================================================================================
2771 /*!
2772  * \brief Creates pyObject
2773  */
2774 //================================================================================
2775
2776 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd)
2777   : myCreationCmd(theCreationCmd), myNbCalls(0), myIsRemoved(false)
2778 {
2779   if ( !theCreationCmd.IsNull() && !theCreationCmd->IsEmpty() )
2780     myIsRemoved = theGen->IsDead( theCreationCmd->GetResultValue() );
2781 }
2782
2783 //================================================================================
2784 /*!
2785  * \brief Return method name giving access to an interaface object wrapped by python class
2786   * \retval const char* - method name
2787  */
2788 //================================================================================
2789
2790 const char* _pyObject::AccessorMethod() const
2791 {
2792   return 0;
2793 }
2794 //================================================================================
2795 /*!
2796  * \brief Return ID of a father
2797  */
2798 //================================================================================
2799
2800 _pyID _pyObject::FatherID(const _pyID & childID)
2801 {
2802   int colPos = childID.SearchFromEnd(':');
2803   if ( colPos > 0 )
2804     return childID.SubString( 1, colPos-1 );
2805   return "";
2806 }
2807
2808 //================================================================================
2809 /*!
2810  * \brief SelfEraser erases creation command if no more it's commands invoked
2811  */
2812 //================================================================================
2813
2814 void _pySelfEraser::Flush()
2815 {
2816   if ( GetNbCalls() == 0 )
2817     GetCreationCmd()->Clear();
2818 }
2819
2820 //================================================================================
2821 /*!
2822  * \brief count invoked commands
2823  */
2824 //================================================================================
2825
2826 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
2827 {
2828   _pyObject::Process(theCommand); // count calls of Process()
2829   GetCreationCmd()->AddDependantCmd( theCommand );
2830 }
2831
2832 //================================================================================
2833 /*!
2834  * \brief Clear creation command if no commands invoked
2835  */
2836 //================================================================================
2837
2838 void _pySubMesh::Flush()
2839 {
2840   if ( GetNbCalls() == 0 ) // move to the end of all commands
2841     theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
2842   else if ( !myCreator.IsNull() )
2843     // move to be just after creator
2844     myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
2845 }
2846
2847 //================================================================================
2848 /*!
2849  * \brief To convert creation of a group by filter
2850  */
2851 //================================================================================
2852
2853 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
2854 {
2855   // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
2856   // group = mesh.CreateEmptyGroup( elemType, groupName )
2857   // aFilter.SetMesh(mesh)
2858   // nbAdd = group.AddFrom( aFilter )
2859   if ( theCommand->GetMethod() == "AddFrom" )
2860   {
2861     _pyID idSource = theCommand->GetArg(1);
2862     // check if idSource is a filter
2863     Handle(_pyObject) filter = theGen->FindObject( idSource );
2864     if ( filter.IsNull() || !filter->IsKind(STANDARD_TYPE(_pyFilter)))
2865       return;
2866     // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
2867     list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
2868     while ( *cmdIt != theCommand ) ++cmdIt;
2869     while ( (*cmdIt)->GetOrderNb() != 1 )
2870     {
2871       const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
2872       if ((setMeshCmd->GetObject() == idSource ||
2873            setMeshCmd->GetObject() == Handle(_pyFilter)::DownCast(filter)->GetNewID() )
2874           &&
2875           setMeshCmd->GetMethod() == "SetMesh")
2876       {
2877         setMeshCmd->Clear();
2878         break;
2879       }
2880     }
2881     // replace 3 commands by one
2882     theCommand->Clear();
2883     const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
2884     TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
2885     makeGroupCmd->SetMethod( "MakeGroupByFilter" );
2886     makeGroupCmd->SetArg( 1, name );
2887     makeGroupCmd->SetArg( 2, idSource );
2888     // set new name of a filter
2889     filter->Process( makeGroupCmd );
2890   }
2891   else if ( theCommand->GetMethod() == "SetFilter" )
2892   {
2893     // set new name of a filter
2894     _pyID filterID = theCommand->GetArg(1);
2895     Handle(_pyObject) filter = theGen->FindObject( filterID );
2896     if ( !filter.IsNull() )
2897       filter->Process( theCommand );
2898   }
2899 }
2900
2901 //================================================================================
2902 /*!
2903  * \brief Constructor of _pyFilter
2904  */
2905 //================================================================================
2906
2907 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
2908   :_pyObject(theCreationCmd), myNewID( newID )
2909 {
2910 }
2911
2912 //================================================================================
2913 /*!
2914  * \brief To convert creation of a filter by criteria and
2915  * to replace an old name by a new one
2916  */
2917 //================================================================================
2918
2919 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
2920 {
2921   if ( theCommand->GetObject() == GetID() )
2922     _pyObject::Process(theCommand); // count commands
2923
2924   if ( !myNewID.IsEmpty() )
2925   {
2926     if ( theCommand->GetObject() == GetID() )
2927       theCommand->SetObject( myNewID );
2928     else if ( theCommand->GetResultValue() == GetID() )
2929       theCommand->SetResultValue( myNewID );
2930     else
2931       for ( int i = 1, nb = theCommand->GetNbArgs(); i <= nb; ++i )
2932         if ( theCommand->GetArg( i ) == GetID() )
2933         {
2934           theCommand->SetArg( i, myNewID );
2935           break;
2936         }
2937   }
2938
2939   // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
2940   // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
2941   // aFilter0x2aaab0487080.SetCriteria(aCriteria)
2942   if ( GetNbCalls() == 0 && // none method was called before SetCriteria()
2943        theCommand->GetMethod() == "SetCriteria")
2944   {
2945     // aFilter.SetCriteria(aCriteria) ->
2946     // aFilter = smesh.GetFilterFromCriteria(criteria)
2947     if ( myNewID.IsEmpty() )
2948       theCommand->SetResultValue( GetID() );
2949     else
2950       theCommand->SetResultValue( myNewID );
2951     theCommand->SetObject( SMESH_2smeshpy::GenName() );
2952     theCommand->SetMethod( "GetFilterFromCriteria" );
2953
2954     // Clear aFilterManager.CreateFilter()
2955     GetCreationCmd()->Clear();
2956   }
2957   else if ( theCommand->GetMethod() == "SetMesh")
2958   {
2959     theGen->AddMeshAccessorMethod( theCommand );
2960   }
2961 }
2962
2963 //================================================================================
2964 /*!
2965  * \brief Set new filter name to the creation command
2966  */
2967 //================================================================================
2968
2969 void _pyFilter::Flush()
2970 {
2971   if ( !myNewID.IsEmpty() && !GetCreationCmd()->IsEmpty() )
2972     GetCreationCmd()->SetResultValue( myNewID );
2973 }