Salome HOME
Update copyright information
[modules/smesh.git] / src / SMESH_I / SMESH_2smeshpy.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH_I : idl implementation based on 'SMESH' unit's calsses
24 // File      : SMESH_2smeshpy.cxx
25 // Created   : Fri Nov 18 13:20:10 2005
26 // Author    : Edward AGAPOV (eap)
27 //
28 #include "SMESH_2smeshpy.hxx"
29
30 #include "utilities.h"
31 #include "SMESH_PythonDump.hxx"
32 #include "SMESH_NoteBook.hxx"
33 #include "SMESH_Filter_i.hxx"
34
35 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
36 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
37
38 #include "SMESH_Gen_i.hxx"
39 /* SALOME headers that include CORBA headers that include windows.h
40  * that defines GetObject symbol as GetObjectA should stand before SALOME headers
41  * that declare methods named GetObject - to apply the same rules of GetObject renaming
42  * and thus to avoid mess with GetObject symbol on Windows */
43
44 #include <LDOMParser.hxx>
45
46 #ifdef WNT
47 #include <windows.h>
48 #else
49 #include <unistd.h>
50 #endif
51
52
53 IMPLEMENT_STANDARD_HANDLE (_pyObject          ,Standard_Transient);
54 IMPLEMENT_STANDARD_HANDLE (_pyCommand         ,Standard_Transient);
55 IMPLEMENT_STANDARD_HANDLE (_pyHypothesisReader,Standard_Transient);
56 IMPLEMENT_STANDARD_HANDLE (_pyGen             ,_pyObject);
57 IMPLEMENT_STANDARD_HANDLE (_pyMesh            ,_pyObject);
58 IMPLEMENT_STANDARD_HANDLE (_pySubMesh         ,_pyObject);
59 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor      ,_pyObject);
60 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis      ,_pyObject);
61 IMPLEMENT_STANDARD_HANDLE (_pySelfEraser      ,_pyObject);
62 IMPLEMENT_STANDARD_HANDLE (_pyGroup           ,_pyObject);
63 IMPLEMENT_STANDARD_HANDLE (_pyFilter          ,_pyObject);
64 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm       ,_pyHypothesis);
65 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
66 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
67
68 IMPLEMENT_STANDARD_RTTIEXT(_pyObject          ,Standard_Transient);
69 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand         ,Standard_Transient);
70 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
71 IMPLEMENT_STANDARD_RTTIEXT(_pyGen             ,_pyObject);
72 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh            ,_pyObject);
73 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh         ,_pyObject);
74 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor      ,_pyObject);
75 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis      ,_pyObject);
76 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser      ,_pyObject);
77 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup           ,_pyObject);
78 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter          ,_pyObject);
79 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm       ,_pyHypothesis);
80 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
81 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
82 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
83 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
84
85 using namespace std;
86 using SMESH::TPythonDump;
87
88 /*!
89  * \brief Container of commands into which the initial script is split.
90  *        It also contains data coresponding to SMESH_Gen contents
91  */
92 static Handle(_pyGen) theGen;
93
94 static TCollection_AsciiString theEmptyString;
95
96 //#define DUMP_CONVERSION
97
98 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
99 #undef DUMP_CONVERSION
100 #endif
101
102
103 namespace {
104
105   //================================================================================
106   /*!
107    * \brief Set of TCollection_AsciiString initialized by C array of C strings
108    */
109   //================================================================================
110
111   struct TStringSet: public set<TCollection_AsciiString>
112   {
113     /*!
114      * \brief Filling. The last string must be ""
115      */
116     void Insert(const char* names[]) {
117       for ( int i = 0; names[i][0] ; ++i )
118         insert( (char*) names[i] );
119     }
120     /*!
121      * \brief Check if a string is in
122      */
123     bool Contains(const TCollection_AsciiString& name ) {
124       return find( name ) != end();
125     }
126   };
127
128   //================================================================================
129   /*!
130    * \brief Returns a mesh by object
131    */
132   //================================================================================
133
134   Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
135   {
136     if ( !obj.IsNull() )
137     {
138       if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
139         return Handle(_pyMesh)::DownCast( obj );
140       else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
141         return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
142       else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
143         return Handle(_pyGroup)::DownCast( obj )->GetMesh();
144     }
145     return Handle(_pyMesh)();
146   }
147
148   //================================================================================
149   /*!
150    * \brief Check if objects used as args have been created by previous commands
151    */
152   //================================================================================
153
154   void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
155   {
156     for ( int iArg = cmd->GetNbArgs(); iArg; --iArg )
157     {
158       const _pyID& arg = cmd->GetArg( iArg );
159       if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
160         continue;
161       list< _pyID > idList = cmd->GetStudyEntries( arg );
162       list< _pyID >::iterator id = idList.begin();
163       for ( ; id != idList.end(); ++id )
164         if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
165         {
166           cmd->Comment();
167           cmd->GetString() += " ### " ;
168           cmd->GetString() += *id + " has not been yet created";
169           return;
170         }
171     }
172     const _pyID& obj = cmd->GetObject();
173     if ( !obj.IsEmpty() && cmd->IsStudyEntry( obj ) && !presentObjects.count( obj ))
174     {
175       cmd->Comment();
176       cmd->GetString() += " ### not created object" ;
177     }
178     const _pyID& result = cmd->GetResultValue();
179     if ( result.IsEmpty() || result.Value( 1 ) == '"' || result.Value( 1 ) == '\'' )
180       return;
181     list< _pyID > idList = cmd->GetStudyEntries( result );
182     list< _pyID >::iterator id = idList.begin();
183     for ( ; id != idList.end(); ++id )
184       presentObjects.insert( *id );
185   }
186
187   //================================================================================
188   /*!
189    * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
190    */
191   //================================================================================
192
193   void fixFunctorType( TCollection_AsciiString& Type,
194                        TCollection_AsciiString& Compare,
195                        TCollection_AsciiString& UnaryOp,
196                        TCollection_AsciiString& BinaryOp )
197   {
198     // The problem is that dumps of old studies created using filters becomes invalid
199     // when new items are inserted in the enum SMESH::FunctorType since values
200     // of this enum are dumped as integer values.
201     // This function corrects enum values of old studies given as args (Type,Compare,...)
202     // We can find out how to correct them by value of BinaryOp which can have only two
203     // values: FT_Undefined or FT_LogicalNOT.
204     // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
205     // where PythonDump appeared
206     // v 3.0.0: FT_Undefined == 25
207     // v 3.1.0: FT_Undefined == 26, new items:
208     //   - FT_Volume3D              = 7
209     // v 4.1.2: FT_Undefined == 27, new items:
210     //   - FT_BelongToGenSurface    = 17
211     // v 5.1.1: FT_Undefined == 32, new items:
212     //   - FT_FreeNodes             = 10
213     //   - FT_FreeFaces             = 11
214     //   - FT_LinearOrQuadratic     = 23
215     //   - FT_GroupColor            = 24
216     //   - FT_ElemGeomType          = 25
217     // v 5.1.5: FT_Undefined == 33, new items:
218     //   - FT_CoplanarFaces         = 26
219     // v 6.2.0: FT_Undefined == 39, new items:
220     //   - FT_MaxElementLength2D    = 8
221     //   - FT_MaxElementLength3D    = 9
222     //   - FT_BareBorderVolume      = 25
223     //   - FT_BareBorderFace        = 26
224     //   - FT_OverConstrainedVolume = 27
225     //   - FT_OverConstrainedFace   = 28
226     // v 6.5.0: FT_Undefined == 43, new items:
227     //   - FT_EqualNodes            = 14
228     //   - FT_EqualEdges            = 15
229     //   - FT_EqualFaces            = 16
230     //   - FT_EqualVolumes          = 17
231
232     typedef map< int, vector< int > > TUndef2newItems;
233     static TUndef2newItems undef2newItems;
234     if ( undef2newItems.empty() )
235     {
236       undef2newItems[ 26 ].push_back( 7 );
237       undef2newItems[ 27 ].push_back( 17 );
238       { int items[] = { 10, 11, 23, 24, 25 };
239         undef2newItems[ 32 ].assign( items, items+5 ); }
240       undef2newItems[ 33 ].push_back( 26 );
241       { int items[] = { 8, 9, 25, 26, 27, 28 };
242         undef2newItems[ 39 ].assign( items, items+6 ); }
243       { int items[] = { 14, 15, 16, 17 };
244         undef2newItems[ 43 ].assign( items, items+4 ); }
245     }
246
247     int iType     = Type.IntegerValue();
248     int iCompare  = Compare.IntegerValue();
249     int iUnaryOp  = UnaryOp.IntegerValue();
250     int iBinaryOp = BinaryOp.IntegerValue();
251
252     // find out integer value of FT_Undefined at the moment of dump
253     int oldUndefined = iBinaryOp;
254     if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
255       oldUndefined += 3;
256
257     // apply history to args
258     TUndef2newItems::const_iterator undef_items =
259       undef2newItems.upper_bound( oldUndefined );
260     if ( undef_items != undef2newItems.end() )
261     {
262       int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
263       for ( ; undef_items != undef2newItems.end(); ++undef_items )
264       {
265         const vector< int > & addedItems = undef_items->second;
266         for ( size_t i = 0; i < addedItems.size(); ++i )
267           for ( int iArg = 0; iArg < 4; ++iArg )
268           {
269             int& arg = *pArg[iArg];
270             if ( arg >= addedItems[i] )
271               arg++;
272           }
273       }
274       Type     = TCollection_AsciiString( iType     );
275       Compare  = TCollection_AsciiString( iCompare  );
276       UnaryOp  = TCollection_AsciiString( iUnaryOp  );
277       BinaryOp = TCollection_AsciiString( iBinaryOp );
278     }
279   }
280 }
281
282 //================================================================================
283 /*!
284  * \brief Convert python script using commands of smesh.py
285   * \param theScript - Input script
286   * \retval TCollection_AsciiString - Convertion result
287   * \param theToKeepAllCommands - to keep all commands or
288   *        to exclude commands relating to objects removed from study
289   *
290   * Class SMESH_2smeshpy declared in SMESH_PythonDump.hxx
291  */
292 //================================================================================
293
294 TCollection_AsciiString
295 SMESH_2smeshpy::ConvertScript(const TCollection_AsciiString&            theScript,
296                               Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
297                               Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
298                               SALOMEDS::Study_ptr&                      theStudy,
299                               const bool                                theToKeepAllCommands)
300 {
301   theGen = new _pyGen( theEntry2AccessorMethod, theObjectNames, theStudy, theToKeepAllCommands );
302
303   // split theScript into separate commands
304
305   SMESH_NoteBook * aNoteBook = new SMESH_NoteBook();
306
307   int from = 1, end = theScript.Length(), to;
308   while ( from < end && ( to = theScript.Location( "\n", from, end )))
309   {
310     if ( to != from )
311         // cut out and store a command
312         aNoteBook->AddCommand( theScript.SubString( from, to - 1 ));
313       from = to + 1;
314   }
315
316   aNoteBook->ReplaceVariables();
317
318   TCollection_AsciiString aNoteScript = aNoteBook->GetResultScript();
319   delete aNoteBook;
320   aNoteBook = 0;
321
322   // split theScript into separate commands
323   from = 1, end = aNoteScript.Length();
324   while ( from < end && ( to = aNoteScript.Location( "\n", from, end )))
325   {
326     if ( to != from )
327       // cut out and store a command
328       theGen->AddCommand( aNoteScript.SubString( from, to - 1 ));
329     from = to + 1;
330   }
331
332   // finish conversion
333   theGen->Flush();
334 #ifdef DUMP_CONVERSION
335   MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
336 #endif
337
338   // clean commmands of removed objects depending on myIsPublished flag
339   theGen->ClearCommands();
340
341   // reorder commands after conversion
342   list< Handle(_pyCommand) >::iterator cmd;
343   bool orderChanges;
344   do {
345     orderChanges = false;
346     for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
347       if ( (*cmd)->SetDependentCmdsAfter() )
348         orderChanges = true;
349   } while ( orderChanges );
350
351   // concat commands back into a script
352   TCollection_AsciiString aScript, aPrevCmd;
353   set<_pyID> createdObjects;
354   for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
355   {
356 #ifdef DUMP_CONVERSION
357     MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
358 #endif
359     if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
360       CheckObjectPresence( *cmd, createdObjects );
361       aPrevCmd = (*cmd)->GetString();
362       aScript += "\n";
363       aScript += aPrevCmd;
364     }
365   }
366   aScript += "\n";
367
368   theGen->Free();
369   theGen.Nullify();
370
371   return aScript;
372 }
373
374 //================================================================================
375 /*!
376  * \brief _pyGen constructor
377  */
378 //================================================================================
379
380 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
381                Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
382                SALOMEDS::Study_ptr&                      theStudy,
383                const bool                                theToKeepAllCommands)
384   : _pyObject( new _pyCommand( "", 0 )),
385     myNbCommands( 0 ),
386     myID2AccessorMethod( theEntry2AccessorMethod ),
387     myObjectNames( theObjectNames ),
388     myNbFilters( 0 ),
389     myToKeepAllCommands( theToKeepAllCommands ),
390     myStudy( SALOMEDS::Study::_duplicate( theStudy )),
391     myGeomIDNb(0), myGeomIDIndex(-1)
392 {
393   // make that GetID() to return TPythonDump::SMESHGenName()
394   GetCreationCmd()->Clear();
395   GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
396   GetCreationCmd()->GetString() += "=";
397
398   // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
399   if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
400   {
401     // find a GEOM entry
402     _pyID geomID;
403     SALOMEDS::SComponent_var geomComp = theStudy->FindComponent("GEOM");
404     if ( geomComp->_is_nil() ) return;
405     CORBA::String_var entry = geomComp->GetID();
406     geomID = entry.in();
407
408     // find a SMESH entry
409     _pyID smeshID;
410     Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
411     for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
412       if ( _pyCommand::IsStudyEntry( e2n.Key() ))
413         smeshID = e2n.Key();
414
415     // find 1st difference between smeshID and geomID
416     if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
417       for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
418         if ( geomID.Value( i ) != smeshID.Value( i ))
419         {
420           myGeomIDNb = geomID.Value( i );
421           myGeomIDIndex = i;
422         }
423   }
424 }
425
426 //================================================================================
427 /*!
428  * \brief name of SMESH_Gen in smesh.py
429  */
430 //================================================================================
431
432 const char* _pyGen::AccessorMethod() const
433 {
434   return SMESH_2smeshpy::GenName();
435 }
436
437 //================================================================================
438 /*!
439  * \brief Convert a command using a specific converter
440   * \param theCommand - the command to convert
441  */
442 //================================================================================
443
444 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
445 {
446   // store theCommand in the sequence
447   myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
448
449   Handle(_pyCommand) aCommand = myCommands.back();
450 #ifdef DUMP_CONVERSION
451   MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
452 #endif
453
454   const _pyID& objID = aCommand->GetObject();
455
456   if ( objID.IsEmpty() )
457     return aCommand;
458
459   // Find an object to process theCommand
460
461   // SMESH_Gen method?
462   if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
463   {
464     this->Process( aCommand );
465     return aCommand;
466   }
467
468   // SMESH_Mesh method?
469   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
470   if ( id_mesh != myMeshes.end() )
471   {
472     //id_mesh->second->AddProcessedCmd( aCommand );
473
474     // check for mesh editor object
475     if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
476       _pyID editorID = aCommand->GetResultValue();
477       Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
478       myMeshEditors.insert( make_pair( editorID, editor ));
479       return aCommand;
480     }
481     // check for SubMesh objects
482     else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
483       _pyID subMeshID = aCommand->GetResultValue();
484       Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
485       myObjects.insert( make_pair( subMeshID, subMesh ));
486     }
487
488     id_mesh->second->Process( aCommand );
489     id_mesh->second->AddProcessedCmd( aCommand );
490     return aCommand;
491   }
492
493   // SMESH_MeshEditor method?
494   map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
495   if ( id_editor != myMeshEditors.end() )
496   {
497     const TCollection_AsciiString& method = aCommand->GetMethod();
498
499     // some commands of SMESH_MeshEditor create meshes and groups
500     _pyID meshID, groups;
501     if ( method.Search("MakeMesh") != -1 )
502       meshID = aCommand->GetResultValue();
503     else if ( method == "MakeBoundaryMesh")
504       meshID = aCommand->GetResultValue(1);
505     else if ( method == "MakeBoundaryElements")
506       meshID = aCommand->GetResultValue(2);
507
508     if ( method.Search("MakeGroups") != -1  ||
509          method == "ExtrusionAlongPathX"    ||
510          method == "ExtrusionAlongPathObjX" ||
511          method == "DoubleNodeGroupNew"     ||
512          method == "DoubleNodeGroupsNew"    ||
513          method == "DoubleNodeElemGroupNew" ||
514          method == "DoubleNodeElemGroupsNew" )
515       groups = aCommand->GetResultValue();
516     else if ( method == "MakeBoundaryMesh" )
517       groups = aCommand->GetResultValue(2);
518     else if ( method == "MakeBoundaryElements")
519       groups = aCommand->GetResultValue(3);
520
521     id_editor->second->Process( aCommand );
522     id_editor->second->AddProcessedCmd( aCommand );
523
524     if ( !meshID.IsEmpty() &&
525          !myMeshes.count( meshID ) &&
526          aCommand->IsStudyEntry( meshID ))
527     {
528       TCollection_AsciiString processedCommand = aCommand->GetString();
529       Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
530       myMeshes.insert( make_pair( meshID, mesh ));
531       aCommand->Clear();
532       aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
533     }
534     if ( !groups.IsEmpty() )
535     {
536       if ( !aCommand->IsStudyEntry( meshID ))
537         meshID = id_editor->second->GetMesh();
538       Handle(_pyMesh) mesh = myMeshes[ meshID ];
539
540       list< _pyID > idList = aCommand->GetStudyEntries( groups );
541       list< _pyID >::iterator grID = idList.begin();
542       for ( ; grID != idList.end(); ++grID )
543         if ( !myObjects.count( *grID ))
544         {
545           Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
546           AddObject( group );
547           if ( !mesh.IsNull() ) mesh->AddGroup( group );
548         }
549     }
550     return aCommand;
551   } // SMESH_MeshEditor methods
552
553   // SMESH_Hypothesis method?
554   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
555   for ( ; hyp != myHypos.end(); ++hyp )
556     if ( !(*hyp)->IsAlgo() && objID == (*hyp)->GetID() ) {
557       (*hyp)->Process( aCommand );
558       (*hyp)->AddProcessedCmd( aCommand );
559       return aCommand;
560     }
561
562   // aFilterManager.CreateFilter() ?
563   if ( aCommand->GetMethod() == "CreateFilter" )
564   {
565     // Set a more human readable name to a filter
566     // aFilter0x7fbf6c71cfb0 -> aFilter_nb
567     _pyID newID, filterID = aCommand->GetResultValue();
568     int pos = filterID.Search( "0x" );
569     if ( pos > 1 )
570       newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
571
572     Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
573     AddObject( filter );
574   }
575
576   // other object method?
577   map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
578   if ( id_obj != myObjects.end() ) {
579     id_obj->second->Process( aCommand );
580     id_obj->second->AddProcessedCmd( aCommand );
581     return aCommand;
582   }
583
584   // Add access to a wrapped mesh
585   AddMeshAccessorMethod( aCommand );
586
587   // Add access to a wrapped algorithm
588   //  AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
589
590   // PAL12227. PythonDump was not updated at proper time; result is
591   //     aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
592   // TypeError: __init__() takes exactly 11 arguments (10 given)
593   const char wrongCommand[] = "SMESH.Filter.Criterion(";
594   if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
595   {
596     _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
597     // there must be 10 arguments, 5-th arg ThresholdID is missing,
598     const int wrongNbArgs = 9, missingArg = 5;
599     if ( tmpCmd.GetNbArgs() == wrongNbArgs )
600     {
601       for ( int i = wrongNbArgs; i > missingArg; --i )
602         tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
603       tmpCmd.SetArg(  missingArg, "''");
604       aCommand->GetString().Trunc( beg - 1 );
605       aCommand->GetString() += tmpCmd.GetString();
606     }
607     // IMP issue 0021014
608     // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
609     //                  1           2        3       4        5       6        7
610     // instead of "SMESH.Filter.Criterion(
611     // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
612     // 1    2       3         4            5           6       7        8         9             10
613     // in order to avoid the problem of type mismatch of long and FunctorType
614     const TCollection_AsciiString
615       SMESH("SMESH."), dfltFunctor = "SMESH.FT_Undefined", dftlTol = "1e-07", dftlPreci = "-1";
616     TCollection_AsciiString
617       Type          = aCommand->GetArg(1),  // long
618       Compare       = aCommand->GetArg(2),  // long
619       Threshold     = aCommand->GetArg(3),  // double
620       ThresholdStr  = aCommand->GetArg(4),  // string
621       ThresholdID   = aCommand->GetArg(5),  // string
622       UnaryOp       = aCommand->GetArg(6),  // long
623       BinaryOp      = aCommand->GetArg(7),  // long
624       Tolerance     = aCommand->GetArg(8),  // double
625       TypeOfElement = aCommand->GetArg(9),  // ElementType
626       Precision     = aCommand->GetArg(10); // long
627     fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
628     Type     = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
629     Compare  = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
630     UnaryOp  = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
631     BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
632
633     aCommand->RemoveArgs();
634     aCommand->SetObject( SMESH_2smeshpy::GenName() );
635     aCommand->SetMethod( "GetCriterion" );
636
637     aCommand->SetArg( 1, TypeOfElement );
638     aCommand->SetArg( 2, Type );
639     aCommand->SetArg( 3, Compare );
640
641     if ( Type == "SMESH.FT_ElemGeomType" && Threshold.IsIntegerValue() )
642     {
643       // set SMESH.GeometryType instead of a numerical Threshold
644       const char* types[SMESH::Geom_POLYHEDRA+1] = {
645         "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
646         "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
647         "Geom_POLYHEDRA"
648       };
649       int iGeom = Threshold.IntegerValue();
650       if ( -1 < iGeom && iGeom < SMESH::Geom_POLYHEDRA+1 )
651         Threshold = SMESH + types[ iGeom ];
652     }
653     if ( ThresholdID.Length() != 2 && ThresholdStr.Length() != 2) // not '' or ""
654       aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
655     else if ( ThresholdStr.Length() != 2 )
656       aCommand->SetArg( 4, ThresholdStr );
657     else if ( ThresholdID.Length() != 2 )
658       aCommand->SetArg( 4, ThresholdID );
659     else
660       aCommand->SetArg( 4, Threshold );
661     // find the last not default arg
662     int lastDefault = 8;
663     if ( Tolerance == dftlTol ) {
664       lastDefault = 7;
665       if ( BinaryOp == dfltFunctor ) {
666         lastDefault = 6;
667         if ( UnaryOp == dfltFunctor )
668           lastDefault = 5;
669       }
670     }
671     if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
672     if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
673     if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
674     if ( Precision != dftlPreci )
675     {
676       TCollection_AsciiString crit = aCommand->GetResultValue();
677       aCommand->GetString() += "; ";
678       aCommand->GetString() += crit + ".Precision = " + Precision;
679     }
680   }
681   return aCommand;
682 }
683
684 //================================================================================
685 /*!
686  * \brief Convert the command or remember it for later conversion
687   * \param theCommand - The python command calling a method of SMESH_Gen
688  */
689 //================================================================================
690
691 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
692 {
693   // there are methods to convert:
694   // CreateMesh( shape )
695   // Concatenate( [mesh1, ...], ... )
696   // CreateHypothesis( theHypType, theLibName )
697   // Compute( mesh, geom )
698   // Evaluate( mesh, geom )
699   // mesh creation
700   TCollection_AsciiString method = theCommand->GetMethod();
701
702   if ( method == "CreateMesh" || method == "CreateEmptyMesh")
703   {
704     Handle(_pyMesh) mesh = new _pyMesh( theCommand );
705     myMeshes.insert( make_pair( mesh->GetID(), mesh ));
706     return;
707   }
708   if ( method == "CreateMeshesFromUNV" ||
709        method == "CreateMeshesFromSTL" ||
710        method == "CreateMeshesFromCGNS" ||
711        method == "CopyMesh" )
712   {
713     Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
714     myMeshes.insert( make_pair( mesh->GetID(), mesh ));
715     return;
716   }
717   if( method == "CreateMeshesFromMED" || method == "CreateMeshesFromSAUV")
718   {
719     for(int ind = 0;ind<theCommand->GetNbResultValues();ind++)
720     {
721       const _pyID& meshID = theCommand->GetResultValue(ind+1);
722       if ( !theCommand->IsStudyEntry( meshID ) ) continue;
723       Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue(ind+1));
724       myMeshes.insert( make_pair( mesh->GetID(), mesh ));
725     }
726   }
727
728   // CreateHypothesis()
729   if ( method == "CreateHypothesis" )
730   {
731     // issue 199929, remove standard library name (default parameter)
732     const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
733     if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
734       // keep first argument
735       TCollection_AsciiString arg = theCommand->GetArg( 1 );
736       theCommand->RemoveArgs();
737       theCommand->SetArg( 1, arg );
738     }
739
740     myHypos.push_back( _pyHypothesis::NewHypothesis( theCommand ));
741     return;
742   }
743
744   // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
745   if ( method == "Compute" )
746   {
747     const _pyID& meshID = theCommand->GetArg( 1 );
748     map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
749     if ( id_mesh != myMeshes.end() ) {
750       theCommand->SetObject( meshID );
751       theCommand->RemoveArgs();
752       id_mesh->second->Process( theCommand );
753       id_mesh->second->AddProcessedCmd( theCommand );
754       return;
755     }
756   }
757
758   // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
759   if ( method == "Evaluate" )
760   {
761     const _pyID& meshID = theCommand->GetArg( 1 );
762     map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
763     if ( id_mesh != myMeshes.end() ) {
764       theCommand->SetObject( meshID );
765       _pyID geom = theCommand->GetArg( 2 );
766       theCommand->RemoveArgs();
767       theCommand->SetArg( 1, geom );
768       id_mesh->second->AddProcessedCmd( theCommand );
769       return;
770     }
771   }
772
773   // objects erasing creation command if no more it's commands invoked:
774   // SMESH_Pattern, FilterManager
775   if ( method == "GetPattern" ||
776        method == "CreateFilterManager" ||
777        method == "CreateMeasurements" ) {
778     Handle(_pyObject) obj = new _pySelfEraser( theCommand );
779     if ( !myObjects.insert( make_pair( obj->GetID(), obj )).second )
780       theCommand->Clear(); // already created
781   }
782   // Concatenate( [mesh1, ...], ... )
783   else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
784   {
785     if ( method == "ConcatenateWithGroups" ) {
786       theCommand->SetMethod( "Concatenate" );
787       theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
788     }
789     Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
790     myMeshes.insert( make_pair( mesh->GetID(), mesh ));
791     AddMeshAccessorMethod( theCommand );
792   }
793   else if ( method == "SetName" ) // SetName(obj,name)
794   {
795     // store theCommand as one of object commands to erase it along with the object
796     const _pyID& objID = theCommand->GetArg( 1 );
797     Handle(_pyObject) obj = FindObject( objID );
798     if ( !obj.IsNull() )
799       obj->AddProcessedCmd( theCommand );
800   }
801
802   // Replace name of SMESH_Gen
803
804   // names of SMESH_Gen methods fully equal to methods defined in smesh.py
805   static TStringSet smeshpyMethods;
806   if ( smeshpyMethods.empty() ) {
807     const char * names[] =
808       { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
809         "GetPattern","GetSubShapesId",
810         "" }; // <- mark of array end
811     smeshpyMethods.Insert( names );
812   }
813   if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
814     // smeshgen.Method() --> smesh.Method()
815     theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
816   else
817     // smeshgen.Method() --> smesh.smesh.Method()
818     theCommand->SetObject( SMESH_2smeshpy::GenName() );
819 }
820
821 //================================================================================
822 /*!
823  * \brief Convert the remembered commands
824  */
825 //================================================================================
826
827 void _pyGen::Flush()
828 {
829   // create an empty command
830   myLastCommand = new _pyCommand();
831
832   map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
833   map< _pyID, Handle(_pyObject) >::iterator id_obj;
834   list< Handle(_pyHypothesis) >::iterator hyp;
835
836   if ( IsToKeepAllCommands() ) // historical dump
837   {
838     // set myIsPublished = true to all objects
839     for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
840       id_mesh->second->SetRemovedFromStudy( false );
841     for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
842       (*hyp)->SetRemovedFromStudy( false );
843     for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
844       id_obj->second->SetRemovedFromStudy( false );
845   }
846   else
847   {
848     // let hypotheses find referred objects in order to prevent clearing
849     // not published referred hyps (it's needed for hyps like "LayerDistribution")
850     list< Handle(_pyMesh) > fatherMeshes;
851     for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
852       if ( !hyp->IsNull() )
853         (*hyp)->GetReferredMeshesAndGeom( fatherMeshes );
854   }
855   // set myIsPublished = false to all objects depending on
856   // meshes built on a removed geometry
857   for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
858     if ( id_mesh->second->IsNotGeomPublished() )
859       id_mesh->second->SetRemovedFromStudy( true );
860
861   // Flush meshes
862   for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
863     if ( ! id_mesh->second.IsNull() )
864       id_mesh->second->Flush();
865
866   // Flush hyps
867   for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
868     if ( !hyp->IsNull() ) {
869       (*hyp)->Flush();
870       // smeshgen.CreateHypothesis() --> smesh.smesh.CreateHypothesis()
871       if ( !(*hyp)->IsWrapped() )
872         (*hyp)->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
873     }
874
875   // Flush other objects
876   for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
877     if ( ! id_obj->second.IsNull() )
878       id_obj->second->Flush();
879
880   myLastCommand->SetOrderNb( ++myNbCommands );
881   myCommands.push_back( myLastCommand );
882 }
883
884 //================================================================================
885 /*!
886  * \brief Clean commmands of removed objects depending on myIsPublished flag
887  */
888 //================================================================================
889
890 void _pyGen::ClearCommands()
891 {
892   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
893   for ( ; id_mesh != myMeshes.end(); ++id_mesh )
894     id_mesh->second->ClearCommands();
895
896   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
897   for ( ; hyp != myHypos.end(); ++hyp )
898     if ( !hyp->IsNull() )
899       (*hyp)->ClearCommands();
900
901   map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
902   for ( ; id_obj != myObjects.end(); ++id_obj )
903     id_obj->second->ClearCommands();
904 }
905
906 //================================================================================
907 /*!
908  * \brief Release mutual handles of objects
909  */
910 //================================================================================
911
912 void _pyGen::Free()
913 {
914   map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
915   for ( ; id_mesh != myMeshes.end(); ++id_mesh )
916     id_mesh->second->Free();
917   myMeshes.clear();
918
919   map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
920   for ( ; id_ed != myMeshEditors.end(); ++id_ed )
921     id_ed->second->Free();
922   myMeshEditors.clear();
923
924   map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
925   for ( ; id_obj != myObjects.end(); ++id_obj )
926     id_obj->second->Free();
927   myObjects.clear();
928
929   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
930   for ( ; hyp != myHypos.end(); ++hyp )
931     if ( !hyp->IsNull() )
932       (*hyp)->Free();
933   myHypos.clear();
934
935   myFile2ExportedMesh.clear();
936 }
937
938 //================================================================================
939 /*!
940  * \brief Add access method to mesh that is an argument
941   * \param theCmd - command to add access method
942   * \retval bool - true if added
943  */
944 //================================================================================
945
946 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
947 {
948   bool added = false;
949   map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
950   for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
951     if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
952       added = true;
953   }
954   return added;
955 }
956
957 //================================================================================
958 /*!
959  * \brief Add access method to algo that is an object or an argument
960   * \param theCmd - command to add access method
961   * \retval bool - true if added
962  */
963 //================================================================================
964
965 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
966 {
967   bool added = false;
968   list< Handle(_pyHypothesis) >::const_iterator hyp = myHypos.begin();
969   for ( ; hyp != myHypos.end(); ++hyp ) {
970     if ( (*hyp)->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
971          theCmd->AddAccessorMethod( (*hyp)->GetID(), (*hyp)->AccessorMethod() ))
972       added = true;
973   }
974   return added;
975 }
976
977 //================================================================================
978 /*!
979  * \brief Find hypothesis by ID (entry)
980   * \param theHypID - The hypothesis ID
981   * \retval Handle(_pyHypothesis) - The found hypothesis
982  */
983 //================================================================================
984
985 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
986 {
987   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
988   for ( ; hyp != myHypos.end(); ++hyp )
989     if ( !hyp->IsNull() && theHypID == (*hyp)->GetID() )
990       return *hyp;
991   return Handle(_pyHypothesis)();
992 }
993
994 //================================================================================
995 /*!
996  * \brief Find algorithm the created algorithm
997   * \param theGeom - The shape ID the algorithm was created on
998   * \param theMesh - The mesh ID that created the algorithm
999   * \param dim - The algo dimension
1000   * \retval Handle(_pyHypothesis) - The found algo
1001  */
1002 //================================================================================
1003
1004 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1005                                         const Handle(_pyHypothesis)& theHypothesis )
1006 {
1007   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1008   for ( ; hyp != myHypos.end(); ++hyp )
1009     if ( !hyp->IsNull() &&
1010          (*hyp)->IsAlgo() &&
1011          theHypothesis->CanBeCreatedBy( (*hyp)->GetAlgoType() ) &&
1012          (*hyp)->GetGeom() == theGeom &&
1013          (*hyp)->GetMesh() == theMesh )
1014       return *hyp;
1015   return 0;
1016 }
1017
1018 //================================================================================
1019 /*!
1020  * \brief Find subMesh by ID (entry)
1021   * \param theSubMeshID - The subMesh ID
1022   * \retval Handle(_pySubMesh) - The found subMesh
1023  */
1024 //================================================================================
1025
1026 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1027 {
1028   map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1029   if ( id_subMesh != myObjects.end() )
1030     return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1031   return Handle(_pySubMesh)();
1032 }
1033
1034
1035 //================================================================================
1036 /*!
1037  * \brief Change order of commands in the script
1038   * \param theCmd1 - One command
1039   * \param theCmd2 - Another command
1040  */
1041 //================================================================================
1042
1043 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1044 {
1045   list< Handle(_pyCommand) >::iterator pos1, pos2;
1046   pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1047   pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1048   myCommands.insert( pos1, theCmd2 );
1049   myCommands.insert( pos2, theCmd1 );
1050   myCommands.erase( pos1 );
1051   myCommands.erase( pos2 );
1052
1053   int nb1 = theCmd1->GetOrderNb();
1054   theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1055   theCmd2->SetOrderNb( nb1 );
1056 //   cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1057 //        << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1058 }
1059
1060 //================================================================================
1061 /*!
1062  * \brief Set one command after the other
1063   * \param theCmd - Command to move
1064   * \param theAfterCmd - Command ater which to insert the first one
1065  */
1066 //================================================================================
1067
1068 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1069 {
1070   setNeighbourCommand( theCmd, theAfterCmd, true );
1071 }
1072
1073 //================================================================================
1074 /*!
1075  * \brief Set one command before the other
1076   * \param theCmd - Command to move
1077   * \param theBeforeCmd - Command before which to insert the first one
1078  */
1079 //================================================================================
1080
1081 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1082 {
1083   setNeighbourCommand( theCmd, theBeforeCmd, false );
1084 }
1085
1086 //================================================================================
1087 /*!
1088  * \brief Set one command before or after the other
1089   * \param theCmd - Command to move
1090   * \param theOtherCmd - Command ater or before which to insert the first one
1091  */
1092 //================================================================================
1093
1094 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1095                                   Handle(_pyCommand)& theOtherCmd,
1096                                   const bool theIsAfter )
1097 {
1098   list< Handle(_pyCommand) >::iterator pos;
1099   pos = find( myCommands.begin(), myCommands.end(), theCmd );
1100   myCommands.erase( pos );
1101   pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1102   myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1103
1104   int i = 1;
1105   for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1106     (*pos)->SetOrderNb( i++ );
1107 }
1108
1109 //================================================================================
1110 /*!
1111  * \brief Set command be last in list of commands
1112   * \param theCmd - Command to be last
1113  */
1114 //================================================================================
1115
1116 Handle(_pyCommand)& _pyGen::GetLastCommand()
1117 {
1118   return myLastCommand;
1119 }
1120
1121 //================================================================================
1122 /*!
1123  * \brief Set method to access to object wrapped with python class
1124   * \param theID - The wrapped object entry
1125   * \param theMethod - The accessor method
1126  */
1127 //================================================================================
1128
1129 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1130 {
1131   myID2AccessorMethod.Bind( theID, (char*) theMethod );
1132 }
1133
1134 //================================================================================
1135 /*!
1136  * \brief Generated new ID for object and assign with existing name
1137   * \param theID - ID of existing object
1138  */
1139 //================================================================================
1140
1141 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1142 {
1143   int index = 1;
1144   _pyID aNewID;
1145   do {
1146     aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1147   }
1148   while ( myObjectNames.IsBound( aNewID ) );
1149
1150   myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1151                       ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1152                       : _pyID( "A" ) + aNewID );
1153   return aNewID;
1154 }
1155
1156 //================================================================================
1157 /*!
1158  * \brief Stores theObj in myObjects
1159  */
1160 //================================================================================
1161
1162 void _pyGen::AddObject( Handle(_pyObject)& theObj )
1163 {
1164   if ( theObj.IsNull() ) return;
1165
1166   if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1167     myMeshes.insert( make_pair( theObj->GetID(), Handle(_pyMesh)::DownCast( theObj )));
1168
1169   else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1170     myMeshEditors.insert( make_pair( theObj->GetID(), Handle(_pyMeshEditor)::DownCast( theObj )));
1171
1172   else
1173     myObjects.insert( make_pair( theObj->GetID(), theObj ));
1174 }
1175
1176 //================================================================================
1177 /*!
1178  * \brief Re-register an object with other ID to make it Process() commands of
1179  * other object having this ID
1180  */
1181 //================================================================================
1182
1183 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1184 {
1185   if ( theObj.IsNull() ) return;
1186
1187   if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1188     myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1189
1190   else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1191     myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1192
1193   else
1194     myObjects.insert( make_pair( theID, theObj ));
1195 }
1196
1197 //================================================================================
1198 /*!
1199  * \brief Finds a _pyObject by ID
1200  */
1201 //================================================================================
1202
1203 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID )  const
1204 {
1205   {
1206     map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1207     if ( id_obj != myObjects.end() )
1208       return id_obj->second;
1209   }
1210   {
1211     map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1212     if ( id_obj != myMeshes.end() )
1213       return id_obj->second;
1214   }
1215   // {
1216   //   map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1217   //   if ( id_obj != myMeshEditors.end() )
1218   //     return id_obj->second;
1219   // }
1220   return Handle(_pyObject)();
1221 }
1222
1223 //================================================================================
1224 /*!
1225  * \brief Check if a study entry is under GEOM component
1226  */
1227 //================================================================================
1228
1229 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1230 {
1231   if ( myGeomIDNb )
1232   {
1233     return ( myGeomIDIndex <= theObjID.Length() &&
1234              int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb);
1235   }
1236   return false;
1237 }
1238
1239 //================================================================================
1240 /*!
1241  * \brief Returns true if an object is not present in a study
1242  */
1243 //================================================================================
1244
1245 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1246 {
1247   if ( theObjID.IsEmpty() ) return false;
1248
1249   if ( myObjectNames.IsBound( theObjID ))
1250     return false; // SMESH object is in study
1251
1252   // either the SMESH object is not in study or it is a GEOM object
1253   if ( IsGeomObject( theObjID ))
1254   {
1255     SALOMEDS::SObject_var so = myStudy->FindObjectID( theObjID.ToCString() );
1256     if ( so->_is_nil() ) return true;
1257     CORBA::Object_var obj = so->GetObject();
1258     return CORBA::is_nil( obj );
1259   }
1260   return true; // SMESH object not in study
1261 }
1262
1263 //================================================================================
1264 /*!
1265  * \brief Return reader of  hypotheses of plugins
1266  */
1267 //================================================================================
1268
1269 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1270 {
1271   if (myHypReader.IsNull() )
1272     ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1273
1274   return myHypReader;
1275 }
1276
1277
1278 //================================================================================
1279 /*!
1280  * \brief Mesh created by SMESH_Gen
1281  */
1282 //================================================================================
1283
1284 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1285   : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1286 {
1287   if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1288     myGeomNotInStudy = true;
1289
1290   // convert my creation command --> smeshpy.Mesh(...)
1291   Handle(_pyCommand) creationCmd = GetCreationCmd();
1292   creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1293   creationCmd->SetMethod( "Mesh" );
1294   theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1295 }
1296
1297 //================================================================================
1298 /*!
1299  * \brief Mesh created by SMESH_MeshEditor
1300  */
1301 //================================================================================
1302
1303 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1304   _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1305 {
1306   if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1307   {
1308     // this mesh depends on the exported mesh
1309     const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1310     if ( !file.IsEmpty() )
1311     {
1312       ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1313       addFatherMesh( exportData.myMesh );
1314       if ( !exportData.myLastComputeCmd.IsNull() )
1315       {
1316         // restore cleared Compute() by which the exported mesh was generated
1317         exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1318         // protect that Compute() cmd from clearing
1319         if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1320           exportData.myMesh->myLastComputeCmd.Nullify();
1321       }
1322     }
1323   }
1324   else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1325   {
1326     // this mesh depends on concatenated meshes
1327     const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1328     list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1329     list< _pyID >::iterator meshID = idList.begin();
1330     for ( ; meshID != idList.end(); ++meshID )
1331       addFatherMesh( *meshID );
1332   }
1333   else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1334   {
1335     // this mesh depends on a copied IdSource
1336     const _pyID& objID = theCreationCmd->GetArg( 1 );
1337     addFatherMesh( objID );
1338   }
1339   else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1340             theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1341             theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1342   {
1343     // this mesh depends on a source mesh
1344     // (theCreationCmd is already Process()ed by _pyMeshEditor)
1345     const _pyID& meshID = theCreationCmd->GetObject();
1346     addFatherMesh( meshID );
1347   }
1348     
1349   // convert my creation command
1350   Handle(_pyCommand) creationCmd = GetCreationCmd();
1351   creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1352   theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1353 }
1354
1355 //================================================================================
1356 /*!
1357  * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1358   * \param theCommand - Engine method called for this mesh
1359  */
1360 //================================================================================
1361
1362 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1363 {
1364   // some methods of SMESH_Mesh interface needs special conversion
1365   // to methods of Mesh python class
1366   //
1367   // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1368   //     --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1369   // 2. AddHypothesis(geom, hyp)
1370   //     --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1371   // 3. CreateGroupFromGEOM(type, name, grp)
1372   //     --> in Mesh.Group(grp, name="")
1373   // 4. ExportToMED(f, auto_groups, version)
1374   //     --> in Mesh.ExportMED( f, auto_groups, version )
1375   // 5. etc
1376
1377   const TCollection_AsciiString& method = theCommand->GetMethod();
1378   // ----------------------------------------------------------------------
1379   if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1380   {
1381     if ( !theGen->IsToKeepAllCommands() ) // !historical
1382     {
1383       list< Handle(_pyHypothesis) >::iterator hyp;
1384       if ( !myLastComputeCmd.IsNull() )
1385       {
1386         for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1387           (*hyp)->ComputeDiscarded( myLastComputeCmd );
1388
1389         myLastComputeCmd->Clear();
1390       }
1391       myLastComputeCmd = theCommand;
1392
1393       for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1394         (*hyp)->MeshComputed( myLastComputeCmd );
1395     }
1396     Flush();
1397   }
1398   // ----------------------------------------------------------------------
1399   else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1400   {
1401     if ( !theGen->IsToKeepAllCommands() ) // !historical
1402     {
1403       int untilCmdNb =
1404         myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1405       // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1406       // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1407       //   (*cmd)->Clear();
1408       if ( !myLastComputeCmd.IsNull() )
1409       {
1410         list< Handle(_pyHypothesis) >::iterator hyp;
1411         for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1412           (*hyp)->ComputeDiscarded( myLastComputeCmd );
1413
1414         myLastComputeCmd->Clear();
1415       }
1416
1417       list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1418       for ( ; e != myEditors.end(); ++e )
1419       {
1420         list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1421         list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1422         for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1423           if ( !(*cmd)->IsEmpty() )
1424           {
1425             if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1426               (*cmd)->Clear();
1427           }
1428       }
1429       myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1430     }
1431   }
1432   // ----------------------------------------------------------------------
1433   else if ( method == "GetSubMesh" ) { // collect submeshes of the mesh
1434     Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1435     if ( !subMesh.IsNull() ) {
1436       subMesh->SetCreator( this );
1437       mySubmeshes.push_back( subMesh );
1438     }
1439   }
1440   else if ( method == "RemoveSubMesh" ) { // move submesh creation before its removal
1441     Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetArg(1) );
1442     if ( !subMesh.IsNull() )
1443       subMesh->Process( theCommand );
1444     AddMeshAccess( theCommand );
1445   }
1446   // ----------------------------------------------------------------------
1447   else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1448     myAddHypCmds.push_back( theCommand );
1449     // set mesh to hypo
1450     const _pyID& hypID = theCommand->GetArg( 2 );
1451     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1452     if ( !hyp.IsNull() ) {
1453       myHypos.push_back( hyp );
1454       if ( hyp->GetMesh().IsEmpty() )
1455         hyp->SetMesh( this->GetID() );
1456     }
1457   }
1458   // ----------------------------------------------------------------------
1459   else if ( method == "CreateGroup" ||
1460             method == "CreateGroupFromGEOM" ||
1461             method == "CreateGroupFromFilter" )
1462   {
1463     Handle(_pyGroup) group = new _pyGroup( theCommand );
1464     myGroups.push_back( group );
1465     theGen->AddObject( group );
1466   }
1467   // ----------------------------------------------------------------------
1468   else if ( theCommand->MethodStartsFrom( "Export" ))
1469   {
1470     if ( method == "ExportToMED" ||   // ExportToMED()  --> ExportMED()
1471          method == "ExportToMEDX" ) { // ExportToMEDX() --> ExportMED()
1472       theCommand->SetMethod( "ExportMED" );
1473     }
1474     else if ( method == "ExportCGNS" )
1475     { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1476       _pyID partID = theCommand->GetArg( 1 );
1477       int nbArgs = theCommand->GetNbArgs();
1478       for ( int i = 2; i <= nbArgs; ++i )
1479         theCommand->SetArg( i-1, theCommand->GetArg( i ));
1480       theCommand->SetArg( nbArgs, partID );
1481     }
1482     else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1483     { // ExportPartTo*(part, ...) -> Export*(..., part)
1484       //
1485       // remove "PartTo" from the method
1486       TCollection_AsciiString newMethod = method;
1487       newMethod.Remove( 7, 6 );
1488       theCommand->SetMethod( newMethod );
1489       // make the 1st arg be the last one
1490       _pyID partID = theCommand->GetArg( 1 );
1491       int nbArgs = theCommand->GetNbArgs();
1492       for ( int i = 2; i <= nbArgs; ++i )
1493         theCommand->SetArg( i-1, theCommand->GetArg( i ));
1494       theCommand->SetArg( nbArgs, partID );
1495     }
1496     // remember file name
1497     theGen->AddExportedMesh( theCommand->GetArg( 1 ),
1498                              ExportedMeshData( this, myLastComputeCmd ));
1499   }
1500   // ----------------------------------------------------------------------
1501   else if ( method == "RemoveHypothesis" ) // (geom, hyp)
1502   {
1503     _pyID hypID = theCommand->GetArg( 2 );
1504
1505     // check if this mesh still has corresponding addition command
1506     bool hasAddCmd = false;
1507     list< Handle(_pyCommand) >::iterator cmd = myAddHypCmds.begin();
1508     while ( cmd != myAddHypCmds.end() )
1509     {
1510       // AddHypothesis(geom, hyp)
1511       if ( hypID == (*cmd)->GetArg( 2 )) { // erase both (add and remove) commands
1512         theCommand->Clear();
1513         (*cmd)->Clear();
1514         cmd = myAddHypCmds.erase( cmd );
1515         hasAddCmd = true;
1516       }
1517       else {
1518         ++cmd;
1519       }
1520     }
1521     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1522     if ( ! hasAddCmd && hypID.Length() != 0 ) { // hypo addition already wrapped
1523       // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
1524       _pyID geom = theCommand->GetArg( 1 );
1525       theCommand->RemoveArgs();
1526       theCommand->SetArg( 1, hypID );
1527       if ( geom != GetGeom() )
1528         theCommand->SetArg( 2, geom );
1529     }
1530     // remove hyp from myHypos
1531     myHypos.remove( hyp );
1532   }
1533   // check for SubMesh order commands
1534   else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
1535   {
1536     // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
1537     // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
1538     // commands are moved at the end of the script
1539     TCollection_AsciiString subIDs =
1540       ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
1541     list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
1542     list< _pyID >::iterator subID = idList.begin();
1543     for ( ; subID != idList.end(); ++subID )
1544     {
1545       Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
1546       if ( !subMesh.IsNull() )
1547         subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
1548     }
1549   }
1550   // update list of groups
1551   else if ( method == "GetGroups" )
1552   {
1553     TCollection_AsciiString grIDs = theCommand->GetResultValue();
1554     list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1555     list< _pyID >::iterator grID = idList.begin();
1556     for ( ; grID != idList.end(); ++grID )
1557     {
1558       Handle(_pyObject) obj = theGen->FindObject( *grID );
1559       if ( obj.IsNull() )
1560       {
1561         Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1562         theGen->AddObject( group );
1563         myGroups.push_back( group );
1564       }
1565     }
1566   }
1567   // add accessor method if necessary
1568   else
1569   {
1570     if ( NeedMeshAccess( theCommand ))
1571       // apply theCommand to the mesh wrapped by smeshpy mesh
1572       AddMeshAccess( theCommand );
1573   }
1574 }
1575
1576 //================================================================================
1577 /*!
1578  * \brief Return True if addition of accesor method is needed
1579  */
1580 //================================================================================
1581
1582 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
1583 {
1584   // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
1585   // so no conversion is needed for them at all:
1586   static TStringSet sameMethods;
1587   if ( sameMethods.empty() ) {
1588     const char * names[] =
1589       { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
1590         "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
1591         "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
1592         "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
1593         "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
1594         "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
1595         "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
1596         "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
1597         "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
1598         "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
1599         "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
1600         "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
1601         "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
1602         ,"" }; // <- mark of end
1603     sameMethods.Insert( names );
1604   }
1605
1606   return !sameMethods.Contains( theCommand->GetMethod() );
1607 }
1608
1609 //================================================================================
1610 /*!
1611  * \brief Convert creation and addition of all algos and hypos
1612  */
1613 //================================================================================
1614
1615 void _pyMesh::Flush()
1616 {
1617   {
1618     // get the meshes this mesh depends on via hypotheses
1619     list< Handle(_pyMesh) > fatherMeshes;
1620     list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1621     for ( ; hyp != myHypos.end(); ++hyp )
1622       if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
1623         myGeomNotInStudy = true;
1624
1625     list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
1626     for ( ; m != fatherMeshes.end(); ++m )
1627       addFatherMesh( *m );
1628     // if ( removedGeom )
1629     //     SetRemovedFromStudy(); // as reffered geometry not in study
1630   }
1631   if ( myGeomNotInStudy )
1632     return;
1633
1634   list < Handle(_pyCommand) >::iterator cmd;
1635
1636   // try to convert algo addition like this:
1637   // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
1638   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
1639   {
1640     Handle(_pyCommand) addCmd = *cmd;
1641
1642     _pyID algoID = addCmd->GetArg( 2 );
1643     Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
1644     if ( algo.IsNull() || !algo->IsAlgo() )
1645       continue;
1646
1647     // check and create new algorithm instance if it is already wrapped
1648     if ( algo->IsWrapped() ) {
1649       _pyID localAlgoID = theGen->GenerateNewID( algoID );
1650       TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
1651         TCollection_AsciiString( " = " ) + theGen->GetID() +
1652         TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
1653         TCollection_AsciiString( "\" )" );
1654
1655       Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
1656       Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
1657       if ( !newAlgo.IsNull() ) {
1658         newAlgo->Assign( algo, this->GetID() );
1659         newAlgo->SetCreationCmd( newCmd );
1660         algo = newAlgo;
1661         // set algorithm creation
1662         theGen->SetCommandBefore( newCmd, addCmd );
1663         myHypos.push_back( newAlgo );
1664         if ( !myLastComputeCmd.IsNull() &&
1665              newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
1666           newAlgo->MeshComputed( myLastComputeCmd );
1667       }
1668       else
1669         newCmd->Clear();
1670     }
1671     _pyID geom = addCmd->GetArg( 1 );
1672     bool isLocalAlgo = ( geom != GetGeom() );
1673
1674     // try to convert
1675     if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
1676     {
1677       // wrapped algo is created after mesh creation
1678       GetCreationCmd()->AddDependantCmd( addCmd );
1679
1680       if ( isLocalAlgo ) {
1681         // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
1682         addCmd->SetArg( addCmd->GetNbArgs() + 1,
1683                         TCollection_AsciiString( "geom=" ) + geom );
1684         // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
1685         list < Handle(_pySubMesh) >::iterator smIt;
1686         for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
1687           Handle(_pySubMesh) subMesh = *smIt;
1688           Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
1689           if ( geom == subCmd->GetArg( 1 )) {
1690             subCmd->SetObject( algo->GetID() );
1691             subCmd->RemoveArgs();
1692             subMesh->SetCreator( algo );
1693           }
1694         }
1695       }
1696     }
1697     else // KO - ALGO was already created
1698     {
1699       // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
1700       addCmd->RemoveArgs();
1701       addCmd->SetArg( 1, algoID );
1702       if ( isLocalAlgo )
1703         addCmd->SetArg( 2, geom );
1704     }
1705   }
1706
1707   // try to convert hypo addition like this:
1708   // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
1709   for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
1710   {
1711     Handle(_pyCommand) addCmd = *cmd;
1712     _pyID hypID = addCmd->GetArg( 2 );
1713     Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1714     if ( hyp.IsNull() || hyp->IsAlgo() )
1715       continue;
1716     bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
1717     if ( !converted ) {
1718       // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
1719       _pyID geom = addCmd->GetArg( 1 );
1720       addCmd->RemoveArgs();
1721       addCmd->SetArg( 1, hypID );
1722       if ( geom != GetGeom() )
1723         addCmd->SetArg( 2, geom );
1724     }
1725   }
1726
1727   myAddHypCmds.clear();
1728   mySubmeshes.clear();
1729
1730   // flush hypotheses
1731   list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1732   for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1733     (*hyp)->Flush();
1734 }
1735
1736 //================================================================================
1737 /*!
1738  * \brief Sets myIsPublished of me and of all objects depending on me.
1739  */
1740 //================================================================================
1741
1742 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
1743 {
1744   _pyObject::SetRemovedFromStudy(isRemoved);
1745
1746   list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
1747   for ( ; sm != mySubmeshes.end(); ++sm )
1748     (*sm)->SetRemovedFromStudy(isRemoved);
1749
1750   list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
1751   for ( ; gr != myGroups.end(); ++gr )
1752     (*gr)->SetRemovedFromStudy(isRemoved);
1753
1754   list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
1755   for ( ; m != myChildMeshes.end(); ++m )
1756     (*m)->SetRemovedFromStudy(isRemoved);
1757
1758   list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1759   for ( ; e != myEditors.end(); ++e )
1760     (*e)->SetRemovedFromStudy(isRemoved);
1761 }
1762
1763 //================================================================================
1764 /*!
1765  * \brief Return true if none of myChildMeshes is in study
1766  */
1767 //================================================================================
1768
1769 bool _pyMesh::CanClear()
1770 {
1771   if ( IsInStudy() )
1772     return false;
1773
1774   list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
1775   for ( ; m != myChildMeshes.end(); ++m )
1776     if ( !(*m)->CanClear() )
1777       return false;
1778
1779   return true;
1780 }
1781
1782 //================================================================================
1783 /*!
1784  * \brief Clear my commands and commands of mesh editor
1785  */
1786 //================================================================================
1787
1788 void _pyMesh::ClearCommands()
1789 {
1790   if ( !CanClear() )
1791   {
1792     if ( !IsInStudy() )
1793     {
1794       // mark all sub-objects as not removed, except child meshes
1795       list< Handle(_pyMesh) > children;
1796       children.swap( myChildMeshes );
1797       SetRemovedFromStudy( false );
1798       children.swap( myChildMeshes );
1799     }
1800     return;
1801   }
1802   _pyObject::ClearCommands();
1803
1804   list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
1805   for ( ; sm != mySubmeshes.end(); ++sm )
1806     (*sm)->ClearCommands();
1807   
1808   list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
1809   for ( ; gr != myGroups.end(); ++gr )
1810     (*gr)->ClearCommands();
1811
1812   list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1813   for ( ; e != myEditors.end(); ++e )
1814     (*e)->ClearCommands();
1815 }
1816
1817 //================================================================================
1818 /*!
1819  * \brief Add a father mesh by ID
1820  */
1821 //================================================================================
1822
1823 void _pyMesh::addFatherMesh( const _pyID& meshID )
1824 {
1825   if ( !meshID.IsEmpty() )
1826     addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
1827 }
1828
1829 //================================================================================
1830 /*!
1831  * \brief Add a father mesh
1832  */
1833 //================================================================================
1834
1835 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
1836 {
1837   if ( !mesh.IsNull() )
1838   {
1839     //myFatherMeshes.push_back( mesh );
1840     mesh->myChildMeshes.push_back( this );
1841
1842     // protect last Compute() from clearing by the next Compute()
1843     mesh->myLastComputeCmd.Nullify();
1844   }
1845 }
1846
1847 //================================================================================
1848 /*!
1849  * \brief MeshEditor convert its commands to ones of mesh
1850  */
1851 //================================================================================
1852
1853 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
1854   _pyObject( theCreationCmd )
1855 {
1856   myMesh = theCreationCmd->GetObject();
1857   myCreationCmdStr = theCreationCmd->GetString();
1858   theCreationCmd->Clear();
1859
1860   Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
1861   if ( !mesh.IsNull() )
1862     mesh->AddEditor( this );
1863 }
1864
1865 //================================================================================
1866 /*!
1867  * \brief convert its commands to ones of mesh
1868  */
1869 //================================================================================
1870
1871 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
1872 {
1873   // names of SMESH_MeshEditor methods fully equal to methods of python class Mesh, so
1874   // commands calling this methods are converted to calls of methods of Mesh
1875   static TStringSet sameMethods;
1876   if ( sameMethods.empty() ) {
1877     const char * names[] = {
1878       "RemoveElements","RemoveNodes","RemoveOrphanNodes","AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace",
1879       "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces","MoveNode", "MoveClosestNodeToPoint",
1880       "InverseDiag","DeleteDiag","Reorient","ReorientObject","TriToQuad","SplitQuad","SplitQuadObject",
1881       "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
1882       "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
1883       "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
1884       "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
1885       "ExtrusionAlongPath","ExtrusionAlongPathObject","ExtrusionAlongPathX",
1886       "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
1887       "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
1888       "FindCoincidentNodes",/*"FindCoincidentNodesOnPart",*/"MergeNodes","FindEqualElements",
1889       "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
1890       "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
1891       "GetLastCreatedElems",
1892       "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh",
1893       "TranslateObjectMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
1894       "MakeBoundaryElements"
1895       ,"" }; // <- mark of the end
1896     sameMethods.Insert( names );
1897   }
1898
1899   // names of SMESH_MeshEditor methods which differ from methods of class Mesh
1900   // only by last two arguments
1901   static TStringSet diffLastTwoArgsMethods;
1902   if (diffLastTwoArgsMethods.empty() ) {
1903     const char * names[] = {
1904       "MirrorMakeGroups","MirrorObjectMakeGroups",
1905       "TranslateMakeGroups","TranslateObjectMakeGroups",
1906       "RotateMakeGroups","RotateObjectMakeGroups",
1907       ""};// <- mark of the end
1908     diffLastTwoArgsMethods.Insert( names );
1909   }
1910
1911   const TCollection_AsciiString & method = theCommand->GetMethod();
1912   bool isPyMeshMethod = sameMethods.Contains( method );
1913   if ( !isPyMeshMethod )
1914   {
1915     //Replace SMESH_MeshEditor "MakeGroups" functions by the Mesh
1916     //functions with the flag "theMakeGroups = True" like:
1917     //SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
1918     int pos = method.Search("MakeGroups");
1919     if( pos != -1)
1920     {
1921       isPyMeshMethod = true;
1922       bool is0DmethId  = ( method == "ExtrusionSweepMakeGroups0D" );
1923       bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
1924
1925       // 1. Remove "MakeGroups" from the Command
1926       TCollection_AsciiString aMethod = theCommand->GetMethod();
1927       int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
1928       
1929       if(is0DmethObj)
1930         pos = pos-2;  //Remove "0D" from the Command too
1931       aMethod.Trunc(pos-1);
1932       theCommand->SetMethod(aMethod);
1933
1934       // 2. And add last "True" argument(s)
1935       while(nbArgsToAdd--)
1936         theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
1937       if( is0DmethId || is0DmethObj )
1938         theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
1939     }
1940   }
1941
1942   // ExtrusionSweep0D() -> ExtrusionSweep()
1943   // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
1944   if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D"  ||
1945                             method == "ExtrusionSweepObject0D" ))
1946   {
1947     isPyMeshMethod=true;
1948     theCommand->SetMethod( method.SubString( 1, method.Length()-2));
1949     theCommand->SetArg(theCommand->GetNbArgs()+1,"False");  //sets flag "MakeGroups = False"
1950     theCommand->SetArg(theCommand->GetNbArgs()+1,"True");  //sets flag "IsNode = True"
1951   }
1952   // set "ExtrusionAlongPathX()" instead of "ExtrusionAlongPathObjX()"
1953   if ( !isPyMeshMethod && method == "ExtrusionAlongPathObjX")
1954   {
1955     isPyMeshMethod=true;
1956     theCommand->SetMethod("ExtrusionAlongPathX");
1957   }
1958
1959   // set "FindCoincidentNodesOnPart()" instead of "FindCoincidentNodesOnPartBut()"
1960   if ( !isPyMeshMethod && method == "FindCoincidentNodesOnPartBut")
1961   {
1962     isPyMeshMethod=true;
1963     theCommand->SetMethod("FindCoincidentNodesOnPart");
1964   }
1965   // DoubleNodeElemGroupNew() -> DoubleNodeElemGroup()
1966   // DoubleNodeGroupNew() -> DoubleNodeGroup()
1967   // DoubleNodeGroupsNew() -> DoubleNodeGroups()
1968   // DoubleNodeElemGroupsNew() -> DoubleNodeElemGroups()
1969   if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew"  ||
1970                             method == "DoubleNodeElemGroupsNew" ||
1971                             method == "DoubleNodeGroupNew"      ||
1972                             method == "DoubleNodeGroupsNew"))
1973   {
1974     isPyMeshMethod=true;
1975     theCommand->SetMethod( method.SubString( 1, method.Length()-3));
1976     theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
1977   }
1978   // ConvertToQuadraticObject(bool,obj) -> ConvertToQuadratic(bool,obj)
1979   // ConvertFromQuadraticObject(obj) -> ConvertFromQuadratic(obj)
1980   if ( !isPyMeshMethod && ( method == "ConvertToQuadraticObject" ||
1981                             method == "ConvertFromQuadraticObject" ))
1982   {
1983     isPyMeshMethod=true;
1984     theCommand->SetMethod( method.SubString( 1, method.Length()-6));
1985     // prevent moving creation of the converted sub-mesh to the end of the script
1986     bool isFromQua = ( method.Value( 8 ) == 'F' );
1987     Handle(_pySubMesh) sm = theGen->FindSubMesh( theCommand->GetArg( isFromQua ? 1 : 2 ));
1988     if ( !sm.IsNull() )
1989       sm->Process( theCommand );
1990   }
1991   // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
1992   // FindElementsByPoint(x, y, z, elementType, meshPart)
1993   if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
1994   {
1995     isPyMeshMethod=true;
1996     theCommand->SetMethod( "FindElementsByPoint" );
1997     // make the 1st arg be the last one
1998     _pyID partID = theCommand->GetArg( 1 );
1999     int nbArgs = theCommand->GetNbArgs();
2000     for ( int i = 2; i <= nbArgs; ++i )
2001       theCommand->SetArg( i-1, theCommand->GetArg( i ));
2002     theCommand->SetArg( nbArgs, partID );
2003   }
2004
2005   // meshes made by *MakeMesh() methods are not wrapped by _pyMesh,
2006   // so let _pyMesh care of it (TMP?)
2007   //     if ( theCommand->GetMethod().Search("MakeMesh") != -1 )
2008   //       _pyMesh( new _pyCommand( theCommand->GetString(), 0 )); // for theGen->SetAccessorMethod()
2009   if ( isPyMeshMethod )
2010   {
2011     theCommand->SetObject( myMesh );
2012   }
2013   else
2014   {
2015     // editor creation command is needed only if any editor function is called
2016     theGen->AddMeshAccessorMethod( theCommand ); // for *Object()
2017     if ( !myCreationCmdStr.IsEmpty() ) {
2018       GetCreationCmd()->GetString() = myCreationCmdStr;
2019       myCreationCmdStr.Clear();
2020     }
2021   }
2022 }
2023
2024 //================================================================================
2025 /*!
2026  * \brief Return true if my mesh can be removed
2027  */
2028 //================================================================================
2029
2030 bool _pyMeshEditor::CanClear()
2031 {
2032   Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2033   return mesh.IsNull() ? true : mesh->CanClear();
2034 }
2035
2036 //================================================================================
2037 /*!
2038  * \brief _pyHypothesis constructor
2039   * \param theCreationCmd -
2040  */
2041 //================================================================================
2042
2043 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2044   _pyObject( theCreationCmd ), myCurCrMethod(0)
2045 {
2046   myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2047 }
2048
2049 //================================================================================
2050 /*!
2051  * \brief Creates algorithm or hypothesis
2052   * \param theCreationCmd - The engine command creating a hypothesis
2053   * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2054  */
2055 //================================================================================
2056
2057 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2058 {
2059   // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2060   ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2061
2062   Handle(_pyHypothesis) hyp, algo;
2063
2064   // "theHypType"
2065   const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2066   if ( hypTypeQuoted.IsEmpty() )
2067     return hyp;
2068   // theHypType
2069   TCollection_AsciiString  hypType =
2070     hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2071
2072   algo = new _pyAlgorithm( theCreationCmd );
2073   hyp  = new _pyHypothesis( theCreationCmd );
2074
2075   if ( hypType == "NumberOfSegments" ) {
2076     hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2077     hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2078     // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2079     hyp->AddArgMethod( "SetNumberOfSegments" );
2080     // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2081     hyp->AddArgMethod( "SetScaleFactor" );
2082     hyp->AddArgMethod( "SetReversedEdges" );
2083     // same for ""CompositeSegment_1D:
2084     hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2085     hyp->AddArgMethod( "SetNumberOfSegments" );
2086     hyp->AddArgMethod( "SetScaleFactor" );
2087     hyp->AddArgMethod( "SetReversedEdges" );
2088   }
2089   else if ( hypType == "SegmentLengthAroundVertex" ) {
2090     hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2091     hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2092     hyp->AddArgMethod( "SetLength" );
2093     // same for ""CompositeSegment_1D:
2094     hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2095     hyp->AddArgMethod( "SetLength" );
2096   }
2097   else if ( hypType == "LayerDistribution2D" ) {
2098     hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2099     hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2100   }
2101   else if ( hypType == "LayerDistribution" ) {
2102     hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2103     hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2104   }
2105   else if ( hypType == "CartesianParameters3D" ) {
2106     hyp = new _pyComplexParamHypo( theCreationCmd );
2107     hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2108     for ( int iArg = 0; iArg < 4; ++iArg )
2109       hyp->setCreationArg( iArg+1, "[]");
2110   }
2111   else
2112   {
2113     hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2114   }
2115
2116   return algo->IsValid() ? algo : hyp;
2117 }
2118
2119 //================================================================================
2120 /*!
2121  * \brief Returns true if addition of this hypothesis to a given mesh can be
2122  *        wrapped into hypothesis creation
2123  */
2124 //================================================================================
2125
2126 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2127 {
2128   if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2129   {
2130     Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2131     if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2132       return true;
2133   }
2134   return false;
2135 }
2136
2137 //================================================================================
2138 /*!
2139  * \brief Convert the command adding a hypothesis to mesh into a smesh command
2140   * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2141   * \param theAlgo - The algo that can create this hypo
2142   * \retval bool - false if the command cant be converted
2143  */
2144 //================================================================================
2145
2146 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2147                                        const _pyID&              theMesh)
2148 {
2149   ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2150
2151   if ( !IsWrappable( theMesh ))
2152     return false;
2153
2154   myGeom = theCmd->GetArg( 1 );
2155
2156   Handle(_pyHypothesis) algo;
2157   if ( !IsAlgo() ) {
2158     // find algo created on myGeom in theMesh
2159     algo = theGen->FindAlgo( myGeom, theMesh, this );
2160     if ( algo.IsNull() )
2161       return false;
2162     // attach hypothesis creation command to be after algo creation command
2163     // because it can be new created instance of algorithm
2164     algo->GetCreationCmd()->AddDependantCmd( theCmd );
2165   }
2166   myIsWrapped = true;
2167
2168   // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2169   theCmd->SetResultValue( GetID() );
2170   theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2171   theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2172   // set args (geom will be set by _pyMesh calling this method)
2173   theCmd->RemoveArgs();
2174   for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2175     if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2176       theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2177     else
2178       theCmd->SetArg( i+1, "[]");
2179   }
2180   // set a new creation command
2181   GetCreationCmd()->Clear();
2182   // replace creation command by wrapped instance
2183   // please note, that hypothesis attaches to algo creation command (see upper)
2184   SetCreationCmd( theCmd );
2185
2186
2187   // clear commands setting arg values
2188   list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2189   for ( ; argCmd != myArgCommands.end(); ++argCmd )
2190     (*argCmd)->Clear();
2191
2192   // set unknown arg commands after hypo creation
2193   Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2194   list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2195   for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2196     afterCmd->AddDependantCmd( *cmd );
2197   }
2198
2199   return myIsWrapped;
2200 }
2201
2202 //================================================================================
2203 /*!
2204  * \brief Remember hypothesis parameter values
2205  * \param theCommand - The called hypothesis method
2206  */
2207 //================================================================================
2208
2209 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2210 {
2211   ASSERT( !myIsAlgo );
2212   if ( !theGen->IsToKeepAllCommands() )
2213     rememberCmdOfParameter( theCommand );
2214   // set args
2215   bool usedCommand = false;
2216   TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2217   for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2218   {
2219     CreationMethod& crMethod = type2meth->second;
2220     for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2221       if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2222         if ( !usedCommand )
2223           myArgCommands.push_back( theCommand );
2224         usedCommand = true;
2225         while ( crMethod.myArgs.size() < i+1 )
2226           crMethod.myArgs.push_back( "[]" );
2227         crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2228       }
2229     }
2230   }
2231   if ( !usedCommand )
2232     myUnusedCommands.push_back( theCommand );
2233 }
2234
2235 //================================================================================
2236 /*!
2237  * \brief Finish conversion
2238  */
2239 //================================================================================
2240
2241 void _pyHypothesis::Flush()
2242 {
2243   if ( !IsAlgo() )
2244   {
2245     list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2246     for ( ; cmd != myArgCommands.end(); ++cmd ) {
2247       // Add access to a wrapped mesh
2248       theGen->AddMeshAccessorMethod( *cmd );
2249       // Add access to a wrapped algorithm
2250       theGen->AddAlgoAccessorMethod( *cmd );
2251     }
2252     cmd = myUnusedCommands.begin();
2253     for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2254       // Add access to a wrapped mesh
2255       theGen->AddMeshAccessorMethod( *cmd );
2256       // Add access to a wrapped algorithm
2257       theGen->AddAlgoAccessorMethod( *cmd );
2258     }
2259   }
2260   // forget previous hypothesis modifications
2261   myArgCommands.clear();
2262   myUnusedCommands.clear();
2263 }
2264
2265 //================================================================================
2266 /*!
2267  * \brief clear creation, arg and unkown commands
2268  */
2269 //================================================================================
2270
2271 void _pyHypothesis::ClearAllCommands()
2272 {
2273   GetCreationCmd()->Clear();
2274   list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2275   for ( ; cmd != myArgCommands.end(); ++cmd )
2276     ( *cmd )->Clear();
2277   cmd = myUnusedCommands.begin();
2278   for ( ; cmd != myUnusedCommands.end(); ++cmd )
2279     ( *cmd )->Clear();
2280 }
2281
2282
2283 //================================================================================
2284 /*!
2285  * \brief Assign fields of theOther to me except myIsWrapped
2286  */
2287 //================================================================================
2288
2289 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2290                             const _pyID&                 theMesh )
2291 {
2292   // myCreationCmd = theOther->myCreationCmd;
2293   myIsAlgo                  = theOther->myIsAlgo;
2294   myIsWrapped               = false;
2295   myGeom                    = theOther->myGeom;
2296   myMesh                    = theMesh;
2297   myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2298   //myArgCommands             = theOther->myArgCommands;
2299   //myUnusedCommands          = theOther->myUnusedCommands;
2300   // init myCurCrMethod
2301   GetCreationMethod( theOther->GetAlgoType() );
2302 }
2303
2304 //================================================================================
2305 /*!
2306  * \brief Analyze my erasability depending on myReferredObjs
2307  */
2308 //================================================================================
2309
2310 bool _pyHypothesis::CanClear()
2311 {
2312   if ( IsInStudy() )
2313   {
2314     list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2315     for ( ; obj != myReferredObjs.end(); ++obj )
2316       if ( (*obj)->CanClear() )
2317         return true;
2318     return false;
2319   }
2320   return true;
2321 }
2322
2323 //================================================================================
2324 /*!
2325  * \brief Clear my commands depending on usage by meshes
2326  */
2327 //================================================================================
2328
2329 void _pyHypothesis::ClearCommands()
2330 {
2331   // if ( !theGen->IsToKeepAllCommands() )
2332   // {
2333   //   bool isUsed = false;
2334   //   int lastComputeOrder = 0;
2335   //   list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2336   //   for ( ; cmd != myComputeCmds.end(); ++cmd )
2337   //     if ( ! (*cmd)->IsEmpty() )
2338   //     {
2339   //       isUsed = true;
2340   //       if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2341   //         lastComputeOrder = (*cmd)->GetOrderNb();
2342   //     }
2343   //   if ( !isUsed )
2344   //   {
2345   //     SetRemovedFromStudy( true );
2346   //   }
2347   //   else
2348   //   {
2349   //     // clear my commands invoked after lastComputeOrder
2350   //     // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2351   //     // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2352   //     // {
2353   //     //   list< Handle(_pyCommand)> & cmds = m2c->second;
2354   //     //   if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2355   //     //     cmds.back()->Clear();
2356   //     // }
2357   //   }
2358   // }
2359   _pyObject::ClearCommands();
2360 }
2361
2362 //================================================================================
2363 /*!
2364  * \brief Find arguments that are objects like mesh, group, geometry
2365  *  \param meshes - referred meshes (directly or indirrectly)
2366  *  \retval bool - false if a referred geometry is not in the study
2367  */
2368 //================================================================================
2369
2370 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2371 {
2372   if ( IsAlgo() ) return true;
2373
2374   bool geomPublished = true;
2375   vector< _AString > args;
2376   TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2377   for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2378   {
2379     CreationMethod& crMethod = type2meth->second;
2380     args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2381   }
2382   list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2383   for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2384     for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2385       args.push_back( (*cmd)->GetArg( nb ));
2386   }
2387
2388   for ( size_t i = 0; i < args.size(); ++i )
2389   {
2390     list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2391     if ( idList.empty() && !args[ i ].IsEmpty() )
2392       idList.push_back( args[ i ]);
2393     list< _pyID >::iterator id = idList.begin();
2394     for ( ; id != idList.end(); ++id )
2395     {
2396       Handle(_pyObject)   obj = theGen->FindObject( *id );
2397       if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2398       if ( obj.IsNull() )
2399       {
2400         if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2401           geomPublished = false;
2402       }
2403       else
2404       {
2405         myReferredObjs.push_back( obj );
2406         Handle(_pyMesh) mesh = ObjectToMesh( obj );
2407         if ( !mesh.IsNull() )
2408           meshes.push_back( mesh );
2409         // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2410         else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2411           obj->SetRemovedFromStudy( false );
2412       }
2413     }
2414   }
2415   return geomPublished;
2416 }
2417
2418 //================================================================================
2419 /*!
2420  * \brief Remember theCommand setting a parameter
2421  */
2422 //================================================================================
2423
2424 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2425 {
2426   // parameters are discriminated by method name
2427   TCollection_AsciiString method = theCommand->GetMethod();
2428
2429   // discriminate commands setting different parameters via one method
2430   // by passing parameter names like e.g. SetOption("size", "0.2")
2431   if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
2432        theCommand->GetNbArgs() > 1 )
2433   {
2434     // mangle method by appending a 1st textual arg
2435     for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
2436     {
2437       const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
2438       if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
2439       if ( !isalpha( arg.Value(2))) continue;
2440       method += arg;
2441       break;
2442     }
2443   }
2444   // parameters are discriminated by method name
2445   list< Handle(_pyCommand)>& cmds = myMeth2Commands[ theCommand->GetMethod() ];
2446   if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
2447   {
2448     cmds.back()->Clear(); // previous parameter value has not been used
2449     cmds.back() = theCommand;
2450   }
2451   else
2452   {
2453     cmds.push_back( theCommand );
2454   }
2455 }
2456
2457 //================================================================================
2458 /*!
2459  * \brief Return true if a setting parameter command ha been used to compute mesh
2460  */
2461 //================================================================================
2462
2463 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
2464                                          _pyCommand::TAddr          avoidComputeAddr ) const
2465 {
2466   bool isUsed = false;
2467   map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
2468     myComputeAddr2Cmds.begin();
2469   for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
2470   {
2471     if ( addr2cmds->first == avoidComputeAddr ) continue;
2472     const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
2473     isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
2474   }
2475   return isUsed;
2476 }
2477
2478 //================================================================================
2479 /*!
2480  * \brief Save commands setting parameters as they are used for a mesh computation
2481  */
2482 //================================================================================
2483
2484 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
2485 {
2486   myComputeCmds.push_back( theComputeCmd );
2487   list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2488
2489   map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2490   for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2491     savedCmds.push_back( m2c->second.back() );
2492 }
2493
2494 //================================================================================
2495 /*!
2496  * \brief Clear commands setting parameters as a mesh computed using them is cleared
2497  */
2498 //================================================================================
2499
2500 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
2501 {
2502   list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2503
2504   list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
2505   for ( ; cmd != savedCmds.end(); ++cmd )
2506   {
2507     // check if a cmd has been used to compute another mesh
2508     if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
2509       continue;
2510     // check if a cmd is a sole command setting its parameter;
2511     // don't use method name for search as it can change
2512     map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
2513       m2cmds = myMeth2Commands.begin();
2514     for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
2515     {
2516       list< Handle(_pyCommand)>& cmds = m2cmds->second;
2517       list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
2518       if ( cmdIt != cmds.end() )
2519       {
2520         if ( cmds.back() != *cmd )
2521         {
2522           cmds.erase( cmdIt );
2523           (*cmd)->Clear();
2524         }
2525         break;
2526       }
2527     }
2528   }
2529   myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
2530 }
2531
2532 //================================================================================
2533 /*!
2534  * \brief Sets an argNb-th argument of current creation command
2535  *  \param argNb - argument index countered from 1
2536  */
2537 //================================================================================
2538
2539 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
2540 {
2541   if ( myCurCrMethod )
2542   {
2543     while ( myCurCrMethod->myArgs.size() < argNb )
2544       myCurCrMethod->myArgs.push_back( "None" );
2545     if ( arg.IsEmpty() )
2546       myCurCrMethod->myArgs[ argNb-1 ] = "None";
2547     else
2548       myCurCrMethod->myArgs[ argNb-1 ] = arg;
2549   }
2550 }
2551
2552
2553 //================================================================================
2554 /*!
2555  * \brief Remember hypothesis parameter values
2556  * \param theCommand - The called hypothesis method
2557  */
2558 //================================================================================
2559
2560 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
2561 {
2562   if ( GetAlgoType() == "Cartesian_3D" )
2563   {
2564     // CartesianParameters3D hyp
2565
2566     if ( theCommand->GetMethod() == "SetSizeThreshold" )
2567     {
2568       setCreationArg( 4, theCommand->GetArg( 1 ));
2569       myArgCommands.push_back( theCommand );
2570       return;
2571     }
2572     if ( theCommand->GetMethod() == "SetGrid" ||
2573          theCommand->GetMethod() == "SetGridSpacing" )
2574     {
2575       TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
2576       int iArg = axis.Value(1) - '0';
2577       if ( theCommand->GetMethod() == "SetGrid" )
2578       {
2579         setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
2580       }
2581       else
2582       {
2583         myCurCrMethod->myArgs[ iArg ] = "[ ";
2584         myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
2585         myCurCrMethod->myArgs[ iArg ] += ", ";
2586         myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
2587         myCurCrMethod->myArgs[ iArg ] += "]";
2588       }
2589       myArgCommands.push_back( theCommand );
2590       rememberCmdOfParameter( theCommand );
2591       return;
2592     }
2593   }
2594
2595   if( theCommand->GetMethod() == "SetLength" )
2596   {
2597     // NOW it is OBSOLETE
2598     // ex: hyp.SetLength(start, 1)
2599     //     hyp.SetLength(end,   0)
2600     ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
2601     int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
2602     TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2603     for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2604     {
2605       CreationMethod& crMethod = type2meth->second;
2606         while ( crMethod.myArgs.size() < i+1 )
2607           crMethod.myArgs.push_back( "[]" );
2608         crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
2609     }
2610     myArgCommands.push_back( theCommand );
2611   }
2612   else
2613   {
2614     _pyHypothesis::Process( theCommand );
2615   }
2616 }
2617 //================================================================================
2618 /*!
2619  * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
2620  */
2621 //================================================================================
2622
2623 void _pyComplexParamHypo::Flush()
2624 {
2625   if ( IsWrapped() )
2626   {
2627     list < Handle(_pyCommand) >::iterator cmd = myUnusedCommands.begin();
2628     for ( ; cmd != myUnusedCommands.end(); ++cmd )
2629       if ((*cmd)->GetMethod() == "SetObjectEntry" )
2630         (*cmd)->Clear();
2631   }
2632 }
2633
2634 //================================================================================
2635 /*!
2636  * \brief Convert methods of 1D hypotheses to my own methods
2637   * \param theCommand - The called hypothesis method
2638  */
2639 //================================================================================
2640
2641 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
2642 {
2643   if ( theCommand->GetMethod() != "SetLayerDistribution" )
2644     return;
2645
2646   const _pyID& hyp1dID = theCommand->GetArg( 1 );
2647   // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
2648   // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
2649   // {
2650   //   TCollection_AsciiString cmd =
2651   //     my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
2652   //   Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
2653   //   theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
2654   //   hyp1d = my1dHyp;
2655   // }
2656   // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
2657   // {
2658   //   // 1D hypo is already set, so distribution changes and the old
2659   //   // 1D hypo is thrown away
2660   //   my1dHyp->ClearAllCommands();
2661   // }
2662   // my1dHyp = hyp1d;
2663   // //my1dHyp->SetRemovedFromStudy( false );
2664
2665   // if ( !myArgCommands.empty() )
2666   //   myArgCommands.back()->Clear();
2667   myCurCrMethod->myArgs.push_back( hyp1dID );
2668   myArgCommands.push_back( theCommand );
2669 }
2670
2671 //================================================================================
2672 /*!
2673  * \brief
2674   * \param theAdditionCmd - command to be converted
2675   * \param theMesh - mesh instance
2676   * \retval bool - status
2677  */
2678 //================================================================================
2679
2680 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
2681                                                   const _pyID&              theMesh)
2682 {
2683   myIsWrapped = false;
2684
2685   if ( my1dHyp.IsNull() )
2686     return false;
2687
2688   // set "SetLayerDistribution()" after addition cmd
2689   theAdditionCmd->AddDependantCmd( myArgCommands.front() );
2690
2691   _pyID geom = theAdditionCmd->GetArg( 1 );
2692
2693   Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
2694   if ( !algo.IsNull() )
2695   {
2696     my1dHyp->SetMesh( theMesh );
2697     my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
2698                                   algo->GetAlgoType().ToCString());
2699     if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
2700       return false;
2701
2702     // clear "SetLayerDistribution()" cmd
2703     myArgCommands.back()->Clear();
2704
2705     // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
2706
2707     // find RadialPrism algo created on <geom> for theMesh
2708     GetCreationCmd()->SetObject( algo->GetID() );
2709     GetCreationCmd()->SetMethod( myAlgoMethod );
2710     GetCreationCmd()->RemoveArgs();
2711     theAdditionCmd->AddDependantCmd( GetCreationCmd() );
2712     myIsWrapped = true;
2713   }
2714   return myIsWrapped;
2715 }
2716
2717 //================================================================================
2718 /*!
2719  * \brief
2720  */
2721 //================================================================================
2722
2723 void _pyLayerDistributionHypo::Flush()
2724 {
2725   // as creation of 1D hyp was written later then it's edition,
2726   // we need to find all it's edition calls and process them
2727   list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2728   _pyID prevNewName;
2729   for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
2730   {    
2731     const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
2732     if ( hyp1dID.IsEmpty() ) continue;
2733
2734     Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
2735
2736     // make a new name for 1D hyp = "HypType" + "_Distribution"
2737     _pyID newName;
2738     if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
2739     {
2740       if ( prevNewName.IsEmpty() ) continue;
2741       newName = prevNewName;
2742     }
2743     else
2744     {
2745       if ( hyp1d->IsWrapped() ) {
2746         newName = hyp1d->GetCreationCmd()->GetMethod();
2747       }
2748       else {
2749         TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
2750         newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2751       }
2752       newName += "_Distribution";
2753       prevNewName = newName;
2754     
2755       hyp1d->GetCreationCmd()->SetResultValue( newName );
2756     }
2757     list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
2758     list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
2759     for ( ; cmdIt != cmds.end(); ++cmdIt ) {
2760       const _pyID& objID = (*cmdIt)->GetObject();
2761       if ( objID == hyp1dID ) {
2762         if ( !hyp1d.IsNull() )
2763         {
2764           hyp1d->Process( *cmdIt );
2765           hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
2766         }
2767         ( *cmdIt )->SetObject( newName );
2768       }
2769     }
2770     // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
2771     (*cmd)->SetArg( 1, newName );
2772   }
2773 }
2774
2775 //================================================================================
2776 /*!
2777  * \brief additionally to Addition2Creation, clears SetDistrType() command
2778   * \param theCmd - AddHypothesis() command
2779   * \param theMesh - mesh to which a hypothesis is added
2780   * \retval bool - convertion result
2781  */
2782 //================================================================================
2783
2784 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
2785                                                 const _pyID&              theMesh)
2786 {
2787   if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
2788     // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
2789     bool scaleDistrType = false;
2790     list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
2791     for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
2792       if ( (*cmd)->GetMethod() == "SetDistrType" ) {
2793         if ( (*cmd)->GetArg( 1 ) == "1" ) {
2794           scaleDistrType = true;
2795           (*cmd)->Clear();
2796         }
2797         else if ( !scaleDistrType ) {
2798           // distribution type changed: remove scale factor from args
2799           TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2800           for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2801           {
2802             CreationMethod& crMethod = type2meth->second;
2803             if ( crMethod.myArgs.size() == 2 )
2804               crMethod.myArgs.pop_back();
2805           }
2806           break;
2807         }
2808       }
2809     }
2810   }
2811   return _pyHypothesis::Addition2Creation( theCmd, theMesh );
2812 }
2813
2814 //================================================================================
2815 /*!
2816  * \brief remove repeated commands defining distribution
2817  */
2818 //================================================================================
2819
2820 void _pyNumberOfSegmentsHyp::Flush()
2821 {
2822   // find number of the last SetDistrType() command
2823   list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
2824   int distrTypeNb = 0;
2825   for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
2826     if ( (*cmd)->GetMethod() == "SetDistrType" )
2827       distrTypeNb = (*cmd)->GetOrderNb();
2828     else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" )
2829       (*cmd)->Clear();
2830
2831   // clear commands before the last SetDistrType()
2832   list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
2833   for ( int i = 0; i < 2; ++i ) {
2834     set<TCollection_AsciiString> uniqueMethods;
2835     list<Handle(_pyCommand)> & cmdList = *cmds[i];
2836     for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
2837     {
2838       bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
2839       const TCollection_AsciiString& method = (*cmd)->GetMethod();
2840       if ( !clear || method == "SetNumberOfSegments" ) {
2841         bool isNewInSet = uniqueMethods.insert( method ).second;
2842         clear = !isNewInSet;
2843       }
2844       if ( clear )
2845         (*cmd)->Clear();
2846     }
2847     cmdList.clear();
2848   }
2849 }
2850
2851 //================================================================================
2852 /*!
2853  * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
2854  * into regular1D.LengthNearVertex( length, vertex )
2855   * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
2856   * \param theMesh - The mesh needing this hypo
2857   * \retval bool - false if the command cant be converted
2858  */
2859 //================================================================================
2860
2861 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
2862                                                          const _pyID&              theMeshID)
2863 {
2864   if ( IsWrappable( theMeshID )) {
2865
2866     _pyID vertex = theCmd->GetArg( 1 );
2867
2868     // the problem here is that segment algo will not be found
2869     // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
2870     // geometry where segment algorithm is assigned
2871     Handle(_pyHypothesis) algo;
2872     _pyID geom = vertex;
2873     while ( algo.IsNull() && !geom.IsEmpty()) {
2874       // try to find geom as a father of <vertex>
2875       geom = FatherID( geom );
2876       algo = theGen->FindAlgo( geom, theMeshID, this );
2877     }
2878     if ( algo.IsNull() )
2879       return false; // also possible to find geom as brother of veretex...
2880     // set geom instead of vertex
2881     theCmd->SetArg( 1, geom );
2882
2883     // set vertex as a second arg
2884     if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
2885     setCreationArg( 2, vertex );
2886
2887     // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
2888     // theMeshID.LengthNearVertex( length, vertex )
2889     return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
2890   }
2891   return false;
2892 }
2893
2894 //================================================================================
2895 /*!
2896  * \brief _pyAlgorithm constructor
2897  * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
2898  */
2899 //================================================================================
2900
2901 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
2902   : _pyHypothesis( theCreationCmd )
2903 {
2904   myIsAlgo = true;
2905 }
2906
2907 //================================================================================
2908 /*!
2909  * \brief Convert the command adding an algorithm to mesh
2910   * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
2911   * \param theMesh - The mesh needing this algo
2912   * \retval bool - false if the command cant be converted
2913  */
2914 //================================================================================
2915
2916 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
2917                                       const _pyID&              theMeshID)
2918 {
2919   // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
2920   if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
2921     theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
2922     return true;
2923   }
2924   return false;
2925 }
2926
2927 //================================================================================
2928 /*!
2929  * \brief Return starting position of a part of python command
2930   * \param thePartIndex - The index of command part
2931   * \retval int - Part position
2932  */
2933 //================================================================================
2934
2935 int _pyCommand::GetBegPos( int thePartIndex )
2936 {
2937   if ( IsEmpty() )
2938     return EMPTY;
2939   if ( myBegPos.Length() < thePartIndex )
2940     return UNKNOWN;
2941   return myBegPos( thePartIndex );
2942 }
2943
2944 //================================================================================
2945 /*!
2946  * \brief Store starting position of a part of python command
2947   * \param thePartIndex - The index of command part
2948   * \param thePosition - Part position
2949  */
2950 //================================================================================
2951
2952 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
2953 {
2954   while ( myBegPos.Length() < thePartIndex )
2955     myBegPos.Append( UNKNOWN );
2956   myBegPos( thePartIndex ) = thePosition;
2957 }
2958
2959 //================================================================================
2960 /*!
2961  * \brief Returns whitespace symbols at the line beginning
2962   * \retval TCollection_AsciiString - result
2963  */
2964 //================================================================================
2965
2966 TCollection_AsciiString _pyCommand::GetIndentation()
2967 {
2968   int end = 1;
2969   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
2970     GetWord( myString, end, true );
2971   else
2972     end = GetBegPos( RESULT_IND );
2973   return myString.SubString( 1, end - 1 );
2974 }
2975
2976 //================================================================================
2977 /*!
2978  * \brief Return substring of python command looking like ResultValue = Obj.Meth()
2979   * \retval const TCollection_AsciiString & - ResultValue substring
2980  */
2981 //================================================================================
2982
2983 const TCollection_AsciiString & _pyCommand::GetResultValue()
2984 {
2985   if ( GetBegPos( RESULT_IND ) == UNKNOWN )
2986   {
2987     SetBegPos( RESULT_IND, EMPTY );
2988     int begPos, endPos = myString.Location( "=", 1, Length() );
2989     if ( endPos )
2990     {
2991       begPos = 1;
2992       while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
2993       if ( begPos < endPos )
2994       {
2995         SetBegPos( RESULT_IND, begPos );
2996         --endPos;
2997         while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
2998         myRes = myString.SubString( begPos, endPos );
2999       }
3000     }
3001   }
3002   return myRes;
3003 }
3004
3005 //================================================================================
3006 /*!
3007  * \brief Return number of python command result value ResultValue = Obj.Meth()
3008   * \retval const int
3009  */
3010 //================================================================================
3011
3012 const int _pyCommand::GetNbResultValues()
3013 {
3014   int begPos = 1;
3015   int Nb=0;
3016   int endPos = myString.Location( "=", 1, Length() );
3017   TCollection_AsciiString str = "";
3018   while ( begPos < endPos) {
3019     str = GetWord( myString, begPos, true );
3020     begPos = begPos+ str.Length();
3021     Nb++;
3022   }
3023   return (Nb-1);
3024 }
3025
3026
3027 //================================================================================
3028 /*!
3029  * \brief Return substring of python command looking like
3030  *  ResultValue1 , ResultValue1,... = Obj.Meth() with res index
3031  * \retval const TCollection_AsciiString & - ResultValue with res index substring
3032  */
3033 //================================================================================
3034 const TCollection_AsciiString & _pyCommand::GetResultValue(int res)
3035 {
3036   int begPos = 1;
3037   int Nb=0;
3038   int endPos = myString.Location( "=", 1, Length() );
3039   while ( begPos < endPos) {
3040     myRes = GetWord( myString, begPos, true );
3041     begPos = begPos + myRes.Length();
3042     Nb++;
3043     if(res == Nb){
3044       myRes.RemoveAll('[');myRes.RemoveAll(']');
3045       return myRes;
3046     }
3047     if(Nb>res)
3048       break;
3049   }
3050   return theEmptyString;
3051 }
3052
3053 //================================================================================
3054 /*!
3055  * \brief Return substring of python command looking like ResVal = Object.Meth()
3056   * \retval const TCollection_AsciiString & - Object substring
3057  */
3058 //================================================================================
3059
3060 const TCollection_AsciiString & _pyCommand::GetObject()
3061 {
3062   if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3063   {
3064     // beginning
3065     int begPos = GetBegPos( RESULT_IND ) + myRes.Length();
3066     if ( begPos < 1 ) {
3067       begPos = myString.Location( "=", 1, Length() ) + 1;
3068       // is '=' in the string argument (for example, name) or not
3069       int nb1 = 0; // number of ' character at the left of =
3070       int nb2 = 0; // number of " character at the left of =
3071       for ( int i = 1; i < begPos-1; i++ ) {
3072         if ( myString.Value( i )=='\'' )
3073           nb1 += 1;
3074         else if ( myString.Value( i )=='"' )
3075           nb2 += 1;
3076       }
3077       // if number of ' or " is not divisible by 2,
3078       // then get an object at the start of the command
3079       if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3080         begPos = 1;
3081     }
3082     myObj = GetWord( myString, begPos, true );
3083     // check if object is complex,
3084     // so far consider case like "smesh.smesh.Method()"
3085     if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3086       //if ( bracketPos==0 ) bracketPos = Length();
3087       int dotPos = begPos+myObj.Length();
3088       while ( dotPos+1 < bracketPos ) {
3089         if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3090           dotPos = pos;
3091         else
3092           break;
3093       }
3094       if ( dotPos > begPos+myObj.Length() )
3095         myObj = myString.SubString( begPos, dotPos-1 );
3096     }
3097     // 1st word after '=' is an object
3098     // else // no method -> no object
3099     // {
3100     //   myObj.Clear();
3101     //   begPos = EMPTY;
3102     // }
3103     // store
3104     SetBegPos( OBJECT_IND, begPos );
3105   }
3106   //SCRUTE(myObj);
3107   return myObj;
3108 }
3109
3110 //================================================================================
3111 /*!
3112  * \brief Return substring of python command looking like ResVal = Obj.Method()
3113   * \retval const TCollection_AsciiString & - Method substring
3114  */
3115 //================================================================================
3116
3117 const TCollection_AsciiString & _pyCommand::GetMethod()
3118 {
3119   if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3120   {
3121     // beginning
3122     int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3123     bool forward = true;
3124     if ( begPos < 1 ) {
3125       begPos = myString.Location( "(", 1, Length() ) - 1;
3126       forward = false;
3127     }
3128     // store
3129     myMeth = GetWord( myString, begPos, forward );
3130     SetBegPos( METHOD_IND, begPos );
3131   }
3132   //SCRUTE(myMeth);
3133   return myMeth;
3134 }
3135
3136 //================================================================================
3137 /*!
3138  * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3139   * \retval const TCollection_AsciiString & - Arg<index> substring
3140  */
3141 //================================================================================
3142
3143 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3144 {
3145   if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3146   {
3147     // Find all args
3148
3149     int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3150     if ( pos < 1 )
3151       pos = myString.Location( "(", 1, Length() );
3152     else
3153       --pos;
3154
3155     // we are at or before '(', skip it if present
3156     if ( pos > 0 ) {
3157       while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3158       if ( pos > Length() )
3159         pos = 0;
3160     }
3161     if ( pos < 1 ) {
3162       SetBegPos( ARG1_IND, 0 ); // even no '('
3163       return theEmptyString;
3164     }
3165     ++pos;
3166
3167     list< TCollection_AsciiString > separatorStack( 1, ",)");
3168     bool ignoreNesting = false;
3169     int prevPos = pos;
3170     while ( pos <= Length() )
3171     {
3172       const char chr = myString.Value( pos );
3173
3174       if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3175       {
3176         if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3177         {
3178           while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3179             ++prevPos;
3180           TCollection_AsciiString arg;
3181           if ( pos-1 >= prevPos ) {
3182             arg = myString.SubString( prevPos, pos-1 );
3183             arg.RightAdjust(); // remove spaces
3184             arg.LeftAdjust();
3185           }
3186           if ( !arg.IsEmpty() || chr == ',' )
3187           {
3188             SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3189             myArgs.Append( arg );
3190           }
3191           if ( chr == ')' )
3192             break;
3193           prevPos = pos+1;
3194         }
3195         else // end of nesting args found
3196         {
3197           separatorStack.pop_back();
3198           ignoreNesting = false;
3199         }
3200       }
3201       else if ( !ignoreNesting )
3202       {
3203         switch ( chr ) {
3204         case '(' : separatorStack.push_back(")"); break;
3205         case '[' : separatorStack.push_back("]"); break;
3206         case '\'': separatorStack.push_back("'");  ignoreNesting=true; break;
3207         case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3208         default:;
3209         }
3210       }
3211       ++pos;
3212     }
3213   }
3214   if ( myArgs.Length() < index )
3215     return theEmptyString;
3216   return myArgs( index );
3217 }
3218
3219 //================================================================================
3220 /*!
3221  * \brief Check if char is a word part
3222   * \param c - The character to check
3223   * \retval bool - The check result
3224  */
3225 //================================================================================
3226
3227 static inline bool isWord(const char c, const bool dotIsWord)
3228 {
3229   return
3230     !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3231 }
3232
3233 //================================================================================
3234 /*!
3235  * \brief Looks for a word in the string and returns word's beginning
3236   * \param theString - The input string
3237   * \param theStartPos - The position to start the search, returning word's beginning
3238   * \param theForward - The search direction
3239   * \retval TCollection_AsciiString - The found word
3240  */
3241 //================================================================================
3242
3243 TCollection_AsciiString _pyCommand::GetWord( const TCollection_AsciiString & theString,
3244                                             int &      theStartPos,
3245                                             const bool theForward,
3246                                             const bool dotIsWord )
3247 {
3248   int beg = theStartPos, end = theStartPos;
3249   theStartPos = EMPTY;
3250   if ( beg < 1 || beg > theString.Length() )
3251     return theEmptyString;
3252
3253   if ( theForward ) { // search forward
3254     // beg
3255     while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3256       ++beg;
3257     if ( beg > theString.Length() )
3258       return theEmptyString; // no word found
3259     // end
3260     end = beg + 1;
3261     char begChar = theString.Value( beg );
3262     if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3263       char endChar = ( begChar == '[' ) ? ']' : begChar;
3264       // end is at the corresponding quoting mark or bracket
3265       while ( end < theString.Length() &&
3266               ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3267         ++end;
3268     }
3269     else {
3270       while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3271         ++end;
3272       --end;
3273     }
3274   }
3275   else {  // search backward
3276     // end
3277     while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3278       --end;
3279     if ( end == 0 )
3280       return theEmptyString; // no word found
3281     beg = end - 1;
3282     char endChar = theString.Value( end );
3283     if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3284       char begChar = ( endChar == ']' ) ? '[' : endChar;
3285       // beg is at the corresponding quoting mark
3286       while ( beg > 1 &&
3287               ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3288         --beg;
3289     }
3290     else {
3291       while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3292         --beg;
3293       ++beg;
3294     }
3295   }
3296   theStartPos = beg;
3297   //cout << theString << " ---- " << beg << " - " << end << endl;
3298   return theString.SubString( beg, end );
3299 }
3300
3301 //================================================================================
3302 /*!
3303  * \brief Returns true if the string looks like a study entry
3304  */
3305 //================================================================================
3306
3307 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3308 {
3309   if ( str.Length() < 5 ) return false;
3310
3311   int nbColons = 0, isColon;
3312   for ( int i = 1; i <= str.Length(); ++i )
3313   {
3314     char c = str.Value(i);
3315     if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3316       return false;
3317     nbColons += isColon;
3318   }
3319   return nbColons > 2 && str.Length()-nbColons > 2;
3320 }
3321
3322 //================================================================================
3323 /*!
3324  * \brief Finds entries in a sting
3325  */
3326 //================================================================================
3327
3328 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3329 {
3330   std::list< _pyID > resList;
3331   int pos = 0;
3332   while ( ++pos <= str.Length() )
3333   {
3334     if ( !isdigit( str.Value( pos ))) continue;
3335     if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3336
3337     int end = pos;
3338     while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3339     _pyID entry = str.SubString( pos, end-1 );
3340     pos = end;
3341     if ( IsStudyEntry( entry ))
3342       resList.push_back( entry );
3343   }
3344   return resList;
3345 }
3346
3347 //================================================================================
3348 /*!
3349  * \brief Look for position where not space char is
3350   * \param theString - The string
3351   * \param thePos - The position to search from and which returns result
3352   * \retval bool - false if there are only space after thePos in theString
3353  *
3354  *
3355  */
3356 //================================================================================
3357
3358 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
3359 {
3360   if ( thePos < 1 || thePos > theString.Length() )
3361     return false;
3362
3363   while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
3364     ++thePos;
3365
3366   return thePos <= theString.Length();
3367 }
3368
3369 //================================================================================
3370 /*!
3371  * \brief Modify a part of the command
3372   * \param thePartIndex - The index of the part
3373   * \param thePart - The new part string
3374   * \param theOldPart - The old part
3375  */
3376 //================================================================================
3377
3378 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
3379                         TCollection_AsciiString& theOldPart)
3380 {
3381   int pos = GetBegPos( thePartIndex );
3382   if ( pos <= Length() && theOldPart != thePart)
3383   {
3384     TCollection_AsciiString seperator;
3385     if ( pos < 1 ) {
3386       pos = GetBegPos( thePartIndex + 1 );
3387       if ( pos < 1 ) return;
3388       switch ( thePartIndex ) {
3389       case RESULT_IND: seperator = " = "; break;
3390       case OBJECT_IND: seperator = "."; break;
3391       case METHOD_IND: seperator = "()"; break;
3392       default:;
3393       }
3394     }
3395     myString.Remove( pos, theOldPart.Length() );
3396     if ( !seperator.IsEmpty() )
3397       myString.Insert( pos , seperator );
3398     myString.Insert( pos, thePart );
3399     // update starting positions of the following parts
3400     int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
3401     for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
3402       if ( myBegPos( i ) > 0 )
3403         myBegPos( i ) += posDelta;
3404     }
3405     theOldPart = thePart;
3406   }
3407 }
3408
3409 //================================================================================
3410 /*!
3411  * \brief Set agrument
3412   * \param index - The argument index, it counts from 1
3413   * \param theArg - The argument string
3414  */
3415 //================================================================================
3416
3417 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
3418 {
3419   FindAllArgs();
3420   int argInd = ARG1_IND + index - 1;
3421   int pos = GetBegPos( argInd );
3422   if ( pos < 1 ) // no index-th arg exist, append inexistent args
3423   {
3424     // find a closing parenthesis
3425     if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
3426       int lastArgInd = GetNbArgs();
3427       pos = GetBegPos( ARG1_IND + lastArgInd  - 1 ) + GetArg( lastArgInd ).Length();
3428       while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
3429         ++pos;
3430     }
3431     else {
3432       pos = Length();
3433       while ( pos > 0 && myString.Value( pos ) != ')' )
3434         --pos;
3435     }
3436     if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
3437       myString += "()";
3438       pos = Length();
3439     }
3440     while ( myArgs.Length() < index ) {
3441       if ( myArgs.Length() )
3442         myString.Insert( pos++, "," );
3443       myArgs.Append("None");
3444       myString.Insert( pos, myArgs.Last() );
3445       SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
3446       pos += myArgs.Last().Length();
3447     }
3448   }
3449   SetPart( argInd, theArg, myArgs( index ));
3450 }
3451
3452 //================================================================================
3453 /*!
3454  * \brief Empty arg list
3455  */
3456 //================================================================================
3457
3458 void _pyCommand::RemoveArgs()
3459 {
3460   if ( int pos = myString.Location( '(', 1, Length() ))
3461     myString.Trunc( pos );
3462   myString += ")";
3463   myArgs.Clear();
3464   if ( myBegPos.Length() >= ARG1_IND )
3465     myBegPos.Remove( ARG1_IND, myBegPos.Length() );
3466 }
3467
3468 //================================================================================
3469 /*!
3470  * \brief Comment a python command
3471  */
3472 //================================================================================
3473
3474 void _pyCommand::Comment()
3475 {
3476   if ( IsEmpty() ) return;
3477
3478   int i = 1;
3479   while ( i <= Length() && isspace( myString.Value(i) )) ++i;
3480   if ( i <= Length() )
3481   {
3482     myString.Insert( i, "#" );
3483     for ( int iPart = 0; iPart < myBegPos.Length(); ++iPart )
3484     {
3485       int begPos = GetBegPos( iPart );
3486       if ( begPos != UNKNOWN )
3487         SetBegPos( iPart, begPos + 1 );
3488     }
3489   }
3490 }
3491
3492 //================================================================================
3493 /*!
3494  * \brief Set dependent commands after this one
3495  */
3496 //================================================================================
3497
3498 bool _pyCommand::SetDependentCmdsAfter() const
3499 {
3500   bool orderChanged = false;
3501   list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
3502   for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
3503     if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
3504       orderChanged = true;
3505       theGen->SetCommandAfter( *cmd, this );
3506       (*cmd)->SetDependentCmdsAfter();
3507     }
3508   }
3509   return orderChanged;
3510 }
3511 //================================================================================
3512 /*!
3513  * \brief Insert accessor method after theObjectID
3514   * \param theObjectID - id of the accessed object
3515   * \param theAcsMethod - name of the method giving access to the object
3516   * \retval bool - false if theObjectID is not found in the command string
3517  */
3518 //================================================================================
3519
3520 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
3521 {
3522   if ( !theAcsMethod )
3523     return false;
3524   // start object search from the object, i.e. ignore result
3525   GetObject();
3526   int beg = GetBegPos( OBJECT_IND );
3527   if ( beg < 1 || beg > Length() )
3528     return false;
3529   bool added = false;
3530   while (( beg = myString.Location( theObjectID, beg, Length() )))
3531   {
3532     // check that theObjectID is not just a part of a longer ID
3533     int afterEnd = beg + theObjectID.Length();
3534     Standard_Character c = myString.Value( afterEnd );
3535     if ( !isalnum( c ) && c != ':' ) {
3536       // check if accessor method already present
3537       if ( c != '.' ||
3538            myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
3539         // insertion
3540         int oldLen = Length();
3541         myString.Insert( afterEnd, (char*) theAcsMethod );
3542         myString.Insert( afterEnd, "." );
3543         // update starting positions of the parts following the modified one
3544         int posDelta = Length() - oldLen;
3545         for ( int i = 1; i <= myBegPos.Length(); ++i ) {
3546           if ( myBegPos( i ) > afterEnd )
3547             myBegPos( i ) += posDelta;
3548         }
3549         added = true;
3550       }
3551     }
3552     beg = afterEnd; // is a part - next search
3553   }
3554   return added;
3555 }
3556
3557 //================================================================================
3558 /*!
3559  * \brief Creates pyObject
3560  */
3561 //================================================================================
3562
3563 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
3564   : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
3565 {
3566   setID( theID );
3567 }
3568
3569 //================================================================================
3570 /*!
3571  * \brief Set up myID and myIsPublished
3572  */
3573 //================================================================================
3574
3575 void _pyObject::setID(const _pyID& theID)
3576 {
3577   myID = theID;
3578   myIsPublished = !theGen->IsNotPublished( GetID() );
3579 }
3580
3581 //================================================================================
3582 /*!
3583  * \brief Clear myCreationCmd and myProcessedCmds
3584  */
3585 //================================================================================
3586
3587 void _pyObject::ClearCommands()
3588 {
3589   if ( !CanClear() )
3590     return;
3591
3592   if ( !myCreationCmd.IsNull() )
3593     myCreationCmd->Clear();
3594
3595   list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
3596   for ( ; cmd != myProcessedCmds.end(); ++cmd )
3597     (*cmd)->Clear();
3598 }
3599
3600 //================================================================================
3601 /*!
3602  * \brief Return method name giving access to an interaface object wrapped by python class
3603   * \retval const char* - method name
3604  */
3605 //================================================================================
3606
3607 const char* _pyObject::AccessorMethod() const
3608 {
3609   return 0;
3610 }
3611 //================================================================================
3612 /*!
3613  * \brief Return ID of a father
3614  */
3615 //================================================================================
3616
3617 _pyID _pyObject::FatherID(const _pyID & childID)
3618 {
3619   int colPos = childID.SearchFromEnd(':');
3620   if ( colPos > 0 )
3621     return childID.SubString( 1, colPos-1 );
3622   return "";
3623 }
3624
3625 //================================================================================
3626 /*!
3627  * \brief SelfEraser erases creation command if no more it's commands invoked
3628  */
3629 //================================================================================
3630
3631 void _pySelfEraser::Flush()
3632 {
3633   if ( GetNbCalls() == 0 )
3634     GetCreationCmd()->Clear();
3635 }
3636
3637 //================================================================================
3638 /*!
3639  * \brief _pySubMesh constructor
3640  */
3641 //================================================================================
3642
3643 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd):
3644   _pyObject(theCreationCmd)
3645 {
3646   myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
3647 }
3648
3649 //================================================================================
3650 /*!
3651  * \brief count invoked commands
3652  */
3653 //================================================================================
3654
3655 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
3656 {
3657   _pyObject::Process(theCommand); // count calls of Process()
3658   GetCreationCmd()->AddDependantCmd( theCommand );
3659 }
3660
3661 //================================================================================
3662 /*!
3663  * \brief Move creation command depending on invoked commands
3664  */
3665 //================================================================================
3666
3667 void _pySubMesh::Flush()
3668 {
3669   if ( GetNbCalls() == 0 ) // move to the end of all commands
3670     theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
3671   else if ( !myCreator.IsNull() )
3672     // move to be just after creator
3673     myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
3674 }
3675
3676 //================================================================================
3677 /*!
3678  * \brief Creates _pyGroup
3679  */
3680 //================================================================================
3681
3682 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
3683   :_pySubMesh(theCreationCmd)
3684 {
3685   if ( !id.IsEmpty() )
3686     setID( id );
3687
3688   const _AString& method = theCreationCmd->GetMethod();
3689   if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
3690   {
3691     theCreationCmd->SetMethod( "CreateEmptyGroup" );
3692   }
3693   // ----------------------------------------------------------------------
3694   else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
3695   {
3696     _pyID geom = theCreationCmd->GetArg( 3 );
3697     // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
3698     // next if(){...} section is commented
3699     //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
3700     //  theCreationCmd->SetMethod( "Group" );
3701     //  theCreationCmd->RemoveArgs();
3702     //  theCreationCmd->SetArg( 1, geom );
3703     //}
3704     //else {
3705     // ------------------------->>>>> GroupOnGeom( geom, name, typ )
3706       _pyID type = theCreationCmd->GetArg( 1 );
3707       _pyID name = theCreationCmd->GetArg( 2 );
3708       theCreationCmd->SetMethod( "GroupOnGeom" );
3709       theCreationCmd->RemoveArgs();
3710       theCreationCmd->SetArg( 1, geom );
3711       theCreationCmd->SetArg( 2, name );
3712       theCreationCmd->SetArg( 3, type );
3713     //}
3714   }
3715   else if ( method == "CreateGroupFromFilter" )
3716   {
3717     // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
3718     theCreationCmd->SetMethod( "GroupOnFilter" );
3719
3720     _pyID filterID = theCreationCmd->GetArg(3);
3721     Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
3722     if ( !filter.IsNull())
3723     {
3724       if ( !filter->GetNewID().IsEmpty() )
3725         theCreationCmd->SetArg( 3, filter->GetNewID() );
3726       filter->AddUser( this );
3727     }
3728     myFilter = filter;
3729   }
3730 }
3731
3732 //================================================================================
3733 /*!
3734  * \brief To convert creation of a group by filter
3735  */
3736 //================================================================================
3737
3738 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
3739 {
3740   // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
3741   // group = mesh.CreateEmptyGroup( elemType, groupName )
3742   // aFilter.SetMesh(mesh)
3743   // nbAdd = group.AddFrom( aFilter )
3744   Handle(_pyFilter) filter;
3745   if ( theCommand->GetMethod() == "AddFrom" )
3746   {
3747     _pyID idSource = theCommand->GetArg(1);
3748     // check if idSource is a filter
3749     filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
3750     if ( !filter.IsNull() )
3751     {
3752       // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
3753       list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
3754       while ( *cmdIt != theCommand ) ++cmdIt;
3755       while ( (*cmdIt)->GetOrderNb() != 1 )
3756       {
3757         const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
3758         if ((setMeshCmd->GetObject() == idSource ||
3759              setMeshCmd->GetObject() == filter->GetNewID() )
3760             &&
3761             setMeshCmd->GetMethod() == "SetMesh")
3762         {
3763           setMeshCmd->Clear();
3764           break;
3765         }
3766       }
3767       // replace 3 commands by one
3768       theCommand->Clear();
3769       const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
3770       TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
3771       if ( !filter->GetNewID().IsEmpty() )
3772         idSource = filter->GetNewID();
3773       makeGroupCmd->SetMethod( "MakeGroupByFilter" );
3774       makeGroupCmd->SetArg( 1, name );
3775       makeGroupCmd->SetArg( 2, idSource );
3776     }
3777   }
3778   else if ( theCommand->GetMethod() == "SetFilter" )
3779   {
3780     // set new name of a filter or clear the command if the same filter is set
3781     _pyID filterID = theCommand->GetArg(1);
3782     filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
3783     if ( !myFilter.IsNull() && filter == myFilter )
3784       theCommand->Clear();
3785     else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
3786       theCommand->SetArg( 1, filter->GetNewID() );
3787     myFilter = filter;
3788   }
3789   else if ( theCommand->GetMethod() == "GetFilter" )
3790   {
3791     // GetFilter() returns a filter with other ID, make myFilter process
3792     // calls of the returned filter
3793     if ( !myFilter.IsNull() )
3794     {
3795       theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
3796       theCommand->Clear();
3797     }
3798   }
3799
3800   if ( !filter.IsNull() )
3801     filter->AddUser( this );
3802
3803   theGen->AddMeshAccessorMethod( theCommand );
3804 }
3805
3806 //================================================================================
3807 /*!
3808  * \brief Constructor of _pyFilter
3809  */
3810 //================================================================================
3811
3812 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
3813   :_pyObject(theCreationCmd), myNewID( newID )
3814 {
3815 }
3816
3817 //================================================================================
3818 /*!
3819  * \brief To convert creation of a filter by criteria and
3820  * to replace an old name by a new one
3821  */
3822 //================================================================================
3823
3824 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
3825 {
3826   if ( theCommand->GetObject() == GetID() )
3827     _pyObject::Process(theCommand); // count commands
3828
3829   if ( !myNewID.IsEmpty() )
3830     theCommand->SetObject( myNewID );
3831     
3832   // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
3833   // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
3834   // aFilter0x2aaab0487080.SetCriteria(aCriteria)
3835   if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
3836        theCommand->GetMethod() == "SetCriteria")
3837   {
3838     // aFilter.SetCriteria(aCriteria) ->
3839     // aFilter = smesh.GetFilterFromCriteria(criteria)
3840     if ( myNewID.IsEmpty() )
3841       theCommand->SetResultValue( GetID() );
3842     else
3843       theCommand->SetResultValue( myNewID );
3844     theCommand->SetObject( SMESH_2smeshpy::GenName() );
3845     theCommand->SetMethod( "GetFilterFromCriteria" );
3846
3847     // Clear aFilterManager.CreateFilter()
3848     GetCreationCmd()->Clear();
3849   }
3850   else if ( theCommand->GetMethod() == "SetMesh" )
3851   {
3852     if ( myMesh == theCommand->GetArg( 1 ))
3853       theCommand->Clear();
3854     else
3855       myMesh = theCommand->GetArg( 1 );
3856     theGen->AddMeshAccessorMethod( theCommand );
3857   }
3858 }
3859
3860 //================================================================================
3861 /*!
3862  * \brief Set new filter name to the creation command
3863  */
3864 //================================================================================
3865
3866 void _pyFilter::Flush()
3867 {
3868   if ( !myNewID.IsEmpty() && !GetCreationCmd()->IsEmpty() )
3869     GetCreationCmd()->SetResultValue( myNewID );
3870 }
3871
3872 //================================================================================
3873 /*!
3874  * \brief Return true if all my users can be cleared
3875  */
3876 //================================================================================
3877
3878 bool _pyFilter::CanClear()
3879 {
3880   list< Handle(_pyObject) >::iterator obj = myUsers.begin();
3881   for ( ; obj != myUsers.end(); ++obj )
3882     if ( !(*obj)->CanClear() )
3883       return false;
3884
3885   return true;
3886 }
3887
3888 //================================================================================
3889 /*!
3890  * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
3891  */
3892 //================================================================================
3893
3894 _pyHypothesisReader::_pyHypothesisReader()
3895 {
3896   // Get paths to xml files of plugins
3897   vector< string > xmlPaths;
3898   string sep;
3899   if ( const char* meshersList = getenv("SMESH_MeshersList") )
3900   {
3901     string meshers = meshersList, plugin;
3902     string::size_type from = 0, pos;
3903     while ( from < meshers.size() )
3904     {
3905       // cut off plugin name
3906       pos = meshers.find( ':', from );
3907       if ( pos != string::npos )
3908         plugin = meshers.substr( from, pos-from );
3909       else
3910         plugin = meshers.substr( from ), pos = meshers.size();
3911       from = pos + 1;
3912
3913       // get PLUGIN_ROOT_DIR path
3914       string rootDirVar, pluginSubDir = plugin;
3915       if ( plugin == "StdMeshers" )
3916         rootDirVar = "SMESH", pluginSubDir = "smesh";
3917       else
3918         for ( pos = 0; pos < plugin.size(); ++pos )
3919           rootDirVar += toupper( plugin[pos] );
3920       rootDirVar += "_ROOT_DIR";
3921
3922       const char* rootDir = getenv( rootDirVar.c_str() );
3923       if ( !rootDir || strlen(rootDir) == 0 )
3924       {
3925         rootDirVar = plugin + "_ROOT_DIR"; // HexoticPLUGIN_ROOT_DIR
3926         rootDir = getenv( rootDirVar.c_str() );
3927         if ( !rootDir || strlen(rootDir) == 0 ) continue;
3928       }
3929
3930       // get a separator from rootDir
3931       for ( pos = strlen( rootDir )-1; pos >= 0 && sep.empty(); --pos )
3932         if ( rootDir[pos] == '/' || rootDir[pos] == '\\' )
3933         {
3934           sep = rootDir[pos];
3935           break;
3936         }
3937 #ifdef WNT
3938       if (sep.empty() ) sep = "\\";
3939 #else
3940       if (sep.empty() ) sep = "/";
3941 #endif
3942
3943       // get a path to resource file
3944       string xmlPath = rootDir;
3945       if ( xmlPath[ xmlPath.size()-1 ] != sep[0] )
3946         xmlPath += sep;
3947       xmlPath += "share" + sep + "salome" + sep + "resources" + sep;
3948       for ( pos = 0; pos < pluginSubDir.size(); ++pos )
3949         xmlPath += tolower( pluginSubDir[pos] );
3950       xmlPath += sep + plugin + ".xml";
3951       bool fileOK;
3952 #ifdef WNT
3953       fileOK = (GetFileAttributes(xmlPath.c_str()) != INVALID_FILE_ATTRIBUTES);
3954 #else
3955       fileOK = (access(xmlPath.c_str(), F_OK) == 0);
3956 #endif
3957       if ( fileOK )
3958         xmlPaths.push_back( xmlPath );
3959     }
3960   }
3961
3962   // Read xml files
3963   LDOMParser xmlParser;
3964   for ( size_t i = 0; i < xmlPaths.size(); ++i )
3965   {
3966     bool error = xmlParser.parse( xmlPaths[i].c_str() );
3967     if ( error )
3968     {
3969       _AString data;
3970       INFOS( xmlParser.GetError(data) );
3971       continue;
3972     }
3973     // <algorithm type="Regular_1D"
3974     //            label-id="Wire discretisation"
3975     //            ...>
3976     //   <python-wrap>
3977     //     <algo>Regular_1D=Segment()</algo>
3978     //     <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
3979     //
3980     LDOM_Document xmlDoc = xmlParser.getDocument();
3981     LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
3982     for ( int i = 0; i < algoNodeList.getLength(); ++i )
3983     {
3984       LDOM_Node algoNode = algoNodeList.item( i );
3985       LDOM_Element& algoElem = (LDOM_Element&) algoNode;
3986       LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
3987       if ( pyAlgoNodeList.getLength() < 1 ) continue;
3988
3989       _AString text, algoType, method, arg;
3990       for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
3991       {
3992         LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
3993         LDOM_Node textNode   = pyAlgoNode.getFirstChild();
3994         text = textNode.getNodeValue();
3995         Handle(_pyCommand) algoCmd = new _pyCommand( text );
3996         algoType = algoCmd->GetResultValue();
3997         method   = algoCmd->GetMethod();
3998         arg      = algoCmd->GetArg(1);
3999         if ( !algoType.IsEmpty() && !method.IsEmpty() )
4000         {
4001           Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4002           algo->SetConvMethodAndType( method, algoType );
4003           if ( !arg.IsEmpty() )
4004             algo->setCreationArg( 1, arg );
4005
4006           myType2Hyp[ algoType ] = algo;
4007           break;
4008         }
4009       }
4010       if ( algoType.IsEmpty() ) continue;
4011
4012       LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4013       _AString hypType;
4014       Handle( _pyHypothesis ) hyp;
4015       for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4016       {
4017         LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4018         LDOM_Node textNode   = pyHypoNode.getFirstChild();
4019         text = textNode.getNodeValue();
4020         Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4021         hypType = hypoCmd->GetResultValue();
4022         method  = hypoCmd->GetMethod();
4023         if ( !hypType.IsEmpty() && !method.IsEmpty() )
4024         {
4025           map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4026           if ( type2hyp == myType2Hyp.end() )
4027             hyp = new _pyHypothesis( hypoCmd );
4028           else
4029             hyp = type2hyp->second;
4030           hyp->SetConvMethodAndType( method, algoType );
4031           for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4032           {
4033             _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4034             _AString argMethod = argCmd.GetMethod();
4035             _AString argNbText = argCmd.GetArg( 1 );
4036             if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4037               hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4038             else
4039               hyp->AddArgMethod( argMethod,
4040                                  argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4041           }
4042           myType2Hyp[ hypType ] = hyp;
4043         }
4044       }
4045     }
4046   }
4047 }
4048
4049 //================================================================================
4050 /*!
4051  * \brief Returns a new hypothesis initialized according to the read information
4052  */
4053 //================================================================================
4054
4055 Handle(_pyHypothesis)
4056 _pyHypothesisReader::GetHypothesis(const _AString&           hypType,
4057                                    const Handle(_pyCommand)& creationCmd) const
4058 {
4059   Handle(_pyHypothesis) resHyp, sampleHyp;
4060
4061   map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4062   if ( type2hyp != myType2Hyp.end() )
4063     sampleHyp = type2hyp->second;
4064
4065   if ( sampleHyp.IsNull() )
4066   {
4067     resHyp = new _pyHypothesis(creationCmd);
4068   }
4069   else
4070   {
4071     if ( sampleHyp->IsAlgo() )
4072       resHyp = new _pyAlgorithm( creationCmd );
4073     else
4074       resHyp = new _pyHypothesis(creationCmd);
4075     resHyp->Assign( sampleHyp, _pyID() );
4076   }
4077   return resHyp;
4078 }