Salome HOME
IMP19942 - Convert group on geometry into group of elements
[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       _pyID type = theCommand->GetArg( 1 );
834       _pyID name = theCommand->GetArg( 2 );
835       theCommand->SetMethod( "GroupOnGeom" );
836       theCommand->RemoveArgs();
837       theCommand->SetArg( 1, grp );
838       theCommand->SetArg( 2, name );
839       theCommand->SetArg( 3, type );
840     }
841   }
842   // ----------------------------------------------------------------------
843   else if ( method == "ExportToMED" ) { // ExportToMED() --> ExportMED()
844     theCommand->SetMethod( "ExportMED" );
845   }
846   // ----------------------------------------------------------------------
847   else if ( method == "CreateGroup" ) { // CreateGroup() --> CreateEmptyGroup()
848     theCommand->SetMethod( "CreateEmptyGroup" );
849   }
850   // ----------------------------------------------------------------------
851   else if ( method == "RemoveHypothesis" ) // (geom, hyp)
852   {
853     _pyID hypID = theCommand->GetArg( 2 );
854
855     // check if this mesh still has corresponding addition command
856     bool hasAddCmd = false;
857     list< Handle(_pyCommand) >::iterator cmd = myAddHypCmds.begin();
858     while ( cmd != myAddHypCmds.end() )
859     {
860       // AddHypothesis(geom, hyp)
861       if ( hypID == (*cmd)->GetArg( 2 )) { // erase both (add and remove) commands
862         theCommand->Clear();
863         (*cmd)->Clear();
864         cmd = myAddHypCmds.erase( cmd );
865         hasAddCmd = true;
866       }
867       else {
868         ++cmd;
869       }
870     }
871     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
872     if ( ! hasAddCmd && hypID.Length() != 0 ) { // hypo addition already wrapped
873       // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
874       _pyID geom = theCommand->GetArg( 1 );
875       theCommand->RemoveArgs();
876       theCommand->SetArg( 1, hypID );
877       if ( geom != GetGeom() )
878         theCommand->SetArg( 2, geom );
879     }
880     // remove hyp from myHypos
881     myHypos.remove( hyp );
882   }
883   // add accessor method if necessary
884   else
885   {
886     if ( NeedMeshAccess( theCommand ))
887       // apply theCommand to the mesh wrapped by smeshpy mesh
888       AddMeshAccess( theCommand );
889   }
890 }
891
892 //================================================================================
893 /*!
894  * \brief Return True if addition of accesor method is needed
895  */
896 //================================================================================
897
898 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
899 {
900   // names of SMESH_Mesh methods fully equal to methods of class Mesh, so
901   // no conversion is needed for them at all:
902   static TStringSet sameMethods;
903   if ( sameMethods.empty() ) {
904     const char * names[] =
905       { "ExportDAT","ExportUNV","ExportSTL", "RemoveGroup","RemoveGroupWithContents",
906         "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
907         "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
908         "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
909         "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
910         "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
911         "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
912         "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
913         "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
914         "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
915         "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
916         "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
917         "Clear", "ConvertToStandalone"
918         ,"" }; // <- mark of end
919     sameMethods.Insert( names );
920   }
921
922   return !sameMethods.Contains( theCommand->GetMethod() );
923 }
924
925 //================================================================================
926 /*!
927  * \brief Convert creation and addition of all algos and hypos
928  */
929 //================================================================================
930
931 void _pyMesh::Flush()
932 {
933   list < Handle(_pyCommand) >::iterator cmd;
934
935   // try to convert algo addition like this:
936   // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
937   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
938   {
939     Handle(_pyCommand) addCmd = *cmd;
940
941     _pyID algoID = addCmd->GetArg( 2 );
942     Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
943     if ( algo.IsNull() || !algo->IsAlgo() )
944       continue;
945
946     // check and create new algorithm instance if it is already wrapped
947     if ( algo->IsWrapped() ) {
948       _pyID localAlgoID = theGen->GenerateNewID( algoID );
949       TCollection_AsciiString aNewCmdStr = localAlgoID +
950         TCollection_AsciiString( " = " ) + theGen->GetID() +
951         TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
952         TCollection_AsciiString( "\" )" );
953       
954       Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
955       Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
956       if ( !newAlgo.IsNull() ) {
957         newAlgo->Assign( algo, this->GetID() );
958         newAlgo->SetCreationCmd( newCmd );
959         algo = newAlgo;
960         // set algorithm creation
961         theGen->SetCommandBefore( newCmd, addCmd );
962       }
963       else
964         newCmd->Clear();
965     }
966     _pyID geom = addCmd->GetArg( 1 );
967     bool isLocalAlgo = ( geom != GetGeom() );
968     
969     // try to convert
970     if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
971     {
972       // wrapped algo is created atfer mesh creation
973       GetCreationCmd()->AddDependantCmd( addCmd );
974
975       if ( isLocalAlgo ) {
976         // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
977         addCmd->SetArg( addCmd->GetNbArgs() + 1,
978                         TCollection_AsciiString( "geom=" ) + geom );
979         // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
980         list < Handle(_pySubMesh) >::iterator smIt;
981         for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
982           Handle(_pySubMesh) subMesh = *smIt;
983           Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
984           if ( geom == subCmd->GetArg( 1 )) {
985             subCmd->SetObject( algo->GetID() );
986             subCmd->RemoveArgs();
987             subMesh->SetCreator( algo );
988           }
989         }
990       }
991     }
992     else // KO - ALGO was already created
993     {
994       // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
995       addCmd->RemoveArgs();
996       addCmd->SetArg( 1, algoID );
997       if ( isLocalAlgo )
998         addCmd->SetArg( 2, geom );
999     }
1000   }
1001
1002   // try to convert hypo addition like this:
1003   // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
1004   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
1005   {
1006     Handle(_pyCommand) addCmd = *cmd;
1007     _pyID hypID = addCmd->GetArg( 2 );
1008     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1009     if ( hyp.IsNull() || hyp->IsAlgo() )
1010       continue;
1011     bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
1012     if ( !converted ) {
1013       // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
1014       _pyID geom = addCmd->GetArg( 1 );
1015       addCmd->RemoveArgs();
1016       addCmd->SetArg( 1, hypID );
1017       if ( geom != GetGeom() )
1018         addCmd->SetArg( 2, geom );
1019     }
1020   }
1021
1022   // sm = mesh.GetSubMesh(geom, name) --> sm = mesh.GetMesh().GetSubMesh(geom, name)
1023 //   for ( cmd = mySubmeshes.begin(); cmd != mySubmeshes.end(); ++cmd ) {
1024 //     Handle(_pyCommand) subCmd = *cmd;
1025 //     if ( subCmd->GetNbArgs() > 0 )
1026 //       AddMeshAccess( subCmd );
1027 //   }
1028   myAddHypCmds.clear();
1029   mySubmeshes.clear();
1030
1031   // flush hypotheses
1032   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1033   for ( ; hyp != myHypos.end(); ++hyp )
1034     (*hyp)->Flush();
1035 }
1036
1037 //================================================================================
1038 /*!
1039  * \brief MeshEditor convert its commands to ones of mesh
1040  */
1041 //================================================================================
1042
1043 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
1044   _pyObject( theCreationCmd )
1045 {
1046   myMesh = theCreationCmd->GetObject();
1047   myCreationCmdStr = theCreationCmd->GetString();
1048   theCreationCmd->Clear();
1049 }
1050
1051 //================================================================================
1052 /*!
1053  * \brief convert its commands to ones of mesh
1054  */
1055 //================================================================================
1056
1057 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
1058 {
1059   // names of SMESH_MeshEditor methods fully equal to methods of class Mesh, so
1060   // commands calling this methods are converted to calls of methods of Mesh
1061   static TStringSet sameMethods;
1062   if ( sameMethods.empty() ) {
1063     const char * names[] = {
1064       "RemoveElements","RemoveNodes","AddNode","AddEdge","AddFace","AddPolygonalFace",
1065       "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces","MoveNode",
1066       "InverseDiag","DeleteDiag","Reorient","ReorientObject","SplitQuad","SplitQuadObject",
1067       "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
1068       "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
1069       "RotationSweep","RotationSweepObject","ExtrusionSweep","AdvancedExtrusion",
1070       "ExtrusionSweepObject","ExtrusionSweepObject1D","ExtrusionSweepObject2D","Mirror",
1071       "MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
1072       "FindCoincidentNodes","FindCoincidentNodesOnPart","MergeNodes","FindEqualElements",
1073       "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
1074       "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
1075       "GetLastCreatedElems",
1076       "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh",
1077       "TranslateObjectMakeMesh","RotateMakeMesh","RotateObjectMakeMesh"
1078       ,"" }; // <- mark of the end
1079     sameMethods.Insert( names );
1080   }
1081
1082   // names of SMESH_MeshEditor methods which differ from methods of class Mesh
1083   // only last two arguments
1084   static TStringSet diffLastTwoArgsMethods;
1085   if (diffLastTwoArgsMethods.empty() ){
1086     const char * names[] = {
1087       "MirrorMakeGroups","MirrorObjectMakeGroups",
1088       "TranslateMakeGroups","TranslateObjectMakeGroups",
1089       "RotateMakeGroups","RotateObjectMakeGroups",
1090       ""};// <- mark of the end
1091     diffLastTwoArgsMethods.Insert( names );
1092   }
1093
1094   if ( sameMethods.Contains( theCommand->GetMethod() )) {
1095     theCommand->SetObject( myMesh );
1096
1097     // meshes made by *MakeMesh() methods are not wrapped by _pyMesh,
1098     // so let _pyMesh care of it (TMP?)
1099 //     if ( theCommand->GetMethod().Search("MakeMesh") != -1 )
1100 //       _pyMesh( new _pyCommand( theCommand->GetString(), 0 )); // for theGen->SetAccessorMethod()
1101   }
1102   else {
1103     
1104     //Replace SMESH_MeshEditor "MakeGroups" functions on the Mesh 
1105     //functions with the flag "theMakeGroups = True" like:
1106     //SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
1107     int pos = theCommand->GetMethod().Search("MakeGroups");
1108     if( pos != -1) {  
1109       // 1. Remove "MakeGroups" from the Command
1110       TCollection_AsciiString aMethod = theCommand->GetMethod();
1111       int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
1112       aMethod.Trunc(pos-1);
1113       theCommand->SetMethod(aMethod);
1114
1115       // 2. Set Mesh object instead of SMESH_MeshEditor
1116       theCommand->SetObject( myMesh );
1117
1118       // 3. And add last "True" argument
1119       while(nbArgsToAdd--)
1120         theCommand->SetArg(theCommand->GetNbArgs()+1,"True ");
1121     }
1122     else {
1123       // editor creation command is needed only if any editor function is called
1124       theGen->AddMeshAccessorMethod( theCommand ); // for *Object()
1125       if ( !myCreationCmdStr.IsEmpty() ) {
1126         GetCreationCmd()->GetString() = myCreationCmdStr;
1127         myCreationCmdStr.Clear();
1128       }
1129     }
1130   }
1131 }
1132
1133 //================================================================================
1134 /*!
1135  * \brief _pyHypothesis constructor
1136   * \param theCreationCmd - 
1137  */
1138 //================================================================================
1139
1140 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
1141   _pyObject( theCreationCmd )
1142 {
1143   myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
1144 }
1145
1146 //================================================================================
1147 /*!
1148  * \brief Creates algorithm or hypothesis
1149   * \param theCreationCmd - The engine command creating a hypothesis
1150   * \retval Handle(_pyHypothesis) - Result _pyHypothesis
1151  */
1152 //================================================================================
1153
1154 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
1155 {
1156   // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
1157   ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
1158
1159   Handle(_pyHypothesis) hyp, algo;
1160
1161   // "theHypType"
1162   const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
1163   if ( hypTypeQuoted.IsEmpty() )
1164     return hyp;
1165   // theHypType
1166   TCollection_AsciiString  hypType =
1167     hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
1168
1169   algo = new _pyAlgorithm( theCreationCmd );
1170   hyp  = new _pyHypothesis( theCreationCmd );
1171
1172   // 1D Regular_1D ----------
1173   if ( hypType == "Regular_1D" ) {
1174     // set mesh's method creating algo,
1175     // i.e. convertion result will be "regular1d = Mesh.Segment()",
1176     // and set hypType by which algo creating a hypothesis is searched for
1177     algo->SetConvMethodAndType("Segment", hypType.ToCString());
1178   }
1179   else if ( hypType == "CompositeSegment_1D" ) {
1180     algo->SetConvMethodAndType("Segment", "Regular_1D");
1181     algo->myArgs.Append( "algo=smesh.COMPOSITE");
1182   }
1183   else if ( hypType == "LocalLength" ) {
1184     // set algo's method creating hyp, and algo type
1185     hyp->SetConvMethodAndType( "LocalLength", "Regular_1D");
1186     // set method whose 1 arg will become the 1-st arg of hyp creation command
1187     // i.e. convertion result will be "locallength = regular1d.LocalLength(<arg of SetLength()>)"
1188     hyp->AddArgMethod( "SetLength" );
1189   }
1190   else if ( hypType == "NumberOfSegments" ) {
1191     hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
1192     hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
1193     // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
1194     hyp->AddArgMethod( "SetNumberOfSegments" );
1195     // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
1196     hyp->AddArgMethod( "SetScaleFactor" );
1197   }
1198   else if ( hypType == "Arithmetic1D" ) {
1199     hyp = new _pyComplexParamHypo( theCreationCmd );
1200     hyp->SetConvMethodAndType( "Arithmetic1D", "Regular_1D");
1201   }
1202   else if ( hypType == "StartEndLength" ) {
1203     hyp = new _pyComplexParamHypo( theCreationCmd );
1204     hyp->SetConvMethodAndType( "StartEndLength", "Regular_1D");
1205   }
1206   else if ( hypType == "Deflection1D" ) {
1207     hyp->SetConvMethodAndType( "Deflection1D", "Regular_1D");
1208     hyp->AddArgMethod( "SetDeflection" );
1209   }
1210   else if ( hypType == "Propagation" ) {
1211     hyp->SetConvMethodAndType( "Propagation", "Regular_1D");
1212   }
1213   else if ( hypType == "QuadraticMesh" ) {
1214     hyp->SetConvMethodAndType( "QuadraticMesh", "Regular_1D");
1215   }
1216   else if ( hypType == "AutomaticLength" ) {
1217     hyp->SetConvMethodAndType( "AutomaticLength", "Regular_1D");
1218     hyp->AddArgMethod( "SetFineness");
1219   }
1220   else if ( hypType == "SegmentLengthAroundVertex" ) {
1221     hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
1222     hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
1223     hyp->AddArgMethod( "SetLength" );
1224   }
1225   // 1D Python_1D ----------
1226   else if ( hypType == "Python_1D" ) {
1227     algo->SetConvMethodAndType( "Segment", hypType.ToCString());
1228     algo->myArgs.Append( "algo=smesh.PYTHON");
1229   }
1230   else if ( hypType == "PythonSplit1D" ) {
1231     hyp->SetConvMethodAndType( "PythonSplit1D", "Python_1D");
1232     hyp->AddArgMethod( "SetNumberOfSegments");
1233     hyp->AddArgMethod( "SetPythonLog10RatioFunction");
1234   }
1235   // MEFISTO_2D ----------
1236   else if ( hypType == "MEFISTO_2D" ) { // MEFISTO_2D
1237     algo->SetConvMethodAndType( "Triangle", hypType.ToCString());
1238   }
1239   else if ( hypType == "MaxElementArea" ) {
1240     hyp->SetConvMethodAndType( "MaxElementArea", "MEFISTO_2D");
1241     hyp->SetConvMethodAndType( "MaxElementArea", "NETGEN_2D_ONLY");
1242     hyp->AddArgMethod( "SetMaxElementArea");
1243   }
1244   else if ( hypType == "LengthFromEdges" ) {
1245     hyp->SetConvMethodAndType( "LengthFromEdges", "MEFISTO_2D");
1246     hyp->SetConvMethodAndType( "LengthFromEdges", "NETGEN_2D_ONLY");
1247   }
1248   // Quadrangle_2D ----------
1249   else if ( hypType == "Quadrangle_2D" ) {
1250     algo->SetConvMethodAndType( "Quadrangle" , hypType.ToCString());
1251   }
1252   else if ( hypType == "QuadranglePreference" ) {
1253     hyp->SetConvMethodAndType( "QuadranglePreference", "Quadrangle_2D");
1254     hyp->SetConvMethodAndType( "QuadranglePreference", "NETGEN_2D_ONLY");
1255   }
1256   else if ( hypType == "TrianglePreference" ) {
1257     hyp->SetConvMethodAndType( "TrianglePreference", "Quadrangle_2D");
1258   }     
1259   // NETGEN ----------
1260 //   else if ( hypType == "NETGEN_2D") { // 1D-2D
1261 //     algo->SetConvMethodAndType( "Triangle" , hypType.ToCString());
1262 //     algo->myArgs.Append( "algo=smesh.NETGEN" );
1263 //   }
1264   else if ( hypType == "NETGEN_2D_ONLY") { // 2D
1265     algo->SetConvMethodAndType( "Triangle" , hypType.ToCString());
1266     algo->myArgs.Append( "algo=smesh.NETGEN_2D" );
1267   }
1268   else if ( hypType == "NETGEN_3D") { // 3D
1269     algo->SetConvMethodAndType( "Tetrahedron" , hypType.ToCString());
1270     algo->myArgs.Append( "algo=smesh.NETGEN" );
1271   }
1272   else if ( hypType == "MaxElementVolume") {
1273     hyp->SetConvMethodAndType( "MaxElementVolume", "NETGEN_3D");
1274     hyp->AddArgMethod( "SetMaxElementVolume" );
1275   }
1276   // GHS3D_3D ----------
1277   else if ( hypType == "GHS3D_3D" ) {
1278     algo->SetConvMethodAndType( "Tetrahedron", hypType.ToCString());
1279     algo->myArgs.Append( "algo=smesh.GHS3D" );
1280   }
1281   // Hexa_3D ---------
1282   else if ( hypType == "Hexa_3D" ) {
1283     algo->SetConvMethodAndType( "Hexahedron", hypType.ToCString());
1284   }
1285   // Repetitive Projection_1D ---------
1286   else if ( hypType == "Projection_1D" ) {
1287     algo->SetConvMethodAndType( "Projection1D", hypType.ToCString());
1288   }
1289   else if ( hypType == "ProjectionSource1D" ) {
1290     hyp->SetConvMethodAndType( "SourceEdge", "Projection_1D");
1291     hyp->AddArgMethod( "SetSourceEdge");
1292     hyp->AddArgMethod( "SetSourceMesh");
1293     // 2 args of SetVertexAssociation() will become the 3-th and 4-th args of hyp creation command
1294     hyp->AddArgMethod( "SetVertexAssociation", 2 );
1295   }
1296   // Projection_2D ---------
1297   else if ( hypType == "Projection_2D" ) {
1298     algo->SetConvMethodAndType( "Projection2D", hypType.ToCString());
1299   }
1300   else if ( hypType == "ProjectionSource2D" ) {
1301     hyp->SetConvMethodAndType( "SourceFace", "Projection_2D");
1302     hyp->AddArgMethod( "SetSourceFace");
1303     hyp->AddArgMethod( "SetSourceMesh");
1304     hyp->AddArgMethod( "SetVertexAssociation", 4 );
1305   }
1306   // Projection_3D ---------
1307   else if ( hypType == "Projection_3D" ) {
1308     algo->SetConvMethodAndType( "Projection3D", hypType.ToCString());
1309   }
1310   else if ( hypType == "ProjectionSource3D" ) {
1311     hyp->SetConvMethodAndType( "SourceShape3D", "Projection_3D");
1312     hyp->AddArgMethod( "SetSource3DShape");
1313     hyp->AddArgMethod( "SetSourceMesh");
1314     hyp->AddArgMethod( "SetVertexAssociation", 4 );
1315   }
1316   // Prism_3D ---------
1317   else if ( hypType == "Prism_3D" ) {
1318     algo->SetConvMethodAndType( "Prism", hypType.ToCString());
1319   }
1320   // RadialPrism_3D ---------
1321   else if ( hypType == "RadialPrism_3D" ) {
1322     algo->SetConvMethodAndType( "Prism", hypType.ToCString());
1323   }
1324   else if ( hypType == "NumberOfLayers" ) {
1325     hyp->SetConvMethodAndType( "NumberOfLayers", "RadialPrism_3D");
1326     hyp->AddArgMethod( "SetNumberOfLayers" );
1327   }
1328   else if ( hypType == "LayerDistribution" ) {
1329     hyp = new _pyLayerDistributionHypo( theCreationCmd );
1330     hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
1331   }
1332
1333   if ( algo->IsValid() ) {
1334     return algo;
1335   }
1336   return hyp;
1337 }
1338
1339 //================================================================================
1340 /*!
1341  * \brief Convert the command adding a hypothesis to mesh into a smesh command
1342   * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
1343   * \param theAlgo - The algo that can create this hypo
1344   * \retval bool - false if the command cant be converted
1345  */
1346 //================================================================================
1347
1348 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
1349                                        const _pyID&              theMesh)
1350 {
1351   ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
1352
1353   if ( !IsWrappable( theMesh ))
1354     return false;
1355
1356   myGeom = theCmd->GetArg( 1 );
1357
1358   Handle(_pyHypothesis) algo;
1359   if ( !IsAlgo() ) {
1360     // find algo created on myGeom in theMesh
1361     algo = theGen->FindAlgo( myGeom, theMesh, this );
1362     if ( algo.IsNull() )
1363       return false;
1364     algo->GetCreationCmd()->AddDependantCmd( theCmd );
1365   }
1366   myIsWrapped = true;
1367
1368   // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
1369   theCmd->SetResultValue( GetID() );
1370   theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
1371   theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
1372   // set args
1373   theCmd->RemoveArgs();
1374   for ( int i = 1; i <= myArgs.Length(); ++i ) {
1375     if ( !myArgs( i ).IsEmpty() )
1376       theCmd->SetArg( i, myArgs( i ));
1377     else
1378       theCmd->SetArg( i, "[]");
1379   }
1380   // set a new creation command
1381   GetCreationCmd()->Clear();
1382   // set dependance between creation and addition to mesh
1383   // SetCreationCmd( theCmd );
1384   GetCreationCmd()->AddDependantCmd( theCmd );
1385     
1386
1387   // clear commands setting arg values
1388   list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
1389   for ( ; argCmd != myArgCommands.end(); ++argCmd )
1390     (*argCmd)->Clear();
1391
1392   // set unknown arg commands after hypo creation
1393   Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
1394   list<Handle(_pyCommand)>::iterator cmd = myUnknownCommands.begin();
1395   for ( ; cmd != myUnknownCommands.end(); ++cmd ) {
1396     afterCmd->AddDependantCmd( *cmd );
1397   }
1398
1399   return myIsWrapped;
1400 }
1401
1402 //================================================================================
1403 /*!
1404  * \brief Remember hypothesis parameter values
1405  * \param theCommand - The called hypothesis method
1406  */
1407 //================================================================================
1408
1409 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
1410 {
1411   ASSERT( !myIsAlgo );
1412   // set args
1413   int nbArgs = 0;
1414   for ( int i = 1; i <= myArgMethods.Length(); ++i ) {
1415     if ( myArgMethods( i ) == theCommand->GetMethod() ) {
1416       while ( myArgs.Length() < nbArgs + myNbArgsByMethod( i ))
1417         myArgs.Append( "[]" );
1418       for ( int iArg = 1; iArg <= myNbArgsByMethod( i ); ++iArg )
1419         myArgs( nbArgs + iArg ) = theCommand->GetArg( iArg ); // arg value
1420       myArgCommands.push_back( theCommand );
1421       return;
1422     }
1423     nbArgs += myNbArgsByMethod( i );
1424   }
1425   myUnknownCommands.push_back( theCommand );
1426 }
1427
1428 //================================================================================
1429 /*!
1430  * \brief Finish conversion
1431  */
1432 //================================================================================
1433
1434 void _pyHypothesis::Flush()
1435 {
1436   if ( IsWrapped() ) {
1437   }
1438   else {
1439     list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
1440     for ( ; cmd != myArgCommands.end(); ++cmd ) {
1441       // Add access to a wrapped mesh
1442       theGen->AddMeshAccessorMethod( *cmd );
1443       // Add access to a wrapped algorithm
1444       theGen->AddAlgoAccessorMethod( *cmd );
1445     }
1446     cmd = myUnknownCommands.begin();
1447     for ( ; cmd != myUnknownCommands.end(); ++cmd ) {
1448       // Add access to a wrapped mesh
1449       theGen->AddMeshAccessorMethod( *cmd );
1450       // Add access to a wrapped algorithm
1451       theGen->AddAlgoAccessorMethod( *cmd );
1452     }
1453   }
1454   // forget previous hypothesis modifications
1455   myArgCommands.clear();
1456   myUnknownCommands.clear();
1457 }
1458
1459 //================================================================================
1460 /*!
1461  * \brief clear creation, arg and unkown commands
1462  */
1463 //================================================================================
1464
1465 void _pyHypothesis::ClearAllCommands()
1466 {
1467   GetCreationCmd()->Clear();
1468   list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
1469   for ( ; cmd != myArgCommands.end(); ++cmd )
1470     ( *cmd )->Clear();
1471   cmd = myUnknownCommands.begin();
1472   for ( ; cmd != myUnknownCommands.end(); ++cmd )
1473     ( *cmd )->Clear();
1474 }
1475
1476
1477 //================================================================================
1478 /*!
1479  * \brief Assign fields of theOther to me except myIsWrapped
1480  */
1481 //================================================================================
1482
1483 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
1484                             const _pyID&                 theMesh )
1485 {
1486   myIsWrapped = false;
1487   myMesh = theMesh;
1488
1489   // myCreationCmd = theOther->myCreationCmd;
1490   myIsAlgo = theOther->myIsAlgo;
1491   myGeom = theOther->myGeom;
1492   myType2CreationMethod = theOther->myType2CreationMethod;
1493   myArgs = theOther->myArgs;
1494   myArgMethods = theOther->myArgMethods;
1495   myNbArgsByMethod = theOther->myNbArgsByMethod;
1496   myArgCommands = theOther->myArgCommands;
1497   myUnknownCommands = theOther->myUnknownCommands;
1498 }
1499
1500 //================================================================================
1501 /*!
1502  * \brief Remember hypothesis parameter values
1503   * \param theCommand - The called hypothesis method
1504  */
1505 //================================================================================
1506
1507 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
1508 {
1509   // ex: hyp.SetLength(start, 1)
1510   //     hyp.SetLength(end,   0)
1511   ASSERT(( theCommand->GetMethod() == "SetLength" ));
1512   ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
1513   int i = 2 - theCommand->GetArg( 2 ).IntegerValue();
1514   while ( myArgs.Length() < i )
1515     myArgs.Append( "[]" );
1516   myArgs( i ) = theCommand->GetArg( 1 ); // arg value
1517   myArgCommands.push_back( theCommand );
1518 }
1519
1520 //================================================================================
1521 /*!
1522  * \brief Convert methods of 1D hypotheses to my own methods
1523   * \param theCommand - The called hypothesis method
1524  */
1525 //================================================================================
1526
1527 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
1528 {
1529   if ( theCommand->GetMethod() != "SetLayerDistribution" )
1530     return;
1531
1532   _pyID newName; // name for 1D hyp = "HypType" + "_Distribution"
1533
1534   const _pyID& hyp1dID = theCommand->GetArg( 1 );
1535   Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
1536   if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
1537     hyp1d = my1dHyp;
1538   else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() ) {
1539     // 1D hypo is already set, so distribution changes and the old
1540     // 1D hypo is thrown away
1541     my1dHyp->ClearAllCommands();
1542   }
1543   my1dHyp = hyp1d;
1544   if ( my1dHyp.IsNull() )
1545     return; // something wrong :(
1546
1547   // make a new name for 1D hyp = "HypType" + "_Distribution"
1548   if ( my1dHyp->GetCreationCmd()->GetMethod() == "CreateHypothesis" ) {
1549     // not yet converted creation cmd
1550     TCollection_AsciiString hypTypeQuoted = my1dHyp->GetCreationCmd()->GetArg(1);
1551     TCollection_AsciiString hypType = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
1552     newName = hypType + "_Distribution";
1553     my1dHyp->GetCreationCmd()->SetResultValue( newName );
1554   }
1555   else {
1556     // already converted creation cmd
1557     newName = my1dHyp->GetCreationCmd()->GetResultValue();
1558   }
1559
1560   // as creation of 1D hyp was written later then it's edition,
1561   // we need to find all it's edition calls and process them
1562   list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
1563   list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
1564   for ( ; cmdIt != cmds.end(); ++cmdIt ) {
1565     const _pyID& objID = (*cmdIt)->GetObject();
1566     if ( objID == hyp1dID ) {
1567       my1dHyp->Process( *cmdIt );
1568       my1dHyp->GetCreationCmd()->AddDependantCmd( *cmdIt );
1569       ( *cmdIt )->SetObject( newName );
1570     }
1571   }
1572   if ( !myArgCommands.empty() )
1573     myArgCommands.front()->Clear();
1574   theCommand->SetArg( 1, newName );
1575   myArgCommands.push_back( theCommand );
1576   // copy hyp1d's creation method and args
1577 //   myCreationMethod = hyp1d->GetCreationMethod();
1578 //   myArgs           = hyp1d->GetArgs();
1579 //   // make them cleared at conversion
1580 //   myArgCommands = hyp1d->GetArgCommands();
1581
1582 //   // to be cleared at convertion only
1583 //   myArgCommands.push_back( theCommand );
1584 }
1585
1586 //================================================================================
1587 /*!
1588  * \brief 
1589   * \param theAdditionCmd - command to be converted
1590   * \param theMesh - mesh instance
1591   * \retval bool - status
1592  */
1593 //================================================================================
1594
1595 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
1596                                                   const _pyID&              theMesh)
1597 {
1598   myIsWrapped = false;
1599
1600   if ( my1dHyp.IsNull() )
1601     return false;
1602
1603   // set "SetLayerDistribution()" after addition cmd
1604   theAdditionCmd->AddDependantCmd( myArgCommands.front() );
1605
1606   _pyID geom = theAdditionCmd->GetArg( 1 );
1607
1608   my1dHyp->SetMesh( theMesh );
1609   if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
1610     return false;
1611
1612   // clear "SetLayerDistribution()" cmd
1613   myArgCommands.front()->Clear();
1614
1615   // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
1616
1617   // find RadialPrism algo created on <geom> for theMesh
1618   Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
1619   if ( !algo.IsNull() ) {
1620     GetCreationCmd()->SetObject( algo->GetID() );
1621     GetCreationCmd()->SetMethod( "Get3DHypothesis" );
1622     GetCreationCmd()->RemoveArgs();
1623     theAdditionCmd->AddDependantCmd( GetCreationCmd() );
1624     myIsWrapped = true;
1625   }
1626   return myIsWrapped;
1627 }
1628
1629 //================================================================================
1630 /*!
1631  * \brief 
1632  */
1633 //================================================================================
1634
1635 void _pyLayerDistributionHypo::Flush()
1636 {
1637   //my1dHyp.Nullify();
1638   //_pyHypothesis::Flush();
1639 }
1640
1641 //================================================================================
1642 /*!
1643  * \brief additionally to Addition2Creation, clears SetDistrType() command
1644   * \param theCmd - AddHypothesis() command
1645   * \param theMesh - mesh to which a hypothesis is added
1646   * \retval bool - convertion result
1647  */
1648 //================================================================================
1649
1650 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
1651                                                 const _pyID&              theMesh)
1652 {
1653   if ( IsWrappable( theMesh ) && myArgs.Length() > 1 ) {
1654     // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
1655     bool scaleDistrType = false;
1656     list<Handle(_pyCommand)>::reverse_iterator cmd = myUnknownCommands.rbegin();
1657     for ( ; cmd != myUnknownCommands.rend(); ++cmd ) {
1658       if ( (*cmd)->GetMethod() == "SetDistrType" ) {
1659         if ( (*cmd)->GetArg( 1 ) == "1" ) {
1660           scaleDistrType = true;
1661           (*cmd)->Clear();
1662         }
1663         else if ( !scaleDistrType ) {
1664           // distribution type changed: remove scale factor from args
1665           myArgs.Remove( 2, myArgs.Length() );
1666           break;
1667         }
1668       }
1669     }
1670   }
1671   return _pyHypothesis::Addition2Creation( theCmd, theMesh );
1672 }
1673
1674 //================================================================================
1675 /*!
1676  * \brief remove repeated commands defining distribution
1677  */
1678 //================================================================================
1679
1680 void _pyNumberOfSegmentsHyp::Flush()
1681 {
1682   // find number of the last SetDistrType() command
1683   list<Handle(_pyCommand)>::reverse_iterator cmd = myUnknownCommands.rbegin();
1684   int distrTypeNb = 0;
1685   for ( ; !distrTypeNb && cmd != myUnknownCommands.rend(); ++cmd )
1686     if ( (*cmd)->GetMethod() == "SetDistrType" )
1687       distrTypeNb = (*cmd)->GetOrderNb();
1688
1689   // clear commands before the last SetDistrType()
1690   list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnknownCommands };
1691   for ( int i = 0; i < 2; ++i ) {
1692     set<TCollection_AsciiString> uniqueMethods;
1693     list<Handle(_pyCommand)> & cmdList = *cmds[i];
1694     for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
1695     {
1696       bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
1697       const TCollection_AsciiString& method = (*cmd)->GetMethod();
1698       if ( !clear || method == "SetNumberOfSegments" ) {
1699         bool isNewInSet = uniqueMethods.insert( method ).second;
1700         clear = !isNewInSet;
1701       }
1702       if ( clear )
1703         (*cmd)->Clear();
1704     }
1705     cmdList.clear();
1706   }
1707 }
1708
1709 //================================================================================
1710 /*!
1711  * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
1712  * into regular1D.LengthNearVertex( length, vertex )
1713   * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
1714   * \param theMesh - The mesh needing this hypo
1715   * \retval bool - false if the command cant be converted
1716  */
1717 //================================================================================
1718   
1719 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
1720                                                          const _pyID&              theMeshID)
1721 {
1722   if ( IsWrappable( theMeshID )) {
1723
1724     _pyID vertex = theCmd->GetArg( 1 );
1725
1726     // the problem here is that segment algo will not be found
1727     // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
1728     // geometry where segment algorithm is assigned
1729     Handle(_pyHypothesis) algo;
1730     _pyID geom = vertex;
1731     while ( algo.IsNull() && !geom.IsEmpty()) {
1732       // try to find geom as a father of <vertex>
1733       geom = FatherID( geom );
1734       algo = theGen->FindAlgo( geom, theMeshID, this );
1735     }
1736     if ( algo.IsNull() )
1737       return false; // also possible to find geom as brother of veretex...
1738     // set geom instead of vertex
1739     theCmd->SetArg( 1, geom );
1740
1741     // set vertex as a second arg
1742     if ( myArgs.Length() < 1) myArgs.Append( "1" ); // :(
1743     myArgs.Append( vertex );
1744
1745     // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
1746     // theMeshID.LengthNearVertex( length, vertex )
1747     return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
1748   }
1749   return false;
1750 }
1751
1752 //================================================================================
1753 /*!
1754  * \brief _pyAlgorithm constructor
1755  * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
1756  */
1757 //================================================================================
1758
1759 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
1760   : _pyHypothesis( theCreationCmd )
1761 {
1762   myIsAlgo = true;
1763 }
1764
1765 //================================================================================
1766 /*!
1767  * \brief Convert the command adding an algorithm to mesh
1768   * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
1769   * \param theMesh - The mesh needing this algo 
1770   * \retval bool - false if the command cant be converted
1771  */
1772 //================================================================================
1773   
1774 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
1775                                       const _pyID&              theMeshID)
1776 {
1777   // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
1778   if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
1779     theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
1780     return true;
1781   }
1782   return false;
1783 }
1784
1785 //================================================================================
1786 /*!
1787  * \brief Return starting position of a part of python command
1788   * \param thePartIndex - The index of command part
1789   * \retval int - Part position
1790  */
1791 //================================================================================
1792
1793 int _pyCommand::GetBegPos( int thePartIndex )
1794 {
1795   if ( IsEmpty() )
1796     return EMPTY;
1797   if ( myBegPos.Length() < thePartIndex )
1798     return UNKNOWN;
1799   return myBegPos( thePartIndex );
1800 }
1801
1802 //================================================================================
1803 /*!
1804  * \brief Store starting position of a part of python command
1805   * \param thePartIndex - The index of command part
1806   * \param thePosition - Part position
1807  */
1808 //================================================================================
1809
1810 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
1811 {
1812   while ( myBegPos.Length() < thePartIndex )
1813     myBegPos.Append( UNKNOWN );
1814   myBegPos( thePartIndex ) = thePosition;
1815 }
1816
1817 //================================================================================
1818 /*!
1819  * \brief Returns whitespace symbols at the line beginning
1820   * \retval TCollection_AsciiString - result
1821  */
1822 //================================================================================
1823
1824 TCollection_AsciiString _pyCommand::GetIndentation()
1825 {
1826   int end = 1;
1827   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
1828     GetWord( myString, end, true );
1829   else
1830     end = GetBegPos( RESULT_IND );
1831   return myString.SubString( 1, end - 1 );
1832 }
1833
1834 //================================================================================
1835 /*!
1836  * \brief Return substring of python command looking like ResultValue = Obj.Meth()
1837   * \retval const TCollection_AsciiString & - ResultValue substring
1838  */
1839 //================================================================================
1840
1841 const TCollection_AsciiString & _pyCommand::GetResultValue()
1842 {
1843   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
1844   {
1845     int begPos = myString.Location( "=", 1, Length() );
1846     if ( begPos )
1847       myRes = GetWord( myString, begPos, false );
1848     else
1849       begPos = EMPTY;
1850     SetBegPos( RESULT_IND, begPos );
1851   }
1852   return myRes;
1853 }
1854
1855 //================================================================================
1856 /*!
1857  * \brief Return number of python command result value ResultValue = Obj.Meth()
1858   * \retval const int
1859  */
1860 //================================================================================
1861
1862 const int _pyCommand::GetNbResultValues()
1863 {
1864   int begPos = 1;
1865   int Nb=0;
1866   int endPos = myString.Location( "=", 1, Length() );
1867   TCollection_AsciiString str = "";
1868   while ( begPos < endPos) {
1869     str = GetWord( myString, begPos, true );
1870     begPos = begPos+ str.Length();
1871     Nb++;
1872   }
1873   return (Nb-1);
1874 }
1875
1876
1877 //================================================================================
1878 /*!
1879  * \brief Return substring of python command looking like
1880  *  ResultValue1 , ResultValue1,... = Obj.Meth() with res index
1881  * \retval const TCollection_AsciiString & - ResultValue with res index substring
1882  */
1883 //================================================================================
1884 const TCollection_AsciiString & _pyCommand::GetResultValue(int res)
1885 {
1886   int begPos = 1;
1887   int Nb=0;
1888   int endPos = myString.Location( "=", 1, Length() );
1889   while ( begPos < endPos) {
1890     myRes = GetWord( myString, begPos, true );
1891     begPos = begPos + myRes.Length();
1892     Nb++;
1893     if(res == Nb){
1894       myRes.RemoveAll('[');myRes.RemoveAll(']');
1895       return myRes;
1896     }
1897     if(Nb>res)
1898       break;
1899   }
1900   return theEmptyString;
1901 }
1902
1903 //================================================================================
1904 /*!
1905  * \brief Return substring of python command looking like ResVal = Object.Meth()
1906   * \retval const TCollection_AsciiString & - Object substring
1907  */
1908 //================================================================================
1909
1910 const TCollection_AsciiString & _pyCommand::GetObject()
1911 {
1912   if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
1913   {
1914     // beginning
1915     int begPos = GetBegPos( RESULT_IND ) + myRes.Length();
1916     if ( begPos < 1 )
1917       begPos = myString.Location( "=", 1, Length() ) + 1;
1918     // store
1919     myObj = GetWord( myString, begPos, true );
1920     SetBegPos( OBJECT_IND, begPos );
1921   }
1922   //SCRUTE(myObj);
1923   return myObj;
1924 }
1925
1926 //================================================================================
1927 /*!
1928  * \brief Return substring of python command looking like ResVal = Obj.Method()
1929   * \retval const TCollection_AsciiString & - Method substring
1930  */
1931 //================================================================================
1932
1933 const TCollection_AsciiString & _pyCommand::GetMethod()
1934 {
1935   if ( GetBegPos( METHOD_IND ) == UNKNOWN )
1936   {
1937     // beginning
1938     int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
1939     bool forward = true;
1940     if ( begPos < 1 ) {
1941       begPos = myString.Location( "(", 1, Length() ) - 1;
1942       forward = false;
1943     }
1944     // store
1945     myMeth = GetWord( myString, begPos, forward );
1946     SetBegPos( METHOD_IND, begPos );
1947   }
1948   //SCRUTE(myMeth);
1949   return myMeth;
1950 }
1951
1952 //================================================================================
1953 /*!
1954  * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
1955   * \retval const TCollection_AsciiString & - Arg<index> substring
1956  */
1957 //================================================================================
1958
1959 const TCollection_AsciiString & _pyCommand::GetArg( int index )
1960 {
1961   if ( GetBegPos( ARG1_IND ) == UNKNOWN )
1962   {
1963     // find all args
1964     int begPos = GetBegPos( METHOD_IND ) + myMeth.Length();
1965     if ( begPos < 1 )
1966       begPos = myString.Location( "(", 1, Length() ) + 1;
1967
1968     int i = 0, prevLen = 0;
1969     while ( begPos != EMPTY ) {
1970       begPos += prevLen;
1971       // check if we are looking at the closing parenthesis
1972       while ( begPos <= Length() && isspace( myString.Value( begPos )))
1973         ++begPos;
1974       if ( begPos > Length() || myString.Value( begPos ) == ')' )
1975         break;
1976       myArgs.Append( GetWord( myString, begPos, true, true ));
1977       SetBegPos( ARG1_IND + i, begPos );
1978       prevLen = myArgs.Last().Length();
1979       if ( prevLen == 0 )
1980         myArgs.Remove( myArgs.Length() ); // no more args
1981       i++;
1982     }
1983   }
1984   if ( myArgs.Length() < index )
1985     return theEmptyString;
1986   return myArgs( index );
1987 }
1988
1989 //================================================================================
1990 /*!
1991  * \brief Check if char is a word part
1992   * \param c - The character to check
1993   * \retval bool - The check result
1994  */
1995 //================================================================================
1996
1997 static inline bool isWord(const char c, const bool dotIsWord)
1998 {
1999   return
2000     !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
2001 }
2002
2003 //================================================================================
2004 /*!
2005  * \brief Looks for a word in the string and returns word's beginning
2006   * \param theString - The input string
2007   * \param theStartPos - The position to start the search, returning word's beginning
2008   * \param theForward - The search direction
2009   * \retval TCollection_AsciiString - The found word
2010  */
2011 //================================================================================
2012
2013 TCollection_AsciiString _pyCommand::GetWord( const TCollection_AsciiString & theString,
2014                                             int &      theStartPos,
2015                                             const bool theForward,
2016                                             const bool dotIsWord )
2017 {
2018   int beg = theStartPos, end = theStartPos;
2019   theStartPos = EMPTY;
2020   if ( beg < 1 || beg > theString.Length() )
2021     return theEmptyString;
2022
2023   if ( theForward ) { // search forward
2024     // beg
2025     while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
2026       ++beg;
2027     if ( beg > theString.Length() )
2028       return theEmptyString; // no word found
2029     // end
2030     end = beg + 1;
2031     while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
2032       ++end;
2033     --end;
2034   }
2035   else {  // search backward
2036     // end
2037     while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
2038       --end;
2039     if ( end == 0 )
2040       return theEmptyString; // no word found
2041     beg = end - 1;
2042     while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
2043       --beg;
2044     ++beg;
2045   }
2046   theStartPos = beg;
2047   //cout << theString << " ---- " << beg << " - " << end << endl;
2048   return theString.SubString( beg, end );
2049 }
2050
2051 //================================================================================
2052 /*!
2053  * \brief Look for position where not space char is
2054   * \param theString - The string 
2055   * \param thePos - The position to search from and which returns result
2056   * \retval bool - false if there are only space after thePos in theString
2057  * 
2058  * 
2059  */
2060 //================================================================================
2061
2062 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
2063 {
2064   if ( thePos < 1 || thePos > theString.Length() )
2065     return false;
2066
2067   while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
2068     ++thePos;
2069
2070   return thePos <= theString.Length();
2071 }
2072
2073 //================================================================================
2074 /*!
2075  * \brief Modify a part of the command
2076   * \param thePartIndex - The index of the part
2077   * \param thePart - The new part string
2078   * \param theOldPart - The old part
2079  */
2080 //================================================================================
2081
2082 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
2083                         TCollection_AsciiString& theOldPart)
2084 {
2085   int pos = GetBegPos( thePartIndex );
2086   if ( pos <= Length() && theOldPart != thePart)
2087   {
2088     TCollection_AsciiString seperator;
2089     if ( pos < 1 ) {
2090       pos = GetBegPos( thePartIndex + 1 );
2091       if ( pos < 1 ) return;
2092       switch ( thePartIndex ) {
2093       case RESULT_IND: seperator = " = "; break;
2094       case OBJECT_IND: seperator = "."; break;
2095       case METHOD_IND: seperator = "()"; break;
2096       default:;
2097       }
2098     }      
2099     myString.Remove( pos, theOldPart.Length() );
2100     if ( !seperator.IsEmpty() )
2101       myString.Insert( pos , seperator );
2102     myString.Insert( pos, thePart );
2103     // update starting positions of the following parts
2104     int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
2105     for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
2106       if ( myBegPos( i ) > 0 )
2107         myBegPos( i ) += posDelta;
2108     }
2109     theOldPart = thePart;
2110   }
2111 }
2112
2113 //================================================================================
2114 /*!
2115  * \brief Set agrument
2116   * \param index - The argument index, it counts from 1
2117   * \param theArg - The argument string
2118  */
2119 //================================================================================
2120
2121 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
2122 {
2123   FindAllArgs();
2124   int argInd = ARG1_IND + index - 1;
2125   int pos = GetBegPos( argInd );
2126   if ( pos < 1 ) // no index-th arg exist, append inexistent args
2127   {
2128     // find a closing parenthesis
2129     if ( int lastArgInd = GetNbArgs() ) {
2130       pos = GetBegPos( ARG1_IND + lastArgInd  - 1 ) + GetArg( lastArgInd ).Length();
2131       while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
2132         ++pos;
2133     }
2134     else {
2135       pos = Length();
2136       while ( pos > 0 && myString.Value( pos ) != ')' )
2137         --pos;
2138     }
2139     if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
2140       myString += "()";
2141       pos = Length();
2142     }
2143     while ( myArgs.Length() < index ) {
2144       if ( myArgs.Length() )
2145         myString.Insert( pos++, "," );
2146       myArgs.Append("None");
2147       myString.Insert( pos, myArgs.Last() );
2148       SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
2149       pos += myArgs.Last().Length();
2150     }
2151   }
2152   SetPart( argInd, theArg, myArgs( index ));
2153 }
2154
2155 //================================================================================
2156 /*!
2157  * \brief Empty arg list
2158  */
2159 //================================================================================
2160
2161 void _pyCommand::RemoveArgs()
2162 {
2163   if ( int pos = myString.Location( '(', 1, Length() ))
2164     myString.Trunc( pos );
2165   myString += ")";
2166   myArgs.Clear();
2167   if ( myBegPos.Length() >= ARG1_IND )
2168     myBegPos.Remove( ARG1_IND, myBegPos.Length() );
2169 }
2170
2171 //================================================================================
2172 /*!
2173  * \brief Set dependent commands after this one
2174  */
2175 //================================================================================
2176
2177 bool _pyCommand::SetDependentCmdsAfter() const
2178 {
2179   bool orderChanged = false;
2180   list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
2181   for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
2182     if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
2183       orderChanged = true;
2184       theGen->SetCommandAfter( *cmd, this );
2185       (*cmd)->SetDependentCmdsAfter();
2186     }
2187   }
2188   return orderChanged;
2189 }
2190 //================================================================================
2191 /*!
2192  * \brief Insert accessor method after theObjectID
2193   * \param theObjectID - id of the accessed object
2194   * \param theAcsMethod - name of the method giving access to the object
2195   * \retval bool - false if theObjectID is not found in the command string
2196  */
2197 //================================================================================
2198
2199 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
2200 {
2201   if ( !theAcsMethod )
2202     return false;
2203   // start object search from the object, i.e. ignore result
2204   GetObject();
2205   int beg = GetBegPos( OBJECT_IND );
2206   if ( beg < 1 || beg > Length() )
2207     return false;
2208   bool added = false;
2209   while (( beg = myString.Location( theObjectID, beg, Length() )))
2210   {
2211     // check that theObjectID is not just a part of a longer ID
2212     int afterEnd = beg + theObjectID.Length();
2213     Standard_Character c = myString.Value( afterEnd );
2214     if ( !isalnum( c ) && c != ':' ) {
2215       // check if accessor method already present
2216       if ( c != '.' ||
2217            myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
2218         // insertion
2219         int oldLen = Length();
2220         myString.Insert( afterEnd, (char*) theAcsMethod );
2221         myString.Insert( afterEnd, "." );
2222         // update starting positions of the parts following the modified one
2223         int posDelta = Length() - oldLen;
2224         for ( int i = 1; i <= myBegPos.Length(); ++i ) {
2225           if ( myBegPos( i ) > afterEnd )
2226             myBegPos( i ) += posDelta;
2227         }
2228         added = true;
2229       }
2230     }
2231     beg = afterEnd; // is a part - next search
2232   }
2233   return added;
2234 }
2235
2236 //================================================================================
2237 /*!
2238  * \brief Return method name giving access to an interaface object wrapped by python class
2239   * \retval const char* - method name
2240  */
2241 //================================================================================
2242
2243 const char* _pyObject::AccessorMethod() const
2244 {
2245   return 0;
2246 }
2247 //================================================================================
2248 /*!
2249  * \brief Return ID of a father
2250  */
2251 //================================================================================
2252
2253 _pyID _pyObject::FatherID(const _pyID & childID)
2254 {
2255   int colPos = childID.SearchFromEnd(':');
2256   if ( colPos > 0 )
2257     return childID.SubString( 1, colPos-1 );
2258   return "";
2259 }
2260
2261 //================================================================================
2262 /*!
2263  * \brief FilterManager creates only if at least one command invoked
2264  */
2265 //================================================================================
2266
2267 _pyFilterManager::_pyFilterManager(const Handle(_pyCommand)& theCreationCmd):
2268   _pyObject( theCreationCmd ),
2269   myCmdCount( 0 )
2270 {
2271 }
2272
2273 //================================================================================
2274 /*!
2275  * \brief count invoked commands
2276  */
2277 //================================================================================
2278
2279 void _pyFilterManager::Process( const Handle(_pyCommand)& /*theCommand*/)
2280 {
2281   myCmdCount++;
2282 }
2283
2284 //================================================================================
2285 /*!
2286  * \brief Clear creatin command if no commands invoked
2287  */
2288 //================================================================================
2289
2290 void _pyFilterManager::Flush()
2291 {
2292   if ( !myCmdCount )
2293     GetCreationCmd()->Clear();
2294 }
2295
2296
2297 //================================================================================
2298 /*!
2299  * \brief SubMesh creation can be moved to the end of engine commands
2300  */
2301 //================================================================================
2302
2303 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd):
2304   _pyObject( theCreationCmd ),
2305   myCmdCount( 0 )
2306 {
2307 }
2308
2309 //================================================================================
2310 /*!
2311  * \brief count invoked commands
2312  */
2313 //================================================================================
2314
2315 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
2316 {
2317   myCmdCount++;
2318   GetCreationCmd()->AddDependantCmd( theCommand );
2319 }
2320
2321 //================================================================================
2322 /*!
2323  * \brief Clear creatin command if no commands invoked
2324  */
2325 //================================================================================
2326
2327 void _pySubMesh::Flush()
2328 {
2329   if ( !myCmdCount ) // move to the end of all commands
2330     theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
2331   else if ( !myCreator.IsNull() )
2332     // move to be just after creator
2333     myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
2334 }