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