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