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