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