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