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