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