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