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