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