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