Salome HOME
Merging with WPdev
[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 "utilities.h"
36 #include "SMESH_PythonDump.hxx"
37 #include "Resource_DataMapOfAsciiStringAsciiString.hxx"
38
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h 
41  * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42  * that declare methods named GetObject - to apply the same rules of GetObject renaming
43  * and thus to avoid mess with GetObject symbol on Windows */
44
45 IMPLEMENT_STANDARD_HANDLE (_pyObject          ,Standard_Transient);
46 IMPLEMENT_STANDARD_HANDLE (_pyCommand         ,Standard_Transient);
47 IMPLEMENT_STANDARD_HANDLE (_pyGen             ,_pyObject);
48 IMPLEMENT_STANDARD_HANDLE (_pyMesh            ,_pyObject);
49 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis      ,_pyObject);
50 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm       ,_pyHypothesis);
51 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
52 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
53
54 IMPLEMENT_STANDARD_RTTIEXT(_pyObject          ,Standard_Transient);
55 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand         ,Standard_Transient);
56 IMPLEMENT_STANDARD_RTTIEXT(_pyGen             ,_pyObject);
57 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh            ,_pyObject);
58 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis      ,_pyObject);
59 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm       ,_pyHypothesis);
60 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
61 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
62 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
63
64 using namespace std;
65 using SMESH::TPythonDump;
66
67 /*!
68  * \brief Container of commands into which the initial script is split.
69  *        It also contains data coresponding to SMESH_Gen contents
70  */
71 static Handle(_pyGen) theGen;
72
73 static TCollection_AsciiString theEmptyString;
74
75 //#define DUMP_CONVERSION
76
77 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
78 #undef DUMP_CONVERSION
79 #endif
80
81 //================================================================================
82 /*!
83  * \brief Convert python script using commands of smesh.py
84   * \param theScript - Input script
85   * \retval TCollection_AsciiString - Convertion result
86  */
87 //================================================================================
88
89 TCollection_AsciiString
90 SMESH_2smeshpy::ConvertScript(const TCollection_AsciiString& theScript,
91                               Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod)
92 {
93   theGen = new _pyGen( theEntry2AccessorMethod );
94
95   // split theScript into separate commands
96   int from = 1, end = theScript.Length(), to;
97   while ( from < end && ( to = theScript.Location( "\n", from, end )))
98   {
99     if ( to != from )
100       // cut out and store a command
101       theGen->AddCommand( theScript.SubString( from, to - 1 ));
102     from = to + 1;
103   }
104   // finish conversion
105   theGen->Flush();
106 #ifdef DUMP_CONVERSION
107   cout << endl << " ######## RESULT ######## " << endl<< endl;
108 #endif
109   // reorder commands after conversion
110   list< Handle(_pyCommand) >::iterator cmd;
111   bool orderChanges;
112   do {
113     orderChanges = false;
114     for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
115       if ( (*cmd)->SetDependentCmdsAfter() )
116         orderChanges = true;
117   } while ( orderChanges );
118   
119   // concat commands back into a script
120   TCollection_AsciiString aScript;
121   for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
122   {
123 #ifdef DUMP_CONVERSION
124     cout << "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << endl;
125 #endif
126     if ( !(*cmd)->IsEmpty() ) {
127       aScript += "\n";
128       aScript += (*cmd)->GetString();
129     }
130   }
131   aScript += "\n";
132
133   theGen.Nullify();
134
135   return aScript;
136 }
137
138 //================================================================================
139 /*!
140  * \brief _pyGen constructor
141  */
142 //================================================================================
143
144 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod)
145   : _pyObject( new _pyCommand( TPythonDump::SMESHGenName(), 0 )),
146     myID2AccessorMethod( theEntry2AccessorMethod )
147 {
148   myNbCommands = 0;
149   myHasPattern = false;
150   // make that GetID() to return TPythonDump::SMESHGenName()
151   GetCreationCmd()->GetString() += "=";
152 }
153
154 //================================================================================
155 /*!
156  * \brief Convert a command using a specific converter
157   * \param theCommand - the command to convert
158  */
159 //================================================================================
160
161 void _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
162 {
163   // store theCommand in the sequence
164   myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
165
166   Handle(_pyCommand) aCommand = myCommands.back();
167 #ifdef DUMP_CONVERSION
168   cout << "## COM " << myNbCommands << ": "<< aCommand->GetString() << endl;
169 #endif
170
171   _pyID objID = aCommand->GetObject();
172
173   if ( objID.IsEmpty() )
174     return;
175
176   // SMESH_Gen method?
177   if ( objID == this->GetID() ) {
178     this->Process( aCommand );
179     return;
180   }
181   // SMESH_Mesh method?
182   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
183   if ( id_mesh != myMeshes.end() ) {
184     id_mesh->second->Process( aCommand );
185     return;
186   }
187   // SMESH_Hypothesis method?
188   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
189   for ( ; hyp != myHypos.end(); ++hyp )
190     if ( !(*hyp)->IsAlgo() && objID == (*hyp)->GetID() ) {
191       (*hyp)->Process( aCommand );
192       return;
193     }
194
195   // Add access to a wrapped mesh
196   AddMeshAccessorMethod( aCommand );
197
198   // Add access to a wrapped algorithm
199   AddAlgoAccessorMethod( aCommand );
200
201   // PAL12227. PythonDump was not updated at proper time; result is
202   //     aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
203   // TypeError: __init__() takes exactly 11 arguments (10 given)
204   char wrongCommand[] = "SMESH.Filter.Criterion(";
205   if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
206   {
207     _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
208     // there must be 10 arguments, 5-th arg ThresholdID is missing,
209     const int wrongNbArgs = 9, missingArg = 5;
210     if ( tmpCmd.GetNbArgs() == wrongNbArgs )
211     {
212       for ( int i = wrongNbArgs; i > missingArg; --i )
213         tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
214       tmpCmd.SetArg(  missingArg, "''");
215       aCommand->GetString().Trunc( beg - 1 );
216       aCommand->GetString() += tmpCmd.GetString();
217     }
218   }
219 }
220
221 //================================================================================
222 /*!
223  * \brief Convert the command or remember it for later conversion 
224   * \param theCommand - The python command calling a method of SMESH_Gen
225  */
226 //================================================================================
227
228 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
229 {
230   // there are methods to convert:
231   // CreateMesh( shape )
232   // CreateHypothesis( theHypType, theLibName )
233   // Compute( mesh, geom )
234
235   if ( theCommand->GetMethod() == "CreateMesh" )
236   {
237     Handle(_pyMesh) mesh = new _pyMesh( theCommand );
238     myMeshes.insert( make_pair( mesh->GetID(), mesh ));
239     return;
240   }
241
242   // CreateHypothesis()
243   if ( theCommand->GetMethod() == "CreateHypothesis" )
244   {
245     myHypos.push_back( _pyHypothesis::NewHypothesis( theCommand ));
246     return;
247   }
248
249   // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
250   if ( theCommand->GetMethod() == "Compute" )
251   {
252     const _pyID& meshID = theCommand->GetArg( 1 );
253     map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
254     if ( id_mesh != myMeshes.end() ) {
255       theCommand->SetObject( meshID );
256       theCommand->RemoveArgs();
257       id_mesh->second->Flush();
258       return;
259     }
260   }
261
262   // leave only one smeshgen.GetPattern() in the script
263   if ( theCommand->GetMethod() == "GetPattern" ) {
264     if ( myHasPattern ) {
265       theCommand->Clear();
266       return;
267     }
268     myHasPattern = true;
269   }
270
271   // smeshgen.Method() --> smesh.smesh.Method()
272   theCommand->SetObject( SMESH_2smeshpy::GenName() );
273 }
274
275 //================================================================================
276 /*!
277  * \brief Convert the remembered commands
278  */
279 //================================================================================
280
281 void _pyGen::Flush()
282 {
283   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
284   for ( ; id_mesh != myMeshes.end(); ++id_mesh )
285     if ( ! id_mesh->second.IsNull() )
286       id_mesh->second->Flush();
287
288   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
289   for ( ; hyp != myHypos.end(); ++hyp )
290     if ( !hyp->IsNull() ) {
291       (*hyp)->Flush();
292       // smeshgen.CreateHypothesis() --> smesh.smesh.CreateHypothesis()
293       if ( !(*hyp)->IsWrapped() )
294         (*hyp)->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
295     }
296 }
297
298 //================================================================================
299 /*!
300  * \brief Add access method to mesh that is object or arg
301   * \param theCmd - command to add access method
302   * \retval bool - true if added
303  */
304 //================================================================================
305
306 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
307 {
308   map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
309   for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
310     if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
311       return true;
312   }
313   return false;
314 }
315
316 //================================================================================
317 /*!
318  * \brief Add access method to algo that is object or arg
319   * \param theCmd - command to add access method
320   * \retval bool - true if added
321  */
322 //================================================================================
323
324 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
325 {
326   list< Handle(_pyHypothesis) >::const_iterator hyp = myHypos.begin();
327   for ( ; hyp != myHypos.end(); ++hyp ) {
328     if ( (*hyp)->IsAlgo() &&
329          theCmd->AddAccessorMethod( (*hyp)->GetID(), (*hyp)->AccessorMethod() ))
330       return true;
331   }
332   return false;
333 }
334
335 //================================================================================
336 /*!
337  * \brief Find hypothesis by ID (entry)
338   * \param theHypID - The hypothesis ID
339   * \retval Handle(_pyHypothesis) - The found hypothesis
340  */
341 //================================================================================
342
343 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
344 {
345   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
346   for ( ; hyp != myHypos.end(); ++hyp )
347     if ( !hyp->IsNull() && theHypID == (*hyp)->GetID() )
348       return *hyp;
349   return Handle(_pyHypothesis)();
350 }
351
352 //================================================================================
353 /*!
354  * \brief Find algorithm the created algorithm
355   * \param theGeom - The shape ID the algorithm was created on
356   * \param theMesh - The mesh ID that created the algorithm
357   * \param dim - The algo dimension
358   * \retval Handle(_pyHypothesis) - The found algo
359  */
360 //================================================================================
361
362 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
363                                       const TCollection_AsciiString& theAlgoType )
364 {
365   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
366   for ( ; hyp != myHypos.end(); ++hyp )
367     if ( !hyp->IsNull() &&
368          (*hyp)->IsAlgo() &&
369          (*hyp)->GetType() == theAlgoType &&
370          (*hyp)->GetGeom() == theGeom &&
371          (*hyp)->GetMesh() == theMesh )
372       return *hyp;
373   return 0;
374 }
375
376 //================================================================================
377 /*!
378  * \brief Change order of commands in the script
379   * \param theCmd1 - One command
380   * \param theCmd2 - Another command
381  */
382 //================================================================================
383
384 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
385 {
386   list< Handle(_pyCommand) >::iterator pos1, pos2;
387   pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
388   pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
389   myCommands.insert( pos1, theCmd2 );
390   myCommands.insert( pos2, theCmd1 );
391   myCommands.erase( pos1 );
392   myCommands.erase( pos2 );
393
394   int nb1 = theCmd1->GetOrderNb();
395   theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
396   theCmd2->SetOrderNb( nb1 );
397 //   cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
398 //        << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
399 }
400
401 //================================================================================
402 /*!
403  * \brief Set one command after the other
404   * \param theCmd - Command to move
405   * \param theAfterCmd - Command ater which to insert the first one
406  */
407 //================================================================================
408
409 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
410 {
411 //   cout << "SET\t" << theCmd->GetString() << endl << "AFTER\t" << theAfterCmd->GetString() << endl << endl;
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 //================================================================================
626 /*!
627  * \brief Convert creation and addition of all algos and hypos
628  */
629 //================================================================================
630
631 void _pyMesh::Flush()
632 {
633   list < Handle(_pyCommand) >::iterator cmd, cmd2;
634
635   // try to convert algo addition like this:
636   // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
637   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
638   {
639     Handle(_pyCommand) addCmd = *cmd;
640     const _pyID& algoID = addCmd->GetArg( 2 );
641     Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
642     if ( algo.IsNull() || !algo->IsAlgo() )
643       continue;
644     // try to convert
645     _pyID geom = addCmd->GetArg( 1 );
646     if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
647     {
648       // wrapped algo is created atfer mesh creation
649       GetCreationCmd()->AddDependantCmd( addCmd );
650
651       if ( geom != GetGeom() ) // local algo
652       {
653         // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
654         addCmd->SetArg( addCmd->GetNbArgs() + 1,
655                         TCollection_AsciiString( "geom=" ) + geom );
656         // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
657         for ( cmd2 = mySubmeshes.begin(); cmd2 != mySubmeshes.end(); ++cmd2 ) {
658           Handle(_pyCommand) subCmd = *cmd2;
659           if ( geom == subCmd->GetArg( 1 )) {
660             subCmd->SetObject( algo->GetID() );
661             subCmd->RemoveArgs();
662             addCmd->AddDependantCmd( subCmd );
663           }
664         }
665       }
666     }
667     else // ALGO was already created
668     {
669       // mesh.AddHypothesis(geom, ALGO ) --> mesh.GetMesh().AddHypothesis(geom, ALGO )
670       AddMeshAccess( addCmd );
671       // mesh.GetMesh().AddHypothesis(geom, ALGO ) ->
672       // mesh.GetMesh().AddHypothesis(geom, ALGO.GetAlgorithm() )
673       addCmd->SetArg( 2, addCmd->GetArg( 2 ) + ".GetAlgorithm()" );
674     }
675   }
676
677   // try to convert hypo addition like this:
678   // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
679   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
680   {
681     Handle(_pyCommand) addCmd = *cmd;
682     const _pyID& hypID = addCmd->GetArg( 2 );
683     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
684     if ( hyp.IsNull() || hyp->IsAlgo() )
685       continue;
686     const _pyID& geom = addCmd->GetArg( 1 );
687     // find algo created on <geom> for this mesh
688     Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, this->GetID(), hyp->GetType() );
689     //_pyID algoID = algo.IsNull() ? "" : algo->GetID();
690     if ( !algo.IsNull() && hyp->Addition2Creation( addCmd, this->GetID() )) // OK
691     {
692       addCmd->SetObject( algo->GetID() );
693       algo->GetCreationCmd()->AddDependantCmd( addCmd );
694     }
695     else
696     {
697       AddMeshAccess( addCmd );
698     }
699   }
700
701   // sm = mesh.GetSubMesh(geom, name) --> sm = mesh.GetMesh().GetSubMesh(geom, name)
702   for ( cmd = mySubmeshes.begin(); cmd != mySubmeshes.end(); ++cmd ) {
703     Handle(_pyCommand) subCmd = *cmd;
704     if ( subCmd->GetNbArgs() > 0 )
705       AddMeshAccess( subCmd );
706   }
707   myAddHypCmds.clear();
708   mySubmeshes.clear();
709
710   // flush hypotheses
711   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
712   for ( ; hyp != myHypos.end(); ++hyp )
713     (*hyp)->Flush();
714 }
715
716 //================================================================================
717 /*!
718  * \brief _pyHypothesis constructor
719   * \param theCreationCmd - 
720  */
721 //================================================================================
722
723 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
724   _pyObject( theCreationCmd )
725 {
726   myDim = myIsAlgo = /*myIsLocal = */myIsWrapped = myIsConverted = false;
727 }
728
729 //================================================================================
730 /*!
731  * \brief Creates algorithm or hypothesis
732   * \param theCreationCmd - The engine command creating a hypothesis
733   * \retval Handle(_pyHypothesis) - Result _pyHypothesis
734  */
735 //================================================================================
736
737 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
738 {
739   // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
740   ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
741
742   Handle(_pyHypothesis) hyp, algo;
743
744   // "theHypType"
745   const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
746   if ( hypTypeQuoted.IsEmpty() )
747     return hyp;
748   // theHypType
749   TCollection_AsciiString  hypType =
750     hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
751
752   algo = new _pyAlgorithm( theCreationCmd );
753   hyp  = new _pyHypothesis( theCreationCmd );
754
755   // 1D Regular_1D ----------
756   if ( hypType == "Regular_1D" ) {
757     algo->SetDimMethodType( 1, "Segment");
758   }
759   else if ( hypType == "LocalLength" ) {
760     hyp->SetDimMethodType( 1, "LocalLength", "Regular_1D");
761     hyp->AddArgMethod( "SetLength" );
762   }
763   else if ( hypType == "NumberOfSegments" ) {
764     hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
765     hyp->SetDimMethodType( 1, "NumberOfSegments", "Regular_1D");
766     hyp->AddArgMethod( "SetNumberOfSegments" );
767     hyp->AddArgMethod( "SetScaleFactor" );
768   }
769   else if ( hypType == "Arithmetic1D" ) {
770     hyp = new _pyComplexParamHypo( theCreationCmd );
771     hyp->SetDimMethodType( 1, "Arithmetic1D", "Regular_1D");
772   }
773   else if ( hypType == "StartEndLength" ) {
774     hyp = new _pyComplexParamHypo( theCreationCmd );
775     hyp->SetDimMethodType( 1, "StartEndLength", "Regular_1D");
776   }
777   else if ( hypType == "Deflection1D" ) {
778     hyp->SetDimMethodType( 1, "Deflection1D", "Regular_1D");
779     hyp->AddArgMethod( "SetDeflection" );
780   }
781   else if ( hypType == "Propagation" ) {
782     hyp->SetDimMethodType( 1, "Propagation", "Regular_1D");
783   }
784   else if ( hypType == "QuadraticMesh" ) {
785     hyp->SetDimMethodType( 1, "QuadraticMesh", "Regular_1D");
786   }
787   else if ( hypType == "AutomaticLength" ) {
788     hyp->SetDimMethodType( 1, "AutomaticLength", "Regular_1D");
789     hyp->AddArgMethod( "SetFineness");
790   }
791   // 1D Python_1D ----------
792   else if ( hypType == "Python_1D" ) {
793     algo->SetDimMethodType( 1, "Segment");
794     algo->myArgs.Append( "algo=smesh.PYTHON");
795   }
796   else if ( hypType == "PythonSplit1D" ) {
797     hyp->SetDimMethodType( 1, "PythonSplit1D", "Python_1D");
798     hyp->AddArgMethod( "SetNumberOfSegments");
799     hyp->AddArgMethod( "SetPythonLog10RatioFunction");
800   }
801   // 2D ----------
802   else if ( hypType == "MEFISTO_2D" ) {
803     algo->SetDimMethodType( 2, "Triangle");
804   }
805   else if ( hypType == "MaxElementArea" ) {
806     hyp->SetDimMethodType( 2, "MaxElementArea", "MEFISTO_2D");
807     hyp->AddArgMethod( "SetMaxElementArea");
808   }
809   else if ( hypType == "LengthFromEdges" ) {
810     hyp->SetDimMethodType( 2, "LengthFromEdges", "MEFISTO_2D");
811   }
812   else if ( hypType == "Quadrangle_2D" ) {
813     algo->SetDimMethodType( 2, "Quadrangle" );
814   }
815   else if ( hypType == "QuadranglePreference" ) {
816     hyp->SetDimMethodType( 2, "QuadranglePreference", "Quadrangle_2D");
817   }
818   // 3D ----------
819   else if ( hypType == "NETGEN_3D") {
820     algo->SetDimMethodType( 3, "Tetrahedron" );
821     algo->myArgs.Append( "algo=smesh.NETGEN" );
822   }
823   else if ( hypType == "MaxElementVolume") {
824     hyp->SetDimMethodType( 3, "MaxElementVolume", "NETGEN_3D");
825     hyp->AddArgMethod( "SetMaxElementVolume" );
826   }
827   else if ( hypType == "GHS3D_3D" ) {
828     algo->SetDimMethodType( 3, "Tetrahedron");
829     algo->myArgs.Append( "algo=smesh.GHS3D" );
830   }
831   else if ( hypType == "Hexa_3D" ) {
832     algo->SetDimMethodType( 3, "Hexahedron");
833   }
834   // Repetitive ---------
835   else if ( hypType == "Projection_1D" ) {
836     algo->SetDimMethodType( 1, "Projection1D");
837   }
838   else if ( hypType == "ProjectionSource1D" ) {
839     hyp->SetDimMethodType( 1, "SourceEdge", "Projection_1D");
840     hyp->AddArgMethod( "SetSourceEdge");
841     hyp->AddArgMethod( "SetSourceMesh");
842     hyp->AddArgMethod( "SetVertexAssociation", 2 );
843   }
844   else if ( hypType == "Projection_2D" ) {
845     algo->SetDimMethodType( 2, "Projection2D");
846   }
847   else if ( hypType == "ProjectionSource2D" ) {
848     hyp->SetDimMethodType( 2, "SourceFace", "Projection_2D");
849     hyp->AddArgMethod( "SetSourceFace");
850     hyp->AddArgMethod( "SetSourceMesh");
851     hyp->AddArgMethod( "SetVertexAssociation", 4 );
852   }
853   else if ( hypType == "Projection_3D" ) {
854     algo->SetDimMethodType( 3, "Projection3D");
855   }
856   else if ( hypType == "ProjectionSource3D" ) {
857     hyp->SetDimMethodType( 3, "SourceShape3D", "Projection_3D");
858     hyp->AddArgMethod( "SetSource3DShape");
859     hyp->AddArgMethod( "SetSourceMesh");
860     hyp->AddArgMethod( "SetVertexAssociation", 4 );
861   }
862   else if ( hypType == "Prism_3D" ) {
863     algo->SetDimMethodType( 3, "Prism");
864   }
865   else if ( hypType == "RadialPrism_3D" ) {
866     algo->SetDimMethodType( 3, "Prism");
867   }
868   else if ( hypType == "NumberOfLayers" ) {
869     hyp->SetDimMethodType( 3, "NumberOfLayers", "RadialPrism_3D");
870     hyp->AddArgMethod( "SetNumberOfLayers" );
871   }
872   else if ( hypType == "LayerDistribution" ) {
873     hyp = new _pyLayerDistributionHypo( theCreationCmd );
874     hyp->SetDimMethodType( 3, "LayerDistribution", "RadialPrism_3D");
875 //     hyp->AddArgMethod( "SetSource3DShape");
876 //     hyp->AddArgMethod( "SetSourceMesh");
877 //     hyp->AddArgMethod( "SetVertexAssociation", 4 );
878   }
879
880   if ( algo->GetDim() ) {
881     algo->myType = hypType;
882     return algo;
883   }
884   return hyp;
885 }
886
887 //================================================================================
888 /*!
889  * \brief Convert the command adding a hypothesis to mesh into a smesh command
890   * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
891   * \param theAlgo - The algo that can create this hypo
892   * \retval bool - false if the command cant be converted
893  */
894 //================================================================================
895
896 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
897                                        const _pyID&              theMesh)
898 {
899   ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
900
901   if ( !IsWrappable( theMesh ))
902     return false;
903
904   myIsWrapped = true;
905
906   if ( myIsWrapped )
907   {
908     // mesh.AddHypothesis(geom,hyp) --> hyp = theMesh.myCreationMethod(args)
909     theCmd->SetResultValue( GetID() );
910     theCmd->SetObject( theMesh );
911     theCmd->SetMethod( myCreationMethod );
912     // set args
913     theCmd->RemoveArgs();
914     for ( int i = 1; i <= myArgs.Length(); ++i ) {
915       if ( !myArgs( i ).IsEmpty() )
916         theCmd->SetArg( i, myArgs( i ));
917       else
918         theCmd->SetArg( i, "[]");
919     }
920     // set a new creation command
921     GetCreationCmd()->Clear();
922     SetCreationCmd( theCmd );
923
924     // clear commands setting arg values
925     list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
926     for ( ; argCmd != myArgCommands.end(); ++argCmd )
927       (*argCmd)->Clear();
928   }
929   else
930   {
931 //     // set arg commands after hypo creation
932 //     list<Handle(_pyCommand)>::iterator argCmd = myArgCommands.begin();
933 //     for ( ; argCmd != myArgCommands.end(); ++argCmd )
934 //       if ( !(*argCmd)->IsEmpty() && GetCommandNb() > (*argCmd)->GetOrderNb() )
935 //         theGen->ExchangeCommands( GetCreationCmd(), *argCmd );
936   }
937
938   // set unknown arg commands after hypo creation
939   Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
940   list<Handle(_pyCommand)>::iterator cmd = myUnknownCommands.begin();
941   for ( ; cmd != myUnknownCommands.end(); ++cmd ) {
942     afterCmd->AddDependantCmd( *cmd );
943   }
944
945   return myIsWrapped;
946 }
947
948 //================================================================================
949 /*!
950  * \brief Remember hypothesis parameter values
951  * \param theCommand - The called hypothesis method
952  */
953 //================================================================================
954
955 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
956 {
957   ASSERT( !myIsAlgo );
958   // set args
959   int nbArgs = 0;
960   for ( int i = 1; i <= myArgMethods.Length(); ++i ) {
961     if ( myArgMethods( i ) == theCommand->GetMethod() ) {
962       while ( myArgs.Length() < nbArgs + myNbArgsByMethod( i ))
963         myArgs.Append( "[]" );
964       for ( int iArg = 1; iArg <= myNbArgsByMethod( i ); ++iArg )
965         myArgs( nbArgs + iArg ) = theCommand->GetArg( iArg ); // arg value
966       myArgCommands.push_back( theCommand );
967       return;
968     }
969     nbArgs += myNbArgsByMethod( i );
970   }
971   myUnknownCommands.push_back( theCommand );
972 }
973
974 //================================================================================
975 /*!
976  * \brief Finish conversion
977  */
978 //================================================================================
979
980 void _pyHypothesis::Flush()
981 {
982   if ( IsWrapped() ) {
983   }
984   else {
985     list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
986     for ( ; cmd != myArgCommands.end(); ++cmd ) {
987       // Add access to a wrapped mesh
988       theGen->AddMeshAccessorMethod( *cmd );
989       // Add access to a wrapped algorithm
990       theGen->AddAlgoAccessorMethod( *cmd );
991     }
992     cmd = myUnknownCommands.begin();
993     for ( ; cmd != myUnknownCommands.end(); ++cmd ) {
994       // Add access to a wrapped mesh
995       theGen->AddMeshAccessorMethod( *cmd );
996       // Add access to a wrapped algorithm
997       theGen->AddAlgoAccessorMethod( *cmd );
998     }
999   }
1000   // forget previous hypothesis modifications
1001   myArgCommands.clear();
1002   myUnknownCommands.clear();
1003 }
1004
1005 //================================================================================
1006 /*!
1007  * \brief clear creation, arg and unkown commands
1008  */
1009 //================================================================================
1010
1011 void _pyHypothesis::ClearAllCommands()
1012 {
1013   GetCreationCmd()->Clear();
1014   list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
1015   for ( ; cmd != myArgCommands.end(); ++cmd )
1016     ( *cmd )->Clear();
1017   cmd = myUnknownCommands.begin();
1018   for ( ; cmd != myUnknownCommands.end(); ++cmd )
1019     ( *cmd )->Clear();
1020 }
1021
1022 //================================================================================
1023 /*!
1024  * \brief Remember hypothesis parameter values
1025   * \param theCommand - The called hypothesis method
1026  */
1027 //================================================================================
1028
1029 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
1030 {
1031   // ex: hyp.SetLength(start, 1)
1032   //     hyp.SetLength(end,   0)
1033   ASSERT(( theCommand->GetMethod() == "SetLength" ));
1034   ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
1035   int i = 2 - theCommand->GetArg( 2 ).IntegerValue();
1036   while ( myArgs.Length() < i )
1037     myArgs.Append( "[]" );
1038   myArgs( i ) = theCommand->GetArg( 1 ); // arg value
1039   myArgCommands.push_back( theCommand );
1040 }
1041
1042 //================================================================================
1043 /*!
1044  * \brief Convert methods of 1D hypotheses to my own methods
1045   * \param theCommand - The called hypothesis method
1046  */
1047 //================================================================================
1048
1049 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
1050 {
1051   if ( theCommand->GetMethod() != "SetLayerDistribution" )
1052     return;
1053
1054   _pyID newName; // name for 1D hyp = "HypType" + "_Distribution"
1055
1056   const _pyID& hyp1dID = theCommand->GetArg( 1 );
1057   Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
1058   if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
1059     hyp1d = my1dHyp;
1060   else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() ) {
1061     // 1D hypo is already set, so distribution changes and the old
1062     // 1D hypo is thrown away
1063     my1dHyp->ClearAllCommands();
1064   }
1065   my1dHyp = hyp1d;
1066   if ( my1dHyp.IsNull() )
1067     return; // something wrong :(
1068
1069   // make a new name for 1D hyp = "HypType" + "_Distribution"
1070   if ( my1dHyp->GetCreationCmd()->GetMethod() == "CreateHypothesis" ) {
1071     // not yet converted creation cmd
1072     TCollection_AsciiString hypTypeQuoted = my1dHyp->GetCreationCmd()->GetArg(1);
1073     TCollection_AsciiString hypType = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
1074     newName = hypType + "_Distribution";
1075     my1dHyp->GetCreationCmd()->SetResultValue( newName );
1076   }
1077   else {
1078     // already converted creation cmd
1079     newName = my1dHyp->GetCreationCmd()->GetResultValue();
1080   }
1081
1082   // as creation of 1D hyp was written later then it's edition,
1083   // we need to find all it's edition calls and process them
1084   list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
1085   list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
1086   for ( ; cmdIt != cmds.end(); ++cmdIt ) {
1087     const _pyID& objID = (*cmdIt)->GetObject();
1088     if ( objID == hyp1dID ) {
1089       my1dHyp->Process( *cmdIt );
1090       my1dHyp->GetCreationCmd()->AddDependantCmd( *cmdIt );
1091       ( *cmdIt )->SetObject( newName );
1092     }
1093   }
1094   if ( !myArgCommands.empty() )
1095     myArgCommands.front()->Clear();
1096   theCommand->SetArg( 1, newName );
1097   myArgCommands.push_back( theCommand );
1098   // copy hyp1d's creation method and args
1099 //   myCreationMethod = hyp1d->GetCreationMethod();
1100 //   myArgs           = hyp1d->GetArgs();
1101 //   // make them cleared at conversion
1102 //   myArgCommands = hyp1d->GetArgCommands();
1103
1104 //   // to be cleared at convertion only
1105 //   myArgCommands.push_back( theCommand );
1106 }
1107
1108 //================================================================================
1109 /*!
1110  * \brief 
1111   * \param theAdditionCmd - 
1112   * \param theMesh - 
1113   * \retval bool - 
1114  */
1115 //================================================================================
1116
1117 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
1118                                                   const _pyID&              theMesh)
1119 {
1120   myIsWrapped = false;
1121
1122   if ( my1dHyp.IsNull() )
1123     return false;
1124
1125   // set "SetLayerDistribution()" after addition cmd
1126   theAdditionCmd->AddDependantCmd( myArgCommands.front() );
1127
1128   _pyID geom = theAdditionCmd->GetArg( 1 );
1129
1130   my1dHyp->SetMesh( theMesh );
1131   if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
1132     return false;
1133
1134   // clear "SetLayerDistribution()" cmd
1135   myArgCommands.front()->Clear();
1136
1137   // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
1138
1139   // find RadialPrism algo created on <geom> for theMesh
1140   Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this->GetType() );
1141   if ( !algo.IsNull() ) {
1142     GetCreationCmd()->SetObject( algo->GetID() );
1143     GetCreationCmd()->SetMethod( "Get3DHypothesis" );
1144     GetCreationCmd()->RemoveArgs();
1145     theAdditionCmd->AddDependantCmd( GetCreationCmd() );
1146     myIsWrapped = true;
1147   }
1148   return myIsWrapped;
1149 }
1150
1151 //================================================================================
1152 /*!
1153  * \brief 
1154  */
1155 //================================================================================
1156
1157 void _pyLayerDistributionHypo::Flush()
1158 {
1159   //my1dHyp.Nullify();
1160   //_pyHypothesis::Flush();
1161 }
1162
1163 //================================================================================
1164 /*!
1165  * \brief additionally to Addition2Creation, clears SetDistrType() command
1166   * \param theCmd - AddHypothesis() command
1167   * \param theMesh - mesh to which a hypothesis is added
1168   * \retval bool - convertion result
1169  */
1170 //================================================================================
1171
1172 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
1173                                                 const _pyID&              theMesh)
1174 {
1175   if ( IsWrappable( theMesh ) && myArgs.Length() > 1 ) {
1176     // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
1177     bool scaleDistrType = false;
1178     list<Handle(_pyCommand)>::reverse_iterator cmd = myUnknownCommands.rbegin();
1179     for ( ; cmd != myUnknownCommands.rend(); ++cmd ) {
1180       if ( (*cmd)->GetMethod() == "SetDistrType" ) {
1181         if ( (*cmd)->GetArg( 1 ) == "1" ) {
1182           scaleDistrType = true;
1183           (*cmd)->Clear();
1184         }
1185         else if ( !scaleDistrType ) {
1186           // distribution type changed: remove scale factor from args
1187           myArgs.Remove( 2, myArgs.Length() );
1188           break;
1189         }
1190       }
1191     }
1192   }
1193   return _pyHypothesis::Addition2Creation( theCmd, theMesh );
1194 }
1195
1196 //================================================================================
1197 /*!
1198  * \brief remove repeated commands defining distribution
1199  */
1200 //================================================================================
1201
1202 void _pyNumberOfSegmentsHyp::Flush()
1203 {
1204   // find number of the last SetDistrType() command
1205   list<Handle(_pyCommand)>::reverse_iterator cmd = myUnknownCommands.rbegin();
1206   int distrTypeNb = 0;
1207   for ( ; !distrTypeNb && cmd != myUnknownCommands.rend(); ++cmd )
1208     if ( (*cmd)->GetMethod() == "SetDistrType" )
1209       distrTypeNb = (*cmd)->GetOrderNb();
1210
1211   // clear commands before the last SetDistrType()
1212   list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnknownCommands };
1213   for ( int i = 0; i < 2; ++i ) {
1214     set<TCollection_AsciiString> uniqueMethods;
1215     list<Handle(_pyCommand)> & cmdList = *cmds[i];
1216     for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
1217     {
1218       bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
1219       const TCollection_AsciiString& method = (*cmd)->GetMethod();
1220       if ( !clear || method == "SetNumberOfSegments" ) {
1221         bool isNewInSet = uniqueMethods.insert( method ).second;
1222         clear = !isNewInSet;
1223       }
1224       if ( clear )
1225         (*cmd)->Clear();
1226     }
1227     cmdList.clear();
1228   }
1229 }
1230
1231 //================================================================================
1232 /*!
1233  * \brief _pyAlgorithm constructor
1234  * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
1235  */
1236 //================================================================================
1237
1238 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
1239   : _pyHypothesis( theCreationCmd )
1240 {
1241   myIsAlgo = true;
1242 }
1243
1244 //================================================================================
1245 /*!
1246  * \brief Convert the command adding an algorithm to mesh
1247   * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
1248   * \param theMesh - The mesh needing this algo 
1249   * \retval bool - false if the command cant be converted
1250  */
1251 //================================================================================
1252   
1253 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
1254                                       const _pyID&              theMeshID)
1255 {
1256   if ( IsWrappable( theMeshID )) {
1257
1258     myGeom = theCmd->GetArg( 1 );
1259
1260     // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
1261     if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
1262       theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
1263       return true;
1264     }
1265   }
1266   return false;
1267 }
1268
1269 //================================================================================
1270 /*!
1271  * \brief Return starting position of a part of python command
1272   * \param thePartIndex - The index of command part
1273   * \retval int - Part position
1274  */
1275 //================================================================================
1276
1277 int _pyCommand::GetBegPos( int thePartIndex )
1278 {
1279   if ( IsEmpty() )
1280     return EMPTY;
1281   if ( myBegPos.Length() < thePartIndex )
1282     return UNKNOWN;
1283   return myBegPos( thePartIndex );
1284 }
1285
1286 //================================================================================
1287 /*!
1288  * \brief Store starting position of a part of python command
1289   * \param thePartIndex - The index of command part
1290   * \param thePosition - Part position
1291  */
1292 //================================================================================
1293
1294 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
1295 {
1296   while ( myBegPos.Length() < thePartIndex )
1297     myBegPos.Append( UNKNOWN );
1298   myBegPos( thePartIndex ) = thePosition;
1299 }
1300
1301 //================================================================================
1302 /*!
1303  * \brief Return substring of python command looking like ResultValue = Obj.Meth()
1304   * \retval const TCollection_AsciiString & - ResultValue substring
1305  */
1306 //================================================================================
1307
1308 const TCollection_AsciiString & _pyCommand::GetResultValue()
1309 {
1310   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
1311   {
1312     int begPos = myString.Location( "=", 1, Length() );
1313     if ( begPos )
1314       myRes = GetWord( myString, begPos, false );
1315     else
1316       begPos = EMPTY;
1317     SetBegPos( RESULT_IND, begPos );
1318   }
1319   return myRes;
1320 }
1321
1322 //================================================================================
1323 /*!
1324  * \brief Return substring of python command looking like ResVal = Object.Meth()
1325   * \retval const TCollection_AsciiString & - Object substring
1326  */
1327 //================================================================================
1328
1329 const TCollection_AsciiString & _pyCommand::GetObject()
1330 {
1331   if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
1332   {
1333     // beginning
1334     int begPos = GetBegPos( RESULT_IND ) + myRes.Length();
1335     if ( begPos < 1 )
1336       begPos = myString.Location( "=", 1, Length() ) + 1;
1337     // store
1338     myObj = GetWord( myString, begPos, true );
1339     SetBegPos( OBJECT_IND, begPos );
1340   }
1341   //SCRUTE(myObj);
1342   return myObj;
1343 }
1344
1345 //================================================================================
1346 /*!
1347  * \brief Return substring of python command looking like ResVal = Obj.Method()
1348   * \retval const TCollection_AsciiString & - Method substring
1349  */
1350 //================================================================================
1351
1352 const TCollection_AsciiString & _pyCommand::GetMethod()
1353 {
1354   if ( GetBegPos( METHOD_IND ) == UNKNOWN )
1355   {
1356     // beginning
1357     int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
1358     bool forward = true;
1359     if ( begPos < 1 ) {
1360       begPos = myString.Location( "(", 1, Length() ) - 1;
1361       forward = false;
1362     }
1363     // store
1364     myMeth = GetWord( myString, begPos, forward );
1365     SetBegPos( METHOD_IND, begPos );
1366   }
1367   //SCRUTE(myMeth);
1368   return myMeth;
1369 }
1370
1371 //================================================================================
1372 /*!
1373  * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
1374   * \retval const TCollection_AsciiString & - Arg<index> substring
1375  */
1376 //================================================================================
1377
1378 const TCollection_AsciiString & _pyCommand::GetArg( int index )
1379 {
1380   if ( GetBegPos( ARG1_IND ) == UNKNOWN )
1381   {
1382     // find all args
1383     int begPos = GetBegPos( METHOD_IND ) + myMeth.Length();
1384     if ( begPos < 1 )
1385       begPos = myString.Location( "(", 1, Length() ) + 1;
1386
1387     int i = 0, prevLen = 0;
1388     while ( begPos != EMPTY ) {
1389       begPos += prevLen;
1390       // check if we are looking at the closing parenthesis
1391       while ( begPos <= Length() && isspace( myString.Value( begPos )))
1392         ++begPos;
1393       if ( begPos > Length() || myString.Value( begPos ) == ')' )
1394         break;
1395       myArgs.Append( GetWord( myString, begPos, true, true ));
1396       SetBegPos( ARG1_IND + i, begPos );
1397       prevLen = myArgs.Last().Length();
1398       if ( prevLen == 0 )
1399         myArgs.Remove( myArgs.Length() ); // no more args
1400       i++;
1401     }
1402   }
1403   if ( myArgs.Length() < index )
1404     return theEmptyString;
1405   return myArgs( index );
1406 }
1407
1408 //================================================================================
1409 /*!
1410  * \brief Check if char is a word part
1411   * \param c - The character to check
1412   * \retval bool - The check result
1413  */
1414 //================================================================================
1415
1416 static inline bool isWord(const char c, const bool dotIsWord)
1417 {
1418   return
1419     !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
1420 }
1421
1422 //================================================================================
1423 /*!
1424  * \brief Looks for a word in the string and returns word's beginning
1425   * \param theString - The input string
1426   * \param theStartPos - The position to start the search, returning word's beginning
1427   * \param theForward - The search direction
1428   * \retval TCollection_AsciiString - The found word
1429  */
1430 //================================================================================
1431
1432 TCollection_AsciiString _pyCommand::GetWord( const TCollection_AsciiString & theString,
1433                                             int &      theStartPos,
1434                                             const bool theForward,
1435                                             const bool dotIsWord )
1436 {
1437   int beg = theStartPos, end = theStartPos;
1438   theStartPos = EMPTY;
1439   if ( beg < 1 || beg > theString.Length() )
1440     return theEmptyString;
1441
1442   if ( theForward ) { // search forward
1443     // beg
1444     while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
1445       ++beg;
1446     if ( beg > theString.Length() )
1447       return theEmptyString; // no word found
1448     // end
1449     end = beg + 1;
1450     while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
1451       ++end;
1452     --end;
1453   }
1454   else {  // search backward
1455     // end
1456     while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
1457       --end;
1458     if ( end == 0 )
1459       return theEmptyString; // no word found
1460     beg = end - 1;
1461     while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
1462       --beg;
1463     ++beg;
1464   }
1465   theStartPos = beg;
1466   //cout << theString << " ---- " << beg << " - " << end << endl;
1467   return theString.SubString( beg, end );
1468 }
1469
1470 //================================================================================
1471 /*!
1472  * \brief Look for position where not space char is
1473   * \param theString - The string 
1474   * \param thePos - The position to search from and which returns result
1475   * \retval bool - false if there are only space after thePos in theString
1476  * 
1477  * 
1478  */
1479 //================================================================================
1480
1481 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
1482 {
1483   if ( thePos < 1 || thePos > theString.Length() )
1484     return false;
1485
1486   while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
1487     ++thePos;
1488
1489   return thePos <= theString.Length();
1490 }
1491
1492 //================================================================================
1493 /*!
1494  * \brief Modify a part of the command
1495   * \param thePartIndex - The index of the part
1496   * \param thePart - The new part string
1497   * \param theOldPart - The old part
1498  */
1499 //================================================================================
1500
1501 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
1502                         TCollection_AsciiString& theOldPart)
1503 {
1504   int pos = GetBegPos( thePartIndex );
1505   if ( pos <= Length() && theOldPart != thePart)
1506   {
1507     TCollection_AsciiString seperator;
1508     if ( pos < 1 ) {
1509       pos = GetBegPos( thePartIndex + 1 );
1510       if ( pos < 1 ) return;
1511       switch ( thePartIndex ) {
1512       case RESULT_IND: seperator = " = "; break;
1513       case OBJECT_IND: seperator = "."; break;
1514       case METHOD_IND: seperator = "()"; break;
1515       default:;
1516       }
1517     }      
1518     myString.Remove( pos, theOldPart.Length() );
1519     if ( !seperator.IsEmpty() )
1520       myString.Insert( pos , seperator );
1521     myString.Insert( pos, thePart );
1522     // update starting positions of the following parts
1523     int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
1524     for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
1525       if ( myBegPos( i ) > 0 )
1526         myBegPos( i ) += posDelta;
1527     }
1528     theOldPart = thePart;
1529   }
1530 }
1531
1532 //================================================================================
1533 /*!
1534  * \brief Set agrument
1535   * \param index - The argument index, it counts from 1
1536   * \param theArg - The argument string
1537  */
1538 //================================================================================
1539
1540 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
1541 {
1542   FindAllArgs();
1543   int argInd = ARG1_IND + index - 1;
1544   int pos = GetBegPos( argInd );
1545   if ( pos < 1 ) // no index-th arg exist, append inexistent args
1546   {
1547     // find a closing parenthesis
1548     if ( int lastArgInd = GetNbArgs() ) {
1549       pos = GetBegPos( ARG1_IND + lastArgInd  - 1 ) + GetArg( lastArgInd ).Length();
1550       while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
1551         ++pos;
1552     }
1553     else {
1554       pos = Length();
1555       while ( pos > 0 && myString.Value( pos ) != ')' )
1556         --pos;
1557     }
1558     if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
1559       myString += "()";
1560       pos = Length();
1561     }
1562     while ( myArgs.Length() < index ) {
1563       if ( myArgs.Length() )
1564         myString.Insert( pos++, "," );
1565       myArgs.Append("None");
1566       myString.Insert( pos, myArgs.Last() );
1567       SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
1568       pos += myArgs.Last().Length();
1569     }
1570   }
1571   SetPart( argInd, theArg, myArgs( index ));
1572 }
1573
1574 //================================================================================
1575 /*!
1576  * \brief Empty arg list
1577  */
1578 //================================================================================
1579
1580 void _pyCommand::RemoveArgs()
1581 {
1582   if ( int pos = myString.Location( '(', 1, Length() ))
1583     myString.Trunc( pos );
1584   myString += ")";
1585   myArgs.Clear();
1586   if ( myBegPos.Length() >= ARG1_IND )
1587     myBegPos.Remove( ARG1_IND, myBegPos.Length() );
1588 }
1589
1590 //================================================================================
1591 /*!
1592  * \brief Set dependent commands after this one
1593  */
1594 //================================================================================
1595
1596 bool _pyCommand::SetDependentCmdsAfter() const
1597 {
1598   bool orderChanged = false;
1599   list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
1600   for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
1601     if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
1602       orderChanged = true;
1603       theGen->SetCommandAfter( *cmd, this );
1604       (*cmd)->SetDependentCmdsAfter();
1605     }
1606   }
1607   return orderChanged;
1608 }
1609 //================================================================================
1610 /*!
1611  * \brief Insert accessor method after theObjectID
1612   * \param theObjectID - id of the accessed object
1613   * \param theAcsMethod - name of the method giving access to the object
1614   * \retval bool - false if theObjectID is not found in the command string
1615  */
1616 //================================================================================
1617
1618 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
1619 {
1620   if ( !theAcsMethod )
1621     return false;
1622   // start object search from the object, i.e. ignore result
1623   GetObject();
1624   int beg = GetBegPos( OBJECT_IND );
1625   if ( beg < 1 || beg > Length() )
1626     return false;
1627   while (( beg = myString.Location( theObjectID, beg, Length() )))
1628   {
1629     // check that theObjectID is not just a part of a longer ID
1630     int afterEnd = beg + theObjectID.Length();
1631     Standard_Character c = myString.Value( afterEnd );
1632     if ( !isalnum( c ) && c != ':' ) {
1633       // insertion
1634       int oldLen = Length();
1635       myString.Insert( afterEnd, (char*) theAcsMethod );
1636       myString.Insert( afterEnd, "." );
1637       // update starting positions of the parts following the modified one
1638       int posDelta = Length() - oldLen;
1639       for ( int i = 1; i <= myBegPos.Length(); ++i ) {
1640         if ( myBegPos( i ) > afterEnd )
1641           myBegPos( i ) += posDelta;
1642       }
1643       return true;
1644     }
1645     beg = afterEnd; // is a part - next search
1646   }
1647   return false;
1648 }
1649
1650 //================================================================================
1651 /*!
1652  * \brief Return method name giving access to an interaface object wrapped by python class
1653   * \retval const char* - method name
1654  */
1655 //================================================================================
1656
1657 const char* _pyObject::AccessorMethod() const
1658 {
1659   return 0;
1660 }