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