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