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