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