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