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