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