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