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