Salome HOME
PAL13460 (force the mesh to go through a point)
[modules/smesh.git] / src / SMESH_I / SMESH_2smeshpy.cxx
1 //  SMESH SMESH_I : idl implementation based on 'SMESH' unit's calsses
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
6 //  This library is free software; you can redistribute it and/or 
7 //  modify it under the terms of the GNU Lesser General Public 
8 //  License as published by the Free Software Foundation; either 
9 //  version 2.1 of the License. 
10 // 
11 //  This library is distributed in the hope that it will be useful, 
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
14 //  Lesser General Public License for more details. 
15 // 
16 //  You should have received a copy of the GNU Lesser General Public 
17 //  License along with this library; if not, write to the Free Software 
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
19 // 
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //
23 //
24 //  File   : SMESH_2D_Algo_i.hxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //  $Header$
28
29 // File      : SMESH_2smeshpy.cxx
30 // Created   : Fri Nov 18 13:20:10 2005
31 // Author    : Edward AGAPOV (eap)
32
33 #include "SMESH_2smeshpy.hxx"
34
35 #include "SMESH_Gen_i.hxx"
36 #include "utilities.h"
37 #include "SMESH_PythonDump.hxx"
38 #include "Resource_DataMapOfAsciiStringAsciiString.hxx"
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 (_pyHypothesis      ,_pyObject);
45 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm       ,_pyHypothesis);
46 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
47 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
48
49 IMPLEMENT_STANDARD_RTTIEXT(_pyObject          ,Standard_Transient);
50 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand         ,Standard_Transient);
51 IMPLEMENT_STANDARD_RTTIEXT(_pyGen             ,_pyObject);
52 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh            ,_pyObject);
53 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis      ,_pyObject);
54 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm       ,_pyHypothesis);
55 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
56 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
57 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
58 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
59
60 using namespace std;
61 using SMESH::TPythonDump;
62
63 /*!
64  * \brief Container of commands into which the initial script is split.
65  *        It also contains data coresponding to SMESH_Gen contents
66  */
67 static Handle(_pyGen) theGen;
68
69 static TCollection_AsciiString theEmptyString;
70
71 //#define DUMP_CONVERSION
72
73 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
74 #undef DUMP_CONVERSION
75 #endif
76
77 //================================================================================
78 /*!
79  * \brief Convert python script using commands of smesh.py
80   * \param theScript - Input script
81   * \retval TCollection_AsciiString - Convertion result
82  */
83 //================================================================================
84
85 TCollection_AsciiString
86 SMESH_2smeshpy::ConvertScript(const TCollection_AsciiString& theScript,
87                               Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod)
88 {
89   theGen = new _pyGen( theEntry2AccessorMethod );
90
91   // split theScript into separate commands
92   int from = 1, end = theScript.Length(), to;
93   while ( from < end && ( to = theScript.Location( "\n", from, end )))
94   {
95     if ( to != from )
96       // cut out and store a command
97       theGen->AddCommand( theScript.SubString( from, to - 1 ));
98     from = to + 1;
99   }
100   // finish conversion
101   theGen->Flush();
102 #ifdef DUMP_CONVERSION
103   cout << endl << " ######## RESULT ######## " << endl<< endl;
104 #endif
105   // reorder commands after conversion
106   list< Handle(_pyCommand) >::iterator cmd;
107   bool orderChanges;
108   do {
109     orderChanges = false;
110     for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
111       if ( (*cmd)->SetDependentCmdsAfter() )
112         orderChanges = true;
113   } while ( orderChanges );
114   
115   // concat commands back into a script
116   TCollection_AsciiString aScript;
117   for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
118   {
119 #ifdef DUMP_CONVERSION
120     cout << "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << endl;
121 #endif
122     if ( !(*cmd)->IsEmpty() ) {
123       aScript += "\n";
124       aScript += (*cmd)->GetString();
125     }
126   }
127   aScript += "\n";
128
129   theGen.Nullify();
130
131   return aScript;
132 }
133
134 //================================================================================
135 /*!
136  * \brief _pyGen constructor
137  */
138 //================================================================================
139
140 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod)
141   : _pyObject( new _pyCommand( TPythonDump::SMESHGenName(), 0 )),
142     myID2AccessorMethod( theEntry2AccessorMethod )
143 {
144   myNbCommands = 0;
145   myHasPattern = false;
146   // make that GetID() to return TPythonDump::SMESHGenName()
147   GetCreationCmd()->GetString() += "=";
148 }
149
150 //================================================================================
151 /*!
152  * \brief Convert a command using a specific converter
153   * \param theCommand - the command to convert
154  */
155 //================================================================================
156
157 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
158 {
159   // store theCommand in the sequence
160   myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
161
162   Handle(_pyCommand) aCommand = myCommands.back();
163 #ifdef DUMP_CONVERSION
164   cout << "## COM " << myNbCommands << ": "<< aCommand->GetString() << endl;
165 #endif
166
167   _pyID objID = aCommand->GetObject();
168
169   if ( objID.IsEmpty() )
170     return aCommand;
171
172   // SMESH_Gen method?
173   if ( objID == this->GetID() ) {
174     this->Process( aCommand );
175     return aCommand;
176   }
177   // SMESH_Mesh method?
178   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
179   if ( id_mesh != myMeshes.end() ) {
180     id_mesh->second->Process( aCommand );
181     return aCommand;
182   }
183   // SMESH_Hypothesis method?
184   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
185   for ( ; hyp != myHypos.end(); ++hyp )
186     if ( !(*hyp)->IsAlgo() && objID == (*hyp)->GetID() ) {
187       (*hyp)->Process( aCommand );
188       return aCommand;
189     }
190
191   // Add access to a wrapped mesh
192   AddMeshAccessorMethod( aCommand );
193
194   // Add access to a wrapped algorithm
195   AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
196
197   // PAL12227. PythonDump was not updated at proper time; result is
198   //     aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
199   // TypeError: __init__() takes exactly 11 arguments (10 given)
200   char wrongCommand[] = "SMESH.Filter.Criterion(";
201   if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
202   {
203     _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
204     // there must be 10 arguments, 5-th arg ThresholdID is missing,
205     const int wrongNbArgs = 9, missingArg = 5;
206     if ( tmpCmd.GetNbArgs() == wrongNbArgs )
207     {
208       for ( int i = wrongNbArgs; i > missingArg; --i )
209         tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
210       tmpCmd.SetArg(  missingArg, "''");
211       aCommand->GetString().Trunc( beg - 1 );
212       aCommand->GetString() += tmpCmd.GetString();
213     }
214   }
215   return aCommand;
216 }
217
218 //================================================================================
219 /*!
220  * \brief Convert the command or remember it for later conversion 
221   * \param theCommand - The python command calling a method of SMESH_Gen
222  */
223 //================================================================================
224
225 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
226 {
227   // there are methods to convert:
228   // CreateMesh( shape )
229   // CreateHypothesis( theHypType, theLibName )
230   // Compute( mesh, geom )
231
232   if ( theCommand->GetMethod() == "CreateMesh" ||
233        theCommand->GetMethod() == "CreateEmptyMesh" )
234   {
235     Handle(_pyMesh) mesh = new _pyMesh( theCommand );
236     myMeshes.insert( make_pair( mesh->GetID(), mesh ));
237     return;
238   }
239
240   // CreateHypothesis()
241   if ( theCommand->GetMethod() == "CreateHypothesis" )
242   {
243     myHypos.push_back( _pyHypothesis::NewHypothesis( theCommand ));
244     return;
245   }
246
247   // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
248   if ( theCommand->GetMethod() == "Compute" )
249   {
250     const _pyID& meshID = theCommand->GetArg( 1 );
251     map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
252     if ( id_mesh != myMeshes.end() ) {
253       theCommand->SetObject( meshID );
254       theCommand->RemoveArgs();
255       id_mesh->second->Flush();
256       return;
257     }
258   }
259
260   // leave only one smeshgen.GetPattern() in the script
261   if ( theCommand->GetMethod() == "GetPattern" ) {
262     if ( myHasPattern ) {
263       theCommand->Clear();
264       return;
265     }
266     myHasPattern = true;
267   }
268
269   // smeshgen.Method() --> smesh.smesh.Method()
270   theCommand->SetObject( SMESH_2smeshpy::GenName() );
271 }
272
273 //================================================================================
274 /*!
275  * \brief Convert the remembered commands
276  */
277 //================================================================================
278
279 void _pyGen::Flush()
280 {
281   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
282   for ( ; id_mesh != myMeshes.end(); ++id_mesh )
283     if ( ! id_mesh->second.IsNull() )
284       id_mesh->second->Flush();
285
286   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
287   for ( ; hyp != myHypos.end(); ++hyp )
288     if ( !hyp->IsNull() ) {
289       (*hyp)->Flush();
290       // smeshgen.CreateHypothesis() --> smesh.smesh.CreateHypothesis()
291       if ( !(*hyp)->IsWrapped() )
292         (*hyp)->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
293     }
294 }
295
296 //================================================================================
297 /*!
298  * \brief Add access method to mesh that is an object or an argument
299   * \param theCmd - command to add access method
300   * \retval bool - true if added
301  */
302 //================================================================================
303
304 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
305 {
306   map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
307   for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
308     if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
309       return true;
310   }
311   return false;
312 }
313
314 //================================================================================
315 /*!
316  * \brief Add access method to algo that is an object or an argument
317   * \param theCmd - command to add access method
318   * \retval bool - true if added
319  */
320 //================================================================================
321
322 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
323 {
324   list< Handle(_pyHypothesis) >::const_iterator hyp = myHypos.begin();
325   for ( ; hyp != myHypos.end(); ++hyp ) {
326     if ( (*hyp)->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
327          theCmd->AddAccessorMethod( (*hyp)->GetID(), (*hyp)->AccessorMethod() ))
328       return true;
329   }
330   return false;
331 }
332
333 //================================================================================
334 /*!
335  * \brief Find hypothesis by ID (entry)
336   * \param theHypID - The hypothesis ID
337   * \retval Handle(_pyHypothesis) - The found hypothesis
338  */
339 //================================================================================
340
341 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
342 {
343   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
344   for ( ; hyp != myHypos.end(); ++hyp )
345     if ( !hyp->IsNull() && theHypID == (*hyp)->GetID() )
346       return *hyp;
347   return Handle(_pyHypothesis)();
348 }
349
350 //================================================================================
351 /*!
352  * \brief Find algorithm the created algorithm
353   * \param theGeom - The shape ID the algorithm was created on
354   * \param theMesh - The mesh ID that created the algorithm
355   * \param dim - The algo dimension
356   * \retval Handle(_pyHypothesis) - The found algo
357  */
358 //================================================================================
359
360 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
361                                       const TCollection_AsciiString& theAlgoType )
362 {
363   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
364   for ( ; hyp != myHypos.end(); ++hyp )
365     if ( !hyp->IsNull() &&
366          (*hyp)->IsAlgo() &&
367          (*hyp)->GetType() == theAlgoType &&
368          (*hyp)->GetGeom() == theGeom &&
369          (*hyp)->GetMesh() == theMesh )
370       return *hyp;
371   return 0;
372 }
373
374 //================================================================================
375 /*!
376  * \brief Change order of commands in the script
377   * \param theCmd1 - One command
378   * \param theCmd2 - Another command
379  */
380 //================================================================================
381
382 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
383 {
384   list< Handle(_pyCommand) >::iterator pos1, pos2;
385   pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
386   pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
387   myCommands.insert( pos1, theCmd2 );
388   myCommands.insert( pos2, theCmd1 );
389   myCommands.erase( pos1 );
390   myCommands.erase( pos2 );
391
392   int nb1 = theCmd1->GetOrderNb();
393   theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
394   theCmd2->SetOrderNb( nb1 );
395 //   cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
396 //        << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
397 }
398
399 //================================================================================
400 /*!
401  * \brief Set one command after the other
402   * \param theCmd - Command to move
403   * \param theAfterCmd - Command ater which to insert the first one
404  */
405 //================================================================================
406
407 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
408 {
409 #ifdef _DEBUG_
410 //cout << "SET\t" << theAfterCmd->GetString() << endl << "BEFORE\t" << theCmd->GetString() << endl<<endl;
411 #endif
412   list< Handle(_pyCommand) >::iterator pos;
413   pos = find( myCommands.begin(), myCommands.end(), theCmd );
414   myCommands.erase( pos );
415   pos = find( myCommands.begin(), myCommands.end(), theAfterCmd );
416   myCommands.insert( ++pos, theCmd );
417
418   int i = 1;
419   for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
420     (*pos)->SetOrderNb( i++ );
421 }
422
423 //================================================================================
424 /*!
425  * \brief Set method to access to object wrapped with python class
426   * \param theID - The wrapped object entry
427   * \param theMethod - The accessor method
428  */
429 //================================================================================
430
431 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
432 {
433   myID2AccessorMethod.Bind( theID, (char*) theMethod );
434 }
435
436 //================================================================================
437 /*!
438  * \brief Find out type of geom group
439   * \param grpID - The geom group entry
440   * \retval int - The type
441  */
442 //================================================================================
443
444 static bool sameGroupType( const _pyID&                   grpID,
445                            const TCollection_AsciiString& theType)
446 {
447   // define group type as smesh.Mesh.Group() does
448   int type = -1;
449   SALOMEDS::Study_var study = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
450   SALOMEDS::SObject_var aSObj = study->FindObjectID( grpID.ToCString() );
451   if ( !aSObj->_is_nil() ) {
452     GEOM::GEOM_Object_var aGeomObj = GEOM::GEOM_Object::_narrow( aSObj->GetObject() );
453     if ( !aGeomObj->_is_nil() ) {
454       switch ( aGeomObj->GetShapeType() ) {
455       case GEOM::VERTEX: type = SMESH::NODE; break;
456       case GEOM::EDGE:   type = SMESH::EDGE; break;
457       case GEOM::FACE:   type = SMESH::FACE; break;
458       case GEOM::SOLID:
459       case GEOM::SHELL:  type = SMESH::VOLUME; break;
460       case GEOM::COMPOUND: {
461         GEOM::GEOM_Gen_var aGeomGen = SMESH_Gen_i::GetSMESHGen()->GetGeomEngine();
462         if ( !aGeomGen->_is_nil() ) {
463           GEOM::GEOM_IGroupOperations_var aGrpOp =
464             aGeomGen->GetIGroupOperations( study->StudyId() );
465           if ( !aGrpOp->_is_nil() ) {
466             switch ( aGrpOp->GetType( aGeomObj )) {
467             case TopAbs_VERTEX: type = SMESH::NODE; break;
468             case TopAbs_EDGE:   type = SMESH::EDGE; break;
469             case TopAbs_FACE:   type = SMESH::FACE; break;
470             case TopAbs_SOLID:  type = SMESH::VOLUME; break;
471             default:;
472             }
473           }
474         }
475       }
476       default:;
477       }
478     }
479   }
480   if ( type < 0 ) {
481     MESSAGE("Type of the group " << grpID << " not found");
482     return false;
483   }
484   if ( theType.IsIntegerValue() )
485     return type == theType.IntegerValue();
486
487   switch ( type ) {
488   case SMESH::NODE:   return theType.Location( "NODE", 1, theType.Length() );
489   case SMESH::EDGE:   return theType.Location( "EDGE", 1, theType.Length() );
490   case SMESH::FACE:   return theType.Location( "FACE", 1, theType.Length() );
491   case SMESH::VOLUME: return theType.Location( "VOLUME", 1, theType.Length() );
492   default:;
493   }
494   return false;
495 }
496
497 //================================================================================
498 /*!
499  * \brief 
500   * \param theCreationCmd - 
501  */
502 //================================================================================
503
504 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd):
505   _pyObject(theCreationCmd), myHasEditor(false)
506 {
507   // convert my creation command
508   Handle(_pyCommand) creationCmd = GetCreationCmd();
509   creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
510   creationCmd->SetMethod( "Mesh" );
511
512   theGen->SetAccessorMethod( GetID(), "GetMesh()" );
513 }
514
515 //================================================================================
516 /*!
517  * \brief Convert a IDL API command of SMESH::Mesh to a method call of python Mesh
518   * \param theCommand - Engine method called for this mesh
519  */
520 //================================================================================
521
522 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
523 {
524   // smesh.py wraps the following methods:
525   //
526   // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
527   //     --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
528   // 2. AddHypothesis(geom, hyp)
529   //     --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
530   // 3. CreateGroupFromGEOM(type, name, grp)
531   //     --> in Mesh.Group(grp, name="")
532   // 4. ExportToMED(f, opt, version)
533   //     --> in Mesh.ExportToMED( f, version, opt=0 )
534   // 5. ExportMED(f, opt)
535   //     --> in Mesh.ExportMED( f,opt=0 )
536   // 6. ExportDAT(f)
537   //     --> in Mesh.ExportDAT( f )
538   // 7. ExportUNV(f)
539   //     --> in Mesh.ExportUNV(f)
540   // 8. ExportSTL(f, ascii)
541   //     --> in Mesh.ExportSTL(f, ascii=1)
542
543   const TCollection_AsciiString method = theCommand->GetMethod();
544   if ( method == "GetSubMesh" ) {
545     mySubmeshes.push_back( theCommand );
546   }
547   else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
548     myAddHypCmds.push_back( theCommand );
549     // set mesh to hypo
550     const _pyID& hypID = theCommand->GetArg( 2 );
551     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
552     if ( !hyp.IsNull() ) {
553       myHypos.push_back( hyp );
554       if ( hyp->GetMesh().IsEmpty() )
555         hyp->SetMesh( this->GetID() );
556     }
557   }
558   else if ( method == "CreateGroupFromGEOM" ) {// (type, name, grp)
559     _pyID grp = theCommand->GetArg( 3 );
560     if ( sameGroupType( grp, theCommand->GetArg( 1 )) ) { // --> Group(grp)
561       theCommand->SetMethod( "Group" );
562       theCommand->RemoveArgs();
563       theCommand->SetArg( 1, grp );
564     }
565     else {
566       AddMeshAccess( theCommand );
567     }
568   }
569   else if ( method == "ExportToMED" ) {//(f, opt, version)
570     // --> (f, version, opt)
571     _pyID opt = theCommand->GetArg( 2 );
572     _pyID ver = theCommand->GetArg( 3 );
573     theCommand->SetArg( 2, ver );
574     theCommand->SetArg( 3, opt );
575   }
576   else if ( method == "RemoveHypothesis" ) // (geom, hyp)
577   {
578     const _pyID & hypID = theCommand->GetArg( 2 );
579
580     // check if this mesh still has corresponding addition command
581     bool hasAddCmd = false;
582     list< Handle(_pyCommand) >::iterator cmd = myAddHypCmds.begin();
583     while ( cmd != myAddHypCmds.end() )
584     {
585       // AddHypothesis(geom, hyp)
586       if ( hypID == (*cmd)->GetArg( 2 )) { // erase both (add and remove) commands
587         theCommand->Clear();
588         (*cmd)->Clear();
589         cmd = myAddHypCmds.erase( cmd );
590         hasAddCmd = true;
591       }
592       else {
593         ++cmd;
594       }
595     }
596     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
597     if ( ! hasAddCmd ) { // hypo addition already wrapped
598       // access to wrapped mesh
599       AddMeshAccess( theCommand );
600       // access to wrapped algo
601       if ( !hyp.IsNull() && hyp->IsAlgo() && hyp->IsWrapped() )
602         theCommand->SetArg( 2, theCommand->GetArg( 2 ) + ".GetAlgorithm()" );
603     }
604     // remove hyp from myHypos
605     myHypos.remove( hyp );
606   }
607
608   // leave only one "  mesh_editor_<nb> = mesh.GetMeshEditor()"
609   else if ( theCommand->GetMethod() == "GetMeshEditor")
610   {
611     if ( myHasEditor )
612       theCommand->Clear();
613     else
614       AddMeshAccess( theCommand );
615     myHasEditor = true;
616   }
617
618   // apply theCommand to the mesh wrapped by smeshpy mesh
619   else
620   {
621     AddMeshAccess( theCommand );
622   }
623 }
624
625 namespace {
626
627   //================================================================================
628   /*!
629    * \brief add addition result treatement command
630     * \param addCmd - hypothesis addition command
631    */
632   //================================================================================
633
634   void addErrorTreatmentCmd( Handle(_pyCommand) & addCmd,
635                              const bool           isAlgo)
636   {
637     return; // TO DEBUD - TreatHypoStatus() is not placed right after addCmd
638     // addCmd: status = mesh.AddHypothesis( geom, hypo )
639     // treatement command:
640     //    def TreatHypoStatus(status, hypName, geomName, isAlgo):
641     TCollection_AsciiString status = addCmd->GetResultValue();
642     if ( !status.IsEmpty() ) {
643       const _pyID& geomID = addCmd->GetArg( 1 );
644       const _pyID& hypoID = addCmd->GetArg( 2 );
645       TCollection_AsciiString cmdStr = addCmd->GetIndentation() +
646         SMESH_2smeshpy::SmeshpyName() + ".TreatHypoStatus( " + status + ", " +
647         SMESH_2smeshpy::SmeshpyName() + ".GetName(" + hypoID + "), " +
648         SMESH_2smeshpy::SmeshpyName() + ".GetName(" + geomID + "), " +
649         (char*)( isAlgo ? "True" : "False" ) + " )";
650       Handle(_pyCommand) cmd = theGen->AddCommand( cmdStr );
651       addCmd->AddDependantCmd( cmd, true );
652     }
653   }
654 }
655
656 //================================================================================
657 /*!
658  * \brief Convert creation and addition of all algos and hypos
659  */
660 //================================================================================
661
662 void _pyMesh::Flush()
663 {
664   list < Handle(_pyCommand) >::iterator cmd, cmd2;
665
666   // try to convert algo addition like this:
667   // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
668   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
669   {
670     Handle(_pyCommand) addCmd = *cmd;
671     const _pyID& algoID = addCmd->GetArg( 2 );
672     Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
673     if ( algo.IsNull() || !algo->IsAlgo() )
674       continue;
675     // try to convert
676     _pyID geom = addCmd->GetArg( 1 );
677     if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
678     {
679       // wrapped algo is created atfer mesh creation
680       GetCreationCmd()->AddDependantCmd( addCmd );
681
682       if ( geom != GetGeom() ) // local algo
683       {
684         // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
685         addCmd->SetArg( addCmd->GetNbArgs() + 1,
686                         TCollection_AsciiString( "geom=" ) + geom );
687         // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
688         for ( cmd2 = mySubmeshes.begin(); cmd2 != mySubmeshes.end(); ++cmd2 ) {
689           Handle(_pyCommand) subCmd = *cmd2;
690           if ( geom == subCmd->GetArg( 1 )) {
691             subCmd->SetObject( algo->GetID() );
692             subCmd->RemoveArgs();
693             addCmd->AddDependantCmd( subCmd );
694           }
695         }
696       }
697     }
698     else // ALGO was already created
699     {
700       // mesh.AddHypothesis(geom, ALGO ) --> mesh.GetMesh().AddHypothesis(geom, ALGO )
701       AddMeshAccess( addCmd );
702       // mesh.GetMesh().AddHypothesis(geom, ALGO ) ->
703       // mesh.GetMesh().AddHypothesis(geom, ALGO.GetAlgorithm() )
704       addCmd->SetArg( 2, addCmd->GetArg( 2 ) + ".GetAlgorithm()" );
705       // add addition result treatement cmd
706       addErrorTreatmentCmd( addCmd, true );
707     }
708   }
709
710   // try to convert hypo addition like this:
711   // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
712   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
713   {
714     Handle(_pyCommand) addCmd = *cmd;
715     const _pyID& hypID = addCmd->GetArg( 2 );
716     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
717     if ( hyp.IsNull() || hyp->IsAlgo() )
718       continue;
719     if ( !hyp->Addition2Creation( addCmd, this->GetID() ))
720     {
721       AddMeshAccess( addCmd );
722       // add addition result treatement cmd
723       addErrorTreatmentCmd( addCmd, false );
724     }
725   }
726
727   // sm = mesh.GetSubMesh(geom, name) --> sm = mesh.GetMesh().GetSubMesh(geom, name)
728   for ( cmd = mySubmeshes.begin(); cmd != mySubmeshes.end(); ++cmd ) {
729     Handle(_pyCommand) subCmd = *cmd;
730     if ( subCmd->GetNbArgs() > 0 )
731       AddMeshAccess( subCmd );
732   }
733   myAddHypCmds.clear();
734   mySubmeshes.clear();
735
736   // flush hypotheses
737   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
738   for ( ; hyp != myHypos.end(); ++hyp )
739     (*hyp)->Flush();
740 }
741
742 //================================================================================
743 /*!
744  * \brief _pyHypothesis constructor
745   * \param theCreationCmd - 
746  */
747 //================================================================================
748
749 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
750   _pyObject( theCreationCmd )
751 {
752   myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
753 }
754
755 //================================================================================
756 /*!
757  * \brief Creates algorithm or hypothesis
758   * \param theCreationCmd - The engine command creating a hypothesis
759   * \retval Handle(_pyHypothesis) - Result _pyHypothesis
760  */
761 //================================================================================
762
763 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
764 {
765   // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
766   ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
767
768   Handle(_pyHypothesis) hyp, algo;
769
770   // "theHypType"
771   const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
772   if ( hypTypeQuoted.IsEmpty() )
773     return hyp;
774   // theHypType
775   TCollection_AsciiString  hypType =
776     hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
777
778   algo = new _pyAlgorithm( theCreationCmd );
779   hyp  = new _pyHypothesis( theCreationCmd );
780
781   // 1D Regular_1D ----------
782   if ( hypType == "Regular_1D" ) {
783     // set mesh's method creating algo,
784     // i.e. convertion result will be "regular1d = Mesh.Segment()",
785     // and set hypType by which algo creating a hypothesis is searched for
786     algo->SetConvMethodAndType("Segment", hypType.ToCString());
787   }
788   else if ( hypType == "CompositeSegment_1D" ) {
789     algo->SetConvMethodAndType("Segment", "Regular_1D");
790     algo->myArgs.Append( "algo=smesh.COMPOSITE");
791   }
792   else if ( hypType == "LocalLength" ) {
793     // set algo's method creating hyp, and algo type
794     hyp->SetConvMethodAndType( "LocalLength", "Regular_1D");
795     // set method whose 1 arg will become the 1-st arg of hyp creation command
796     // i.e. convertion result will be "locallength = regular1d.LocalLength(<arg of SetLength()>)"
797     hyp->AddArgMethod( "SetLength" );
798   }
799   else if ( hypType == "NumberOfSegments" ) {
800     hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
801     hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
802     // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
803     hyp->AddArgMethod( "SetNumberOfSegments" );
804     // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
805     hyp->AddArgMethod( "SetScaleFactor" );
806   }
807   else if ( hypType == "Arithmetic1D" ) {
808     hyp = new _pyComplexParamHypo( theCreationCmd );
809     hyp->SetConvMethodAndType( "Arithmetic1D", "Regular_1D");
810   }
811   else if ( hypType == "StartEndLength" ) {
812     hyp = new _pyComplexParamHypo( theCreationCmd );
813     hyp->SetConvMethodAndType( "StartEndLength", "Regular_1D");
814   }
815   else if ( hypType == "Deflection1D" ) {
816     hyp->SetConvMethodAndType( "Deflection1D", "Regular_1D");
817     hyp->AddArgMethod( "SetDeflection" );
818   }
819   else if ( hypType == "Propagation" ) {
820     hyp->SetConvMethodAndType( "Propagation", "Regular_1D");
821   }
822   else if ( hypType == "QuadraticMesh" ) {
823     hyp->SetConvMethodAndType( "QuadraticMesh", "Regular_1D");
824   }
825   else if ( hypType == "AutomaticLength" ) {
826     hyp->SetConvMethodAndType( "AutomaticLength", "Regular_1D");
827     hyp->AddArgMethod( "SetFineness");
828   }
829   else if ( hypType == "SegmentLengthAroundVertex" ) {
830     hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
831     hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
832     hyp->AddArgMethod( "SetLength" );
833   }
834   // 1D Python_1D ----------
835   else if ( hypType == "Python_1D" ) {
836     algo->SetConvMethodAndType( "Segment", hypType.ToCString());
837     algo->myArgs.Append( "algo=smesh.PYTHON");
838   }
839   else if ( hypType == "PythonSplit1D" ) {
840     hyp->SetConvMethodAndType( "PythonSplit1D", "Python_1D");
841     hyp->AddArgMethod( "SetNumberOfSegments");
842     hyp->AddArgMethod( "SetPythonLog10RatioFunction");
843   }
844   // 2D ----------
845   else if ( hypType == "MEFISTO_2D" ) {
846     algo->SetConvMethodAndType( "Triangle", hypType.ToCString());
847   }
848   else if ( hypType == "MaxElementArea" ) {
849     hyp->SetConvMethodAndType( "MaxElementArea", "MEFISTO_2D");
850     hyp->AddArgMethod( "SetMaxElementArea");
851   }
852   else if ( hypType == "LengthFromEdges" ) {
853     hyp->SetConvMethodAndType( "LengthFromEdges", "MEFISTO_2D");
854   }
855   else if ( hypType == "Quadrangle_2D" ) {
856     algo->SetConvMethodAndType( "Quadrangle" , hypType.ToCString());
857   }
858   else if ( hypType == "QuadranglePreference" ) {
859     hyp->SetConvMethodAndType( "QuadranglePreference", "Quadrangle_2D");
860   }
861   // 3D ----------
862   else if ( hypType == "NETGEN_3D") {
863     algo->SetConvMethodAndType( "Tetrahedron" , hypType.ToCString());
864     algo->myArgs.Append( "algo=smesh.NETGEN" );
865   }
866   else if ( hypType == "MaxElementVolume") {
867     hyp->SetConvMethodAndType( "MaxElementVolume", "NETGEN_3D");
868     hyp->AddArgMethod( "SetMaxElementVolume" );
869   }
870   else if ( hypType == "GHS3D_3D" ) {
871     algo->SetConvMethodAndType( "Tetrahedron", hypType.ToCString());
872     algo->myArgs.Append( "algo=smesh.GHS3D" );
873   }
874   else if ( hypType == "Hexa_3D" ) {
875     algo->SetConvMethodAndType( "Hexahedron", hypType.ToCString());
876   }
877   // Repetitive ---------
878   else if ( hypType == "Projection_1D" ) {
879     algo->SetConvMethodAndType( "Projection1D", hypType.ToCString());
880   }
881   else if ( hypType == "ProjectionSource1D" ) {
882     hyp->SetConvMethodAndType( "SourceEdge", "Projection_1D");
883     hyp->AddArgMethod( "SetSourceEdge");
884     hyp->AddArgMethod( "SetSourceMesh");
885     // 2 args of SetVertexAssociation() will become the 3-th and 4-th args of hyp creation command
886     hyp->AddArgMethod( "SetVertexAssociation", 2 );
887   }
888   else if ( hypType == "Projection_2D" ) {
889     algo->SetConvMethodAndType( "Projection2D", hypType.ToCString());
890   }
891   else if ( hypType == "ProjectionSource2D" ) {
892     hyp->SetConvMethodAndType( "SourceFace", "Projection_2D");
893     hyp->AddArgMethod( "SetSourceFace");
894     hyp->AddArgMethod( "SetSourceMesh");
895     hyp->AddArgMethod( "SetVertexAssociation", 4 );
896   }
897   else if ( hypType == "Projection_3D" ) {
898     algo->SetConvMethodAndType( "Projection3D", hypType.ToCString());
899   }
900   else if ( hypType == "ProjectionSource3D" ) {
901     hyp->SetConvMethodAndType( "SourceShape3D", "Projection_3D");
902     hyp->AddArgMethod( "SetSource3DShape");
903     hyp->AddArgMethod( "SetSourceMesh");
904     hyp->AddArgMethod( "SetVertexAssociation", 4 );
905   }
906   else if ( hypType == "Prism_3D" ) {
907     algo->SetConvMethodAndType( "Prism", hypType.ToCString());
908   }
909   else if ( hypType == "RadialPrism_3D" ) {
910     algo->SetConvMethodAndType( "Prism", hypType.ToCString());
911   }
912   else if ( hypType == "NumberOfLayers" ) {
913     hyp->SetConvMethodAndType( "NumberOfLayers", "RadialPrism_3D");
914     hyp->AddArgMethod( "SetNumberOfLayers" );
915   }
916   else if ( hypType == "LayerDistribution" ) {
917     hyp = new _pyLayerDistributionHypo( theCreationCmd );
918     hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
919   }
920
921   if ( !algo->GetCreationMethod().IsEmpty() ) {
922     return algo;
923   }
924   return hyp;
925 }
926
927 //================================================================================
928 /*!
929  * \brief Convert the command adding a hypothesis to mesh into a smesh command
930   * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
931   * \param theAlgo - The algo that can create this hypo
932   * \retval bool - false if the command cant be converted
933  */
934 //================================================================================
935
936 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
937                                        const _pyID&              theMesh)
938 {
939   ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
940
941   if ( !IsWrappable( theMesh ))
942     return false;
943
944   myGeom = theCmd->GetArg( 1 );
945
946   Handle(_pyHypothesis) algo;
947   if ( !IsAlgo() ) {
948     // find algo created on myGeom in theMesh
949     algo = theGen->FindAlgo( myGeom, theMesh, GetType() );
950     if ( algo.IsNull() )
951       return false;
952     algo->GetCreationCmd()->AddDependantCmd( theCmd );
953   }
954   myIsWrapped = true;
955
956   // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
957   theCmd->SetResultValue( GetID() );
958   theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
959   theCmd->SetMethod( myCreationMethod );
960   // set args
961   theCmd->RemoveArgs();
962   for ( int i = 1; i <= myArgs.Length(); ++i ) {
963     if ( !myArgs( i ).IsEmpty() )
964       theCmd->SetArg( i, myArgs( i ));
965     else
966       theCmd->SetArg( i, "[]");
967   }
968   // set a new creation command
969   GetCreationCmd()->Clear();
970   SetCreationCmd( theCmd );
971
972   // clear commands setting arg values
973   list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
974   for ( ; argCmd != myArgCommands.end(); ++argCmd )
975     (*argCmd)->Clear();
976
977   // set unknown arg commands after hypo creation
978   Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
979   list<Handle(_pyCommand)>::iterator cmd = myUnknownCommands.begin();
980   for ( ; cmd != myUnknownCommands.end(); ++cmd ) {
981     afterCmd->AddDependantCmd( *cmd );
982   }
983
984   return myIsWrapped;
985 }
986
987 //================================================================================
988 /*!
989  * \brief Remember hypothesis parameter values
990  * \param theCommand - The called hypothesis method
991  */
992 //================================================================================
993
994 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
995 {
996   ASSERT( !myIsAlgo );
997   // set args
998   int nbArgs = 0;
999   for ( int i = 1; i <= myArgMethods.Length(); ++i ) {
1000     if ( myArgMethods( i ) == theCommand->GetMethod() ) {
1001       while ( myArgs.Length() < nbArgs + myNbArgsByMethod( i ))
1002         myArgs.Append( "[]" );
1003       for ( int iArg = 1; iArg <= myNbArgsByMethod( i ); ++iArg )
1004         myArgs( nbArgs + iArg ) = theCommand->GetArg( iArg ); // arg value
1005       myArgCommands.push_back( theCommand );
1006       return;
1007     }
1008     nbArgs += myNbArgsByMethod( i );
1009   }
1010   myUnknownCommands.push_back( theCommand );
1011 }
1012
1013 //================================================================================
1014 /*!
1015  * \brief Finish conversion
1016  */
1017 //================================================================================
1018
1019 void _pyHypothesis::Flush()
1020 {
1021   if ( IsWrapped() ) {
1022   }
1023   else {
1024     list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
1025     for ( ; cmd != myArgCommands.end(); ++cmd ) {
1026       // Add access to a wrapped mesh
1027       theGen->AddMeshAccessorMethod( *cmd );
1028       // Add access to a wrapped algorithm
1029       theGen->AddAlgoAccessorMethod( *cmd );
1030     }
1031     cmd = myUnknownCommands.begin();
1032     for ( ; cmd != myUnknownCommands.end(); ++cmd ) {
1033       // Add access to a wrapped mesh
1034       theGen->AddMeshAccessorMethod( *cmd );
1035       // Add access to a wrapped algorithm
1036       theGen->AddAlgoAccessorMethod( *cmd );
1037     }
1038   }
1039   // forget previous hypothesis modifications
1040   myArgCommands.clear();
1041   myUnknownCommands.clear();
1042 }
1043
1044 //================================================================================
1045 /*!
1046  * \brief clear creation, arg and unkown commands
1047  */
1048 //================================================================================
1049
1050 void _pyHypothesis::ClearAllCommands()
1051 {
1052   GetCreationCmd()->Clear();
1053   list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
1054   for ( ; cmd != myArgCommands.end(); ++cmd )
1055     ( *cmd )->Clear();
1056   cmd = myUnknownCommands.begin();
1057   for ( ; cmd != myUnknownCommands.end(); ++cmd )
1058     ( *cmd )->Clear();
1059 }
1060
1061 //================================================================================
1062 /*!
1063  * \brief Remember hypothesis parameter values
1064   * \param theCommand - The called hypothesis method
1065  */
1066 //================================================================================
1067
1068 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
1069 {
1070   // ex: hyp.SetLength(start, 1)
1071   //     hyp.SetLength(end,   0)
1072   ASSERT(( theCommand->GetMethod() == "SetLength" ));
1073   ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
1074   int i = 2 - theCommand->GetArg( 2 ).IntegerValue();
1075   while ( myArgs.Length() < i )
1076     myArgs.Append( "[]" );
1077   myArgs( i ) = theCommand->GetArg( 1 ); // arg value
1078   myArgCommands.push_back( theCommand );
1079 }
1080
1081 //================================================================================
1082 /*!
1083  * \brief Convert methods of 1D hypotheses to my own methods
1084   * \param theCommand - The called hypothesis method
1085  */
1086 //================================================================================
1087
1088 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
1089 {
1090   if ( theCommand->GetMethod() != "SetLayerDistribution" )
1091     return;
1092
1093   _pyID newName; // name for 1D hyp = "HypType" + "_Distribution"
1094
1095   const _pyID& hyp1dID = theCommand->GetArg( 1 );
1096   Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
1097   if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
1098     hyp1d = my1dHyp;
1099   else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() ) {
1100     // 1D hypo is already set, so distribution changes and the old
1101     // 1D hypo is thrown away
1102     my1dHyp->ClearAllCommands();
1103   }
1104   my1dHyp = hyp1d;
1105   if ( my1dHyp.IsNull() )
1106     return; // something wrong :(
1107
1108   // make a new name for 1D hyp = "HypType" + "_Distribution"
1109   if ( my1dHyp->GetCreationCmd()->GetMethod() == "CreateHypothesis" ) {
1110     // not yet converted creation cmd
1111     TCollection_AsciiString hypTypeQuoted = my1dHyp->GetCreationCmd()->GetArg(1);
1112     TCollection_AsciiString hypType = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
1113     newName = hypType + "_Distribution";
1114     my1dHyp->GetCreationCmd()->SetResultValue( newName );
1115   }
1116   else {
1117     // already converted creation cmd
1118     newName = my1dHyp->GetCreationCmd()->GetResultValue();
1119   }
1120
1121   // as creation of 1D hyp was written later then it's edition,
1122   // we need to find all it's edition calls and process them
1123   list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
1124   list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
1125   for ( ; cmdIt != cmds.end(); ++cmdIt ) {
1126     const _pyID& objID = (*cmdIt)->GetObject();
1127     if ( objID == hyp1dID ) {
1128       my1dHyp->Process( *cmdIt );
1129       my1dHyp->GetCreationCmd()->AddDependantCmd( *cmdIt );
1130       ( *cmdIt )->SetObject( newName );
1131     }
1132   }
1133   if ( !myArgCommands.empty() )
1134     myArgCommands.front()->Clear();
1135   theCommand->SetArg( 1, newName );
1136   myArgCommands.push_back( theCommand );
1137   // copy hyp1d's creation method and args
1138 //   myCreationMethod = hyp1d->GetCreationMethod();
1139 //   myArgs           = hyp1d->GetArgs();
1140 //   // make them cleared at conversion
1141 //   myArgCommands = hyp1d->GetArgCommands();
1142
1143 //   // to be cleared at convertion only
1144 //   myArgCommands.push_back( theCommand );
1145 }
1146
1147 //================================================================================
1148 /*!
1149  * \brief 
1150   * \param theAdditionCmd - 
1151   * \param theMesh - 
1152   * \retval bool - 
1153  */
1154 //================================================================================
1155
1156 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
1157                                                   const _pyID&              theMesh)
1158 {
1159   myIsWrapped = false;
1160
1161   if ( my1dHyp.IsNull() )
1162     return false;
1163
1164   // set "SetLayerDistribution()" after addition cmd
1165   theAdditionCmd->AddDependantCmd( myArgCommands.front() );
1166
1167   _pyID geom = theAdditionCmd->GetArg( 1 );
1168
1169   my1dHyp->SetMesh( theMesh );
1170   if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
1171     return false;
1172
1173   // clear "SetLayerDistribution()" cmd
1174   myArgCommands.front()->Clear();
1175
1176   // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
1177
1178   // find RadialPrism algo created on <geom> for theMesh
1179   Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this->GetType() );
1180   if ( !algo.IsNull() ) {
1181     GetCreationCmd()->SetObject( algo->GetID() );
1182     GetCreationCmd()->SetMethod( "Get3DHypothesis" );
1183     GetCreationCmd()->RemoveArgs();
1184     theAdditionCmd->AddDependantCmd( GetCreationCmd() );
1185     myIsWrapped = true;
1186   }
1187   return myIsWrapped;
1188 }
1189
1190 //================================================================================
1191 /*!
1192  * \brief 
1193  */
1194 //================================================================================
1195
1196 void _pyLayerDistributionHypo::Flush()
1197 {
1198   //my1dHyp.Nullify();
1199   //_pyHypothesis::Flush();
1200 }
1201
1202 //================================================================================
1203 /*!
1204  * \brief additionally to Addition2Creation, clears SetDistrType() command
1205   * \param theCmd - AddHypothesis() command
1206   * \param theMesh - mesh to which a hypothesis is added
1207   * \retval bool - convertion result
1208  */
1209 //================================================================================
1210
1211 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
1212                                                 const _pyID&              theMesh)
1213 {
1214   if ( IsWrappable( theMesh ) && myArgs.Length() > 1 ) {
1215     // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
1216     bool scaleDistrType = false;
1217     list<Handle(_pyCommand)>::reverse_iterator cmd = myUnknownCommands.rbegin();
1218     for ( ; cmd != myUnknownCommands.rend(); ++cmd ) {
1219       if ( (*cmd)->GetMethod() == "SetDistrType" ) {
1220         if ( (*cmd)->GetArg( 1 ) == "1" ) {
1221           scaleDistrType = true;
1222           (*cmd)->Clear();
1223         }
1224         else if ( !scaleDistrType ) {
1225           // distribution type changed: remove scale factor from args
1226           myArgs.Remove( 2, myArgs.Length() );
1227           break;
1228         }
1229       }
1230     }
1231   }
1232   return _pyHypothesis::Addition2Creation( theCmd, theMesh );
1233 }
1234
1235 //================================================================================
1236 /*!
1237  * \brief remove repeated commands defining distribution
1238  */
1239 //================================================================================
1240
1241 void _pyNumberOfSegmentsHyp::Flush()
1242 {
1243   // find number of the last SetDistrType() command
1244   list<Handle(_pyCommand)>::reverse_iterator cmd = myUnknownCommands.rbegin();
1245   int distrTypeNb = 0;
1246   for ( ; !distrTypeNb && cmd != myUnknownCommands.rend(); ++cmd )
1247     if ( (*cmd)->GetMethod() == "SetDistrType" )
1248       distrTypeNb = (*cmd)->GetOrderNb();
1249
1250   // clear commands before the last SetDistrType()
1251   list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnknownCommands };
1252   for ( int i = 0; i < 2; ++i ) {
1253     set<TCollection_AsciiString> uniqueMethods;
1254     list<Handle(_pyCommand)> & cmdList = *cmds[i];
1255     for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
1256     {
1257       bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
1258       const TCollection_AsciiString& method = (*cmd)->GetMethod();
1259       if ( !clear || method == "SetNumberOfSegments" ) {
1260         bool isNewInSet = uniqueMethods.insert( method ).second;
1261         clear = !isNewInSet;
1262       }
1263       if ( clear )
1264         (*cmd)->Clear();
1265     }
1266     cmdList.clear();
1267   }
1268 }
1269
1270 //================================================================================
1271 /*!
1272  * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
1273  * into regular1D.LengthNearVertex( length, vertex )
1274   * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
1275   * \param theMesh - The mesh needing this hypo
1276   * \retval bool - false if the command cant be converted
1277  */
1278 //================================================================================
1279   
1280 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
1281                                                          const _pyID&              theMeshID)
1282 {
1283   if ( IsWrappable( theMeshID )) {
1284
1285     _pyID vertex = theCmd->GetArg( 1 );
1286
1287     // the problem here is that segment algo will not be found
1288     // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
1289     // geometry where segment algorithm is assigned
1290     Handle(_pyHypothesis) algo;
1291     _pyID geom = vertex;
1292     while ( algo.IsNull() && !geom.IsEmpty()) {
1293       // try to find geom as a father of <vertex>
1294       geom = FatherID( geom );
1295       algo = theGen->FindAlgo( geom, theMeshID, GetType() );
1296     }
1297     if ( algo.IsNull() )
1298       return false; // also possible to find geom as brother of veretex...
1299     // set geom instead of vertex
1300     theCmd->SetArg( 1, geom );
1301
1302     // set vertex as a second arg
1303     if ( myArgs.Length() < 1) myArgs.Append( "1" ); // :(
1304     myArgs.Append( vertex );
1305
1306     // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
1307     // theMeshID.LengthNearVertex( length, vertex )
1308     return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
1309   }
1310   return false;
1311 }
1312
1313 //================================================================================
1314 /*!
1315  * \brief _pyAlgorithm constructor
1316  * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
1317  */
1318 //================================================================================
1319
1320 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
1321   : _pyHypothesis( theCreationCmd )
1322 {
1323   myIsAlgo = true;
1324 }
1325
1326 //================================================================================
1327 /*!
1328  * \brief Convert the command adding an algorithm to mesh
1329   * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
1330   * \param theMesh - The mesh needing this algo 
1331   * \retval bool - false if the command cant be converted
1332  */
1333 //================================================================================
1334   
1335 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
1336                                       const _pyID&              theMeshID)
1337 {
1338   // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
1339   if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
1340     theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
1341     return true;
1342   }
1343   return false;
1344 }
1345
1346 //================================================================================
1347 /*!
1348  * \brief Return starting position of a part of python command
1349   * \param thePartIndex - The index of command part
1350   * \retval int - Part position
1351  */
1352 //================================================================================
1353
1354 int _pyCommand::GetBegPos( int thePartIndex )
1355 {
1356   if ( IsEmpty() )
1357     return EMPTY;
1358   if ( myBegPos.Length() < thePartIndex )
1359     return UNKNOWN;
1360   return myBegPos( thePartIndex );
1361 }
1362
1363 //================================================================================
1364 /*!
1365  * \brief Store starting position of a part of python command
1366   * \param thePartIndex - The index of command part
1367   * \param thePosition - Part position
1368  */
1369 //================================================================================
1370
1371 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
1372 {
1373   while ( myBegPos.Length() < thePartIndex )
1374     myBegPos.Append( UNKNOWN );
1375   myBegPos( thePartIndex ) = thePosition;
1376 }
1377
1378 //================================================================================
1379 /*!
1380  * \brief Returns whitespace symbols at the line beginning
1381   * \retval TCollection_AsciiString - result
1382  */
1383 //================================================================================
1384
1385 TCollection_AsciiString _pyCommand::GetIndentation()
1386 {
1387   int end = 1;
1388   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
1389     GetWord( myString, end, true );
1390   else
1391     end = GetBegPos( RESULT_IND );
1392   return myString.SubString( 1, end - 1 );
1393 }
1394
1395 //================================================================================
1396 /*!
1397  * \brief Return substring of python command looking like ResultValue = Obj.Meth()
1398   * \retval const TCollection_AsciiString & - ResultValue substring
1399  */
1400 //================================================================================
1401
1402 const TCollection_AsciiString & _pyCommand::GetResultValue()
1403 {
1404   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
1405   {
1406     int begPos = myString.Location( "=", 1, Length() );
1407     if ( begPos )
1408       myRes = GetWord( myString, begPos, false );
1409     else
1410       begPos = EMPTY;
1411     SetBegPos( RESULT_IND, begPos );
1412   }
1413   return myRes;
1414 }
1415
1416 //================================================================================
1417 /*!
1418  * \brief Return substring of python command looking like ResVal = Object.Meth()
1419   * \retval const TCollection_AsciiString & - Object substring
1420  */
1421 //================================================================================
1422
1423 const TCollection_AsciiString & _pyCommand::GetObject()
1424 {
1425   if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
1426   {
1427     // beginning
1428     int begPos = GetBegPos( RESULT_IND ) + myRes.Length();
1429     if ( begPos < 1 )
1430       begPos = myString.Location( "=", 1, Length() ) + 1;
1431     // store
1432     myObj = GetWord( myString, begPos, true );
1433     SetBegPos( OBJECT_IND, begPos );
1434   }
1435   //SCRUTE(myObj);
1436   return myObj;
1437 }
1438
1439 //================================================================================
1440 /*!
1441  * \brief Return substring of python command looking like ResVal = Obj.Method()
1442   * \retval const TCollection_AsciiString & - Method substring
1443  */
1444 //================================================================================
1445
1446 const TCollection_AsciiString & _pyCommand::GetMethod()
1447 {
1448   if ( GetBegPos( METHOD_IND ) == UNKNOWN )
1449   {
1450     // beginning
1451     int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
1452     bool forward = true;
1453     if ( begPos < 1 ) {
1454       begPos = myString.Location( "(", 1, Length() ) - 1;
1455       forward = false;
1456     }
1457     // store
1458     myMeth = GetWord( myString, begPos, forward );
1459     SetBegPos( METHOD_IND, begPos );
1460   }
1461   //SCRUTE(myMeth);
1462   return myMeth;
1463 }
1464
1465 //================================================================================
1466 /*!
1467  * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
1468   * \retval const TCollection_AsciiString & - Arg<index> substring
1469  */
1470 //================================================================================
1471
1472 const TCollection_AsciiString & _pyCommand::GetArg( int index )
1473 {
1474   if ( GetBegPos( ARG1_IND ) == UNKNOWN )
1475   {
1476     // find all args
1477     int begPos = GetBegPos( METHOD_IND ) + myMeth.Length();
1478     if ( begPos < 1 )
1479       begPos = myString.Location( "(", 1, Length() ) + 1;
1480
1481     int i = 0, prevLen = 0;
1482     while ( begPos != EMPTY ) {
1483       begPos += prevLen;
1484       // check if we are looking at the closing parenthesis
1485       while ( begPos <= Length() && isspace( myString.Value( begPos )))
1486         ++begPos;
1487       if ( begPos > Length() || myString.Value( begPos ) == ')' )
1488         break;
1489       myArgs.Append( GetWord( myString, begPos, true, true ));
1490       SetBegPos( ARG1_IND + i, begPos );
1491       prevLen = myArgs.Last().Length();
1492       if ( prevLen == 0 )
1493         myArgs.Remove( myArgs.Length() ); // no more args
1494       i++;
1495     }
1496   }
1497   if ( myArgs.Length() < index )
1498     return theEmptyString;
1499   return myArgs( index );
1500 }
1501
1502 //================================================================================
1503 /*!
1504  * \brief Check if char is a word part
1505   * \param c - The character to check
1506   * \retval bool - The check result
1507  */
1508 //================================================================================
1509
1510 static inline bool isWord(const char c, const bool dotIsWord)
1511 {
1512   return
1513     !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
1514 }
1515
1516 //================================================================================
1517 /*!
1518  * \brief Looks for a word in the string and returns word's beginning
1519   * \param theString - The input string
1520   * \param theStartPos - The position to start the search, returning word's beginning
1521   * \param theForward - The search direction
1522   * \retval TCollection_AsciiString - The found word
1523  */
1524 //================================================================================
1525
1526 TCollection_AsciiString _pyCommand::GetWord( const TCollection_AsciiString & theString,
1527                                             int &      theStartPos,
1528                                             const bool theForward,
1529                                             const bool dotIsWord )
1530 {
1531   int beg = theStartPos, end = theStartPos;
1532   theStartPos = EMPTY;
1533   if ( beg < 1 || beg > theString.Length() )
1534     return theEmptyString;
1535
1536   if ( theForward ) { // search forward
1537     // beg
1538     while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
1539       ++beg;
1540     if ( beg > theString.Length() )
1541       return theEmptyString; // no word found
1542     // end
1543     end = beg + 1;
1544     while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
1545       ++end;
1546     --end;
1547   }
1548   else {  // search backward
1549     // end
1550     while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
1551       --end;
1552     if ( end == 0 )
1553       return theEmptyString; // no word found
1554     beg = end - 1;
1555     while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
1556       --beg;
1557     ++beg;
1558   }
1559   theStartPos = beg;
1560   //cout << theString << " ---- " << beg << " - " << end << endl;
1561   return theString.SubString( beg, end );
1562 }
1563
1564 //================================================================================
1565 /*!
1566  * \brief Look for position where not space char is
1567   * \param theString - The string 
1568   * \param thePos - The position to search from and which returns result
1569   * \retval bool - false if there are only space after thePos in theString
1570  * 
1571  * 
1572  */
1573 //================================================================================
1574
1575 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
1576 {
1577   if ( thePos < 1 || thePos > theString.Length() )
1578     return false;
1579
1580   while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
1581     ++thePos;
1582
1583   return thePos <= theString.Length();
1584 }
1585
1586 //================================================================================
1587 /*!
1588  * \brief Modify a part of the command
1589   * \param thePartIndex - The index of the part
1590   * \param thePart - The new part string
1591   * \param theOldPart - The old part
1592  */
1593 //================================================================================
1594
1595 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
1596                         TCollection_AsciiString& theOldPart)
1597 {
1598   int pos = GetBegPos( thePartIndex );
1599   if ( pos <= Length() && theOldPart != thePart)
1600   {
1601     TCollection_AsciiString seperator;
1602     if ( pos < 1 ) {
1603       pos = GetBegPos( thePartIndex + 1 );
1604       if ( pos < 1 ) return;
1605       switch ( thePartIndex ) {
1606       case RESULT_IND: seperator = " = "; break;
1607       case OBJECT_IND: seperator = "."; break;
1608       case METHOD_IND: seperator = "()"; break;
1609       default:;
1610       }
1611     }      
1612     myString.Remove( pos, theOldPart.Length() );
1613     if ( !seperator.IsEmpty() )
1614       myString.Insert( pos , seperator );
1615     myString.Insert( pos, thePart );
1616     // update starting positions of the following parts
1617     int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
1618     for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
1619       if ( myBegPos( i ) > 0 )
1620         myBegPos( i ) += posDelta;
1621     }
1622     theOldPart = thePart;
1623   }
1624 }
1625
1626 //================================================================================
1627 /*!
1628  * \brief Set agrument
1629   * \param index - The argument index, it counts from 1
1630   * \param theArg - The argument string
1631  */
1632 //================================================================================
1633
1634 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
1635 {
1636   FindAllArgs();
1637   int argInd = ARG1_IND + index - 1;
1638   int pos = GetBegPos( argInd );
1639   if ( pos < 1 ) // no index-th arg exist, append inexistent args
1640   {
1641     // find a closing parenthesis
1642     if ( int lastArgInd = GetNbArgs() ) {
1643       pos = GetBegPos( ARG1_IND + lastArgInd  - 1 ) + GetArg( lastArgInd ).Length();
1644       while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
1645         ++pos;
1646     }
1647     else {
1648       pos = Length();
1649       while ( pos > 0 && myString.Value( pos ) != ')' )
1650         --pos;
1651     }
1652     if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
1653       myString += "()";
1654       pos = Length();
1655     }
1656     while ( myArgs.Length() < index ) {
1657       if ( myArgs.Length() )
1658         myString.Insert( pos++, "," );
1659       myArgs.Append("None");
1660       myString.Insert( pos, myArgs.Last() );
1661       SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
1662       pos += myArgs.Last().Length();
1663     }
1664   }
1665   SetPart( argInd, theArg, myArgs( index ));
1666 }
1667
1668 //================================================================================
1669 /*!
1670  * \brief Empty arg list
1671  */
1672 //================================================================================
1673
1674 void _pyCommand::RemoveArgs()
1675 {
1676   if ( int pos = myString.Location( '(', 1, Length() ))
1677     myString.Trunc( pos );
1678   myString += ")";
1679   myArgs.Clear();
1680   if ( myBegPos.Length() >= ARG1_IND )
1681     myBegPos.Remove( ARG1_IND, myBegPos.Length() );
1682 }
1683
1684 //================================================================================
1685 /*!
1686  * \brief Set dependent commands after this one
1687  */
1688 //================================================================================
1689
1690 bool _pyCommand::SetDependentCmdsAfter() const
1691 {
1692   bool orderChanged = false;
1693   list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
1694   for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
1695     if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
1696       orderChanged = true;
1697       theGen->SetCommandAfter( *cmd, this );
1698       (*cmd)->SetDependentCmdsAfter();
1699     }
1700   }
1701   return orderChanged;
1702 }
1703 //================================================================================
1704 /*!
1705  * \brief Insert accessor method after theObjectID
1706   * \param theObjectID - id of the accessed object
1707   * \param theAcsMethod - name of the method giving access to the object
1708   * \retval bool - false if theObjectID is not found in the command string
1709  */
1710 //================================================================================
1711
1712 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
1713 {
1714   if ( !theAcsMethod )
1715     return false;
1716   // start object search from the object, i.e. ignore result
1717   GetObject();
1718   int beg = GetBegPos( OBJECT_IND );
1719   if ( beg < 1 || beg > Length() )
1720     return false;
1721   while (( beg = myString.Location( theObjectID, beg, Length() )))
1722   {
1723     // check that theObjectID is not just a part of a longer ID
1724     int afterEnd = beg + theObjectID.Length();
1725     Standard_Character c = myString.Value( afterEnd );
1726     if ( !isalnum( c ) && c != ':' ) {
1727       // check if accessor method already present
1728       if ( c != '.' ||
1729            myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
1730         // insertion
1731         int oldLen = Length();
1732         myString.Insert( afterEnd, (char*) theAcsMethod );
1733         myString.Insert( afterEnd, "." );
1734         // update starting positions of the parts following the modified one
1735         int posDelta = Length() - oldLen;
1736         for ( int i = 1; i <= myBegPos.Length(); ++i ) {
1737           if ( myBegPos( i ) > afterEnd )
1738             myBegPos( i ) += posDelta;
1739         }
1740         return true;
1741       }
1742     }
1743     beg = afterEnd; // is a part - next search
1744   }
1745   return false;
1746 }
1747
1748 //================================================================================
1749 /*!
1750  * \brief Return method name giving access to an interaface object wrapped by python class
1751   * \retval const char* - method name
1752  */
1753 //================================================================================
1754
1755 const char* _pyObject::AccessorMethod() const
1756 {
1757   return 0;
1758 }
1759 //================================================================================
1760 /*!
1761  * \brief Return ID of a father
1762  */
1763 //================================================================================
1764
1765 _pyID _pyObject::FatherID(const _pyID & childID)
1766 {
1767   int colPos = childID.SearchFromEnd(':');
1768   if ( colPos > 0 )
1769     return childID.SubString( 1, colPos-1 );
1770   return "";
1771 }