Salome HOME
PAL10494 (SMESH python dump uses idl interface). Add SMESH_2smeshpy, a converter...
[modules/smesh.git] / src / SMESH_I / SMESH_2smeshpy.cxx
1 // File      : SMESH_2smeshpy.cxx
2 // Created   : Fri Nov 18 13:20:10 2005
3 // Author    : Edward AGAPOV (eap)
4
5 #include "SMESH_2smeshpy.hxx"
6
7 #include "SMESH_Gen_i.hxx"
8 #include "utilities.h"
9 #include "SMESH_PythonDump.hxx"
10 #include "Resource_DataMapOfAsciiStringAsciiString.hxx"
11
12 IMPLEMENT_STANDARD_HANDLE (_pyObject          ,Standard_Transient);
13 IMPLEMENT_STANDARD_HANDLE (_pyCommand         ,Standard_Transient);
14 IMPLEMENT_STANDARD_HANDLE (_pyGen             ,_pyObject);
15 IMPLEMENT_STANDARD_HANDLE (_pyMesh            ,_pyObject);
16 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis      ,_pyObject);
17 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm       ,_pyHypothesis);
18 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
19 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
20
21 using namespace std;
22 using SMESH::TPythonDump;
23
24 /*!
25  * \brief Container of commands into which the initial script is split.
26  *        It also contains data coresponding to SMESH_Gen contents
27  */
28 static Handle(_pyGen) theGen;
29
30 static TCollection_AsciiString theEmptyString;
31
32 //#define DUMP_CONVERSION
33
34 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
35 #undef DUMP_CONVERSION
36 #endif
37
38 //================================================================================
39 /*!
40  * \brief Convert python script using commands of smesh.py
41   * \param theScript - Input script
42   * \retval TCollection_AsciiString - Convertion result
43  */
44 //================================================================================
45
46 TCollection_AsciiString
47 SMESH_2smeshpy::ConvertScript(const TCollection_AsciiString& theScript,
48                               Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod)
49 {
50   theGen = new _pyGen( theEntry2AccessorMethod );
51
52   // split theScript into separate commands
53   int from = 1, end = theScript.Length(), to;
54   while ( from < end && ( to = theScript.Location( "\n", from, end )))
55   {
56     if ( to != from )
57       // cut out and store a command
58       theGen->AddCommand( theScript.SubString( from, to - 1 ));
59     from = to + 1;
60   }
61   // finish conversion
62   theGen->Flush();
63 #ifdef DUMP_CONVERSION
64   cout << endl << " ######## RESULT ######## " << endl<< endl;
65 #endif
66   // concat commands back into a script
67   TCollection_AsciiString aScript;
68   list< Handle(_pyCommand) >::iterator cmd = theGen->GetCommands().begin();
69   for ( ; cmd != theGen->GetCommands().end(); ++cmd ) {
70 #ifdef DUMP_CONVERSION
71     cout << "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << endl;
72 #endif
73     if ( !(*cmd)->IsEmpty() ) {
74       aScript += "\n";
75       aScript += (*cmd)->GetString();
76     }
77   }
78   aScript += "\n";
79
80   theGen.Nullify();
81
82   return aScript;
83 }
84
85 //================================================================================
86 /*!
87  * \brief _pyGen constructor
88  */
89 //================================================================================
90
91 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod)
92   : _pyObject( new _pyCommand( TPythonDump::SMESHGenName(), 0 )),
93     myID2AccessorMethod( theEntry2AccessorMethod )
94 {
95   myNbCommands = 0;
96   // make that GetID() to return TPythonDump::SMESHGenName()
97   GetCreationCmd()->GetString() += "=";
98 }
99
100 //================================================================================
101 /*!
102  * \brief Convert a command using a specific converter
103   * \param theCommand - the command to convert
104   * \retval bool - convertion result
105  */
106 //================================================================================
107
108 void _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
109 {
110   // store theCommand in the sequence
111   myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
112
113   Handle(_pyCommand) aCommand = myCommands.back();
114 #ifdef DUMP_CONVERSION
115   cout << "## COM " << myNbCommands << ": "<< aCommand->GetString() << endl;
116 #endif
117
118   _pyID objID = aCommand->GetObject();
119
120   if ( objID.IsEmpty() )
121     return;
122
123   // SMESH_Gen method?
124   if ( objID == this->GetID() ) {
125     this->Process( aCommand );
126     return;
127   }
128   // SMESH_Mesh method?
129   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
130   if ( id_mesh != myMeshes.end() ) {
131     id_mesh->second->Process( aCommand );
132     return;
133   }
134   // SMESH_Hypothesis method
135   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
136   for ( ; hyp != myHypos.end(); ++hyp )
137     if ( !(*hyp)->IsAlgo() && objID == (*hyp)->GetID() )
138       (*hyp)->Process( aCommand );
139
140   // Mesh provides SMESH_IDSource interface used in SMESH_MeshEditor.
141   // Add access to wrapped mesh
142   if ( objID == TPythonDump::MeshEditorName() ) {
143     // in all SMESH_MeshEditor's commands, a SMESH_IDSource is the first arg
144     id_mesh = myMeshes.find( aCommand->GetArg( 1 ));
145     if ( id_mesh != myMeshes.end() )
146       aCommand->SetArg( 1 , aCommand->GetArg( 1 ) + ".GetMesh()" );
147   }
148 }
149
150 //================================================================================
151 /*!
152  * \brief Convert the command or remember it for later conversion 
153   * \param theCommand - The python command calling a method of SMESH_Gen
154  */
155 //================================================================================
156
157 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
158 {
159   // there are methods to convert:
160   // CreateMesh( shape )
161   // CreateHypothesis( theHypType, theLibName )
162   // Compute( mesh, geom )
163
164   if ( theCommand->GetMethod() == "CreateMesh" )
165   {
166     Handle(_pyMesh) mesh = new _pyMesh( theCommand );
167     myMeshes.insert( make_pair( mesh->GetID(), mesh ));
168     return;
169   }
170
171   // CreateHypothesis()
172   if ( theCommand->GetMethod() == "CreateHypothesis" )
173   {
174     myHypos.push_back( _pyHypothesis::NewHypothesis( theCommand ));
175     return;
176   }
177
178   // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
179   if ( theCommand->GetMethod() == "Compute" )
180   {
181     const _pyID& meshID = theCommand->GetArg( 1 );
182     map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
183     if ( id_mesh != myMeshes.end() ) {
184       theCommand->SetObject( meshID );
185       theCommand->RemoveArgs();
186       id_mesh->second->Flush();
187       return;
188     }
189   }
190
191   // smeshgen.Method() --> smesh.smesh.Method()
192   theCommand->SetObject( SMESH_2smeshpy::GenName() );
193 }
194
195 //================================================================================
196 /*!
197  * \brief Convert the remembered commands
198  */
199 //================================================================================
200
201 void _pyGen::Flush()
202 {
203   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
204   for ( ; id_mesh != myMeshes.end(); ++id_mesh )
205     if ( ! id_mesh->second.IsNull() )
206       id_mesh->second->Flush();
207
208   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
209   for ( ; hyp != myHypos.end(); ++hyp )
210     if ( !hyp->IsNull() ) {
211       (*hyp)->Flush();
212       // smeshgen.CreateHypothesis() --> smesh.smesh.CreateHypothesis()
213       if ( !(*hyp)->GetCreationCmd()->IsEmpty() )
214         (*hyp)->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
215     }
216 }
217
218 //================================================================================
219 /*!
220  * \brief Find hypothesis by ID (entry)
221   * \param theHypID - The hypothesis ID
222   * \retval Handle(_pyHypothesis) - The found hypothesis
223  */
224 //================================================================================
225
226 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
227 {
228   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
229   for ( ; hyp != myHypos.end(); ++hyp )
230     if ( !hyp->IsNull() && theHypID == (*hyp)->GetID() )
231       return *hyp;
232   return Handle(_pyHypothesis)();
233 }
234
235 //================================================================================
236 /*!
237  * \brief Find algorithm the created algorithm
238   * \param theGeom - The shape ID the algorithm was created on
239   * \param theMesh - The mesh ID that created the algorithm
240   * \param dim - The algo dimension
241   * \retval Handle(_pyHypothesis) - The found algo
242  */
243 //================================================================================
244
245 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
246                                       const TCollection_AsciiString& theAlgoType )
247 {
248   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
249   for ( ; hyp != myHypos.end(); ++hyp )
250     if ( !hyp->IsNull() &&
251          (*hyp)->IsAlgo() &&
252          (*hyp)->GetType() == theAlgoType &&
253          (*hyp)->GetGeom() == theGeom &&
254          (*hyp)->GetMesh() == theMesh )
255       return *hyp;
256   return 0;
257 }
258
259 //================================================================================
260 /*!
261  * \brief Change order of commands in the script
262   * \param theCmd1 - One command
263   * \param theCmd2 - Another command
264  */
265 //================================================================================
266
267 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
268 {
269   list< Handle(_pyCommand) >::iterator pos1, pos2;
270   pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
271   pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
272   myCommands.insert( pos1, theCmd2 );
273   myCommands.insert( pos2, theCmd1 );
274   myCommands.erase( pos1 );
275   myCommands.erase( pos2 );
276
277   int nb1 = theCmd1->GetOrderNb();
278   theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
279   theCmd2->SetOrderNb( nb1 );
280 }
281 //================================================================================
282 /*!
283  * \brief Set one command after the other
284   * \param theCmd - Command to move
285   * \param theAfterCmd - Command ater which to insert the first one
286  */
287 //================================================================================
288
289 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
290 {
291   list< Handle(_pyCommand) >::iterator pos;
292   pos = find( myCommands.begin(), myCommands.end(), theCmd );
293   myCommands.erase( pos );
294   pos = find( myCommands.begin(), myCommands.end(), theAfterCmd );
295   myCommands.insert( ++pos, theCmd );
296
297   int i = 1;
298   for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
299     (*pos)->SetOrderNb( i++ );
300 }
301
302 //================================================================================
303 /*!
304  * \brief Set method to access to object wrapped with python class
305   * \param theID - The wrapped object entry
306   * \param theMethod - The accessor method
307  */
308 //================================================================================
309
310 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
311 {
312   myID2AccessorMethod.Bind( theID, (char*) theMethod );
313 }
314
315 //================================================================================
316 /*!
317  * \brief Find out type of geom group
318   * \param grpID - The geom group entry
319   * \retval int - The type
320  */
321 //================================================================================
322
323 static bool sameGroupType( const _pyID&                   grpID,
324                            const TCollection_AsciiString& theType)
325 {
326   // define group type as smesh.Mesh.Group() does
327   int type = -1;
328   SALOMEDS::Study_var study = SMESH_Gen_i::GetSMESHGen()->GetCurrentStudy();
329   SALOMEDS::SObject_var aSObj = study->FindObjectID( grpID.ToCString() );
330   if ( !aSObj->_is_nil() ) {
331     GEOM::GEOM_Object_var aGeomObj = GEOM::GEOM_Object::_narrow( aSObj->GetObject() );
332     if ( !aGeomObj->_is_nil() ) {
333       switch ( aGeomObj->GetShapeType() ) {
334       case GEOM::VERTEX: type = SMESH::NODE; break;
335       case GEOM::EDGE:   type = SMESH::EDGE; break;
336       case GEOM::FACE:   type = SMESH::FACE; break;
337       case GEOM::SOLID:
338       case GEOM::SHELL:  type = SMESH::VOLUME; break;
339       case GEOM::COMPOUND: {
340         GEOM::GEOM_Gen_var aGeomGen = SMESH_Gen_i::GetSMESHGen()->GetGeomEngine();
341         if ( !aGeomGen->_is_nil() ) {
342           GEOM::GEOM_IGroupOperations_var aGrpOp =
343             aGeomGen->GetIGroupOperations( study->StudyId() );
344           if ( !aGrpOp->_is_nil() ) {
345             switch ( aGrpOp->GetType( aGeomObj )) {
346             case TopAbs_VERTEX: type = SMESH::NODE; break;
347             case TopAbs_EDGE:   type = SMESH::EDGE; break;
348             case TopAbs_FACE:   type = SMESH::FACE; break;
349             case TopAbs_SOLID:  type = SMESH::VOLUME; break;
350             default:;
351             }
352           }
353         }
354       }
355       default:;
356       }
357     }
358   }
359   if ( type < 0 ) {
360     MESSAGE("Type of the group " << grpID << " not found");
361     return false;
362   }
363   if ( theType.IsIntegerValue() )
364     return type == theType.IntegerValue();
365
366   switch ( type ) {
367   case SMESH::NODE:   return theType.Location( "NODE", 1, theType.Length() );
368   case SMESH::EDGE:   return theType.Location( "EDGE", 1, theType.Length() );
369   case SMESH::FACE:   return theType.Location( "FACE", 1, theType.Length() );
370   case SMESH::VOLUME: return theType.Location( "VOLUME", 1, theType.Length() );
371   default:;
372   }
373   return false;
374 }
375
376 //================================================================================
377 /*!
378  * \brief 
379   * \param theCreationCmd - 
380  */
381 //================================================================================
382
383 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd): _pyObject(theCreationCmd)
384 {
385   // convert my creation command
386   Handle(_pyCommand) creationCmd = GetCreationCmd();
387   creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
388   creationCmd->SetMethod( "Mesh" );
389
390   theGen->SetAccessorMethod( GetID(), "GetMesh()" );
391 }
392
393 //================================================================================
394 /*!
395             case brief:
396             default:
397   * \param theCommand - Engine method called for this mesh
398  */
399 //================================================================================
400
401 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
402 {
403   // smesh.py wraps the following methods:
404   //
405   // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
406   //     --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
407   // 2. AddHypothesis(geom, hyp)
408   //     --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
409   // 3. CreateGroupFromGEOM(type, name, grp)
410   //     --> in Mesh.Group(grp, name="")
411   // 4. ExportToMED(f, opt, version)
412   //     --> in Mesh.ExportToMED( f, version, opt=0 )
413   // 5. ExportMED(f, opt)
414   //     --> in Mesh.ExportMED( f,opt=0 )
415   // 6. ExportDAT(f)
416   //     --> in Mesh.ExportDAT( f )
417   // 7. ExportUNV(f)
418   //     --> in Mesh.ExportUNV(f)
419   // 8. ExportSTL(f, ascii)
420   //     --> in Mesh.ExportSTL(f, ascii=1)
421
422   const TCollection_AsciiString method = theCommand->GetMethod();
423   if ( method == "GetSubMesh" ) {
424     mySubmeshes.push_back( theCommand );
425   }
426   else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
427     myAddHypCmds.push_back( theCommand );
428     // set mesh to hypo
429     const _pyID& hypID = theCommand->GetArg( 2 );
430     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
431     if ( !hyp.IsNull() && hyp->GetMesh().IsEmpty() )
432       hyp->SetMesh( this->GetID() );
433   }
434   else if ( method == "CreateGroupFromGEOM" ) {// (type, name, grp)
435     _pyID grp = theCommand->GetArg( 3 );
436     if ( sameGroupType( grp, theCommand->GetArg( 1 )) ) { // --> Group(grp)
437       theCommand->SetMethod( "Group" );
438       theCommand->RemoveArgs();
439       theCommand->SetArg( 1, grp );
440     }
441     else {
442       AddMeshAccess( theCommand );
443     }
444   }
445   else if ( method == "ExportToMED" ) {//(f, opt, version)
446     // --> (f, version, opt)
447     _pyID opt = theCommand->GetArg( 2 );
448     _pyID ver = theCommand->GetArg( 3 );
449     theCommand->SetArg( 2, ver );
450     theCommand->SetArg( 3, opt );
451   }
452   else if ( method == "RemoveHypothesis" ) // (geom, hyp)
453   {
454     const _pyID & hypID = theCommand->GetArg( 2 );
455
456     // check if this mesh still has corresponding addition command
457     bool hasAddCmd = false;
458     list< Handle(_pyCommand) >::iterator cmd = myAddHypCmds.begin();
459     while ( cmd != myAddHypCmds.end() )
460     {
461       // AddHypothesis(geom, hyp)
462       if ( hypID == (*cmd)->GetArg( 2 )) { // erase both commands
463         theCommand->Clear();
464         (*cmd)->Clear();
465         cmd = myAddHypCmds.erase( cmd );
466         hasAddCmd = true;
467       }
468       else {
469         ++cmd;
470       }
471     }
472     if ( ! hasAddCmd ) {
473       // access to wrapped mesh
474       AddMeshAccess( theCommand );
475       // access to wrapped algo
476       Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
477       if ( !hyp.IsNull() && hyp->IsAlgo() && hyp->IsWrapped() )
478         theCommand->SetArg( 2, theCommand->GetArg( 2 ) + ".GetAlgorithm()" );
479     }
480   }
481   else { // apply theCommand to the mesh wrapped by smeshpy mesh
482     AddMeshAccess( theCommand );
483   }
484 }
485
486 //================================================================================
487 /*!
488  * \brief Convert creation and addition of all algos and hypos
489  */
490 //================================================================================
491
492 void _pyMesh::Flush()
493 {
494   list < Handle(_pyCommand) >::iterator cmd, cmd2;
495   map< _pyID, Handle(_pyCommand) > algo2additionCmd;
496
497   // try to convert algo addition like this:
498   // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
499   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
500   {
501     Handle(_pyCommand) addCmd = *cmd;
502     const _pyID& algoID = addCmd->GetArg( 2 );
503     Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
504     if ( algo.IsNull() || !algo->IsAlgo() )
505       continue;
506     // try to convert
507     _pyID geom = addCmd->GetArg( 1 );
508     if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
509     {
510       algo2additionCmd[ algo->GetID() ] = addCmd;
511
512       if ( geom != GetGeom() ) // local algo
513       {
514         // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
515         addCmd->SetArg( addCmd->GetNbArgs() + 1,
516                         TCollection_AsciiString( "geom=" ) + geom );
517         // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
518         for ( cmd2 = mySubmeshes.begin(); cmd2 != mySubmeshes.end(); ++cmd2 ) {
519           Handle(_pyCommand) subCmd = *cmd2;
520           if ( geom == subCmd->GetArg( 1 )) {
521             subCmd->SetObject( algo->GetID() );
522             subCmd->RemoveArgs();
523             if ( addCmd->GetOrderNb() > subCmd->GetOrderNb() )
524               theGen->SetCommandAfter( subCmd, addCmd );
525           }
526         }
527       }
528     }
529     else // ALGO was already created
530     {
531       // mesh.AddHypothesis(geom, ALGO ) --> mesh.GetMesh().AddHypothesis(geom, ALGO )
532       AddMeshAccess( addCmd );
533       // mesh.GetMesh().AddHypothesis(geom, ALGO ) ->
534       // mesh.GetMesh().AddHypothesis(geom, ALGO.GetAlgorithm() )
535       addCmd->SetArg( 2, addCmd->GetArg( 2 ) + ".GetAlgorithm()" );
536     }
537   }
538
539   // try to convert hypo addition like this:
540   // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
541   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
542   {
543     Handle(_pyCommand) addCmd = *cmd;
544     const _pyID& hypID = addCmd->GetArg( 2 );
545     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
546     if ( hyp.IsNull() || hyp->IsAlgo() )
547       continue;
548     const _pyID& geom = addCmd->GetArg( 1 );
549     // find algo created on <geom> for this mesh
550     Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, this->GetID(), hyp->GetType() );
551     //_pyID algoID = algo.IsNull() ? "" : algo->GetID();
552     if ( !algo.IsNull() && hyp->Addition2Creation( addCmd, this->GetID() )) // OK
553     {
554       addCmd->SetObject( algo->GetID() );
555       Handle(_pyCommand) algoCmd = algo2additionCmd[ algo->GetID() ];
556       if ( !algoCmd.IsNull() && algoCmd->GetOrderNb() > addCmd->GetOrderNb() )
557         // algo was created later than hyp
558         theGen->ExchangeCommands( algoCmd, addCmd );
559     }
560     else
561     {
562       AddMeshAccess( addCmd );
563     }
564   }
565
566   // sm = mesh.GetSubMesh(geom, name) --> sm = mesh.GetMesh().GetSubMesh(geom, name)
567   for ( cmd = mySubmeshes.begin(); cmd != mySubmeshes.end(); ++cmd ) {
568     Handle(_pyCommand) subCmd = *cmd;
569     if ( subCmd->GetNbArgs() > 0 )
570       AddMeshAccess( subCmd );
571   }
572   myAddHypCmds.clear();
573   mySubmeshes.clear();
574 }
575
576 //================================================================================
577 /*!
578  * \brief _pyHypothesis constructor
579   * \param theCreationCmd - 
580  */
581 //================================================================================
582
583 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
584   _pyObject( theCreationCmd )
585 {
586   myDim = myIsAlgo = /*myIsLocal = */myIsWrapped = myIsConverted = false;
587 }
588
589 //================================================================================
590 /*!
591  * \brief Creates algorithm or hypothesis
592   * \param theCreationCmd - The engine command creating a hypothesis
593   * \retval Handle(_pyHypothesis) - Result _pyHypothesis
594  */
595 //================================================================================
596
597 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
598 {
599   // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
600   ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
601
602   Handle(_pyHypothesis) hyp, algo;
603
604   // "theHypType"
605   const TCollection_AsciiString & hypTypeWithQuotes = theCreationCmd->GetArg( 1 );
606   if ( hypTypeWithQuotes.IsEmpty() )
607     return hyp;
608   // theHypType
609   TCollection_AsciiString  hypType =
610     hypTypeWithQuotes.SubString( 2, hypTypeWithQuotes.Length() - 1 );
611
612   algo = new _pyAlgorithm( theCreationCmd );
613   hyp  = new _pyHypothesis( theCreationCmd );
614
615   // 1D Regular_1D ----------
616   if ( hypType == "Regular_1D" ) {
617     algo->myDim = 1;
618     algo->myCreationMethod = "Segment";
619   }
620   else if ( hypType == "LocalLength" ) {
621     hyp->myDim = 1;
622     hyp->myCreationMethod = "LocalLength";
623     hyp->myType = "Regular_1D";
624     hyp->myArgMethods.Append( "SetLength" );
625   }
626   else if ( hypType == "NumberOfSegments" ) {
627     hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
628     hyp->myDim = 1;
629     hyp->myCreationMethod = "NumberOfSegments";
630     hyp->myType = "Regular_1D";
631     hyp->myArgMethods.Append( "SetNumberOfSegments" );
632     hyp->myArgMethods.Append( "SetScaleFactor" );
633   }
634   else if ( hypType == "Arithmetic1D" ) {
635     hyp = new _pyComplexParamHypo( theCreationCmd );
636     hyp->myDim = 1;
637     hyp->myCreationMethod = "Arithmetic1D";
638     hyp->myType = "Regular_1D";
639   }
640   else if ( hypType == "StartEndLength" ) {
641     hyp = new _pyComplexParamHypo( theCreationCmd );
642     hyp->myDim = 1;
643     hyp->myCreationMethod = "StartEndLength";
644     hyp->myType = "Regular_1D";
645   }
646   else if ( hypType == "Deflection1D" ) {
647     hyp->myDim = 1;
648     hyp->myCreationMethod = "Deflection1D";
649     hyp->myArgMethods.Append( "SetDeflection" );
650     hyp->myType = "Regular_1D";
651   }
652   else if ( hypType == "Propagation" ) {
653     hyp->myDim = 1;
654     hyp->myCreationMethod = "Propagation";
655     hyp->myType = "Regular_1D";
656   }
657   else if ( hypType == "AutomaticLength" ) {
658     hyp->myDim = 1;
659     hyp->myCreationMethod = "AutomaticLength";
660     hyp->myType = "Regular_1D";
661   }
662   // 1D Python_1D ----------
663   else if ( hypType == "Python_1D" ) {
664     algo->myDim = 1;
665     algo->myCreationMethod = "Segment";
666     algo->myArgs.Append( "algo=smesh.PYTHON");
667   }
668   else if ( hypType == "PythonSplit1D" ) {
669     hyp->myDim = 1;
670     hyp->myCreationMethod = "PythonSplit1D";
671     hyp->myType = "Python_1D";
672     hyp->myArgMethods.Append( "SetNumberOfSegments");
673     hyp->myArgMethods.Append( "SetPythonLog10RatioFunction");
674   }
675   // 2D ----------
676   else if ( hypType == "MEFISTO_2D" ) {
677     algo->myDim = 2;
678     algo->myCreationMethod = "Triangle";
679   }
680   else if ( hypType == "MaxElementArea" ) {
681     hyp->myDim = 2;
682     hyp->myCreationMethod = "MaxElementArea";
683     hyp->myType = "MEFISTO_2D";
684     hyp->myArgMethods.Append( "SetMaxElementArea");
685   }
686   else if ( hypType == "LengthFromEdges" ) {
687     hyp->myDim = 2;
688     hyp->myCreationMethod = "LengthFromEdges";
689     hyp->myType = "MEFISTO_2D";
690   }
691   else if ( hypType == "Quadrangle_2D" ) {
692     algo->myDim = 2;
693     algo->myCreationMethod = "Quadrangle";
694   }
695   // 3D ----------
696   else if ( hypType == "NETGEN_3D") {
697     algo->myDim = 3;
698     algo->myCreationMethod = "Tetrahedron";
699     algo->myArgs.Append( "algo=smesh.NETGEN" );
700   }
701   else if ( hypType == "MaxElementVolume") {
702     hyp->myDim = 3;
703     hyp->myCreationMethod = "MaxElementVolume";
704     hyp->myType = "NETGEN_3D";
705     hyp->myArgMethods.Append( "SetMaxElementVolume" );
706   }
707   else if ( hypType == "GHS3D_3D" ) {
708     algo->myDim = 3;
709     algo->myCreationMethod = "Tetrahedron";
710     algo->myArgs.Append( "algo=smesh.GHS3D" );
711   }
712   else if ( hypType == "Hexa_3D" ) {
713     algo->myDim = 3;
714     algo->myCreationMethod = "Hexahedron";
715   }
716
717   if ( algo->GetDim() ) {
718     algo->myType = hypType;
719     return algo;
720   }
721   return hyp;
722 }
723
724 //================================================================================
725 /*!
726  * \brief Convert the command adding a hypothesis to mesh into a smesh command
727   * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
728   * \param theAlgo - The algo that can create this hypo
729   * \retval bool - false if the command cant be converted
730  */
731 //================================================================================
732
733 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
734                                        const _pyID&              theMesh)
735 {
736   ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
737
738   if ( !IsWrappable( theMesh ))
739     return false;
740
741   myIsWrapped = true;
742
743   if ( myIsWrapped )
744   {
745     // mesh.AddHypothesis(geom,hyp) --> hyp = theMesh.myCreationMethod(args)
746     theCmd->SetResultValue( GetID() );
747     theCmd->SetObject( theMesh );
748     theCmd->SetMethod( myCreationMethod );
749     // set args
750     theCmd->RemoveArgs();
751     for ( int i = 1; i <= myArgs.Length(); ++i ) {
752       if ( !myArgs( i ).IsEmpty() )
753         theCmd->SetArg( i, myArgs( i ));
754       else
755         theCmd->SetArg( i, "[]");
756     }
757
758     // clear commands setting arg values
759     list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
760     for ( ; argCmd != myArgCommands.end(); ++argCmd )
761       (*argCmd)->Clear();
762   }
763   else
764   {
765 //     // set arg commands after hypo creation
766 //     list<Handle(_pyCommand)>::iterator argCmd = myArgCommands.begin();
767 //     for ( ; argCmd != myArgCommands.end(); ++argCmd )
768 //       if ( !(*argCmd)->IsEmpty() && GetCommandNb() > (*argCmd)->GetOrderNb() )
769 //         theGen->ExchangeCommands( GetCreationCmd(), *argCmd );
770   }
771
772   // set unknown arg commands after hypo creation
773   Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
774   list<Handle(_pyCommand)>::iterator cmd = myUnknownCommands.begin();
775   for ( ; cmd != myUnknownCommands.end(); ++cmd ) {
776     if ( !(*cmd)->IsEmpty() && afterCmd->GetOrderNb() > (*cmd)->GetOrderNb() ) {
777       theGen->SetCommandAfter( *cmd, afterCmd );
778       afterCmd = *cmd;
779     }
780   }
781   myArgCommands.clear();
782   myUnknownCommands.clear();
783
784   return myIsWrapped;
785 }
786
787 //================================================================================
788 /*!
789  * \brief Remember hypothesis parameter values
790  * \param theCommand - The called hypothesis method
791  */
792 //================================================================================
793
794 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
795 {
796   ASSERT( !myIsAlgo );
797   // set args
798   for ( int i = 1; i <= myArgMethods.Length(); ++i ) {
799     if ( myArgMethods( i ) == theCommand->GetMethod() ) {
800       while ( myArgs.Length() < i )
801         myArgs.Append( "[]" );
802       myArgs( i ) = theCommand->GetArg( 1 ); // arg value
803       myArgCommands.push_back( theCommand );
804       return;
805     }
806   }
807   myUnknownCommands.push_back( theCommand );
808 }
809
810 //================================================================================
811 /*!
812  * \brief Finish conversion
813  */
814 //================================================================================
815
816 void _pyHypothesis::Flush()
817 {
818   if ( IsWrapped() )
819     GetCreationCmd()->Clear();
820 }
821
822 //================================================================================
823 /*!
824  * \brief Remember hypothesis parameter values
825   * \param theCommand - The called hypothesis method
826  */
827 //================================================================================
828
829 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
830 {
831   // ex: hyp.SetLength(start, 1)
832   //     hyp.SetLength(end,   0)
833   ASSERT(( theCommand->GetMethod() == "SetLength" ));
834   ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
835   int i = 2 - theCommand->GetArg( 2 ).IntegerValue();
836   while ( myArgs.Length() < i )
837     myArgs.Append( "[]" );
838   myArgs( i ) = theCommand->GetArg( 1 ); // arg value
839   myArgCommands.push_back( theCommand );
840 }
841
842 //================================================================================
843 /*!
844  * \brief additionally to Addition2Creation, clears SetDistrType() command
845   * \param theCmd - AddHypothesis() command
846   * \param theMesh - mesh to which a hypothesis is added
847   * \retval bool - convertion result
848  */
849 //================================================================================
850
851 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
852                                                 const _pyID&              theMesh)
853 {
854   if ( IsWrappable( theMesh ) && myArgs.Length() > 1 ) {
855     list<Handle(_pyCommand)>::iterator cmd = myUnknownCommands.begin();
856     for ( ; cmd != myUnknownCommands.end(); ++cmd ) {
857       // clear SetDistrType()
858       if ( (*cmd)->GetString().Location( "SetDistrType", 1, (*cmd)->Length() ))
859         (*cmd)->Clear();
860     }
861   }
862   return _pyHypothesis::Addition2Creation( theCmd, theMesh );
863 }
864
865 //================================================================================
866 /*!
867  * \brief _pyAlgorithm constructor
868   * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
869  */
870 //================================================================================
871
872 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
873   : _pyHypothesis( theCreationCmd )
874 {
875   myIsAlgo = true;
876 }
877
878 //================================================================================
879 /*!
880  * \brief Convert the command adding an algorithm to mesh
881   * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
882   * \param theMesh - The mesh needing this algo 
883   * \retval bool - false if the command cant be converted
884  */
885 //================================================================================
886   
887 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
888                                       const _pyID&              theMeshID)
889 {
890   if ( IsWrappable( theMeshID )) {
891
892     myGeom = theCmd->GetArg( 1 );
893
894     // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
895     if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
896       theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
897       return true;
898     }
899   }
900   return false;
901 }
902
903 //================================================================================
904 /*!
905  * \brief Return starting position of a part of python command
906   * \param thePartIndex - The index of command part
907   * \retval int - Part position
908  */
909 //================================================================================
910
911 int _pyCommand::GetBegPos( int thePartIndex )
912 {
913   if ( IsEmpty() )
914     return EMPTY;
915   if ( myBegPos.Length() < thePartIndex )
916     return UNKNOWN;
917   return myBegPos( thePartIndex );
918 }
919
920 //================================================================================
921 /*!
922  * \brief Store starting position of a part of python command
923   * \param thePartIndex - The index of command part
924   * \param thePosition - Part position
925  */
926 //================================================================================
927
928 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
929 {
930   while ( myBegPos.Length() < thePartIndex )
931     myBegPos.Append( UNKNOWN );
932   myBegPos( thePartIndex ) = thePosition;
933 }
934
935 //================================================================================
936 /*!
937  * \brief Return substring of python command looking like ResultValue = Obj.Meth()
938   * \retval const TCollection_AsciiString & - ResultValue substring
939  */
940 //================================================================================
941
942 const TCollection_AsciiString & _pyCommand::GetResultValue()
943 {
944   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
945   {
946     int begPos = myString.Location( "=", 1, Length() );
947     if ( begPos )
948       myRes = GetWord( myString, begPos, false );
949     else
950       begPos = EMPTY;
951     SetBegPos( RESULT_IND, begPos );
952   }
953   return myRes;
954 }
955
956 //================================================================================
957 /*!
958  * \brief Return substring of python command looking like ResVal = Object.Meth()
959   * \retval const TCollection_AsciiString & - Object substring
960  */
961 //================================================================================
962
963 const TCollection_AsciiString & _pyCommand::GetObject()
964 {
965   if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
966   {
967     // beginning
968     int begPos = GetBegPos( RESULT_IND ) + myRes.Length();
969     if ( begPos < 1 )
970       begPos = myString.Location( "=", 1, Length() ) + 1;
971     // store
972     myObj = GetWord( myString, begPos, true );
973     SetBegPos( OBJECT_IND, begPos );
974   }
975   //SCRUTE(myObj);
976   return myObj;
977 }
978
979 //================================================================================
980 /*!
981  * \brief Return substring of python command looking like ResVal = Obj.Method()
982   * \retval const TCollection_AsciiString & - Method substring
983  */
984 //================================================================================
985
986 const TCollection_AsciiString & _pyCommand::GetMethod()
987 {
988   if ( GetBegPos( METHOD_IND ) == UNKNOWN )
989   {
990     // beginning
991     int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
992     bool forward = true;
993     if ( begPos < 1 ) {
994       begPos = myString.Location( "(", 1, Length() ) - 1;
995       forward = false;
996     }
997     // store
998     myMeth = GetWord( myString, begPos, forward );
999     SetBegPos( METHOD_IND, begPos );
1000   }
1001   //SCRUTE(myMeth);
1002   return myMeth;
1003 }
1004
1005 //================================================================================
1006 /*!
1007  * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
1008   * \retval const TCollection_AsciiString & - Arg<index> substring
1009  */
1010 //================================================================================
1011
1012 const TCollection_AsciiString & _pyCommand::GetArg( int index )
1013 {
1014   if ( GetBegPos( ARG1_IND ) == UNKNOWN )
1015   {
1016     // find all args
1017     int begPos = GetBegPos( METHOD_IND ) + myMeth.Length();
1018     if ( begPos < 1 )
1019       begPos = myString.Location( "(", 1, Length() ) + 1;
1020
1021     int i = 0, prevLen = 0;
1022     while ( begPos != EMPTY ) {
1023       begPos += prevLen;
1024       // check if we are looking at the closing parenthesis
1025       while ( begPos <= Length() && isspace( myString.Value( begPos )))
1026         ++begPos;
1027       if ( begPos > Length() || myString.Value( begPos ) == ')' )
1028         break;
1029       myArgs.Append( GetWord( myString, begPos, true, true ));
1030       SetBegPos( ARG1_IND + i, begPos );
1031       prevLen = myArgs.Last().Length();
1032       if ( prevLen == 0 )
1033         myArgs.Remove( myArgs.Length() ); // no more args
1034       i++;
1035     }
1036   }
1037   if ( myArgs.Length() < index )
1038     return theEmptyString;
1039   return myArgs( index );
1040 }
1041
1042 //================================================================================
1043 /*!
1044  * \brief Check if char is a word part
1045   * \param c - The character to check
1046   * \retval bool - The check result
1047  */
1048 //================================================================================
1049
1050 static inline bool isWord(const char c, const bool dotIsWord)
1051 {
1052   return
1053     !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
1054 }
1055
1056 //================================================================================
1057 /*!
1058  * \brief Looks for a word in the string and returns word's beginning
1059   * \param theString - The input string
1060   * \param theStartPos - The position to start the search, returning word's beginning
1061   * \param theForward - The search direction
1062   * \retval TCollection_AsciiString - The found word
1063  */
1064 //================================================================================
1065
1066 TCollection_AsciiString _pyCommand::GetWord( const TCollection_AsciiString & theString,
1067                                             int &      theStartPos,
1068                                             const bool theForward,
1069                                             const bool dotIsWord )
1070 {
1071   int beg = theStartPos, end = theStartPos;
1072   theStartPos = EMPTY;
1073   if ( beg < 1 || beg > theString.Length() )
1074     return theEmptyString;
1075
1076   if ( theForward ) { // search forward
1077     // beg
1078     while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
1079       ++beg;
1080     if ( beg > theString.Length() )
1081       return theEmptyString; // no word found
1082     // end
1083     end = beg + 1;
1084     while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
1085       ++end;
1086     --end;
1087   }
1088   else {  // search backward
1089     // end
1090     while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
1091       --end;
1092     if ( end == 0 )
1093       return theEmptyString; // no word found
1094     beg = end - 1;
1095     while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
1096       --beg;
1097     ++beg;
1098   }
1099   theStartPos = beg;
1100   //cout << theString << " ---- " << beg << " - " << end << endl;
1101   return theString.SubString( beg, end );
1102 }
1103
1104 //================================================================================
1105 /*!
1106  * \brief Look for position where not space char is
1107   * \param theString - The string 
1108   * \param thePos - The position to search from and which returns result
1109   * \retval bool - false if there are only space after thePos in theString
1110  * 
1111  * 
1112  */
1113 //================================================================================
1114
1115 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
1116 {
1117   if ( thePos < 1 || thePos > theString.Length() )
1118     return false;
1119
1120   while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
1121     ++thePos;
1122
1123   return thePos <= theString.Length();
1124 }
1125
1126 //================================================================================
1127 /*!
1128  * \brief Modify a part of the command
1129   * \param thePartIndex - The index of the part
1130   * \param thePart - The new part string
1131   * \param theOldPart - The old part
1132  */
1133 //================================================================================
1134
1135 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
1136                         TCollection_AsciiString& theOldPart)
1137 {
1138   int pos = GetBegPos( thePartIndex );
1139   if ( pos <= Length() && theOldPart != thePart)
1140   {
1141     TCollection_AsciiString seperator;
1142     if ( pos < 1 ) {
1143       pos = GetBegPos( thePartIndex + 1 );
1144       if ( pos < 1 ) return;
1145       switch ( thePartIndex ) {
1146       case RESULT_IND: seperator = " = "; break;
1147       case OBJECT_IND: seperator = "."; break;
1148       case METHOD_IND: seperator = "()"; break;
1149       default:;
1150       }
1151     }      
1152     myString.Remove( pos, theOldPart.Length() );
1153     if ( !seperator.IsEmpty() )
1154       myString.Insert( pos , seperator );
1155     myString.Insert( pos, thePart );
1156     // update starting positions of the following parts
1157     int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
1158     for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
1159       if ( myBegPos( i ) > 0 )
1160         myBegPos( i ) += posDelta;
1161     }
1162     theOldPart = thePart;
1163   }
1164 }
1165
1166 //================================================================================
1167 /*!
1168  * \brief Set agrument
1169   * \param index - The argument index, it counts from 1
1170   * \param theArg - The argument string
1171  */
1172 //================================================================================
1173
1174 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
1175 {
1176   FindAllArgs();
1177   int argInd = ARG1_IND + index - 1;
1178   int pos = GetBegPos( argInd );
1179   if ( pos < 1 ) // no index-th arg exist, append inexistent args
1180   {
1181     // find a closing parenthesis
1182     pos = Length();
1183     while ( pos > 0 && myString.Value( pos ) != ')' )
1184       --pos;
1185     if ( pos == 0 ) { // no parentheses at all
1186       myString += "()";
1187       pos = Length();
1188     }
1189     while ( myArgs.Length() < index ) {
1190       if ( myArgs.Length() )
1191         myString.Insert( pos++, "," );
1192       myArgs.Append("None");
1193       myString.Insert( pos, myArgs.Last() );
1194       SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
1195       pos += myArgs.Last().Length();
1196     }
1197   }
1198   SetPart( argInd, theArg, myArgs( index ));
1199 }
1200
1201 //================================================================================
1202 /*!
1203  * \brief Empty arg list
1204  */
1205 //================================================================================
1206
1207 void _pyCommand::RemoveArgs()
1208 {
1209   if ( int pos = myString.Location( '(', 1, Length() ))
1210     myString.Trunc( pos );
1211   myString += ")";
1212   myArgs.Clear();
1213   if ( myBegPos.Length() >= ARG1_IND )
1214     myBegPos.Remove( ARG1_IND, myBegPos.Length() );
1215 }