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