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