]> SALOME platform Git repositories - modules/smesh.git/blob - src/SMESH_I/SMESH_2smeshpy.cxx
Salome HOME
0a7e57e861248993625b2e58d287f268011cba07
[modules/smesh.git] / src / SMESH_I / SMESH_2smeshpy.cxx
1 //  Copyright (C) 2007-2008  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 //  SMESH SMESH_I : idl implementation based on 'SMESH' unit's calsses
23 //
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 "Resource_DataMapOfAsciiStringAsciiString.hxx"
33
34 #include "SMESH_Gen_i.hxx"
35 /* SALOME headers that include CORBA headers that include windows.h 
36  * that defines GetObject symbol as GetObjectA should stand before SALOME headers
37  * that declare methods named GetObject - to apply the same rules of GetObject renaming
38  * and thus to avoid mess with GetObject symbol on Windows */
39
40 IMPLEMENT_STANDARD_HANDLE (_pyObject          ,Standard_Transient);
41 IMPLEMENT_STANDARD_HANDLE (_pyCommand         ,Standard_Transient);
42 IMPLEMENT_STANDARD_HANDLE (_pyGen             ,_pyObject);
43 IMPLEMENT_STANDARD_HANDLE (_pyMesh            ,_pyObject);
44 IMPLEMENT_STANDARD_HANDLE (_pySubMesh         ,_pyObject);
45 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor      ,_pyObject);
46 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis      ,_pyObject);
47 IMPLEMENT_STANDARD_HANDLE (_pyFilterManager   ,_pyObject);
48 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm       ,_pyHypothesis);
49 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
50 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
51
52 IMPLEMENT_STANDARD_RTTIEXT(_pyObject          ,Standard_Transient);
53 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand         ,Standard_Transient);
54 IMPLEMENT_STANDARD_RTTIEXT(_pyGen             ,_pyObject);
55 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh            ,_pyObject);
56 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh         ,_pyObject);
57 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor      ,_pyObject);
58 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis      ,_pyObject);
59 IMPLEMENT_STANDARD_RTTIEXT(_pyFilterManager   ,_pyObject);
60 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm       ,_pyHypothesis);
61 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
62 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
63 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
64 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
65
66 using namespace std;
67 using SMESH::TPythonDump;
68
69 /*!
70  * \brief Container of commands into which the initial script is split.
71  *        It also contains data coresponding to SMESH_Gen contents
72  */
73 static Handle(_pyGen) theGen;
74
75 static TCollection_AsciiString theEmptyString;
76
77 //#define DUMP_CONVERSION
78
79 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
80 #undef DUMP_CONVERSION
81 #endif
82
83
84 namespace {
85
86   //================================================================================
87   /*!
88    * \brief Set of TCollection_AsciiString initialized by C array of C strings
89    */
90   //================================================================================
91
92   struct TStringSet: public set<TCollection_AsciiString>
93   {
94     /*!
95      * \brief Filling. The last string must be ""
96      */
97     void Insert(const char* names[]) {
98       for ( int i = 0; names[i][0] ; ++i )
99         insert( (char*) names[i] );
100     }
101     /*!
102      * \brief Check if a string is in
103      */
104     bool Contains(const TCollection_AsciiString& name ) {
105       return find( name ) != end();
106     }
107   };
108 }
109
110 //================================================================================
111 /*!
112  * \brief Convert python script using commands of smesh.py
113   * \param theScript - Input script
114   * \retval TCollection_AsciiString - Convertion result
115   *
116   * Class SMESH_2smeshpy declared in SMESH_PythonDump.hxx
117  */
118 //================================================================================
119
120 TCollection_AsciiString
121 SMESH_2smeshpy::ConvertScript(const TCollection_AsciiString& theScript,
122                               Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
123                               Resource_DataMapOfAsciiStringAsciiString& theObjectNames)
124 {
125   theGen = new _pyGen( theEntry2AccessorMethod, theObjectNames );
126
127   // split theScript into separate commands
128   int from = 1, end = theScript.Length(), to;
129   while ( from < end && ( to = theScript.Location( "\n", from, end )))
130   {
131     if ( to != from )
132       // cut out and store a command
133       theGen->AddCommand( theScript.SubString( from, to - 1 ));
134     from = to + 1;
135   }
136
137   // finish conversion
138   theGen->Flush();
139 #ifdef DUMP_CONVERSION
140   MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
141 #endif
142
143   // reorder commands after conversion
144   list< Handle(_pyCommand) >::iterator cmd;
145   bool orderChanges;
146   do {
147     orderChanges = false;
148     for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
149       if ( (*cmd)->SetDependentCmdsAfter() )
150         orderChanges = true;
151   } while ( orderChanges );
152   
153   // concat commands back into a script
154   TCollection_AsciiString aScript;
155   for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
156   {
157 #ifdef DUMP_CONVERSION
158     MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
159 #endif
160     if ( !(*cmd)->IsEmpty() ) {
161       aScript += "\n";
162       aScript += (*cmd)->GetString();
163     }
164   }
165   aScript += "\n";
166
167   theGen.Nullify();
168
169   return aScript;
170 }
171
172 //================================================================================
173 /*!
174  * \brief _pyGen constructor
175  */
176 //================================================================================
177
178 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
179                Resource_DataMapOfAsciiStringAsciiString& theObjectNames)
180   : _pyObject( new _pyCommand( TPythonDump::SMESHGenName(), 0 )),
181     myID2AccessorMethod( theEntry2AccessorMethod ),
182     myObjectNames( theObjectNames )
183 {
184   myNbCommands = 0;
185   myHasPattern = false;
186   // make that GetID() to return TPythonDump::SMESHGenName()
187   GetCreationCmd()->GetString() += "=";
188 }
189
190 //================================================================================
191 /*!
192  * \brief name of SMESH_Gen in smesh.py
193  */
194 //================================================================================
195
196 const char* _pyGen::AccessorMethod() const
197 {
198   return SMESH_2smeshpy::GenName();
199 }
200
201 //================================================================================
202 /*!
203  * \brief Convert a command using a specific converter
204   * \param theCommand - the command to convert
205  */
206 //================================================================================
207
208 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
209 {
210   // store theCommand in the sequence
211   myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
212
213   Handle(_pyCommand) aCommand = myCommands.back();
214 #ifdef DUMP_CONVERSION
215   MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
216 #endif
217
218   _pyID objID = aCommand->GetObject();
219
220   if ( objID.IsEmpty() )
221     return aCommand;
222
223   // SMESH_Gen method?
224   if ( objID == this->GetID() ) {
225     this->Process( aCommand );
226     return aCommand;
227   }
228   
229   // SMESH_subMesh method?
230   map< _pyID, Handle(_pySubMesh) >::iterator id_subMesh = mySubMeshes.find( objID );
231   if ( id_subMesh != mySubMeshes.end() ) {
232     id_subMesh->second->Process( aCommand );
233     return aCommand;
234   }
235
236   // SMESH_Mesh method?
237   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
238   if ( id_mesh != myMeshes.end() ) {
239     // check for mesh editor object
240     if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
241       _pyID editorID = aCommand->GetResultValue();
242       Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
243       myMeshEditors.insert( make_pair( editorID, editor ));
244       return aCommand;
245     } 
246     // check for SubMesh objects
247     else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
248       _pyID subMeshID = aCommand->GetResultValue();
249       Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
250       mySubMeshes.insert( make_pair( subMeshID, subMesh ));
251     }
252     id_mesh->second->Process( aCommand );
253     return aCommand;
254   }
255
256   //SMESH_FilterManager method?
257   if ( theCommand.Search( "aFilterManager" ) != -1 ) {
258     if ( theCommand.Search( "CreateFilterManager" ) != -1 )
259       myFilterManager = new _pyFilterManager( aCommand );
260     else if ( !myFilterManager.IsNull() )
261       myFilterManager->Process( aCommand );
262     return aCommand;
263   }
264
265   // SMESH_MeshEditor method?
266   map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
267   if ( id_editor != myMeshEditors.end() ) {
268     id_editor->second->Process( aCommand );
269     TCollection_AsciiString processedCommand = aCommand->GetString();
270     // some commands of SMESH_MeshEditor create meshes
271     if ( aCommand->GetMethod().Search("MakeMesh") != -1 ) {
272       Handle(_pyMesh) mesh = new _pyMesh( aCommand, aCommand->GetResultValue() );
273       aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
274       myMeshes.insert( make_pair( mesh->GetID(), mesh ));
275     }
276     return aCommand;
277   }
278   // SMESH_Hypothesis method?
279   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
280   for ( ; hyp != myHypos.end(); ++hyp )
281     if ( !(*hyp)->IsAlgo() && objID == (*hyp)->GetID() ) {
282       (*hyp)->Process( aCommand );
283       return aCommand;
284     }
285
286   // Add access to a wrapped mesh
287   AddMeshAccessorMethod( aCommand );
288
289   // Add access to a wrapped algorithm
290   //  AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
291
292   // PAL12227. PythonDump was not updated at proper time; result is
293   //     aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
294   // TypeError: __init__() takes exactly 11 arguments (10 given)
295   char wrongCommand[] = "SMESH.Filter.Criterion(";
296   if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
297   {
298     _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
299     // there must be 10 arguments, 5-th arg ThresholdID is missing,
300     const int wrongNbArgs = 9, missingArg = 5;
301     if ( tmpCmd.GetNbArgs() == wrongNbArgs )
302     {
303       for ( int i = wrongNbArgs; i > missingArg; --i )
304         tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
305       tmpCmd.SetArg(  missingArg, "''");
306       aCommand->GetString().Trunc( beg - 1 );
307       aCommand->GetString() += tmpCmd.GetString();
308     }
309   }
310   return aCommand;
311 }
312
313 //================================================================================
314 /*!
315  * \brief Convert the command or remember it for later conversion 
316   * \param theCommand - The python command calling a method of SMESH_Gen
317  */
318 //================================================================================
319
320 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
321 {
322   // there are methods to convert:
323   // CreateMesh( shape )
324   // Concatenate( [mesh1, ...], ... )
325   // CreateHypothesis( theHypType, theLibName )
326   // Compute( mesh, geom )
327   // mesh creation
328   TCollection_AsciiString method = theCommand->GetMethod();
329
330   if ( method == "CreateMesh" || method == "CreateEmptyMesh")
331   {
332     Handle(_pyMesh) mesh = new _pyMesh( theCommand );
333     myMeshes.insert( make_pair( mesh->GetID(), mesh ));
334     return;
335   }
336   if ( method == "CreateMeshesFromUNV" || method == "CreateMeshesFromSTL")
337   {
338     Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
339     myMeshes.insert( make_pair( mesh->GetID(), mesh ));
340     return;
341   }
342   if( method == "CreateMeshesFromMED")
343   {
344     for(int ind = 0;ind<theCommand->GetNbResultValues();ind++)
345     {
346       Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue(ind));
347       myMeshes.insert( make_pair( theCommand->GetResultValue(ind), mesh ));     
348     }
349   }
350
351   // CreateHypothesis()
352   if ( method == "CreateHypothesis" )
353   {
354     // issue 199929, remove standard library name (default parameter)
355     const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
356     if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
357       // keep first argument
358       TCollection_AsciiString arg = theCommand->GetArg( 1 );
359       theCommand->RemoveArgs();
360       theCommand->SetArg( 1, arg );
361     }
362
363     myHypos.push_back( _pyHypothesis::NewHypothesis( theCommand ));
364     return;
365   }
366
367   // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
368   if ( method == "Compute" )
369   {
370     const _pyID& meshID = theCommand->GetArg( 1 );
371     map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
372     if ( id_mesh != myMeshes.end() ) {
373       theCommand->SetObject( meshID );
374       theCommand->RemoveArgs();
375       id_mesh->second->Flush();
376       return;
377     }
378   }
379
380   // leave only one smeshgen.GetPattern() in the script
381   if ( method == "GetPattern" ) {
382     if ( myHasPattern ) {
383       theCommand->Clear();
384       return;
385     }
386     myHasPattern = true;
387   }
388
389   // Concatenate( [mesh1, ...], ... )
390   if ( method == "Concatenate" || method == "ConcatenateWithGroups")
391   {
392     if ( method == "ConcatenateWithGroups" ) {
393       theCommand->SetMethod( "Concatenate" );
394       theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
395     }
396     Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
397     myMeshes.insert( make_pair( mesh->GetID(), mesh ));
398     AddMeshAccessorMethod( theCommand );
399   }
400
401   // Replace name of SMESH_Gen
402
403   // names of SMESH_Gen methods fully equal to methods defined in smesh.py
404   static TStringSet smeshpyMethods;
405   if ( smeshpyMethods.empty() ) {
406     const char * names[] =
407       { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
408         "GetPattern","GetSubShapesId",
409         "" }; // <- mark of array end
410     smeshpyMethods.Insert( names );
411   }
412   if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
413     // smeshgen.Method() --> smesh.Method()
414     theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
415   else
416     // smeshgen.Method() --> smesh.smesh.Method()
417     theCommand->SetObject( SMESH_2smeshpy::GenName() );
418 }
419
420 //================================================================================
421 /*!
422  * \brief Convert the remembered commands
423  */
424 //================================================================================
425
426 void _pyGen::Flush()
427 {
428   // create empty command
429   myLastCommand = new _pyCommand();
430
431   if ( !myFilterManager.IsNull() )
432     myFilterManager->Flush();
433
434   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
435   for ( ; id_mesh != myMeshes.end(); ++id_mesh )
436     if ( ! id_mesh->second.IsNull() )
437       id_mesh->second->Flush();
438
439   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
440   for ( ; hyp != myHypos.end(); ++hyp )
441     if ( !hyp->IsNull() ) {
442       (*hyp)->Flush();
443       // smeshgen.CreateHypothesis() --> smesh.smesh.CreateHypothesis()
444       if ( !(*hyp)->IsWrapped() )
445         (*hyp)->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
446     }
447
448   map< _pyID, Handle(_pySubMesh) >::iterator id_subMesh = mySubMeshes.begin();
449   for ( ; id_subMesh != mySubMeshes.end(); ++id_subMesh )
450     if ( ! id_subMesh->second.IsNull() )
451       id_subMesh->second->Flush();
452
453   myLastCommand->SetOrderNb( ++myNbCommands );
454   myCommands.push_back( myLastCommand );
455 }
456
457 //================================================================================
458 /*!
459  * \brief Add access method to mesh that is an argument
460   * \param theCmd - command to add access method
461   * \retval bool - true if added
462  */
463 //================================================================================
464
465 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
466 {
467   bool added = false;
468   map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
469   for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
470     if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
471       added = true;
472   }
473   return added;
474 }
475
476 //================================================================================
477 /*!
478  * \brief Add access method to algo that is an object or an argument
479   * \param theCmd - command to add access method
480   * \retval bool - true if added
481  */
482 //================================================================================
483
484 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
485 {
486   bool added = false;
487   list< Handle(_pyHypothesis) >::const_iterator hyp = myHypos.begin();
488   for ( ; hyp != myHypos.end(); ++hyp ) {
489     if ( (*hyp)->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
490          theCmd->AddAccessorMethod( (*hyp)->GetID(), (*hyp)->AccessorMethod() ))
491       added = true;
492   }
493   return added;
494 }
495
496 //================================================================================
497 /*!
498  * \brief Find hypothesis by ID (entry)
499   * \param theHypID - The hypothesis ID
500   * \retval Handle(_pyHypothesis) - The found hypothesis
501  */
502 //================================================================================
503
504 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
505 {
506   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
507   for ( ; hyp != myHypos.end(); ++hyp )
508     if ( !hyp->IsNull() && theHypID == (*hyp)->GetID() )
509       return *hyp;
510   return Handle(_pyHypothesis)();
511 }
512
513 //================================================================================
514 /*!
515  * \brief Find algorithm the created algorithm
516   * \param theGeom - The shape ID the algorithm was created on
517   * \param theMesh - The mesh ID that created the algorithm
518   * \param dim - The algo dimension
519   * \retval Handle(_pyHypothesis) - The found algo
520  */
521 //================================================================================
522
523 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
524                                         const Handle(_pyHypothesis)& theHypothesis )
525 {
526   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
527   for ( ; hyp != myHypos.end(); ++hyp )
528     if ( !hyp->IsNull() &&
529          (*hyp)->IsAlgo() &&
530          theHypothesis->CanBeCreatedBy( (*hyp)->GetAlgoType() ) &&
531          (*hyp)->GetGeom() == theGeom &&
532          (*hyp)->GetMesh() == theMesh )
533       return *hyp;
534   return 0;
535 }
536
537 //================================================================================
538 /*!
539  * \brief Find subMesh by ID (entry)
540   * \param theSubMeshID - The subMesh ID
541   * \retval Handle(_pySubMesh) - The found subMesh
542  */
543 //================================================================================
544
545 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
546 {
547   map< _pyID, Handle(_pySubMesh) >::iterator id_subMesh = mySubMeshes.begin();
548   for ( ; id_subMesh != mySubMeshes.end(); ++id_subMesh ) {
549     Handle(_pySubMesh) sm = id_subMesh->second;
550     if ( !id_subMesh->second.IsNull() && theSubMeshID == id_subMesh->second->GetID() )
551       return sm;
552   }
553   return Handle(_pySubMesh)();
554 }
555
556
557 //================================================================================
558 /*!
559  * \brief Change order of commands in the script
560   * \param theCmd1 - One command
561   * \param theCmd2 - Another command
562  */
563 //================================================================================
564
565 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
566 {
567   list< Handle(_pyCommand) >::iterator pos1, pos2;
568   pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
569   pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
570   myCommands.insert( pos1, theCmd2 );
571   myCommands.insert( pos2, theCmd1 );
572   myCommands.erase( pos1 );
573   myCommands.erase( pos2 );
574
575   int nb1 = theCmd1->GetOrderNb();
576   theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
577   theCmd2->SetOrderNb( nb1 );
578 //   cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
579 //        << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
580 }
581
582 //================================================================================
583 /*!
584  * \brief Set one command after the other
585   * \param theCmd - Command to move
586   * \param theAfterCmd - Command ater which to insert the first one
587  */
588 //================================================================================
589
590 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
591 {
592   setNeighbourCommand( theCmd, theAfterCmd, true );
593 }
594
595 //================================================================================
596 /*!
597  * \brief Set one command before the other
598   * \param theCmd - Command to move
599   * \param theBeforeCmd - Command before which to insert the first one
600  */
601 //================================================================================
602
603 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
604 {
605   setNeighbourCommand( theCmd, theBeforeCmd, false );
606 }
607
608 //================================================================================
609 /*!
610  * \brief Set one command before or after the other
611   * \param theCmd - Command to move
612   * \param theOtherCmd - Command ater or before which to insert the first one
613  */
614 //================================================================================
615
616 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
617                                   Handle(_pyCommand)& theOtherCmd,
618                                   const bool theIsAfter )
619 {
620   list< Handle(_pyCommand) >::iterator pos;
621   pos = find( myCommands.begin(), myCommands.end(), theCmd );
622   myCommands.erase( pos );
623   pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
624   myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
625
626   int i = 1;
627   for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
628     (*pos)->SetOrderNb( i++ );
629 }
630
631 //================================================================================
632 /*!
633  * \brief Set command be last in list of commands
634   * \param theCmd - Command to be last
635  */
636 //================================================================================
637
638 Handle(_pyCommand)& _pyGen::GetLastCommand()
639 {
640   return myLastCommand;
641 }
642
643 //================================================================================
644 /*!
645  * \brief Set method to access to object wrapped with python class
646   * \param theID - The wrapped object entry
647   * \param theMethod - The accessor method
648  */
649 //================================================================================
650
651 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
652 {
653   myID2AccessorMethod.Bind( theID, (char*) theMethod );
654 }
655
656 //================================================================================
657 /*!
658  * \brief Generated new ID for object and assign with existing name
659   * \param theID - ID of existing object
660  */
661 //================================================================================
662
663 _pyID _pyGen::GenerateNewID( const _pyID& theID )
664 {
665   int index = 1;
666   _pyID aNewID;
667   do {
668     aNewID = theID + _pyID( ":" ) + _pyID( index++ );
669   }
670   while ( myObjectNames.IsBound( aNewID ) );
671     
672   myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID ) 
673                       ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
674                       : _pyID( "A" ) + aNewID );
675   return aNewID;
676 }
677
678 //================================================================================
679 /*!
680  * \brief Find out type of geom group
681   * \param grpID - The geom group entry
682   * \retval int - The type
683  */
684 //================================================================================
685
686 static bool sameGroupType( const _pyID&                   grpID,
687                            const TCollection_AsciiString& theType)
688 {
689   // define group type as smesh.Mesh.Group() does
690   int type = -1;
691   SALOMEDS::Study_var study = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
692   SALOMEDS::SObject_var aSObj = study->FindObjectID( grpID.ToCString() );
693   if ( !aSObj->_is_nil() ) {
694     GEOM::GEOM_Object_var aGeomObj = GEOM::GEOM_Object::_narrow( aSObj->GetObject() );
695     if ( !aGeomObj->_is_nil() ) {
696       switch ( aGeomObj->GetShapeType() ) {
697       case GEOM::VERTEX: type = SMESH::NODE; break;
698       case GEOM::EDGE:   type = SMESH::EDGE; break;
699       case GEOM::FACE:   type = SMESH::FACE; break;
700       case GEOM::SOLID:
701       case GEOM::SHELL:  type = SMESH::VOLUME; break;
702       case GEOM::COMPOUND: {
703         GEOM::GEOM_Gen_ptr aGeomGen = SMESH_Gen_i::GetSMESHGen()->GetGeomEngine();
704         if ( !aGeomGen->_is_nil() ) {
705           GEOM::GEOM_IGroupOperations_var aGrpOp =
706             aGeomGen->GetIGroupOperations( study->StudyId() );
707           if ( !aGrpOp->_is_nil() ) {
708             switch ( aGrpOp->GetType( aGeomObj )) {
709             case TopAbs_VERTEX: type = SMESH::NODE; break;
710             case TopAbs_EDGE:   type = SMESH::EDGE; break;
711             case TopAbs_FACE:   type = SMESH::FACE; break;
712             case TopAbs_SOLID:  type = SMESH::VOLUME; break;
713             default:;
714             }
715           }
716         }
717       }
718       default:;
719       }
720     }
721   }
722   if ( type < 0 ) {
723     MESSAGE("Type of the group " << grpID << " not found");
724     return false;
725   }
726   if ( theType.IsIntegerValue() )
727     return type == theType.IntegerValue();
728
729   switch ( type ) {
730   case SMESH::NODE:   return theType.Location( "NODE", 1, theType.Length() );
731   case SMESH::EDGE:   return theType.Location( "EDGE", 1, theType.Length() );
732   case SMESH::FACE:   return theType.Location( "FACE", 1, theType.Length() );
733   case SMESH::VOLUME: return theType.Location( "VOLUME", 1, theType.Length() );
734   default:;
735   }
736   return false;
737 }
738
739 //================================================================================
740 /*!
741  * \brief 
742   * \param theCreationCmd - 
743  */
744 //================================================================================
745
746 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
747   : _pyObject(theCreationCmd), myHasEditor(false)
748 {
749   // convert my creation command
750   Handle(_pyCommand) creationCmd = GetCreationCmd();
751   //TCollection_AsciiString str = creationCmd->GetMethod();
752 //   if(str != "CreateMeshesFromUNV" &&
753 //      str != "CreateMeshesFromMED" &&
754 //      str != "CreateMeshesFromSTL")
755   creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() ); 
756   creationCmd->SetMethod( "Mesh" );
757
758   theGen->SetAccessorMethod( GetID(), "GetMesh()" );
759 }
760
761 //================================================================================
762 /*!
763  * \brief 
764   * \param theCreationCmd - 
765  */
766 //================================================================================
767 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const TCollection_AsciiString& id):
768   _pyObject(theCreationCmd), myHasEditor(false)
769 {
770   // convert my creation command
771   Handle(_pyCommand) creationCmd = GetCreationCmd();
772   creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() ); 
773   theGen->SetAccessorMethod( id, "GetMesh()" );
774 }
775
776 //================================================================================
777 /*!
778  * \brief Convert a IDL API command of SMESH::Mesh to a method call of python Mesh
779   * \param theCommand - Engine method called for this mesh
780  */
781 //================================================================================
782
783 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
784 {
785   // some methods of SMESH_Mesh interface needs special conversion
786   // to methods of Mesh python class
787   //
788   // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
789   //     --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
790   // 2. AddHypothesis(geom, hyp)
791   //     --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
792   // 3. CreateGroupFromGEOM(type, name, grp)
793   //     --> in Mesh.Group(grp, name="")
794   // 4. ExportToMED(f, auto_groups, version)
795   //     --> in Mesh.ExportMED( f, auto_groups, version )
796   // 5. etc
797
798   const TCollection_AsciiString method = theCommand->GetMethod();
799   // ----------------------------------------------------------------------
800   if ( method == "GetSubMesh" ) {
801     Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
802     if ( !subMesh.IsNull() ) {
803       subMesh->SetCreator( this );
804       mySubmeshes.push_back( subMesh );
805     }
806   }
807   // ----------------------------------------------------------------------
808   else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
809     myAddHypCmds.push_back( theCommand );
810     // set mesh to hypo
811     const _pyID& hypID = theCommand->GetArg( 2 );
812     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
813     if ( !hyp.IsNull() ) {
814       myHypos.push_back( hyp );
815       if ( hyp->GetMesh().IsEmpty() )
816         hyp->SetMesh( this->GetID() );
817     }
818   }
819   // ----------------------------------------------------------------------
820   else if ( method == "CreateGroupFromGEOM" ) {// (type, name, grp)
821     _pyID grp = theCommand->GetArg( 3 );
822     if ( sameGroupType( grp, theCommand->GetArg( 1 )) ) { // --> Group(grp)
823       theCommand->SetMethod( "Group" );
824       theCommand->RemoveArgs();
825       theCommand->SetArg( 1, grp );
826     }
827     else {
828       _pyID type = theCommand->GetArg( 1 );
829       _pyID name = theCommand->GetArg( 2 );
830       theCommand->SetMethod( "GroupOnGeom" );
831       theCommand->RemoveArgs();
832       theCommand->SetArg( 1, grp );
833       theCommand->SetArg( 2, name );
834       theCommand->SetArg( 3, type );
835     }
836   }
837   // ----------------------------------------------------------------------
838   else if ( method == "ExportToMED" ) { // ExportToMED() --> ExportMED()
839     theCommand->SetMethod( "ExportMED" );
840   }
841   // ----------------------------------------------------------------------
842   else if ( method == "CreateGroup" ) { // CreateGroup() --> CreateEmptyGroup()
843     theCommand->SetMethod( "CreateEmptyGroup" );
844   }
845   // ----------------------------------------------------------------------
846   else if ( method == "RemoveHypothesis" ) // (geom, hyp)
847   {
848     _pyID hypID = theCommand->GetArg( 2 );
849
850     // check if this mesh still has corresponding addition command
851     bool hasAddCmd = false;
852     list< Handle(_pyCommand) >::iterator cmd = myAddHypCmds.begin();
853     while ( cmd != myAddHypCmds.end() )
854     {
855       // AddHypothesis(geom, hyp)
856       if ( hypID == (*cmd)->GetArg( 2 )) { // erase both (add and remove) commands
857         theCommand->Clear();
858         (*cmd)->Clear();
859         cmd = myAddHypCmds.erase( cmd );
860         hasAddCmd = true;
861       }
862       else {
863         ++cmd;
864       }
865     }
866     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
867     if ( ! hasAddCmd && hypID.Length() != 0 ) { // hypo addition already wrapped
868       // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
869       _pyID geom = theCommand->GetArg( 1 );
870       theCommand->RemoveArgs();
871       theCommand->SetArg( 1, hypID );
872       if ( geom != GetGeom() )
873         theCommand->SetArg( 2, geom );
874     }
875     // remove hyp from myHypos
876     myHypos.remove( hyp );
877   }
878   // add accessor method if necessary
879   else
880   {
881     if ( NeedMeshAccess( theCommand ))
882       // apply theCommand to the mesh wrapped by smeshpy mesh
883       AddMeshAccess( theCommand );
884   }
885 }
886
887 //================================================================================
888 /*!
889  * \brief Return True if addition of accesor method is needed
890  */
891 //================================================================================
892
893 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
894 {
895   // names of SMESH_Mesh methods fully equal to methods of class Mesh, so
896   // no conversion is needed for them at all:
897   static TStringSet sameMethods;
898   if ( sameMethods.empty() ) {
899     const char * names[] =
900       { "ExportDAT","ExportUNV","ExportSTL", "RemoveGroup","RemoveGroupWithContents",
901         "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
902         "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
903         "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
904         "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
905         "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
906         "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
907         "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
908         "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
909         "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
910         "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
911         "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
912         "Clear", "ConvertToStandalone"
913         ,"" }; // <- mark of end
914     sameMethods.Insert( names );
915   }
916
917   return !sameMethods.Contains( theCommand->GetMethod() );
918 }
919
920 //================================================================================
921 /*!
922  * \brief Convert creation and addition of all algos and hypos
923  */
924 //================================================================================
925
926 void _pyMesh::Flush()
927 {
928   list < Handle(_pyCommand) >::iterator cmd;
929
930   // try to convert algo addition like this:
931   // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
932   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
933   {
934     Handle(_pyCommand) addCmd = *cmd;
935
936     _pyID algoID = addCmd->GetArg( 2 );
937     Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
938     if ( algo.IsNull() || !algo->IsAlgo() )
939       continue;
940
941     // check and create new algorithm instance if it is already wrapped
942     if ( algo->IsWrapped() ) {
943       _pyID localAlgoID = theGen->GenerateNewID( algoID );
944       TCollection_AsciiString aNewCmdStr = localAlgoID +
945         TCollection_AsciiString( " = " ) + theGen->GetID() +
946         TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
947         TCollection_AsciiString( "\" )" );
948       
949       Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
950       Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
951       if ( !newAlgo.IsNull() ) {
952         newAlgo->Assign( algo, this->GetID() );
953         newAlgo->SetCreationCmd( newCmd );
954         algo = newAlgo;
955         // set algorithm creation
956         theGen->SetCommandBefore( newCmd, addCmd );
957       }
958       else
959         newCmd->Clear();
960     }
961     _pyID geom = addCmd->GetArg( 1 );
962     bool isLocalAlgo = ( geom != GetGeom() );
963     
964     // try to convert
965     if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
966     {
967       // wrapped algo is created atfer mesh creation
968       GetCreationCmd()->AddDependantCmd( addCmd );
969
970       if ( isLocalAlgo ) {
971         // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
972         addCmd->SetArg( addCmd->GetNbArgs() + 1,
973                         TCollection_AsciiString( "geom=" ) + geom );
974         // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
975         list < Handle(_pySubMesh) >::iterator smIt;
976         for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
977           Handle(_pySubMesh) subMesh = *smIt;
978           Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
979           if ( geom == subCmd->GetArg( 1 )) {
980             subCmd->SetObject( algo->GetID() );
981             subCmd->RemoveArgs();
982             subMesh->SetCreator( algo );
983           }
984         }
985       }
986     }
987     else // KO - ALGO was already created
988     {
989       // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
990       addCmd->RemoveArgs();
991       addCmd->SetArg( 1, algoID );
992       if ( isLocalAlgo )
993         addCmd->SetArg( 2, geom );
994     }
995   }
996
997   // try to convert hypo addition like this:
998   // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
999   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
1000   {
1001     Handle(_pyCommand) addCmd = *cmd;
1002     _pyID hypID = addCmd->GetArg( 2 );
1003     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1004     if ( hyp.IsNull() || hyp->IsAlgo() )
1005       continue;
1006     bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
1007     if ( !converted ) {
1008       // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
1009       _pyID geom = addCmd->GetArg( 1 );
1010       addCmd->RemoveArgs();
1011       addCmd->SetArg( 1, hypID );
1012       if ( geom != GetGeom() )
1013         addCmd->SetArg( 2, geom );
1014     }
1015   }
1016
1017   // sm = mesh.GetSubMesh(geom, name) --> sm = mesh.GetMesh().GetSubMesh(geom, name)
1018 //   for ( cmd = mySubmeshes.begin(); cmd != mySubmeshes.end(); ++cmd ) {
1019 //     Handle(_pyCommand) subCmd = *cmd;
1020 //     if ( subCmd->GetNbArgs() > 0 )
1021 //       AddMeshAccess( subCmd );
1022 //   }
1023   myAddHypCmds.clear();
1024   mySubmeshes.clear();
1025
1026   // flush hypotheses
1027   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1028   for ( ; hyp != myHypos.end(); ++hyp )
1029     (*hyp)->Flush();
1030 }
1031
1032 //================================================================================
1033 /*!
1034  * \brief MeshEditor convert its commands to ones of mesh
1035  */
1036 //================================================================================
1037
1038 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
1039   _pyObject( theCreationCmd )
1040 {
1041   myMesh = theCreationCmd->GetObject();
1042   myCreationCmdStr = theCreationCmd->GetString();
1043   theCreationCmd->Clear();
1044 }
1045
1046 //================================================================================
1047 /*!
1048  * \brief convert its commands to ones of mesh
1049  */
1050 //================================================================================
1051
1052 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
1053 {
1054   // names of SMESH_MeshEditor methods fully equal to methods of class Mesh, so
1055   // commands calling this methods are converted to calls of methods of Mesh
1056   static TStringSet sameMethods;
1057   if ( sameMethods.empty() ) {
1058     const char * names[] = {
1059       "RemoveElements","RemoveNodes","AddNode","AddEdge","AddFace","AddPolygonalFace",
1060       "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces","MoveNode",
1061       "InverseDiag","DeleteDiag","Reorient","ReorientObject","SplitQuad","SplitQuadObject",
1062       "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
1063       "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
1064       "RotationSweep","RotationSweepObject","ExtrusionSweep","AdvancedExtrusion",
1065       "ExtrusionSweepObject","ExtrusionSweepObject1D","ExtrusionSweepObject2D","Mirror",
1066       "MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
1067       "FindCoincidentNodes","FindCoincidentNodesOnPart","MergeNodes","FindEqualElements",
1068       "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
1069       "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
1070       "GetLastCreatedElems",
1071       "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh",
1072       "TranslateObjectMakeMesh","RotateMakeMesh","RotateObjectMakeMesh"
1073       ,"" }; // <- mark of the end
1074     sameMethods.Insert( names );
1075   }
1076
1077   // names of SMESH_MeshEditor methods which differ from methods of class Mesh
1078   // only last two arguments
1079   static TStringSet diffLastTwoArgsMethods;
1080   if (diffLastTwoArgsMethods.empty() ){
1081     const char * names[] = {
1082       "MirrorMakeGroups","MirrorObjectMakeGroups",
1083       "TranslateMakeGroups","TranslateObjectMakeGroups",
1084       "RotateMakeGroups","RotateObjectMakeGroups",
1085       ""};// <- mark of the end
1086     diffLastTwoArgsMethods.Insert( names );
1087   }
1088
1089   if ( sameMethods.Contains( theCommand->GetMethod() )) {
1090     theCommand->SetObject( myMesh );
1091
1092     // meshes made by *MakeMesh() methods are not wrapped by _pyMesh,
1093     // so let _pyMesh care of it (TMP?)
1094 //     if ( theCommand->GetMethod().Search("MakeMesh") != -1 )
1095 //       _pyMesh( new _pyCommand( theCommand->GetString(), 0 )); // for theGen->SetAccessorMethod()
1096   }
1097   else {
1098     
1099     //Replace SMESH_MeshEditor "MakeGroups" functions on the Mesh 
1100     //functions with the flag "theMakeGroups = True" like:
1101     //SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
1102     int pos = theCommand->GetMethod().Search("MakeGroups");
1103     if( pos != -1) {  
1104       // 1. Remove "MakeGroups" from the Command
1105       TCollection_AsciiString aMethod = theCommand->GetMethod();
1106       int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
1107       aMethod.Trunc(pos-1);
1108       theCommand->SetMethod(aMethod);
1109
1110       // 2. Set Mesh object instead of SMESH_MeshEditor
1111       theCommand->SetObject( myMesh );
1112
1113       // 3. And add last "True" argument
1114       while(nbArgsToAdd--)
1115         theCommand->SetArg(theCommand->GetNbArgs()+1,"True ");
1116     }
1117     else {
1118       // editor creation command is needed only if any editor function is called
1119       theGen->AddMeshAccessorMethod( theCommand ); // for *Object()
1120       if ( !myCreationCmdStr.IsEmpty() ) {
1121         GetCreationCmd()->GetString() = myCreationCmdStr;
1122         myCreationCmdStr.Clear();
1123       }
1124     }
1125   }
1126 }
1127
1128 //================================================================================
1129 /*!
1130  * \brief _pyHypothesis constructor
1131   * \param theCreationCmd - 
1132  */
1133 //================================================================================
1134
1135 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
1136   _pyObject( theCreationCmd )
1137 {
1138   myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
1139 }
1140
1141 //================================================================================
1142 /*!
1143  * \brief Creates algorithm or hypothesis
1144   * \param theCreationCmd - The engine command creating a hypothesis
1145   * \retval Handle(_pyHypothesis) - Result _pyHypothesis
1146  */
1147 //================================================================================
1148
1149 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
1150 {
1151   // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
1152   ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
1153
1154   Handle(_pyHypothesis) hyp, algo;
1155
1156   // "theHypType"
1157   const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
1158   if ( hypTypeQuoted.IsEmpty() )
1159     return hyp;
1160   // theHypType
1161   TCollection_AsciiString  hypType =
1162     hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
1163
1164   algo = new _pyAlgorithm( theCreationCmd );
1165   hyp  = new _pyHypothesis( theCreationCmd );
1166
1167   // 1D Regular_1D ----------
1168   if ( hypType == "Regular_1D" ) {
1169     // set mesh's method creating algo,
1170     // i.e. convertion result will be "regular1d = Mesh.Segment()",
1171     // and set hypType by which algo creating a hypothesis is searched for
1172     algo->SetConvMethodAndType("Segment", hypType.ToCString());
1173   }
1174   else if ( hypType == "CompositeSegment_1D" ) {
1175     algo->SetConvMethodAndType("Segment", "Regular_1D");
1176     algo->myArgs.Append( "algo=smesh.COMPOSITE");
1177   }
1178   else if ( hypType == "LocalLength" ) {
1179     // set algo's method creating hyp, and algo type
1180     hyp->SetConvMethodAndType( "LocalLength", "Regular_1D");
1181     // set method whose 1 arg will become the 1-st arg of hyp creation command
1182     // i.e. convertion result will be "locallength = regular1d.LocalLength(<arg of SetLength()>)"
1183     hyp->AddArgMethod( "SetLength" );
1184   }
1185   else if ( hypType == "MaxLength" ) {
1186     // set algo's method creating hyp, and algo type
1187     hyp->SetConvMethodAndType( "MaxSize", "Regular_1D");
1188     // set method whose 1 arg will become the 1-st arg of hyp creation command
1189     // i.e. convertion result will be "maxsize = regular1d.MaxSize(<arg of SetLength()>)"
1190     hyp->AddArgMethod( "SetLength" );
1191   }
1192   else if ( hypType == "NumberOfSegments" ) {
1193     hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
1194     hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
1195     // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
1196     hyp->AddArgMethod( "SetNumberOfSegments" );
1197     // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
1198     hyp->AddArgMethod( "SetScaleFactor" );
1199   }
1200   else if ( hypType == "Arithmetic1D" ) {
1201     hyp = new _pyComplexParamHypo( theCreationCmd );
1202     hyp->SetConvMethodAndType( "Arithmetic1D", "Regular_1D");
1203   }
1204   else if ( hypType == "StartEndLength" ) {
1205     hyp = new _pyComplexParamHypo( theCreationCmd );
1206     hyp->SetConvMethodAndType( "StartEndLength", "Regular_1D");
1207   }
1208   else if ( hypType == "Deflection1D" ) {
1209     hyp->SetConvMethodAndType( "Deflection1D", "Regular_1D");
1210     hyp->AddArgMethod( "SetDeflection" );
1211   }
1212   else if ( hypType == "Propagation" ) {
1213     hyp->SetConvMethodAndType( "Propagation", "Regular_1D");
1214   }
1215   else if ( hypType == "QuadraticMesh" ) {
1216     hyp->SetConvMethodAndType( "QuadraticMesh", "Regular_1D");
1217   }
1218   else if ( hypType == "AutomaticLength" ) {
1219     hyp->SetConvMethodAndType( "AutomaticLength", "Regular_1D");
1220     hyp->AddArgMethod( "SetFineness");
1221   }
1222   else if ( hypType == "SegmentLengthAroundVertex" ) {
1223     hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
1224     hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
1225     hyp->AddArgMethod( "SetLength" );
1226   }
1227   // 1D Python_1D ----------
1228   else if ( hypType == "Python_1D" ) {
1229     algo->SetConvMethodAndType( "Segment", hypType.ToCString());
1230     algo->myArgs.Append( "algo=smesh.PYTHON");
1231   }
1232   else if ( hypType == "PythonSplit1D" ) {
1233     hyp->SetConvMethodAndType( "PythonSplit1D", "Python_1D");
1234     hyp->AddArgMethod( "SetNumberOfSegments");
1235     hyp->AddArgMethod( "SetPythonLog10RatioFunction");
1236   }
1237   // MEFISTO_2D ----------
1238   else if ( hypType == "MEFISTO_2D" ) { // MEFISTO_2D
1239     algo->SetConvMethodAndType( "Triangle", hypType.ToCString());
1240   }
1241   else if ( hypType == "MaxElementArea" ) {
1242     hyp->SetConvMethodAndType( "MaxElementArea", "MEFISTO_2D");
1243     hyp->SetConvMethodAndType( "MaxElementArea", "NETGEN_2D_ONLY");
1244     hyp->AddArgMethod( "SetMaxElementArea");
1245   }
1246   else if ( hypType == "LengthFromEdges" ) {
1247     hyp->SetConvMethodAndType( "LengthFromEdges", "MEFISTO_2D");
1248     hyp->SetConvMethodAndType( "LengthFromEdges", "NETGEN_2D_ONLY");
1249   }
1250   // Quadrangle_2D ----------
1251   else if ( hypType == "Quadrangle_2D" ) {
1252     algo->SetConvMethodAndType( "Quadrangle" , hypType.ToCString());
1253   }
1254   else if ( hypType == "QuadranglePreference" ) {
1255     hyp->SetConvMethodAndType( "QuadranglePreference", "Quadrangle_2D");
1256     hyp->SetConvMethodAndType( "QuadranglePreference", "NETGEN_2D_ONLY");
1257   }
1258   else if ( hypType == "TrianglePreference" ) {
1259     hyp->SetConvMethodAndType( "TrianglePreference", "Quadrangle_2D");
1260   }     
1261   // NETGEN ----------
1262 //   else if ( hypType == "NETGEN_2D") { // 1D-2D
1263 //     algo->SetConvMethodAndType( "Triangle" , hypType.ToCString());
1264 //     algo->myArgs.Append( "algo=smesh.NETGEN" );
1265 //   }
1266   else if ( hypType == "NETGEN_2D_ONLY") { // 2D
1267     algo->SetConvMethodAndType( "Triangle" , hypType.ToCString());
1268     algo->myArgs.Append( "algo=smesh.NETGEN_2D" );
1269   }
1270   else if ( hypType == "NETGEN_3D") { // 3D
1271     algo->SetConvMethodAndType( "Tetrahedron" , hypType.ToCString());
1272     algo->myArgs.Append( "algo=smesh.NETGEN" );
1273   }
1274   else if ( hypType == "MaxElementVolume") {
1275     hyp->SetConvMethodAndType( "MaxElementVolume", "NETGEN_3D");
1276     hyp->AddArgMethod( "SetMaxElementVolume" );
1277   }
1278   // GHS3D_3D ----------
1279   else if ( hypType == "GHS3D_3D" ) {
1280     algo->SetConvMethodAndType( "Tetrahedron", hypType.ToCString());
1281     algo->myArgs.Append( "algo=smesh.GHS3D" );
1282   }
1283   // Hexa_3D ---------
1284   else if ( hypType == "Hexa_3D" ) {
1285     algo->SetConvMethodAndType( "Hexahedron", hypType.ToCString());
1286   }
1287   // Repetitive Projection_1D ---------
1288   else if ( hypType == "Projection_1D" ) {
1289     algo->SetConvMethodAndType( "Projection1D", hypType.ToCString());
1290   }
1291   else if ( hypType == "ProjectionSource1D" ) {
1292     hyp->SetConvMethodAndType( "SourceEdge", "Projection_1D");
1293     hyp->AddArgMethod( "SetSourceEdge");
1294     hyp->AddArgMethod( "SetSourceMesh");
1295     // 2 args of SetVertexAssociation() will become the 3-th and 4-th args of hyp creation command
1296     hyp->AddArgMethod( "SetVertexAssociation", 2 );
1297   }
1298   // Projection_2D ---------
1299   else if ( hypType == "Projection_2D" ) {
1300     algo->SetConvMethodAndType( "Projection2D", hypType.ToCString());
1301   }
1302   else if ( hypType == "ProjectionSource2D" ) {
1303     hyp->SetConvMethodAndType( "SourceFace", "Projection_2D");
1304     hyp->AddArgMethod( "SetSourceFace");
1305     hyp->AddArgMethod( "SetSourceMesh");
1306     hyp->AddArgMethod( "SetVertexAssociation", 4 );
1307   }
1308   // Projection_3D ---------
1309   else if ( hypType == "Projection_3D" ) {
1310     algo->SetConvMethodAndType( "Projection3D", hypType.ToCString());
1311   }
1312   else if ( hypType == "ProjectionSource3D" ) {
1313     hyp->SetConvMethodAndType( "SourceShape3D", "Projection_3D");
1314     hyp->AddArgMethod( "SetSource3DShape");
1315     hyp->AddArgMethod( "SetSourceMesh");
1316     hyp->AddArgMethod( "SetVertexAssociation", 4 );
1317   }
1318   // Prism_3D ---------
1319   else if ( hypType == "Prism_3D" ) {
1320     algo->SetConvMethodAndType( "Prism", hypType.ToCString());
1321   }
1322   // RadialPrism_3D ---------
1323   else if ( hypType == "RadialPrism_3D" ) {
1324     algo->SetConvMethodAndType( "Prism", hypType.ToCString());
1325   }
1326   else if ( hypType == "NumberOfLayers" ) {
1327     hyp->SetConvMethodAndType( "NumberOfLayers", "RadialPrism_3D");
1328     hyp->AddArgMethod( "SetNumberOfLayers" );
1329   }
1330   else if ( hypType == "LayerDistribution" ) {
1331     hyp = new _pyLayerDistributionHypo( theCreationCmd );
1332     hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
1333   }
1334
1335   if ( algo->IsValid() ) {
1336     return algo;
1337   }
1338   return hyp;
1339 }
1340
1341 //================================================================================
1342 /*!
1343  * \brief Convert the command adding a hypothesis to mesh into a smesh command
1344   * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
1345   * \param theAlgo - The algo that can create this hypo
1346   * \retval bool - false if the command cant be converted
1347  */
1348 //================================================================================
1349
1350 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
1351                                        const _pyID&              theMesh)
1352 {
1353   ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
1354
1355   if ( !IsWrappable( theMesh ))
1356     return false;
1357
1358   myGeom = theCmd->GetArg( 1 );
1359
1360   Handle(_pyHypothesis) algo;
1361   if ( !IsAlgo() ) {
1362     // find algo created on myGeom in theMesh
1363     algo = theGen->FindAlgo( myGeom, theMesh, this );
1364     if ( algo.IsNull() )
1365       return false;
1366     // attach hypothesis creation command to be after algo creation command
1367     // because it can be new created instance of algorithm
1368     algo->GetCreationCmd()->AddDependantCmd( theCmd );
1369   }
1370   myIsWrapped = true;
1371
1372   // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
1373   theCmd->SetResultValue( GetID() );
1374   theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
1375   theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
1376   // set args
1377   theCmd->RemoveArgs();
1378   for ( int i = 1; i <= myArgs.Length(); ++i ) {
1379     if ( !myArgs( i ).IsEmpty() )
1380       theCmd->SetArg( i, myArgs( i ));
1381     else
1382       theCmd->SetArg( i, "[]");
1383   }
1384   // set a new creation command
1385   GetCreationCmd()->Clear();
1386   // replace creation command by wrapped instance
1387   // please note, that hypothesis attaches to algo creation command (see upper)
1388   SetCreationCmd( theCmd );
1389   
1390
1391   // clear commands setting arg values
1392   list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
1393   for ( ; argCmd != myArgCommands.end(); ++argCmd )
1394     (*argCmd)->Clear();
1395
1396   // set unknown arg commands after hypo creation
1397   Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
1398   list<Handle(_pyCommand)>::iterator cmd = myUnknownCommands.begin();
1399   for ( ; cmd != myUnknownCommands.end(); ++cmd ) {
1400     afterCmd->AddDependantCmd( *cmd );
1401   }
1402
1403   return myIsWrapped;
1404 }
1405
1406 //================================================================================
1407 /*!
1408  * \brief Remember hypothesis parameter values
1409  * \param theCommand - The called hypothesis method
1410  */
1411 //================================================================================
1412
1413 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
1414 {
1415   ASSERT( !myIsAlgo );
1416   // set args
1417   int nbArgs = 0;
1418   for ( int i = 1; i <= myArgMethods.Length(); ++i ) {
1419     if ( myArgMethods( i ) == theCommand->GetMethod() ) {
1420       while ( myArgs.Length() < nbArgs + myNbArgsByMethod( i ))
1421         myArgs.Append( "[]" );
1422       for ( int iArg = 1; iArg <= myNbArgsByMethod( i ); ++iArg )
1423         myArgs( nbArgs + iArg ) = theCommand->GetArg( iArg ); // arg value
1424       myArgCommands.push_back( theCommand );
1425       return;
1426     }
1427     nbArgs += myNbArgsByMethod( i );
1428   }
1429   myUnknownCommands.push_back( theCommand );
1430 }
1431
1432 //================================================================================
1433 /*!
1434  * \brief Finish conversion
1435  */
1436 //================================================================================
1437
1438 void _pyHypothesis::Flush()
1439 {
1440   if ( IsWrapped() ) {
1441   }
1442   else {
1443     list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
1444     for ( ; cmd != myArgCommands.end(); ++cmd ) {
1445       // Add access to a wrapped mesh
1446       theGen->AddMeshAccessorMethod( *cmd );
1447       // Add access to a wrapped algorithm
1448       theGen->AddAlgoAccessorMethod( *cmd );
1449     }
1450     cmd = myUnknownCommands.begin();
1451     for ( ; cmd != myUnknownCommands.end(); ++cmd ) {
1452       // Add access to a wrapped mesh
1453       theGen->AddMeshAccessorMethod( *cmd );
1454       // Add access to a wrapped algorithm
1455       theGen->AddAlgoAccessorMethod( *cmd );
1456     }
1457   }
1458   // forget previous hypothesis modifications
1459   myArgCommands.clear();
1460   myUnknownCommands.clear();
1461 }
1462
1463 //================================================================================
1464 /*!
1465  * \brief clear creation, arg and unkown commands
1466  */
1467 //================================================================================
1468
1469 void _pyHypothesis::ClearAllCommands()
1470 {
1471   GetCreationCmd()->Clear();
1472   list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
1473   for ( ; cmd != myArgCommands.end(); ++cmd )
1474     ( *cmd )->Clear();
1475   cmd = myUnknownCommands.begin();
1476   for ( ; cmd != myUnknownCommands.end(); ++cmd )
1477     ( *cmd )->Clear();
1478 }
1479
1480
1481 //================================================================================
1482 /*!
1483  * \brief Assign fields of theOther to me except myIsWrapped
1484  */
1485 //================================================================================
1486
1487 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
1488                             const _pyID&                 theMesh )
1489 {
1490   myIsWrapped = false;
1491   myMesh = theMesh;
1492
1493   // myCreationCmd = theOther->myCreationCmd;
1494   myIsAlgo = theOther->myIsAlgo;
1495   myGeom = theOther->myGeom;
1496   myType2CreationMethod = theOther->myType2CreationMethod;
1497   myArgs = theOther->myArgs;
1498   myArgMethods = theOther->myArgMethods;
1499   myNbArgsByMethod = theOther->myNbArgsByMethod;
1500   myArgCommands = theOther->myArgCommands;
1501   myUnknownCommands = theOther->myUnknownCommands;
1502 }
1503
1504 //================================================================================
1505 /*!
1506  * \brief Remember hypothesis parameter values
1507   * \param theCommand - The called hypothesis method
1508  */
1509 //================================================================================
1510
1511 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
1512 {
1513   // ex: hyp.SetLength(start, 1)
1514   //     hyp.SetLength(end,   0)
1515   ASSERT(( theCommand->GetMethod() == "SetLength" ));
1516   ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
1517   int i = 2 - theCommand->GetArg( 2 ).IntegerValue();
1518   while ( myArgs.Length() < i )
1519     myArgs.Append( "[]" );
1520   myArgs( i ) = theCommand->GetArg( 1 ); // arg value
1521   myArgCommands.push_back( theCommand );
1522 }
1523
1524 //================================================================================
1525 /*!
1526  * \brief Convert methods of 1D hypotheses to my own methods
1527   * \param theCommand - The called hypothesis method
1528  */
1529 //================================================================================
1530
1531 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
1532 {
1533   if ( theCommand->GetMethod() != "SetLayerDistribution" )
1534     return;
1535
1536   _pyID newName; // name for 1D hyp = "HypType" + "_Distribution"
1537
1538   const _pyID& hyp1dID = theCommand->GetArg( 1 );
1539   Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
1540   if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
1541     hyp1d = my1dHyp;
1542   else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() ) {
1543     // 1D hypo is already set, so distribution changes and the old
1544     // 1D hypo is thrown away
1545     my1dHyp->ClearAllCommands();
1546   }
1547   my1dHyp = hyp1d;
1548   if ( my1dHyp.IsNull() )
1549     return; // something wrong :(
1550
1551   // make a new name for 1D hyp = "HypType" + "_Distribution"
1552   if ( my1dHyp->GetCreationCmd()->GetMethod() == "CreateHypothesis" ) {
1553     // not yet converted creation cmd
1554     TCollection_AsciiString hypTypeQuoted = my1dHyp->GetCreationCmd()->GetArg(1);
1555     TCollection_AsciiString hypType = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
1556     newName = hypType + "_Distribution";
1557     my1dHyp->GetCreationCmd()->SetResultValue( newName );
1558   }
1559   else {
1560     // already converted creation cmd
1561     newName = my1dHyp->GetCreationCmd()->GetResultValue();
1562   }
1563
1564   // as creation of 1D hyp was written later then it's edition,
1565   // we need to find all it's edition calls and process them
1566   list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
1567   list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
1568   for ( ; cmdIt != cmds.end(); ++cmdIt ) {
1569     const _pyID& objID = (*cmdIt)->GetObject();
1570     if ( objID == hyp1dID ) {
1571       my1dHyp->Process( *cmdIt );
1572       my1dHyp->GetCreationCmd()->AddDependantCmd( *cmdIt );
1573       ( *cmdIt )->SetObject( newName );
1574     }
1575   }
1576   if ( !myArgCommands.empty() )
1577     myArgCommands.front()->Clear();
1578   theCommand->SetArg( 1, newName );
1579   myArgCommands.push_back( theCommand );
1580   // copy hyp1d's creation method and args
1581 //   myCreationMethod = hyp1d->GetCreationMethod();
1582 //   myArgs           = hyp1d->GetArgs();
1583 //   // make them cleared at conversion
1584 //   myArgCommands = hyp1d->GetArgCommands();
1585
1586 //   // to be cleared at convertion only
1587 //   myArgCommands.push_back( theCommand );
1588 }
1589
1590 //================================================================================
1591 /*!
1592  * \brief 
1593   * \param theAdditionCmd - command to be converted
1594   * \param theMesh - mesh instance
1595   * \retval bool - status
1596  */
1597 //================================================================================
1598
1599 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
1600                                                   const _pyID&              theMesh)
1601 {
1602   myIsWrapped = false;
1603
1604   if ( my1dHyp.IsNull() )
1605     return false;
1606
1607   // set "SetLayerDistribution()" after addition cmd
1608   theAdditionCmd->AddDependantCmd( myArgCommands.front() );
1609
1610   _pyID geom = theAdditionCmd->GetArg( 1 );
1611
1612   my1dHyp->SetMesh( theMesh );
1613   if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
1614     return false;
1615
1616   // clear "SetLayerDistribution()" cmd
1617   myArgCommands.front()->Clear();
1618
1619   // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
1620
1621   // find RadialPrism algo created on <geom> for theMesh
1622   Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
1623   if ( !algo.IsNull() ) {
1624     GetCreationCmd()->SetObject( algo->GetID() );
1625     GetCreationCmd()->SetMethod( "Get3DHypothesis" );
1626     GetCreationCmd()->RemoveArgs();
1627     theAdditionCmd->AddDependantCmd( GetCreationCmd() );
1628     myIsWrapped = true;
1629   }
1630   return myIsWrapped;
1631 }
1632
1633 //================================================================================
1634 /*!
1635  * \brief 
1636  */
1637 //================================================================================
1638
1639 void _pyLayerDistributionHypo::Flush()
1640 {
1641   //my1dHyp.Nullify();
1642   //_pyHypothesis::Flush();
1643 }
1644
1645 //================================================================================
1646 /*!
1647  * \brief additionally to Addition2Creation, clears SetDistrType() command
1648   * \param theCmd - AddHypothesis() command
1649   * \param theMesh - mesh to which a hypothesis is added
1650   * \retval bool - convertion result
1651  */
1652 //================================================================================
1653
1654 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
1655                                                 const _pyID&              theMesh)
1656 {
1657   if ( IsWrappable( theMesh ) && myArgs.Length() > 1 ) {
1658     // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
1659     bool scaleDistrType = false;
1660     list<Handle(_pyCommand)>::reverse_iterator cmd = myUnknownCommands.rbegin();
1661     for ( ; cmd != myUnknownCommands.rend(); ++cmd ) {
1662       if ( (*cmd)->GetMethod() == "SetDistrType" ) {
1663         if ( (*cmd)->GetArg( 1 ) == "1" ) {
1664           scaleDistrType = true;
1665           (*cmd)->Clear();
1666         }
1667         else if ( !scaleDistrType ) {
1668           // distribution type changed: remove scale factor from args
1669           myArgs.Remove( 2, myArgs.Length() );
1670           break;
1671         }
1672       }
1673     }
1674   }
1675   return _pyHypothesis::Addition2Creation( theCmd, theMesh );
1676 }
1677
1678 //================================================================================
1679 /*!
1680  * \brief remove repeated commands defining distribution
1681  */
1682 //================================================================================
1683
1684 void _pyNumberOfSegmentsHyp::Flush()
1685 {
1686   // find number of the last SetDistrType() command
1687   list<Handle(_pyCommand)>::reverse_iterator cmd = myUnknownCommands.rbegin();
1688   int distrTypeNb = 0;
1689   for ( ; !distrTypeNb && cmd != myUnknownCommands.rend(); ++cmd )
1690     if ( (*cmd)->GetMethod() == "SetDistrType" )
1691       distrTypeNb = (*cmd)->GetOrderNb();
1692
1693   // clear commands before the last SetDistrType()
1694   list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnknownCommands };
1695   for ( int i = 0; i < 2; ++i ) {
1696     set<TCollection_AsciiString> uniqueMethods;
1697     list<Handle(_pyCommand)> & cmdList = *cmds[i];
1698     for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
1699     {
1700       bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
1701       const TCollection_AsciiString& method = (*cmd)->GetMethod();
1702       if ( !clear || method == "SetNumberOfSegments" ) {
1703         bool isNewInSet = uniqueMethods.insert( method ).second;
1704         clear = !isNewInSet;
1705       }
1706       if ( clear )
1707         (*cmd)->Clear();
1708     }
1709     cmdList.clear();
1710   }
1711 }
1712
1713 //================================================================================
1714 /*!
1715  * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
1716  * into regular1D.LengthNearVertex( length, vertex )
1717   * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
1718   * \param theMesh - The mesh needing this hypo
1719   * \retval bool - false if the command cant be converted
1720  */
1721 //================================================================================
1722   
1723 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
1724                                                          const _pyID&              theMeshID)
1725 {
1726   if ( IsWrappable( theMeshID )) {
1727
1728     _pyID vertex = theCmd->GetArg( 1 );
1729
1730     // the problem here is that segment algo will not be found
1731     // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
1732     // geometry where segment algorithm is assigned
1733     Handle(_pyHypothesis) algo;
1734     _pyID geom = vertex;
1735     while ( algo.IsNull() && !geom.IsEmpty()) {
1736       // try to find geom as a father of <vertex>
1737       geom = FatherID( geom );
1738       algo = theGen->FindAlgo( geom, theMeshID, this );
1739     }
1740     if ( algo.IsNull() )
1741       return false; // also possible to find geom as brother of veretex...
1742     // set geom instead of vertex
1743     theCmd->SetArg( 1, geom );
1744
1745     // set vertex as a second arg
1746     if ( myArgs.Length() < 1) myArgs.Append( "1" ); // :(
1747     myArgs.Append( vertex );
1748
1749     // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
1750     // theMeshID.LengthNearVertex( length, vertex )
1751     return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
1752   }
1753   return false;
1754 }
1755
1756 //================================================================================
1757 /*!
1758  * \brief _pyAlgorithm constructor
1759  * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
1760  */
1761 //================================================================================
1762
1763 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
1764   : _pyHypothesis( theCreationCmd )
1765 {
1766   myIsAlgo = true;
1767 }
1768
1769 //================================================================================
1770 /*!
1771  * \brief Convert the command adding an algorithm to mesh
1772   * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
1773   * \param theMesh - The mesh needing this algo 
1774   * \retval bool - false if the command cant be converted
1775  */
1776 //================================================================================
1777   
1778 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
1779                                       const _pyID&              theMeshID)
1780 {
1781   // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
1782   if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
1783     theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
1784     return true;
1785   }
1786   return false;
1787 }
1788
1789 //================================================================================
1790 /*!
1791  * \brief Return starting position of a part of python command
1792   * \param thePartIndex - The index of command part
1793   * \retval int - Part position
1794  */
1795 //================================================================================
1796
1797 int _pyCommand::GetBegPos( int thePartIndex )
1798 {
1799   if ( IsEmpty() )
1800     return EMPTY;
1801   if ( myBegPos.Length() < thePartIndex )
1802     return UNKNOWN;
1803   return myBegPos( thePartIndex );
1804 }
1805
1806 //================================================================================
1807 /*!
1808  * \brief Store starting position of a part of python command
1809   * \param thePartIndex - The index of command part
1810   * \param thePosition - Part position
1811  */
1812 //================================================================================
1813
1814 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
1815 {
1816   while ( myBegPos.Length() < thePartIndex )
1817     myBegPos.Append( UNKNOWN );
1818   myBegPos( thePartIndex ) = thePosition;
1819 }
1820
1821 //================================================================================
1822 /*!
1823  * \brief Returns whitespace symbols at the line beginning
1824   * \retval TCollection_AsciiString - result
1825  */
1826 //================================================================================
1827
1828 TCollection_AsciiString _pyCommand::GetIndentation()
1829 {
1830   int end = 1;
1831   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
1832     GetWord( myString, end, true );
1833   else
1834     end = GetBegPos( RESULT_IND );
1835   return myString.SubString( 1, end - 1 );
1836 }
1837
1838 //================================================================================
1839 /*!
1840  * \brief Return substring of python command looking like ResultValue = Obj.Meth()
1841   * \retval const TCollection_AsciiString & - ResultValue substring
1842  */
1843 //================================================================================
1844
1845 const TCollection_AsciiString & _pyCommand::GetResultValue()
1846 {
1847   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
1848   {
1849     int begPos = myString.Location( "=", 1, Length() );
1850     if ( begPos )
1851       myRes = GetWord( myString, begPos, false );
1852     else
1853       begPos = EMPTY;
1854     SetBegPos( RESULT_IND, begPos );
1855   }
1856   return myRes;
1857 }
1858
1859 //================================================================================
1860 /*!
1861  * \brief Return number of python command result value ResultValue = Obj.Meth()
1862   * \retval const int
1863  */
1864 //================================================================================
1865
1866 const int _pyCommand::GetNbResultValues()
1867 {
1868   int begPos = 1;
1869   int Nb=0;
1870   int endPos = myString.Location( "=", 1, Length() );
1871   TCollection_AsciiString str = "";
1872   while ( begPos < endPos) {
1873     str = GetWord( myString, begPos, true );
1874     begPos = begPos+ str.Length();
1875     Nb++;
1876   }
1877   return (Nb-1);
1878 }
1879
1880
1881 //================================================================================
1882 /*!
1883  * \brief Return substring of python command looking like
1884  *  ResultValue1 , ResultValue1,... = Obj.Meth() with res index
1885  * \retval const TCollection_AsciiString & - ResultValue with res index substring
1886  */
1887 //================================================================================
1888 const TCollection_AsciiString & _pyCommand::GetResultValue(int res)
1889 {
1890   int begPos = 1;
1891   int Nb=0;
1892   int endPos = myString.Location( "=", 1, Length() );
1893   while ( begPos < endPos) {
1894     myRes = GetWord( myString, begPos, true );
1895     begPos = begPos + myRes.Length();
1896     Nb++;
1897     if(res == Nb){
1898       myRes.RemoveAll('[');myRes.RemoveAll(']');
1899       return myRes;
1900     }
1901     if(Nb>res)
1902       break;
1903   }
1904   return theEmptyString;
1905 }
1906
1907 //================================================================================
1908 /*!
1909  * \brief Return substring of python command looking like ResVal = Object.Meth()
1910   * \retval const TCollection_AsciiString & - Object substring
1911  */
1912 //================================================================================
1913
1914 const TCollection_AsciiString & _pyCommand::GetObject()
1915 {
1916   if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
1917   {
1918     // beginning
1919     int begPos = GetBegPos( RESULT_IND ) + myRes.Length();
1920     if ( begPos < 1 ) {
1921       begPos = myString.Location( "=", 1, Length() ) + 1;
1922       // is '=' in the string argument (for example, name) or not
1923       int nb1 = 0; // number of ' character at the left of =
1924       int nb2 = 0; // number of " character at the left of =
1925       for ( int i = 1; i < begPos-1; i++ ) {
1926         if ( IsEqual(myString.Value( i ), "'" ) )
1927           nb1 += 1;
1928         else if ( IsEqual( myString.Value( i ), '"' ) )
1929           nb2 += 1;
1930       }
1931       // if number of ' or " is not divisible by 2,
1932       // then get an object at the start of the command
1933       if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
1934         begPos = 1;
1935     }
1936     // store
1937     myObj = GetWord( myString, begPos, true );
1938     SetBegPos( OBJECT_IND, begPos );
1939   }
1940   //SCRUTE(myObj);
1941   return myObj;
1942 }
1943
1944 //================================================================================
1945 /*!
1946  * \brief Return substring of python command looking like ResVal = Obj.Method()
1947   * \retval const TCollection_AsciiString & - Method substring
1948  */
1949 //================================================================================
1950
1951 const TCollection_AsciiString & _pyCommand::GetMethod()
1952 {
1953   if ( GetBegPos( METHOD_IND ) == UNKNOWN )
1954   {
1955     // beginning
1956     int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
1957     bool forward = true;
1958     if ( begPos < 1 ) {
1959       begPos = myString.Location( "(", 1, Length() ) - 1;
1960       forward = false;
1961     }
1962     // store
1963     myMeth = GetWord( myString, begPos, forward );
1964     SetBegPos( METHOD_IND, begPos );
1965   }
1966   //SCRUTE(myMeth);
1967   return myMeth;
1968 }
1969
1970 //================================================================================
1971 /*!
1972  * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
1973   * \retval const TCollection_AsciiString & - Arg<index> substring
1974  */
1975 //================================================================================
1976
1977 const TCollection_AsciiString & _pyCommand::GetArg( int index )
1978 {
1979   if ( GetBegPos( ARG1_IND ) == UNKNOWN )
1980   {
1981     // find all args
1982     int begPos = GetBegPos( METHOD_IND ) + myMeth.Length();
1983     if ( begPos < 1 )
1984       begPos = myString.Location( "(", 1, Length() ) + 1;
1985
1986     int i = 0, prevLen = 0;
1987     while ( begPos != EMPTY ) {
1988       begPos += prevLen;
1989       // check if we are looking at the closing parenthesis
1990       while ( begPos <= Length() && isspace( myString.Value( begPos )))
1991         ++begPos;
1992       if ( begPos > Length() || myString.Value( begPos ) == ')' )
1993         break;
1994       myArgs.Append( GetWord( myString, begPos, true, true ));
1995       SetBegPos( ARG1_IND + i, begPos );
1996       prevLen = myArgs.Last().Length();
1997       if ( prevLen == 0 )
1998         myArgs.Remove( myArgs.Length() ); // no more args
1999       i++;
2000     }
2001   }
2002   if ( myArgs.Length() < index )
2003     return theEmptyString;
2004   return myArgs( index );
2005 }
2006
2007 //================================================================================
2008 /*!
2009  * \brief Check if char is a word part
2010   * \param c - The character to check
2011   * \retval bool - The check result
2012  */
2013 //================================================================================
2014
2015 static inline bool isWord(const char c, const bool dotIsWord)
2016 {
2017   return
2018     !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
2019 }
2020
2021 //================================================================================
2022 /*!
2023  * \brief Looks for a word in the string and returns word's beginning
2024   * \param theString - The input string
2025   * \param theStartPos - The position to start the search, returning word's beginning
2026   * \param theForward - The search direction
2027   * \retval TCollection_AsciiString - The found word
2028  */
2029 //================================================================================
2030
2031 TCollection_AsciiString _pyCommand::GetWord( const TCollection_AsciiString & theString,
2032                                             int &      theStartPos,
2033                                             const bool theForward,
2034                                             const bool dotIsWord )
2035 {
2036   int beg = theStartPos, end = theStartPos;
2037   theStartPos = EMPTY;
2038   if ( beg < 1 || beg > theString.Length() )
2039     return theEmptyString;
2040
2041   if ( theForward ) { // search forward
2042     // beg
2043     while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
2044       ++beg;
2045     if ( beg > theString.Length() )
2046       return theEmptyString; // no word found
2047     // end
2048     end = beg + 1;
2049     while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
2050       ++end;
2051     --end;
2052   }
2053   else {  // search backward
2054     // end
2055     while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
2056       --end;
2057     if ( end == 0 )
2058       return theEmptyString; // no word found
2059     beg = end - 1;
2060     while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
2061       --beg;
2062     ++beg;
2063   }
2064   theStartPos = beg;
2065   //cout << theString << " ---- " << beg << " - " << end << endl;
2066   return theString.SubString( beg, end );
2067 }
2068
2069 //================================================================================
2070 /*!
2071  * \brief Look for position where not space char is
2072   * \param theString - The string 
2073   * \param thePos - The position to search from and which returns result
2074   * \retval bool - false if there are only space after thePos in theString
2075  * 
2076  * 
2077  */
2078 //================================================================================
2079
2080 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
2081 {
2082   if ( thePos < 1 || thePos > theString.Length() )
2083     return false;
2084
2085   while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
2086     ++thePos;
2087
2088   return thePos <= theString.Length();
2089 }
2090
2091 //================================================================================
2092 /*!
2093  * \brief Modify a part of the command
2094   * \param thePartIndex - The index of the part
2095   * \param thePart - The new part string
2096   * \param theOldPart - The old part
2097  */
2098 //================================================================================
2099
2100 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
2101                         TCollection_AsciiString& theOldPart)
2102 {
2103   int pos = GetBegPos( thePartIndex );
2104   if ( pos <= Length() && theOldPart != thePart)
2105   {
2106     TCollection_AsciiString seperator;
2107     if ( pos < 1 ) {
2108       pos = GetBegPos( thePartIndex + 1 );
2109       if ( pos < 1 ) return;
2110       switch ( thePartIndex ) {
2111       case RESULT_IND: seperator = " = "; break;
2112       case OBJECT_IND: seperator = "."; break;
2113       case METHOD_IND: seperator = "()"; break;
2114       default:;
2115       }
2116     }      
2117     myString.Remove( pos, theOldPart.Length() );
2118     if ( !seperator.IsEmpty() )
2119       myString.Insert( pos , seperator );
2120     myString.Insert( pos, thePart );
2121     // update starting positions of the following parts
2122     int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
2123     for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
2124       if ( myBegPos( i ) > 0 )
2125         myBegPos( i ) += posDelta;
2126     }
2127     theOldPart = thePart;
2128   }
2129 }
2130
2131 //================================================================================
2132 /*!
2133  * \brief Set agrument
2134   * \param index - The argument index, it counts from 1
2135   * \param theArg - The argument string
2136  */
2137 //================================================================================
2138
2139 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
2140 {
2141   FindAllArgs();
2142   int argInd = ARG1_IND + index - 1;
2143   int pos = GetBegPos( argInd );
2144   if ( pos < 1 ) // no index-th arg exist, append inexistent args
2145   {
2146     // find a closing parenthesis
2147     if ( int lastArgInd = GetNbArgs() ) {
2148       pos = GetBegPos( ARG1_IND + lastArgInd  - 1 ) + GetArg( lastArgInd ).Length();
2149       while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
2150         ++pos;
2151     }
2152     else {
2153       pos = Length();
2154       while ( pos > 0 && myString.Value( pos ) != ')' )
2155         --pos;
2156     }
2157     if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
2158       myString += "()";
2159       pos = Length();
2160     }
2161     while ( myArgs.Length() < index ) {
2162       if ( myArgs.Length() )
2163         myString.Insert( pos++, "," );
2164       myArgs.Append("None");
2165       myString.Insert( pos, myArgs.Last() );
2166       SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
2167       pos += myArgs.Last().Length();
2168     }
2169   }
2170   SetPart( argInd, theArg, myArgs( index ));
2171 }
2172
2173 //================================================================================
2174 /*!
2175  * \brief Empty arg list
2176  */
2177 //================================================================================
2178
2179 void _pyCommand::RemoveArgs()
2180 {
2181   if ( int pos = myString.Location( '(', 1, Length() ))
2182     myString.Trunc( pos );
2183   myString += ")";
2184   myArgs.Clear();
2185   if ( myBegPos.Length() >= ARG1_IND )
2186     myBegPos.Remove( ARG1_IND, myBegPos.Length() );
2187 }
2188
2189 //================================================================================
2190 /*!
2191  * \brief Set dependent commands after this one
2192  */
2193 //================================================================================
2194
2195 bool _pyCommand::SetDependentCmdsAfter() const
2196 {
2197   bool orderChanged = false;
2198   list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
2199   for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
2200     if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
2201       orderChanged = true;
2202       theGen->SetCommandAfter( *cmd, this );
2203       (*cmd)->SetDependentCmdsAfter();
2204     }
2205   }
2206   return orderChanged;
2207 }
2208 //================================================================================
2209 /*!
2210  * \brief Insert accessor method after theObjectID
2211   * \param theObjectID - id of the accessed object
2212   * \param theAcsMethod - name of the method giving access to the object
2213   * \retval bool - false if theObjectID is not found in the command string
2214  */
2215 //================================================================================
2216
2217 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
2218 {
2219   if ( !theAcsMethod )
2220     return false;
2221   // start object search from the object, i.e. ignore result
2222   GetObject();
2223   int beg = GetBegPos( OBJECT_IND );
2224   if ( beg < 1 || beg > Length() )
2225     return false;
2226   bool added = false;
2227   while (( beg = myString.Location( theObjectID, beg, Length() )))
2228   {
2229     // check that theObjectID is not just a part of a longer ID
2230     int afterEnd = beg + theObjectID.Length();
2231     Standard_Character c = myString.Value( afterEnd );
2232     if ( !isalnum( c ) && c != ':' ) {
2233       // check if accessor method already present
2234       if ( c != '.' ||
2235            myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
2236         // insertion
2237         int oldLen = Length();
2238         myString.Insert( afterEnd, (char*) theAcsMethod );
2239         myString.Insert( afterEnd, "." );
2240         // update starting positions of the parts following the modified one
2241         int posDelta = Length() - oldLen;
2242         for ( int i = 1; i <= myBegPos.Length(); ++i ) {
2243           if ( myBegPos( i ) > afterEnd )
2244             myBegPos( i ) += posDelta;
2245         }
2246         added = true;
2247       }
2248     }
2249     beg = afterEnd; // is a part - next search
2250   }
2251   return added;
2252 }
2253
2254 //================================================================================
2255 /*!
2256  * \brief Return method name giving access to an interaface object wrapped by python class
2257   * \retval const char* - method name
2258  */
2259 //================================================================================
2260
2261 const char* _pyObject::AccessorMethod() const
2262 {
2263   return 0;
2264 }
2265 //================================================================================
2266 /*!
2267  * \brief Return ID of a father
2268  */
2269 //================================================================================
2270
2271 _pyID _pyObject::FatherID(const _pyID & childID)
2272 {
2273   int colPos = childID.SearchFromEnd(':');
2274   if ( colPos > 0 )
2275     return childID.SubString( 1, colPos-1 );
2276   return "";
2277 }
2278
2279 //================================================================================
2280 /*!
2281  * \brief FilterManager creates only if at least one command invoked
2282  */
2283 //================================================================================
2284
2285 _pyFilterManager::_pyFilterManager(const Handle(_pyCommand)& theCreationCmd):
2286   _pyObject( theCreationCmd ),
2287   myCmdCount( 0 )
2288 {
2289 }
2290
2291 //================================================================================
2292 /*!
2293  * \brief count invoked commands
2294  */
2295 //================================================================================
2296
2297 void _pyFilterManager::Process( const Handle(_pyCommand)& /*theCommand*/)
2298 {
2299   myCmdCount++;
2300 }
2301
2302 //================================================================================
2303 /*!
2304  * \brief Clear creatin command if no commands invoked
2305  */
2306 //================================================================================
2307
2308 void _pyFilterManager::Flush()
2309 {
2310   if ( !myCmdCount )
2311     GetCreationCmd()->Clear();
2312 }
2313
2314
2315 //================================================================================
2316 /*!
2317  * \brief SubMesh creation can be moved to the end of engine commands
2318  */
2319 //================================================================================
2320
2321 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd):
2322   _pyObject( theCreationCmd ),
2323   myCmdCount( 0 )
2324 {
2325 }
2326
2327 //================================================================================
2328 /*!
2329  * \brief count invoked commands
2330  */
2331 //================================================================================
2332
2333 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
2334 {
2335   myCmdCount++;
2336   GetCreationCmd()->AddDependantCmd( theCommand );
2337 }
2338
2339 //================================================================================
2340 /*!
2341  * \brief Clear creatin command if no commands invoked
2342  */
2343 //================================================================================
2344
2345 void _pySubMesh::Flush()
2346 {
2347   if ( !myCmdCount ) // move to the end of all commands
2348     theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
2349   else if ( !myCreator.IsNull() )
2350     // move to be just after creator
2351     myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
2352 }