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