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