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