Salome HOME
23416: [CEA 2033] Impossible to re-compute a mesh from an hdf
[modules/smesh.git] / src / SMESHGUI / SMESHGUI.cxx
1 // Copyright (C) 2007-2016  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, or (at your option) any later version.
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 //  File   : SMESHGUI.cxx
23 //  Author : Nicolas REJNERI, Open CASCADE S.A.S.
24
25 #include <Standard_math.hxx>  // E.A. must be included before Python.h to fix compilation on windows
26 #ifdef HAVE_FINITE
27 #undef HAVE_FINITE            // VSR: avoid compilation warning on Linux : "HAVE_FINITE" redefined
28 #endif
29 #include "Python.h"
30
31 //  SMESH includes
32 #include "SMESHGUI.h"
33 #include "SMESHGUI_Add0DElemsOnAllNodesDlg.h"
34 #include "SMESHGUI_AddMeshElementDlg.h"
35 #include "SMESHGUI_AddQuadraticElementDlg.h"
36 #include "SMESHGUI_BuildCompoundDlg.h"
37 #include "SMESHGUI_ClippingDlg.h"
38 #include "SMESHGUI_ComputeDlg.h"
39 #include "SMESHGUI_ConvToQuadOp.h"
40 #include "SMESHGUI_CopyMeshDlg.h"
41 #include "SMESHGUI_CreatePolyhedralVolumeDlg.h"
42 #include "SMESHGUI_DeleteGroupDlg.h"
43 #include "SMESHGUI_Displayer.h"
44 #include "SMESHGUI_DuplicateNodesDlg.h"
45 #include "SMESHGUI_ExtrusionAlongPathDlg.h"
46 #include "SMESHGUI_ExtrusionDlg.h"
47 #include "SMESHGUI_FieldSelectorWdg.h"
48 #include "SMESHGUI_FileInfoDlg.h"
49 #include "SMESHGUI_FileValidator.h"
50 #include "SMESHGUI_FilterDlg.h"
51 #include "SMESHGUI_FilterLibraryDlg.h"
52 #include "SMESHGUI_FindElemByPointDlg.h"
53 #include "SMESHGUI_GroupDlg.h"
54 #include "SMESHGUI_GroupOnShapeDlg.h"
55 #include "SMESHGUI_GroupOpDlg.h"
56 #include "SMESHGUI_Hypotheses.h"
57 #include "SMESHGUI_Make2DFrom3DOp.h"
58 #include "SMESHGUI_MakeNodeAtPointDlg.h"
59 #include "SMESHGUI_Measurements.h"
60 #include "SMESHGUI_MergeDlg.h"
61 #include "SMESHGUI_MeshInfo.h"
62 #include "SMESHGUI_MeshOp.h"
63 #include "SMESHGUI_MeshOrderOp.h"
64 #include "SMESHGUI_MeshPatternDlg.h"
65 #include "SMESHGUI_MultiEditDlg.h"
66 #include "SMESHGUI_NodesDlg.h"
67 #include "SMESHGUI_Operations.h"
68 #include "SMESHGUI_Preferences_ScalarBarDlg.h"
69 #include "SMESHGUI_PropertiesDlg.h"
70 #include "SMESHGUI_RemoveElementsDlg.h"
71 #include "SMESHGUI_RemoveNodesDlg.h"
72 #include "SMESHGUI_RenumberingDlg.h"
73 #include "SMESHGUI_ReorientFacesDlg.h"
74 #include "SMESHGUI_RevolutionDlg.h"
75 #include "SMESHGUI_RotationDlg.h"
76 #include "SMESHGUI_ScaleDlg.h"
77 #include "SMESHGUI_Selection.h"
78 #include "SMESHGUI_SewingDlg.h"
79 #include "SMESHGUI_SingleEditDlg.h"
80 #include "SMESHGUI_SmoothingDlg.h"
81 #include "SMESHGUI_SymmetryDlg.h"
82 #include "SMESHGUI_TranslationDlg.h"
83 #include "SMESHGUI_TransparencyDlg.h"
84 #include "SMESHGUI_DisplayEntitiesDlg.h"
85 #include "SMESHGUI_SplitBiQuad.h"
86
87 #include "SMESHGUI_FilterUtils.h"
88 #include "SMESHGUI_GEOMGenUtils.h"
89 #include "SMESHGUI_GroupUtils.h"
90 #include "SMESHGUI_HypothesesUtils.h"
91 #include "SMESHGUI_MeshUtils.h"
92 #include "SMESHGUI_PatternUtils.h"
93 #include "SMESHGUI_Utils.h"
94 #include "SMESHGUI_VTKUtils.h"
95
96 #include "SMESH_version.h"
97
98 #include "SMESH_ControlsDef.hxx"
99 #include "SMESH_Actor.h"
100 #include "SMESH_ActorUtils.h"
101 #include "SMESH_Client.hxx"
102 #include "SMESH_ScalarBarActor.h"
103 #include "SMESH_TypeFilter.hxx"
104
105 // SALOME GUI includes
106 #include <SalomeApp_Application.h>
107 #include <SalomeApp_CheckFileDlg.h>
108 #include <SalomeApp_DataObject.h>
109 #include <SalomeApp_Study.h>
110 #include <SalomeApp_Tools.h>
111
112 #include <LightApp_DataOwner.h>
113 #include <LightApp_NameDlg.h>
114 #include <LightApp_Preferences.h>
115 #include <LightApp_SelectionMgr.h>
116 #include <LightApp_UpdateFlags.h>
117
118 #include <SVTK_ViewManager.h>
119 #include <SVTK_ViewModel.h>
120 #include <SVTK_ViewWindow.h>
121
122 #include <VTKViewer_Algorithm.h>
123
124 #include <SUIT_Desktop.h>
125 #include <SUIT_FileDlg.h>
126 #include <SUIT_MessageBox.h>
127 #include <SUIT_OverrideCursor.h>
128 #include <SUIT_ResourceMgr.h>
129 #include <SUIT_Session.h>
130
131 #include <QtxPopupMgr.h>
132 #include <QtxFontEdit.h>
133
134 #include <SALOME_ListIO.hxx>
135
136 #ifndef DISABLE_PLOT2DVIEWER
137 #include <SPlot2d_ViewModel.h>
138 #include <SPlot2d_Histogram.h>
139 #endif
140
141 // IDL includes
142 #include <SALOMEconfig.h>
143 #include CORBA_CLIENT_HEADER(SALOMEDS_Attributes)
144 #include CORBA_CLIENT_HEADER(SMESH_MeshEditor)
145 #include CORBA_CLIENT_HEADER(SMESH_Measurements)
146
147 // Qt includes
148 // #define       INCLUDE_MENUITEM_DEF // VSR commented ????????
149 #include <QApplication>
150 #include <QMenu>
151 #include <QTextStream>
152 #include <QListView>
153 #include <QTreeView>
154 #include <QCheckBox>
155 #include <QLayout>
156 #include <QDialogButtonBox>
157
158 // BOOST includes
159 #include <boost/shared_ptr.hpp>
160
161 // VTK includes
162 #include <vtkCallbackCommand.h>
163 #include <vtkCamera.h>
164 #include <vtkLookupTable.h>
165 #include <vtkPlane.h>
166 #include <vtkRenderer.h>
167
168 // SALOME KERNEL includes
169 #include <SALOMEDSClient_ClientFactory.hxx>
170 #include <SALOMEDSClient_IParameters.hxx>
171 #include <SALOMEDSClient_SComponent.hxx>
172 #include <SALOMEDSClient_StudyBuilder.hxx>
173 #include <SALOMEDS_Study.hxx>
174 #include <SALOMEDS_SObject.hxx>
175 #include "utilities.h"
176
177 // OCCT includes
178 #include <Standard_ErrorHandler.hxx>
179 #include <NCollection_DataMap.hxx>
180 #include <NCollection_DoubleMap.hxx>
181
182 #include <Basics_Utils.hxx>
183
184 // Below macro, when uncommented, switches on simplified (more performant) algorithm
185 // of auto-color picking up
186 #define SIMPLE_AUTOCOLOR
187
188 namespace
189 {
190   // Declarations
191   //=============================================================
192   void ImportMeshesFromFile(SMESH::SMESH_Gen_ptr theComponentMesh,
193                             int                  theCommandID);
194
195   void ExportMeshToFile(int theCommandID);
196
197   void SetDisplayMode(int theCommandID, SMESHGUI_StudyId2MarkerMap& theMarkerMap);
198
199   void SetDisplayEntity(int theCommandID);
200
201   int  ActionToControl( int theID, bool theReversed = false );
202
203   void Control( int theCommandID );
204
205   // Definitions
206   //================================================================================
207   /*!
208    * \brief Reads meshes from file
209    */
210   //================================================================================
211
212   void ImportMeshesFromFile( SMESH::SMESH_Gen_ptr theComponentMesh,
213                              int                  theCommandID )
214   {
215     QStringList filter;
216     std::string myExtension;
217
218     if ( theCommandID == SMESHOp::OpImportMED ) {
219       filter.append( QObject::tr( "MED_FILES_FILTER" ) + " (*.*med)" );
220       filter.append( QObject::tr( "ALL_FILES_FILTER" ) + " (*)" );
221     }
222     else if ( theCommandID == SMESHOp::OpImportUNV ) {
223       filter.append( QObject::tr( "IDEAS_FILES_FILTER" ) + " (*.unv)" );
224     }
225     else if ( theCommandID == SMESHOp::OpImportDAT ) {
226       filter.append( QObject::tr( "DAT_FILES_FILTER" ) + " (*.dat)" );
227     }
228     else if ( theCommandID == SMESHOp::OpImportSTL ) {
229       filter.append( QObject::tr( "STL_FILES_FILTER" ) + " (*.stl)" );
230     }
231   #ifdef WITH_CGNS
232     else if ( theCommandID == SMESHOp::OpImportCGNS ) {
233       filter.append( QObject::tr( "CGNS_FILES_FILTER" ) + " (*.cgns)" );
234     }
235   #endif
236     else if ( theCommandID == SMESHOp::OpImportSAUV ) {
237       filter.append( QObject::tr( "SAUV files (*.sauv*)" ) );
238       filter.append( QObject::tr( "All files (*)" ) );
239     }
240     else if ( theCommandID == SMESHOp::OpImportGMF ) {
241       filter.append( QObject::tr( "GMF_ASCII_FILES_FILTER" ) + " (*.mesh)"  );
242       filter.append( QObject::tr( "GMF_BINARY_FILES_FILTER") + " (*.meshb)" );
243     }
244
245     QString anInitialPath = "";
246     if ( SUIT_FileDlg::getLastVisitedPath().isEmpty() )
247       anInitialPath = QDir::currentPath();
248
249     QStringList filenames;
250     bool toCreateGroups = true;
251
252     // if ( theCommandID == SMESHOp::OpImportGMF ) { // GMF
253     //   SalomeApp_CheckFileDlg* fd = new SalomeApp_CheckFileDlg
254     //     ( SMESHGUI::desktop(), true, QObject::tr("SMESH_REQUIRED_GROUPS"), true, true );
255     //   fd->setWindowTitle( QObject::tr( "SMESH_IMPORT_MESH" ) );
256     //   fd->setNameFilters( filter );
257     //   fd->SetChecked( true );
258     //   if ( fd->exec() )
259     //     filenames << fd->selectedFile();
260     //   toCreateGroups = fd->IsChecked();
261
262     //   delete fd;
263     // }
264     // else
265     {
266       filenames = SUIT_FileDlg::getOpenFileNames( SMESHGUI::desktop(),
267                                                   anInitialPath,
268                                                   filter,
269                                                   QObject::tr( "SMESH_IMPORT_MESH" ) );
270     }
271     if ( filenames.count() > 0 )
272     {
273       SUIT_OverrideCursor wc;
274       _PTR(Study) aStudy = SMESH::GetActiveStudyDocument();
275
276       QStringList errors;
277       QStringList anEntryList;
278       bool isEmpty = false;
279       for ( QStringList::ConstIterator it = filenames.begin(); it != filenames.end(); ++it )
280       {
281         QString filename = *it;
282         SMESH::mesh_array_var aMeshes = new SMESH::mesh_array;
283         try {
284           switch ( theCommandID ) {
285           case SMESHOp::OpImportDAT:
286             {
287               // DAT format (currently unsupported)
288               errors.append( QString( "%1 :\n\t%2" ).arg( filename ).
289                              arg( QObject::tr( "SMESH_ERR_NOT_SUPPORTED_FORMAT" ) ) );
290               break;
291             }
292           case SMESHOp::OpImportUNV:
293             {
294               // UNV format
295               aMeshes->length( 1 );
296               aMeshes[0] = theComponentMesh->CreateMeshesFromUNV( filename.toUtf8().constData() );
297               if ( aMeshes[0]->_is_nil() )
298                 errors.append( QString( "%1 :\n\t%2" ).arg( filename ).
299                                arg( QObject::tr( "SMESH_ERR_UNKNOWN_IMPORT_ERROR" ) ) );
300               break;
301             }
302           case SMESHOp::OpImportMED:
303             {
304               // MED format
305               SMESH::DriverMED_ReadStatus res;
306               aMeshes = theComponentMesh->CreateMeshesFromMED( filename.toUtf8().constData(), res );
307               if ( res != SMESH::DRS_OK ) {
308                 errors.append( QString( "%1 :\n\t%2" ).arg( filename ).
309                                arg( QObject::tr( QString( "SMESH_DRS_%1" ).arg( res ).toLatin1().data() ) ) );
310               }
311               break;
312             }
313           case SMESHOp::OpImportSTL:
314             {
315               // STL format
316               aMeshes->length( 1 );
317               aMeshes[0] = theComponentMesh->CreateMeshesFromSTL( filename.toUtf8().constData() );
318               if ( aMeshes[0]->_is_nil() ) {
319                 errors.append( QString( "%1 :\n\t%2" ).arg( filename ).
320                                arg( QObject::tr( "SMESH_ERR_UNKNOWN_IMPORT_ERROR" ) ) );
321               }
322               break;
323             }
324         #ifdef WITH_CGNS
325           case SMESHOp::OpImportCGNS:
326             {
327               // CGNS format
328               SMESH::DriverMED_ReadStatus res;
329               aMeshes = theComponentMesh->CreateMeshesFromCGNS( filename.toUtf8().constData(), res );
330               if ( res != SMESH::DRS_OK ) {
331                 errors.append( QString( "%1 :\n\t%2" ).arg( filename ).
332                                arg( QObject::tr( QString( "SMESH_DRS_%1" ).arg( res ).toLatin1().data() ) ) );
333               }
334               break;
335             }
336         #endif
337           case SMESHOp::OpImportSAUV:
338             {
339               // SAUV format
340               SMESH::DriverMED_ReadStatus res;
341               aMeshes = theComponentMesh->CreateMeshesFromSAUV( filename.toUtf8().constData(), res );
342               if ( res != SMESH::DRS_OK ) {
343                 errors.append( QString( "%1 :\n\t%2" ).arg( filename ).
344                                arg( QObject::tr( QString( "SMESH_DRS_%1" ).arg( res ).toLatin1().data() ) ) );
345               }
346               break;
347             }
348           case SMESHOp::OpImportGMF:
349             {
350               // GMF format
351               SMESH::ComputeError_var res;
352               aMeshes->length( 1 );
353               aMeshes[0] = theComponentMesh->CreateMeshesFromGMF( filename.toUtf8().constData(),
354                                                                   toCreateGroups,
355                                                                   res.out() );
356               if ( res->code != SMESH::DRS_OK ) {
357                 errors.append( QString( "%1 :\n\t%2" ).arg( filename ).
358                                arg( QObject::tr( QString( "SMESH_DRS_%1" ).arg( res->code ).toLatin1().data() ) ) );
359                 if ( strlen( res->comment.in() ) > 0 ) {
360                   errors.back() += ": ";
361                   errors.back() += res->comment.in();
362                 }
363               }
364               break;
365             }
366           }
367         }
368         catch ( const SALOME::SALOME_Exception& S_ex ) {
369           errors.append( QString( "%1 :\n\t%2" ).arg( filename ).
370                          arg( QObject::tr( "SMESH_ERR_UNKNOWN_IMPORT_ERROR" ) ) );
371         }
372
373         for ( int i = 0, iEnd = aMeshes->length(); i < iEnd; i++ )
374         {
375           _PTR(SObject) aMeshSO = SMESH::FindSObject( aMeshes[i] );
376           if ( aMeshSO ) {
377             _PTR(StudyBuilder) aBuilder = aStudy->NewBuilder();
378             _PTR(AttributePixMap) aPixmap = aBuilder->FindOrCreateAttribute( aMeshSO, "AttributePixMap" );
379             aPixmap->SetPixMap( "ICON_SMESH_TREE_MESH_IMPORTED" );
380             if ( theCommandID == SMESHOp::OpImportUNV ) // mesh names aren't taken from the file for UNV import
381               SMESH::SetName( aMeshSO, QFileInfo(filename).fileName() );
382
383             anEntryList.append( aMeshSO->GetID().c_str() );
384           }
385           else {
386             isEmpty = true;
387           }
388         }
389       }
390
391       // update Object browser
392       SMESHGUI::GetSMESHGUI()->updateObjBrowser();
393
394       // browse to the published meshes
395       if( LightApp_Application* anApp =
396           dynamic_cast<LightApp_Application*>( SUIT_Session::session()->activeApplication() ) )
397         anApp->browseObjects( anEntryList );
398
399       // show Error message box if there were errors
400       if ( errors.count() > 0 ) {
401         SUIT_MessageBox::critical( SMESHGUI::desktop(),
402                                    QObject::tr( "SMESH_ERROR" ),
403                                    QObject::tr( "SMESH_IMPORT_ERRORS" ) + "\n" + errors.join( "\n" ) );
404       }
405
406       // show warning message box, if some imported mesh is empty
407       if ( isEmpty ) {
408           SUIT_MessageBox::warning( SMESHGUI::desktop(),
409                                     QObject::tr( "SMESH_WRN_WARNING" ),
410                                     QObject::tr( "SMESH_DRS_SOME_EMPTY" ) );
411       }
412     }
413   }
414
415   //================================================================================
416   /*!
417    * \brief Export selected meshes or groups into a file
418    */
419   //================================================================================
420
421   void ExportMeshToFile( int theCommandID )
422   {
423     LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
424     SALOME_ListIO selected;
425     if( aSel )
426       aSel->selectedObjects( selected );
427
428     const bool isDAT = ( theCommandID == SMESHOp::OpExportDAT ||
429                          theCommandID == SMESHOp::OpPopupExportDAT );
430     const bool isMED = ( theCommandID == SMESHOp::OpExportMED ||
431                          theCommandID == SMESHOp::OpPopupExportMED );
432     const bool isUNV = ( theCommandID == SMESHOp::OpExportUNV ||
433                          theCommandID == SMESHOp::OpPopupExportUNV );
434     const bool isSTL = ( theCommandID == SMESHOp::OpExportSTL ||
435                          theCommandID == SMESHOp::OpPopupExportSTL );
436 #ifdef WITH_CGNS
437     const bool isCGNS= ( theCommandID == SMESHOp::OpExportCGNS ||
438                          theCommandID == SMESHOp::OpPopupExportCGNS );
439 #else
440     const bool isCGNS= false;
441 #endif
442     const bool isSAUV= ( theCommandID == SMESHOp::OpExportSAUV ||
443                          theCommandID == SMESHOp::OpPopupExportSAUV );
444     const bool isGMF = ( theCommandID == SMESHOp::OpExportGMF ||
445                          theCommandID == SMESHOp::OpPopupExportGMF );
446
447     const bool multiMeshSupported = ( isMED || isCGNS ); // file can hold several meshes
448     if ( selected.Extent() == 0 || ( selected.Extent() > 1 && !multiMeshSupported ))
449       return;
450     SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
451     bool aCheckWarn = true;
452     if ( resMgr )
453       aCheckWarn = resMgr->booleanValue( "SMESH", "show_warning", false );
454     // get mesh object from selection and check duplication of their names
455     bool hasDuplicatedMeshNames = false;
456     QList< QPair< SMESH::SMESH_IDSource_var, QString > >           aMeshList;
457     QList< QPair< SMESH::SMESH_IDSource_var, QString > >::iterator aMeshIter;
458     SALOME_ListIteratorOfListIO It( selected );
459     for( ; It.More(); It.Next() )
460     {
461       Handle(SALOME_InteractiveObject) anIObject = It.Value();
462       SMESH::SMESH_IDSource_var aMeshItem =
463         SMESH::IObjectToInterface<SMESH::SMESH_IDSource>(anIObject);
464       if ( aMeshItem->_is_nil() ) {
465         SUIT_MessageBox::warning( SMESHGUI::desktop(),
466                                   QObject::tr( "SMESH_WRN_WARNING" ),
467                                   QObject::tr( "SMESH_BAD_MESH_SELECTION" ));
468         return;
469       }
470       SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( aMeshItem );
471       if ( aCheckWarn && !aGroup->_is_nil() )
472       {
473         QMessageBox msgBox(SUIT_MessageBox::Warning,
474                            QObject::tr("SMESH_WRN_WARNING"),
475                            QObject::tr("SMESH_EXPORT_ONLY_GPOUP"),
476                            QMessageBox::StandardButton::NoButton,
477                            SMESHGUI::desktop());
478         QCheckBox dontShowCheckBox(QObject::tr("SMESH_WRN_SHOW_DLG_CHECKBOX"));
479         msgBox.addButton(QMessageBox::Ok);
480         msgBox.addButton(QMessageBox::Cancel);
481         msgBox.setDefaultButton(QMessageBox::Cancel);
482         QGridLayout* lt = qobject_cast<QGridLayout*>(msgBox.layout());
483         QDialogButtonBox* btnbox = msgBox.findChild<QDialogButtonBox*>();
484         lt->addWidget(&dontShowCheckBox, lt->rowCount(), lt->columnCount()-1, lt->rowCount(), lt->columnCount());
485         lt->addWidget(btnbox, lt->rowCount(), 0, lt->rowCount(), lt->columnCount());
486         if(msgBox.exec() == QMessageBox::Ok)
487         {
488           if(dontShowCheckBox.checkState() == Qt::Checked)
489           {
490             if ( resMgr )
491               resMgr->setValue( "SMESH", "show_warning", false);
492           }
493           aCheckWarn = false;
494         }
495         else
496           return;
497       }
498
499       QString aMeshName = anIObject->getName();
500
501       // check for name duplications
502       if ( !hasDuplicatedMeshNames )
503         for( aMeshIter = aMeshList.begin(); aMeshIter != aMeshList.end(); aMeshIter++ ) {
504           if( aMeshName == (*aMeshIter).second ) {
505             hasDuplicatedMeshNames = true;
506             break;
507           }
508         }
509
510       aMeshList.append( QPair< SMESH::SMESH_IDSource_var, QString >( aMeshItem, aMeshName ) );
511     }
512
513     if( hasDuplicatedMeshNames && isMED ) {
514       int aRet = SUIT_MessageBox::warning(SMESHGUI::desktop(),
515                                           QObject::tr("SMESH_WRN_WARNING"),
516                                           QObject::tr("SMESH_EXPORT_MED_DUPLICATED_MESH_NAMES"),
517                                           QObject::tr("SMESH_BUT_YES"),
518                                           QObject::tr("SMESH_BUT_NO"), 0, 1);
519       if (aRet != 0)
520         return;
521     }
522
523     aMeshIter = aMeshList.begin();
524     SMESH::SMESH_IDSource_var aMeshOrGroup = (*aMeshIter).first;
525     SMESH::SMESH_Mesh_var            aMesh = aMeshOrGroup->GetMesh();
526     QString                      aMeshName = (*aMeshIter).second;
527
528     if ( isMED || isCGNS || isSAUV ) // formats where group names must be unique
529     {
530       // check for equal group names within each mesh
531       for( aMeshIter = aMeshList.begin(); aMeshIter != aMeshList.end(); aMeshIter++ ) {
532         SMESH::SMESH_Mesh_var aMeshItem = SMESH::SMESH_Mesh::_narrow( (*aMeshIter).first );
533         if ( !aMeshItem->_is_nil() && aMeshItem->HasDuplicatedGroupNamesMED()) {
534           int aRet = SUIT_MessageBox::warning
535             (SMESHGUI::desktop(),
536              QObject::tr("SMESH_WRN_WARNING"),
537              QObject::tr("SMESH_EXPORT_MED_DUPLICATED_GRP").arg((*aMeshIter).second),
538              QObject::tr("SMESH_BUT_YES"),
539              QObject::tr("SMESH_BUT_NO"), 0, 1);
540           if (aRet != 0)
541             return;
542         }
543       }
544     }
545     
546     // Warn the user about presence of not supported elements
547     QString format;
548     std::vector< SMESH::EntityType > notSupportedElemTypes, presentNotSupported;
549     if ( isDAT )
550     {
551       format = "DAT";
552       notSupportedElemTypes.push_back( SMESH::Entity_0D );
553       notSupportedElemTypes.push_back( SMESH::Entity_Ball );
554     }
555     else if ( isUNV )
556     {
557       format = "UNV";
558       notSupportedElemTypes.push_back( SMESH::Entity_Polygon );
559       notSupportedElemTypes.push_back( SMESH::Entity_Quad_Polygon );
560       notSupportedElemTypes.push_back( SMESH::Entity_Polyhedra );
561       notSupportedElemTypes.push_back( SMESH::Entity_Quad_Polyhedra );
562       notSupportedElemTypes.push_back( SMESH::Entity_Pyramid );
563       notSupportedElemTypes.push_back( SMESH::Entity_Hexagonal_Prism );
564       notSupportedElemTypes.push_back( SMESH::Entity_0D );
565       notSupportedElemTypes.push_back( SMESH::Entity_Ball );
566     }
567     else if ( isSTL )
568     {
569       format = "STL";
570       notSupportedElemTypes.push_back( SMESH::Entity_Edge );
571       notSupportedElemTypes.push_back( SMESH::Entity_Quad_Edge );
572       notSupportedElemTypes.push_back( SMESH::Entity_0D );
573       notSupportedElemTypes.push_back( SMESH::Entity_Ball );
574     }
575     else if ( isCGNS )
576     {
577       format = "CGNS";
578       notSupportedElemTypes.push_back( SMESH::Entity_Ball );
579     }
580     else if ( isSAUV )
581     {
582       format = "SAUV";
583       notSupportedElemTypes.push_back( SMESH::Entity_Ball );
584       notSupportedElemTypes.push_back( SMESH::Entity_BiQuad_Triangle );
585       notSupportedElemTypes.push_back( SMESH::Entity_BiQuad_Quadrangle );
586       notSupportedElemTypes.push_back( SMESH::Entity_TriQuad_Hexa );
587       notSupportedElemTypes.push_back( SMESH::Entity_Hexagonal_Prism );
588       notSupportedElemTypes.push_back( SMESH::Entity_Polygon );
589       notSupportedElemTypes.push_back( SMESH::Entity_Quad_Polygon );
590       notSupportedElemTypes.push_back( SMESH::Entity_Polyhedra );
591     }
592     else if ( isGMF )
593     {
594       format = "GMF";
595       notSupportedElemTypes.push_back( SMESH::Entity_0D );
596       notSupportedElemTypes.push_back( SMESH::Entity_Polygon );
597       notSupportedElemTypes.push_back( SMESH::Entity_Quad_Polygon );
598       notSupportedElemTypes.push_back( SMESH::Entity_Quad_Pyramid );
599       notSupportedElemTypes.push_back( SMESH::Entity_Quad_Penta );
600       notSupportedElemTypes.push_back( SMESH::Entity_Hexagonal_Prism );
601       notSupportedElemTypes.push_back( SMESH::Entity_Polyhedra );
602       notSupportedElemTypes.push_back( SMESH::Entity_Quad_Polyhedra );
603       notSupportedElemTypes.push_back( SMESH::Entity_Ball );
604     }
605     if ( ! notSupportedElemTypes.empty() )
606     {
607       SMESH::long_array_var nbElems = aMeshOrGroup->GetMeshInfo();
608       for ( size_t iType = 0; iType < notSupportedElemTypes.size(); ++iType )
609         if ( nbElems[ notSupportedElemTypes[ iType ]] > 0 )
610           presentNotSupported.push_back( notSupportedElemTypes[ iType ]);
611     }
612     if ( !presentNotSupported.empty() )
613     {
614       QString typeNames;
615       const char* typeMsg[] = {
616         "SMESH_NODES", "SMESH_ELEMS0D","SMESH_EDGES","SMESH_QUADRATIC_EDGES",
617         "SMESH_TRIANGLES", "SMESH_QUADRATIC_TRIANGLES", "SMESH_BIQUADRATIC_TRIANGLES",
618         "SMESH_QUADRANGLES","SMESH_QUADRATIC_QUADRANGLES", "SMESH_BIQUADRATIC_QUADRANGLES",
619         "SMESH_POLYGONS","SMESH_QUADRATIC_POLYGONS",
620         "SMESH_TETRAHEDRA","SMESH_QUADRATIC_TETRAHEDRONS","SMESH_PYRAMIDS",
621         "SMESH_QUADRATIC_PYRAMIDS","SMESH_HEXAHEDRA","SMESH_QUADRATIC_HEXAHEDRONS",
622         "SMESH_TRIQUADRATIC_HEXAHEDRONS","SMESH_PENTAHEDRA","SMESH_QUADRATIC_PENTAHEDRONS",
623         "SMESH_OCTAHEDRA","SMESH_POLYEDRONS","SMESH_QUADRATIC_POLYEDRONS","SMESH_BALLS"
624       };
625       // is typeMsg complete? (compilation failure mains that enum SMDSAbs_EntityType changed)
626       const int nbTypes = sizeof( typeMsg ) / sizeof( const char* );
627       int _assert[( nbTypes == SMESH::Entity_Last ) ? 2 : -1 ]; _assert[0]=_assert[1];
628
629       QString andStr = " " + QObject::tr("SMESH_AND") + " ", comma(", ");
630       for ( size_t iType = 0; iType < presentNotSupported.size(); ++iType ) {
631         typeNames += QObject::tr( typeMsg[ presentNotSupported[ iType ]]);
632         if ( iType != presentNotSupported.size() - 1 )
633           typeNames += ( iType == presentNotSupported.size() - 2 ) ? andStr : comma;
634       }
635       int aRet = SUIT_MessageBox::warning
636         (SMESHGUI::desktop(),
637          QObject::tr("SMESH_WRN_WARNING"),
638          QObject::tr("EXPORT_NOT_SUPPORTED").arg(aMeshName).arg(format).arg(typeNames),
639          QObject::tr("SMESH_BUT_YES"),
640          QObject::tr("SMESH_BUT_NO"), 0, 1);
641       if (aRet != 0)
642         return;
643     }
644
645     // Get parameters of export operation
646
647     QString            aFilename;
648     SMESH::MED_VERSION aFormat = SMESH::MED_V2_2;
649     // Init the parameters with the default values
650     bool aIsASCII_STL   = true;
651     bool toCreateGroups = false;
652     if ( resMgr )
653       toCreateGroups = resMgr->booleanValue( "SMESH", "auto_groups", false );
654     bool toOverwrite  = true;
655     bool toFindOutDim = true;
656
657     QString aFilter, aTitle = QObject::tr("SMESH_EXPORT_MESH");
658     QString anInitialPath = "";
659     if ( SUIT_FileDlg::getLastVisitedPath().isEmpty() )
660       anInitialPath = QDir::currentPath();
661
662     QList< QPair< GEOM::ListOfFields_var, QString > > aFieldList;
663
664     // Get a file name to write in and additional otions
665     if ( isUNV || isDAT || isGMF ) // Export w/o options
666     {
667       if ( isUNV )
668         aFilter = QObject::tr( "IDEAS_FILES_FILTER" ) + " (*.unv)";
669       else if ( isDAT )
670         aFilter = QObject::tr( "DAT_FILES_FILTER" ) + " (*.dat)";
671       else if ( isGMF )
672         aFilter = QObject::tr( "GMF_ASCII_FILES_FILTER" ) + " (*.mesh)" +
673           ";;" +  QObject::tr( "GMF_BINARY_FILES_FILTER" )  + " (*.meshb)";
674      if ( anInitialPath.isEmpty() ) anInitialPath = SUIT_FileDlg::getLastVisitedPath();
675       aFilename = SUIT_FileDlg::getFileName(SMESHGUI::desktop(),
676                                             anInitialPath + QString("/") + aMeshName,
677                                             aFilter, aTitle, false);
678     }
679     else if ( isCGNS )// Export to CGNS
680     {
681       SUIT_FileDlg* fd = new SUIT_FileDlg( SMESHGUI::desktop(), false, true, true );
682       fd->setWindowTitle( aTitle );
683       fd->setNameFilter( QObject::tr( "CGNS_FILES_FILTER" ) + " (*.cgns)" );
684       if ( !anInitialPath.isEmpty() )
685         fd->setDirectory( anInitialPath );
686       fd->selectFile(aMeshName);
687       SMESHGUI_FileValidator* fv = new SMESHGUI_FileValidator( fd );
688       fd->setValidator( fv );
689
690       if ( fd->exec() )
691         aFilename = fd->selectedFile();
692       toOverwrite = fv->isOverwrite();
693
694       delete fd;
695     }
696     else if ( isSTL ) // Export to STL
697     {
698       QMap<QString, int> aFilterMap;
699       aFilterMap.insert( QObject::tr( "STL_ASCII_FILES_FILTER" ) + " (*.stl)", 1 );
700       aFilterMap.insert( QObject::tr( "STL_BIN_FILES_FILTER" )   + " (*.stl)", 0 );
701
702       QStringList filters;
703       QMap<QString, int>::const_iterator it = aFilterMap.begin();
704       for ( ; it != aFilterMap.end(); ++it )
705         filters.push_back( it.key() );
706
707       SUIT_FileDlg* fd = new SUIT_FileDlg( SMESHGUI::desktop(), false, true, true );
708       fd->setWindowTitle( aTitle );
709       fd->setNameFilters( filters );
710       fd->selectNameFilter( QObject::tr( "STL_ASCII_FILES_FILTER" ) + " (*.stl)" );
711       if ( !anInitialPath.isEmpty() )
712         fd->setDirectory( anInitialPath );
713       fd->selectFile(aMeshName);
714       bool is_ok = false;
715       while (!is_ok) {
716         if ( fd->exec() )
717           aFilename = fd->selectedFile();
718         aIsASCII_STL = (aFilterMap[fd->selectedNameFilter()]) == 1 ? true: false;
719         is_ok = true;
720       }
721       delete fd;
722     }
723     else if ( isMED || isSAUV ) // Export to MED or SAUV
724     {
725       QMap<QString, SMESH::MED_VERSION> aFilterMap;
726       //QString v21 (aMesh->GetVersionString(SMESH::MED_V2_1, 2));
727       if ( isMED ) {
728         QString v22 (aMesh->GetVersionString(SMESH::MED_V2_2, 2));
729         //aFilterMap.insert( QObject::tr( "MED_VX_FILES_FILTER" ).arg( v21 ) + " (*.med)", SMESH::MED_V2_1 );
730         aFilterMap.insert( QObject::tr( "MED_VX_FILES_FILTER" ).arg( v22 ) + " (*.med)", SMESH::MED_V2_2 );
731       }
732       else { // isSAUV
733         aFilterMap.insert("All files (*)", SMESH::MED_V2_1 );
734         aFilterMap.insert("SAUV files (*.sauv)", SMESH::MED_V2_2 );
735         aFilterMap.insert("SAUV files (*.sauve)", SMESH::MED_V2_1 );
736       }
737
738       QStringList filters;
739       QString aDefaultFilter;
740       QMap<QString, SMESH::MED_VERSION>::const_iterator it = aFilterMap.begin();
741       for ( ; it != aFilterMap.end(); ++it ) {
742         filters.push_back( it.key() );
743         if (it.value() == SMESH::MED_V2_2)
744           aDefaultFilter = it.key();
745       }
746       QStringList checkBoxes;
747       checkBoxes << QObject::tr("SMESH_AUTO_GROUPS") << QObject::tr("SMESH_AUTO_DIM");
748
749       SMESHGUI_FieldSelectorWdg* fieldSelWdg = new SMESHGUI_FieldSelectorWdg();
750       QList< QWidget* > wdgList;
751       if ( fieldSelWdg->GetAllFeilds( aMeshList, aFieldList ))
752         wdgList.append( fieldSelWdg );
753
754       SalomeApp_CheckFileDlg* fd =
755         new SalomeApp_CheckFileDlg ( SMESHGUI::desktop(), false, checkBoxes, true, true, wdgList );
756       fd->setWindowTitle( aTitle );
757       fd->setNameFilters( filters );
758       fd->selectNameFilter( aDefaultFilter );
759       fd->SetChecked( toCreateGroups, 0 );
760       fd->SetChecked( toFindOutDim,   1 );
761       if ( !anInitialPath.isEmpty() )
762         fd->setDirectory( anInitialPath );
763       fd->selectFile(aMeshName);
764       
765       
766       QListView *lview = fd->findChild<QListView*>("listView");
767       if( lview ) {
768         lview->setMinimumHeight(200);
769       }
770       QTreeView *tview = fd->findChild<QTreeView*>("treeView");
771       if( tview ) {
772         tview->setMinimumHeight(200);
773       }
774
775       SMESHGUI_FileValidator* fv = new SMESHGUI_FileValidator( fd );
776       fd->setValidator( fv );
777
778       bool is_ok = false;
779       while (!is_ok) {
780         if ( fd->exec() )
781           aFilename = fd->selectedFile();
782         else {
783           aFilename = QString::null;
784           break;
785         }
786         aFormat = aFilterMap[fd->selectedNameFilter()];
787         toOverwrite = fv->isOverwrite();
788         is_ok = true;
789         if ( !aFilename.isEmpty() ) {
790           // med-2.1 does not support poly elements
791           if ( aFormat==SMESH::MED_V2_1 )
792             for( aMeshIter = aMeshList.begin(); aMeshIter != aMeshList.end(); aMeshIter++ ) {
793               SMESH::SMESH_IDSource_var aMeshItem = (*aMeshIter).first;
794               SMESH::long_array_var nbElems = aMeshItem->GetMeshInfo();
795               if ( nbElems[ SMESH::Entity_Polygon   ] + nbElems[ SMESH::Entity_Quad_Polygon   ] +
796                    nbElems[ SMESH::Entity_Polyhedra ] + nbElems[ SMESH::Entity_Quad_Polyhedra ])
797               {
798                 int aRet = SUIT_MessageBox::warning(SMESHGUI::desktop(),
799                                                     QObject::tr("SMESH_WRN_WARNING"),
800                                                     QObject::tr("SMESH_EXPORT_MED_V2_1").arg((*aMeshIter).second),
801                                                     QObject::tr("SMESH_BUT_YES"),
802                                                     QObject::tr("SMESH_BUT_NO"), 0, 1);
803                 if (aRet != 0) {
804                   is_ok = false;
805                   break;
806                 }
807               }
808             }
809           if( !toOverwrite ) {
810             // can't append to an existing using other format
811             SMESH::MED_VERSION aVersion = SMESH::MED_V2_1;
812             bool isVersionOk = SMESHGUI::GetSMESHGen()->GetMEDVersion( aFilename.toUtf8().constData(), aVersion );
813             if( !isVersionOk || aVersion != aFormat ) {
814               int aRet = SUIT_MessageBox::warning(SMESHGUI::desktop(),
815                                                   QObject::tr("SMESH_WRN_WARNING"),
816                                                   QObject::tr("SMESH_EXPORT_MED_VERSION_COLLISION").arg(aFilename),
817                                                   QObject::tr("SMESH_BUT_YES"),
818                                                   QObject::tr("SMESH_BUT_NO"), 0, 1);
819               if (aRet == 0)
820                 toOverwrite = true;
821               else
822                 is_ok = false;
823             }
824
825             QStringList aMeshNamesCollisionList;
826             SMESH::string_array_var aMeshNames = SMESHGUI::GetSMESHGen()->GetMeshNames( aFilename.toUtf8().constData() );
827             for( int i = 0, n = aMeshNames->length(); i < n; i++ ) {
828               QString anExistingMeshName( aMeshNames[ i ] );
829               for( aMeshIter = aMeshList.begin(); aMeshIter != aMeshList.end(); aMeshIter++ ) {
830                 QString anExportMeshName = (*aMeshIter).second;
831                 if( anExportMeshName == anExistingMeshName ) {
832                   aMeshNamesCollisionList.append( anExportMeshName );
833                   break;
834                 }
835               }
836             }
837             if( !aMeshNamesCollisionList.isEmpty() ) {
838               QString aMeshNamesCollisionString = aMeshNamesCollisionList.join( ", " );
839               int aRet = SUIT_MessageBox::warning(SMESHGUI::desktop(),
840                                                   QObject::tr("SMESH_WRN_WARNING"),
841                                                   QObject::tr("SMESH_EXPORT_MED_MESH_NAMES_COLLISION").arg(aMeshNamesCollisionString),
842                                                   QObject::tr("SMESH_BUT_YES"),
843                                                   QObject::tr("SMESH_BUT_NO"),
844                                                   QObject::tr("SMESH_BUT_CANCEL"), 0, 2);
845               if (aRet == 0)
846                 toOverwrite = true;
847               else if (aRet == 2)
848                 is_ok = false;
849             }
850           }
851         }
852       }
853       toCreateGroups = fd->IsChecked(0);
854       toFindOutDim   = fd->IsChecked(1);
855       fieldSelWdg->GetSelectedFeilds();
856       if ( !fieldSelWdg->parent() )
857         delete fieldSelWdg;
858       delete fd;
859     }
860     else
861     {
862       return;
863     }
864
865     // Perform export
866
867     if ( !aFilename.isEmpty() ) {
868       // Check whether the file already exists and delete it if yes
869       QFile aFile( aFilename );
870       if ( aFile.exists() && toOverwrite )
871         aFile.remove();
872       SUIT_OverrideCursor wc;
873
874       try {
875         // Renumbering is not needed since SMDS redesign in V6.2.0 (Nov 2010)
876 //         bool Renumber = false;
877 //         // PAL 14172  : Check of we have to renumber or not from the preferences before export
878 //         if (resMgr)
879 //           Renumber= resMgr->booleanValue("renumbering");
880 //         if (Renumber){
881 //           SMESH::SMESH_MeshEditor_var aMeshEditor = aMesh->GetMeshEditor();
882 //           aMeshEditor->RenumberNodes();
883 //           aMeshEditor->RenumberElements();
884 //           if ( SMESHGUI::automaticUpdate() )
885 //             SMESH::UpdateView();
886 //         }
887         if ( isMED )
888         {
889           aMeshIter = aMeshList.begin();
890           for( int aMeshIndex = 0; aMeshIter != aMeshList.end(); aMeshIter++, aMeshIndex++ )
891           {
892             SMESH::SMESH_IDSource_var aMeshOrGroup = (*aMeshIter).first;
893             SMESH::SMESH_Mesh_var        aMeshItem = aMeshOrGroup->GetMesh();
894             const GEOM::ListOfFields&       fields = aFieldList[ aMeshIndex ].first.in();
895             const QString&            geoAssFields = aFieldList[ aMeshIndex ].second;
896             const bool                   hasFields = ( fields.length() || !geoAssFields.isEmpty() );
897             if ( !hasFields && aMeshOrGroup->_is_equivalent( aMeshItem ))
898               aMeshItem->ExportToMEDX( aFilename.toUtf8().data(), toCreateGroups,
899                                        aFormat, toOverwrite && aMeshIndex == 0, toFindOutDim );
900             else
901               aMeshItem->ExportPartToMED( aMeshOrGroup, aFilename.toUtf8().data(), toCreateGroups,
902                                           aFormat, toOverwrite && aMeshIndex == 0, toFindOutDim,
903                                           fields, geoAssFields.toLatin1().data() );
904           }
905         }
906         else if ( isSAUV )
907         {
908           for( aMeshIter = aMeshList.begin(); aMeshIter != aMeshList.end(); aMeshIter++ )
909           {
910             SMESH::SMESH_Mesh_var aMeshItem = SMESH::SMESH_Mesh::_narrow( (*aMeshIter).first );
911             if( !aMeshItem->_is_nil() )
912               aMeshItem->ExportSAUV( aFilename.toUtf8().data(), toCreateGroups );
913           }
914         }
915         else if ( isDAT )
916         {
917           if ( aMeshOrGroup->_is_equivalent( aMesh ))
918             aMesh->ExportDAT( aFilename.toUtf8().data() );
919           else
920             aMesh->ExportPartToDAT( aMeshOrGroup, aFilename.toUtf8().data() );
921         }
922         else if ( isUNV )
923         {
924           if ( aMeshOrGroup->_is_equivalent( aMesh ))
925             aMesh->ExportUNV( aFilename.toUtf8().data() );
926           else
927             aMesh->ExportPartToUNV( aMeshOrGroup, aFilename.toUtf8().data() );
928         }
929         else if ( isSTL )
930         {
931           if ( aMeshOrGroup->_is_equivalent( aMesh ))
932             aMesh->ExportSTL( aFilename.toUtf8().data(), aIsASCII_STL );
933           else
934             aMesh->ExportPartToSTL( aMeshOrGroup, aFilename.toUtf8().data(), aIsASCII_STL );
935         }
936         else if ( isCGNS )
937         {
938           aMeshIter = aMeshList.begin();
939           for( int aMeshIndex = 0; aMeshIter != aMeshList.end(); aMeshIter++, aMeshIndex++ )
940           {
941             SMESH::SMESH_IDSource_var aMeshOrGroup = (*aMeshIter).first;
942             SMESH::SMESH_Mesh_var        aMeshItem = aMeshOrGroup->GetMesh();
943             aMeshItem->ExportCGNS( aMeshOrGroup,
944                                    aFilename.toUtf8().data(),
945                                    toOverwrite && aMeshIndex == 0 );
946           }
947         }
948         else if ( isGMF )
949         {
950           toCreateGroups = true;
951           aMesh->ExportGMF( aMeshOrGroup, aFilename.toUtf8().data(), toCreateGroups );
952         }
953       }
954       catch (const SALOME::SALOME_Exception& S_ex){
955         wc.suspend();
956         SUIT_MessageBox::warning(SMESHGUI::desktop(),
957                                  QObject::tr("SMESH_WRN_WARNING"),
958                                  QObject::tr("SMESH_EXPORT_FAILED"));
959         wc.resume();
960       }
961     }
962   }
963
964   inline void InverseEntityMode(unsigned int& theOutputMode,
965                                 unsigned int  theMode)
966   {
967     bool anIsNotPresent = ~theOutputMode & theMode;
968     if(anIsNotPresent)
969       theOutputMode |= theMode;
970     else
971       theOutputMode &= ~theMode;
972   }
973
974   void SetDisplayEntity(int theCommandID)
975   {
976     LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
977     SALOME_ListIO selected;
978     if ( aSel )
979       aSel->selectedObjects( selected );
980
981     if ( selected.Extent() >= 1 ) {
982       SUIT_OverrideCursor wc;
983       SALOME_ListIteratorOfListIO It( selected );
984       for( ; It.More(); It.Next()){
985         Handle(SALOME_InteractiveObject) IObject = It.Value();
986         if(IObject->hasEntry()){
987           if(SMESH_Actor *anActor = SMESH::FindActorByEntry(IObject->getEntry())){
988             unsigned int aMode = anActor->GetEntityMode();
989             switch(theCommandID){
990             case SMESHOp::OpDE0DElements: InverseEntityMode(aMode,SMESH_Actor::e0DElements); break;
991             case SMESHOp::OpDEEdges:      InverseEntityMode(aMode,SMESH_Actor::eEdges); break;
992             case SMESHOp::OpDEFaces:      InverseEntityMode(aMode,SMESH_Actor::eFaces); break;
993             case SMESHOp::OpDEVolumes:    InverseEntityMode(aMode,SMESH_Actor::eVolumes); break;
994             case SMESHOp::OpDEBalls:      InverseEntityMode(aMode,SMESH_Actor::eBallElem); break;
995             case SMESHOp::OpDEAllEntity:  aMode = SMESH_Actor::eAllEntity; break;
996             }
997             if(aMode)
998               anActor->SetEntityMode(aMode);
999           }
1000         }
1001       }
1002     }
1003   }
1004
1005   void AutoColor()
1006   {
1007     SalomeApp_Application* app =
1008       dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
1009     if ( !app )
1010       return;
1011
1012     LightApp_SelectionMgr* aSel = app->selectionMgr();
1013     SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
1014     if ( !aSel || !appStudy )
1015       return;
1016
1017     SALOME_ListIO selected;
1018     aSel->selectedObjects( selected );
1019     if ( selected.IsEmpty() )
1020       return;
1021
1022     Handle(SALOME_InteractiveObject) anIObject = selected.First();
1023
1024     _PTR(Study)         aStudy = appStudy->studyDS();
1025     _PTR(SObject) aMainSObject = aStudy->FindObjectID( anIObject->getEntry() );
1026     SMESH::SMESH_Mesh_var aMainObject = SMESH::IObjectToInterface<SMESH::SMESH_Mesh>(anIObject);
1027     if ( aMainObject->_is_nil() )
1028       return;
1029
1030     SUIT_OverrideCursor wc;
1031
1032     aMainObject->SetAutoColor( true ); // mesh groups are re-colored here
1033
1034     QList<SALOMEDS::Color> aReservedColors;
1035
1036     SMESH::ListOfGroups aListOfGroups = *aMainObject->GetGroups();
1037     for ( int i = 0, n = aListOfGroups.length(); i < n; i++ )
1038     {
1039       SMESH::SMESH_GroupBase_var aGroupObject = aListOfGroups[i];
1040
1041 #ifdef SIMPLE_AUTOCOLOR   // simplified algorithm for auto-colors
1042       SALOMEDS::Color aColor = SMESHGUI::getPredefinedUniqueColor();
1043 #else                     // old algorithm  for auto-colors
1044       SALOMEDS::Color aColor = SMESHGUI::getUniqueColor( aReservedColors );
1045       aReservedColors.append( aColor );
1046 #endif                    // SIMPLE_AUTOCOLOR
1047       aGroupObject->SetColor( aColor );
1048
1049       _PTR(SObject) aGroupSObject = SMESH::FindSObject(aGroupObject);
1050       if ( aGroupSObject ) {
1051         QColor c;
1052         int delta;
1053         if ( SMESH_Actor *anActor = SMESH::FindActorByEntry(aGroupSObject->GetID().c_str())) {
1054           switch ( aGroupObject->GetType ()) {
1055           case SMESH::NODE:
1056             anActor->SetNodeColor( aColor.R, aColor.G, aColor.B ); break;
1057           case SMESH::EDGE:
1058             anActor->SetEdgeColor( aColor.R, aColor.G, aColor.B ); break;
1059           case SMESH::ELEM0D:
1060             anActor->Set0DColor( aColor.R, aColor.G, aColor.B ); break;
1061           case SMESH::BALL:
1062             anActor->SetBallColor( aColor.R, aColor.G, aColor.B ); break;
1063           case SMESH::VOLUME:
1064             SMESH::GetColor("SMESH", "volume_color", c, delta, "255,0,170|-100");
1065             anActor->SetVolumeColor( aColor.R, aColor.G, aColor.B, delta ); break;
1066           case SMESH::FACE:
1067           default:
1068             SMESH::GetColor("SMESH", "fill_color", c, delta, "0,170,255|-100");
1069             anActor->SetSufaceColor( aColor.R, aColor.G, aColor.B, delta );
1070           }
1071         }
1072       }
1073     }
1074
1075     SMESH::RepaintCurrentView();
1076   }
1077
1078   void OverallMeshQuality()
1079   {
1080     SMESHGUI::GetSMESHGUI()->EmitSignalDeactivateDialog();
1081     LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
1082     SALOME_ListIO selected;
1083     if( aSel )
1084       aSel->selectedObjects( selected );
1085
1086     if ( selected.IsEmpty() ) return;
1087     SALOME_ListIteratorOfListIO It( selected );
1088     for ( ; It.More(); It.Next() ) {
1089       SMESHGUI_CtrlInfoDlg* ctrlDlg = new SMESHGUI_CtrlInfoDlg( SMESHGUI::desktop() );
1090       ctrlDlg->showInfo( It.Value() );
1091       ctrlDlg->show();
1092     }
1093   }
1094
1095   QString functorToString( SMESH::Controls::FunctorPtr f )
1096   {
1097     QString type = QObject::tr( "UNKNOWN_CONTROL" );
1098     if ( dynamic_cast< SMESH::Controls::Volume* >( f.get() ) )
1099       type = QObject::tr( "VOLUME_3D_ELEMENTS" );
1100     else if ( dynamic_cast< SMESH::Controls::MaxElementLength2D* >( f.get() ) )
1101       type = QObject::tr( "MAX_ELEMENT_LENGTH_2D" );
1102     else if ( dynamic_cast< SMESH::Controls::MaxElementLength3D* >( f.get() ) )
1103       type = QObject::tr( "MAX_ELEMENT_LENGTH_3D" );
1104     else if ( dynamic_cast< SMESH::Controls::MinimumAngle* >( f.get() ) )
1105       type = QObject::tr( "MINIMUMANGLE_ELEMENTS" );
1106     else if ( dynamic_cast< SMESH::Controls::AspectRatio* >( f.get() ) )
1107       type = QObject::tr( "ASPECTRATIO_ELEMENTS" );
1108     else if ( dynamic_cast< SMESH::Controls::AspectRatio3D* >( f.get() ) )
1109       type = QObject::tr( "ASPECTRATIO_3D_ELEMENTS" );
1110     else if ( dynamic_cast< SMESH::Controls::Warping* >( f.get() ) )
1111       type = QObject::tr( "WARP_ELEMENTS" );
1112     else if ( dynamic_cast< SMESH::Controls::Taper* >( f.get() ) )
1113       type = QObject::tr( "TAPER_ELEMENTS" );
1114     else if ( dynamic_cast< SMESH::Controls::Skew* >( f.get() ) )
1115       type = QObject::tr( "SKEW_ELEMENTS" );
1116     else if ( dynamic_cast< SMESH::Controls::Area* >( f.get() ) )
1117       type = QObject::tr( "AREA_ELEMENTS" );
1118     else if ( dynamic_cast< SMESH::Controls::Length* >( f.get() ) )
1119       type = QObject::tr( "LENGTH_EDGES" );
1120     else if ( dynamic_cast< SMESH::Controls::Length2D* >( f.get() ) )
1121       type = QObject::tr( "LENGTH2D_EDGES" );
1122     else if ( dynamic_cast< SMESH::Controls::MultiConnection* >( f.get() ) )
1123       type = QObject::tr( "MULTI_BORDERS" );
1124     else if ( dynamic_cast< SMESH::Controls::MultiConnection2D* >( f.get() ) )
1125       type = QObject::tr( "MULTI2D_BORDERS" );
1126     else if ( dynamic_cast< SMESH::Controls::FreeNodes* >( f.get() ) )
1127       type = QObject::tr( "FREE_NODES" );
1128     else if ( dynamic_cast< SMESH::Controls::FreeEdges* >( f.get() ) )
1129       type = QObject::tr( "FREE_EDGES" );
1130     else if ( dynamic_cast< SMESH::Controls::FreeBorders* >( f.get() ) )
1131       type = QObject::tr( "FREE_BORDERS" );
1132     else if ( dynamic_cast< SMESH::Controls::FreeFaces* >( f.get() ) )
1133       type = QObject::tr( "FREE_FACES" );
1134     else if ( dynamic_cast< SMESH::Controls::BareBorderVolume* >( f.get() ) )
1135       type = QObject::tr( "BARE_BORDER_VOLUME" );
1136     else if ( dynamic_cast< SMESH::Controls::BareBorderFace* >( f.get() ) )
1137       type = QObject::tr( "BARE_BORDER_FACE" );
1138     else if ( dynamic_cast< SMESH::Controls::OverConstrainedVolume* >( f.get() ) )
1139       type = QObject::tr( "OVER_CONSTRAINED_VOLUME" );
1140     else if ( dynamic_cast< SMESH::Controls::OverConstrainedFace* >( f.get() ) )
1141       type = QObject::tr( "OVER_CONSTRAINED_FACE" );
1142     else if ( dynamic_cast< SMESH::Controls::CoincidentNodes* >( f.get() ) )
1143       type = QObject::tr( "EQUAL_NODE" );
1144     else if ( dynamic_cast< SMESH::Controls::CoincidentElements1D* >( f.get() ) )
1145       type = QObject::tr( "EQUAL_EDGE" );
1146     else if ( dynamic_cast< SMESH::Controls::CoincidentElements2D* >( f.get() ) )
1147       type = QObject::tr( "EQUAL_FACE" );
1148     else if ( dynamic_cast< SMESH::Controls::CoincidentElements3D* >( f.get() ) )
1149       type = QObject::tr( "EQUAL_VOLUME" );
1150     else if ( dynamic_cast< SMESH::Controls::NodeConnectivityNumber* >( f.get() ) )
1151       type = QObject::tr( "NODE_CONNECTIVITY_NB" );
1152     return type;
1153   }
1154
1155   void SaveDistribution()
1156   {
1157     LightApp_SelectionMgr* aSel = SMESHGUI::selectionMgr();
1158     SALOME_ListIO selected;
1159     if ( aSel )
1160       aSel->selectedObjects( selected );
1161
1162     if ( selected.Extent() == 1 ) {
1163       Handle(SALOME_InteractiveObject) anIO = selected.First();
1164       if ( anIO->hasEntry() ) {
1165         SMESH_Actor* anActor = SMESH::FindActorByEntry( anIO->getEntry() );
1166         if ( anActor &&
1167              anActor->GetScalarBarActor() &&
1168              anActor->GetControlMode() != SMESH_Actor::eNone )
1169         {
1170           SMESH_ScalarBarActor* aScalarBarActor = anActor->GetScalarBarActor();
1171           SMESH::Controls::FunctorPtr aFunctor = anActor->GetFunctor();
1172           if ( aScalarBarActor && aFunctor ) {
1173             SMESH::Controls::NumericalFunctor* aNumFun =
1174               dynamic_cast<SMESH::Controls::NumericalFunctor*>( aFunctor.get() );
1175             if ( aNumFun ) {
1176               std::vector<int> elements;
1177               SMESH::SMESH_Mesh_var mesh = SMESH::IObjectToInterface<SMESH::SMESH_Mesh>(anIO);
1178               if ( mesh->_is_nil() ) {
1179                 SMESH::SMESH_IDSource_var idSource =
1180                   SMESH::IObjectToInterface<SMESH::SMESH_IDSource>(anIO);
1181                 if ( !idSource->_is_nil() )
1182                 {
1183                   SMESH::long_array_var ids = idSource->GetIDs();
1184                   elements.resize( ids->length() );
1185                   for ( unsigned i = 0; i < elements.size(); ++i )
1186                     elements[i] = ids[i];
1187                 }
1188               }
1189               int nbIntervals = aScalarBarActor->GetMaximumNumberOfColors();
1190               vtkLookupTable* lookupTable =
1191                 static_cast<vtkLookupTable*>(aScalarBarActor->GetLookupTable());
1192               double * minmax = lookupTable->GetRange();
1193               bool isLogarithmic = lookupTable->GetScale() == VTK_SCALE_LOG10;
1194               std::vector<int>    nbEvents;
1195               std::vector<double> funValues;
1196               aNumFun->GetHistogram( nbIntervals, nbEvents, funValues,
1197                                      elements, minmax, isLogarithmic );
1198               QString anInitialPath = "";
1199               if ( SUIT_FileDlg::getLastVisitedPath().isEmpty() )
1200                 anInitialPath = QDir::currentPath();
1201               QString aMeshName = anIO->getName();
1202               QStringList filter;
1203               filter.append( QObject::tr( "TEXT_FILES_FILTER" ) + " (*.txt)" );
1204               filter.append( QObject::tr( "ALL_FILES_FILTER" ) + " (*)" );
1205               QString aFilename = anInitialPath + "/" + aMeshName + "_" +
1206                 functorToString( aFunctor ).toLower().simplified().replace( QRegExp( " |-" ), "_" ) + ".txt";
1207               aFilename = SUIT_FileDlg::getFileName( SMESHGUI::desktop(),
1208                                                      aFilename,
1209                                                      filter,
1210                                                      QObject::tr( "SMESH_SAVE_DISTRIBUTION" ),
1211                                                      false );
1212               if ( !aFilename.isEmpty() ) {
1213                 QFile f( aFilename );
1214                 if ( f.open( QFile::WriteOnly | QFile::Truncate ) ) {
1215                   QTextStream out( &f );
1216                   out << "# Mesh: " << aMeshName << endl;
1217                   out << "# Control: " << functorToString( aFunctor ) << endl;
1218                   out << "#" << endl;
1219                   out.setFieldWidth( 10 );
1220                   for ( int i = 0; i < (int)qMin( nbEvents.size(), funValues.size()-1 ); i++ )
1221                     out << funValues[i] << "\t" << funValues[i+1] << "\t" << nbEvents[i] << endl;
1222                   f.close();
1223                 }
1224               }
1225             }
1226           }
1227         }
1228       }
1229     }
1230   }
1231
1232   void ShowElement( int theCommandID )
1233   {
1234     LightApp_SelectionMgr* aSel = SMESHGUI::selectionMgr();
1235     SALOME_ListIO selected;
1236     if ( aSel )
1237       aSel->selectedObjects( selected );
1238
1239     if ( selected.Extent() == 1 ) {
1240       Handle(SALOME_InteractiveObject) anIO = selected.First();
1241       if ( anIO->hasEntry() ) {
1242         SMESH_Actor* anActor = SMESH::FindActorByEntry( anIO->getEntry() );
1243         if ( anActor &&
1244              anActor->GetScalarBarActor() &&
1245              anActor->GetControlMode() != SMESH_Actor::eNone )
1246         {
1247           SMESH_ScalarBarActor *aScalarBarActor = anActor->GetScalarBarActor();
1248           if ( theCommandID == SMESHOp::OpShowDistribution ) {
1249             aScalarBarActor->SetDistributionVisibility(!aScalarBarActor->GetDistributionVisibility());
1250           }
1251           else if ( theCommandID == SMESHOp::OpShowScalarBar ) {
1252             aScalarBarActor->SetVisibility( !aScalarBarActor->GetVisibility());
1253           }
1254         }
1255       }
1256     }
1257   }
1258
1259 #ifndef DISABLE_PLOT2DVIEWER
1260   void PlotDistribution()
1261   {
1262     SalomeApp_Application* app =
1263       dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
1264     if( !app )
1265       return;
1266
1267     LightApp_SelectionMgr* aSel = SMESHGUI::selectionMgr();
1268     SALOME_ListIO selected;
1269     if ( aSel )
1270       aSel->selectedObjects( selected );
1271
1272     if ( selected.Extent() == 1 ) {
1273       Handle(SALOME_InteractiveObject) anIO = selected.First();
1274       if ( anIO->hasEntry() ) {
1275         //Find Actor by entry before getting Plot2d viewer,
1276         //because after call getViewManager( Plot2d_Viewer::Type(), true ) active window is Plot2d Viewer
1277         SMESH_Actor* anActor = SMESH::FindActorByEntry( anIO->getEntry() );
1278
1279         SUIT_ViewManager* aViewManager =
1280           app->getViewManager( Plot2d_Viewer::Type(), true ); // create if necessary
1281         if( !aViewManager )
1282           return;
1283
1284         SPlot2d_Viewer* aView = dynamic_cast<SPlot2d_Viewer*>(aViewManager->getViewModel());
1285         if ( !aView )
1286           return;
1287
1288         Plot2d_ViewFrame* aPlot = aView->getActiveViewFrame();
1289         if ( !aPlot )
1290           return;
1291
1292         if ( anActor && anActor->GetControlMode() != SMESH_Actor::eNone )
1293         {
1294           SPlot2d_Histogram* aHistogram = anActor->UpdatePlot2Histogram();
1295           QString functorName = functorToString( anActor->GetFunctor());
1296           QString aHistogramName("%1 : %2");
1297           aHistogramName = aHistogramName.arg(anIO->getName()).arg(functorName);
1298           aHistogram->setName(aHistogramName);
1299           aHistogram->setHorTitle(functorName);
1300           aHistogram->setVerTitle(QObject::tr("DISTRIBUTION_NB_ENT"));
1301           aPlot->displayObject(aHistogram, true);
1302         }
1303       }
1304     }
1305   }
1306 #endif //DISABLE_PLOT2DVIEWER
1307
1308   void DisableAutoColor()
1309   {
1310     LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
1311     SALOME_ListIO selected;
1312     if ( aSel )
1313       aSel->selectedObjects( selected );
1314
1315     if ( selected.Extent() ) {
1316       Handle(SALOME_InteractiveObject) anIObject = selected.First();
1317       SMESH::SMESH_Mesh_var aMesh = SMESH::IObjectToInterface<SMESH::SMESH_Mesh>(anIObject);
1318       if ( !aMesh->_is_nil() ) {
1319         aMesh->SetAutoColor( false );
1320       }
1321     }
1322   }
1323
1324   void sortChildren()
1325   {
1326     LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
1327     SALOME_ListIO selected;
1328     if ( aSel ) {
1329       aSel->selectedObjects( selected );
1330       if ( selected.Extent() )
1331       {
1332         Handle(SALOME_InteractiveObject) anIObject = selected.First();
1333         _PTR(Study) aStudy = SMESH::GetActiveStudyDocument();
1334         _PTR(SObject) aSObj = aStudy->FindObjectID(anIObject->getEntry());
1335         if (aSObj) {
1336           if ( aStudy->GetUseCaseBuilder()->SortChildren( aSObj, true/*AscendingOrder*/ ) ) {
1337             SMESHGUI::GetSMESHGUI()->updateObjBrowser();
1338           }
1339         }
1340       }
1341     }
1342   }
1343
1344   void SetDisplayMode(int theCommandID, SMESHGUI_StudyId2MarkerMap& theMarkerMap)
1345   {
1346     SALOME_ListIO selected;
1347     SalomeApp_Application* app =
1348       dynamic_cast< SalomeApp_Application* >( SUIT_Session::session()->activeApplication() );
1349     if ( !app )
1350       return;
1351
1352     LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
1353     SalomeApp_Study*   appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
1354     if ( !aSel || !appStudy )
1355       return;
1356
1357     if ( theCommandID == SMESHOp::OpClipping ) { // Clipping dialog can be activated without selection
1358       if ( SMESHGUI* aModule = SMESHGUI::GetSMESHGUI() ) {
1359         aModule->EmitSignalDeactivateDialog();
1360         if( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( aModule ) )
1361           (new SMESHGUI_ClippingDlg( aModule, aViewWindow ))->show();
1362       }
1363       return;
1364     }
1365
1366     _PTR(Study) aStudy = appStudy->studyDS();
1367
1368     aSel->selectedObjects( selected );
1369
1370     if ( selected.Extent() >= 1 )
1371     {
1372       switch ( theCommandID ) {
1373       case SMESHOp::OpTransparency:
1374       {
1375         SMESHGUI::GetSMESHGUI()->EmitSignalDeactivateDialog();
1376         (new SMESHGUI_TransparencyDlg( SMESHGUI::GetSMESHGUI() ))->show();
1377         return;
1378       }
1379       case SMESHOp::OpProperties:
1380       {
1381         double color[3];
1382         QColor faceColor, edgeColor, nodeColor, elem0dColor, ballColor;
1383         QColor orientationColor, outlineColor, volumeColor;
1384         int deltaF = 0, deltaV = 0;
1385         int elem0dSize   = 1;
1386         //int ballSize     = 1;
1387         double ballScale = 1.0;
1388         int edgeWidth    = 1;
1389         int outlineWidth = 1;
1390         double shrinkCoef = 0.0;
1391         double orientationScale = 0.0;
1392         bool orientation3d = false;
1393         VTK::MarkerType markerType = VTK::MT_NONE;
1394         VTK::MarkerScale markerScale = VTK::MS_NONE;
1395         int markerId = 0;
1396         bool hasNodes = false;
1397         int presentEntities = 0;
1398         bool firstTime  = true;
1399
1400         SALOME_ListIteratorOfListIO It( selected );
1401         for ( ; It.More(); It.Next() ) {
1402           Handle(SALOME_InteractiveObject) IObject = It.Value();
1403           if ( !IObject->hasEntry() ) continue;
1404           SMESH_Actor* anActor = SMESH::FindActorByEntry( IObject->getEntry() );
1405           if ( !anActor || !anActor->GetObject() ) continue;
1406
1407           if ( firstTime ) {
1408             // nodes: color, marker
1409             anActor->GetNodeColor( color[0], color[1], color[2] );
1410             nodeColor.setRgbF( color[0], color[1], color[2] );
1411             markerType  = anActor->GetMarkerType();
1412             markerScale = anActor->GetMarkerScale();
1413             markerId    = anActor->GetMarkerTexture();
1414             // edges: color, width
1415             anActor->GetEdgeColor( color[0], color[1], color[2] );
1416             edgeColor.setRgbF( color[0], color[1], color[2] );
1417             edgeWidth = qMax( (int)anActor->GetLineWidth(), 1 ); // minimum allowed width is 1
1418             // faces: front color, back color (delta)
1419             anActor->GetSufaceColor( color[0], color[1], color[2], deltaF );
1420             faceColor.setRgbF( color[0], color[1], color[2] );
1421             // faces: front color, back color (delta)
1422             anActor->GetVolumeColor( color[0], color[1], color[2], deltaV );
1423             volumeColor.setRgbF( color[0], color[1], color[2] );
1424             // 0d elements: color, size
1425             anActor->Get0DColor( color[0], color[1], color[2] );
1426             elem0dColor.setRgbF( color[0], color[1], color[2] );
1427             elem0dSize = qMax( (int)anActor->Get0DSize(), 1 ); // minimum allowed size is 1
1428             // balls: color, size
1429             anActor->GetBallColor( color[0], color[1], color[2] );
1430             ballColor.setRgbF( color[0], color[1], color[2] );
1431             //ballSize = qMax( (int)anActor->GetBallSize(), 1 ); // minimum allowed size is 1
1432             ballScale = qMax( (double)anActor->GetBallScale(), 1e-2 ); // minimum allowed scale is 1e-2
1433             // outlines: color
1434             anActor->GetOutlineColor( color[0], color[1], color[2] );
1435             outlineColor.setRgbF( color[0], color[1], color[2] );
1436             outlineWidth = qMax( (int)anActor->GetOutlineWidth(), 1 ); // minimum allowed width is 1
1437             // orientation vectors: color, scale, 3d flag
1438             anActor->GetFacesOrientationColor( color[0], color[1], color[2] );
1439             orientationColor.setRgbF( color[0], color[1], color[2] );
1440             orientationScale = anActor->GetFacesOrientationScale();
1441             orientation3d = anActor->GetFacesOrientation3DVectors();
1442             // shrink factor
1443             shrinkCoef = anActor->GetShrinkFactor();
1444           }
1445
1446           firstTime = false; // we only take properties from first object (for performance reasons)
1447
1448           if ( !hasNodes )
1449             hasNodes = anActor->GetObject()->GetNbEntities( SMDSAbs_Node );
1450           if ( !(presentEntities & SMESH_Actor::eEdges) && anActor->GetObject()->GetNbEntities( SMDSAbs_Edge ) )
1451             presentEntities = presentEntities | SMESH_Actor::eEdges;
1452           if ( !(presentEntities & SMESH_Actor::eFaces) && anActor->GetObject()->GetNbEntities( SMDSAbs_Face ) )
1453             presentEntities = presentEntities | SMESH_Actor::eFaces;
1454           if ( !(presentEntities & SMESH_Actor::eVolumes) && anActor->GetObject()->GetNbEntities( SMDSAbs_Volume ) )
1455             presentEntities = presentEntities | SMESH_Actor::eVolumes;
1456           if ( !(presentEntities & SMESH_Actor::e0DElements) && anActor->GetObject()->GetNbEntities( SMDSAbs_0DElement ) )
1457             presentEntities = presentEntities | SMESH_Actor::e0DElements;
1458           if ( !(presentEntities & SMESH_Actor::eBallElem) && anActor->GetObject()->GetNbEntities( SMDSAbs_Ball ) )
1459             presentEntities = presentEntities | SMESH_Actor::eBallElem;
1460           
1461           // as we know that all types of elements are present, we can exit the loop
1462           if ( presentEntities == SMESH_Actor::eAllEntity )
1463             break;
1464         }
1465
1466         SMESHGUI_PropertiesDlg dlg( theMarkerMap[ aStudy->StudyId() ], SMESHGUI::desktop() );
1467         // nodes: color, marker
1468         dlg.setNodeColor( nodeColor );
1469         if( markerType != VTK::MT_USER )
1470           dlg.setNodeMarker( markerType, markerScale );
1471         else
1472           dlg.setNodeCustomMarker( markerId );
1473         // edges: color, line width
1474         dlg.setEdgeColor( edgeColor );
1475         dlg.setEdgeWidth( edgeWidth );
1476         // faces: front color, back color
1477         dlg.setFaceColor( faceColor, deltaF );
1478         // volumes: normal color, reversed color
1479         dlg.setVolumeColor( volumeColor, deltaV );
1480         // outlines: color, line width
1481         dlg.setOutlineColor( outlineColor );
1482         dlg.setOutlineWidth( outlineWidth );
1483         // 0d elements: color, size
1484         dlg.setElem0dColor( elem0dColor );
1485         dlg.setElem0dSize( elem0dSize );
1486         // balls: color, size
1487         dlg.setBallColor( ballColor );
1488         //dlg.setBallSize( ballSize );
1489         dlg.setBallScale( ballScale );
1490         // orientation: color, scale, 3d flag
1491         dlg.setOrientationColor( orientationColor );
1492         dlg.setOrientationSize( int( orientationScale * 100. ) );
1493         dlg.setOrientation3d( orientation3d );
1494         // shrink: scale factor
1495         dlg.setShrinkCoef( int( shrinkCoef * 100. ) );
1496         // hide unused controls
1497         dlg.showControls( presentEntities, hasNodes );
1498         
1499         if ( dlg.exec() ) {
1500           nodeColor        = dlg.nodeColor();
1501           markerType       = dlg.nodeMarkerType();
1502           markerScale      = dlg.nodeMarkerScale();
1503           markerId         = dlg.nodeMarkerId();
1504           edgeColor        = dlg.edgeColor();
1505           edgeWidth        = dlg.edgeWidth();
1506           faceColor        = dlg.faceColor();
1507           deltaF           = dlg.faceColorDelta();
1508           volumeColor      = dlg.volumeColor();
1509           deltaV           = dlg.volumeColorDelta();
1510           outlineColor     = dlg.outlineColor();
1511           outlineWidth     = dlg.outlineWidth();
1512           elem0dColor      = dlg.elem0dColor();
1513           elem0dSize       = dlg.elem0dSize();
1514           ballColor        = dlg.ballColor();
1515          // ballSize         = dlg.ballSize();
1516           ballScale        = dlg.ballScale();
1517           orientationColor = dlg.orientationColor();
1518           orientationScale = dlg.orientationSize() / 100.;
1519           orientation3d    = dlg.orientation3d();
1520           shrinkCoef       = dlg.shrinkCoef() / 100.;
1521
1522           // store point markers map that might be changed by the user
1523           theMarkerMap[ aStudy->StudyId() ] = dlg.customMarkers();
1524
1525           // set properties from dialog box to the presentations
1526           SALOME_ListIteratorOfListIO It( selected );
1527           for ( ; It.More(); It.Next() ) {
1528             Handle(SALOME_InteractiveObject) IObject = It.Value();
1529             if ( !IObject->hasEntry() ) continue;
1530             SMESH_Actor* anActor = SMESH::FindActorByEntry( IObject->getEntry() );
1531             if ( !anActor ) continue;
1532             
1533             // nodes: color, marker
1534             anActor->SetNodeColor( nodeColor.redF(), nodeColor.greenF(), nodeColor.blueF() );
1535             if ( markerType != VTK::MT_USER ) {
1536               anActor->SetMarkerStd( markerType, markerScale );
1537             }
1538             else {
1539               const VTK::MarkerMap& markerMap = theMarkerMap[ aStudy->StudyId() ];
1540               VTK::MarkerMap::const_iterator iter = markerMap.find( markerId );
1541               if ( iter != markerMap.end() )
1542                 anActor->SetMarkerTexture( markerId, iter->second.second );
1543             }
1544             // volumes: normal color, reversed color (delta)
1545             anActor->SetVolumeColor( volumeColor.redF(), volumeColor.greenF(), volumeColor.blueF(), deltaV );
1546             // faces: front color, back color (delta)
1547             anActor->SetSufaceColor( faceColor.redF(), faceColor.greenF(), faceColor.blueF(), deltaF );
1548             // edges: color, width
1549             anActor->SetEdgeColor( edgeColor.redF(), edgeColor.greenF(), edgeColor.blueF() );
1550             anActor->SetLineWidth( edgeWidth );
1551             // outlines: color
1552             anActor->SetOutlineColor( outlineColor.redF(), outlineColor.greenF(), outlineColor.blueF() );
1553             anActor->SetOutlineWidth( outlineWidth );
1554             // 0D elements: color, size
1555             anActor->Set0DColor( elem0dColor.redF(), elem0dColor.greenF(), elem0dColor.blueF() );
1556             anActor->Set0DSize( elem0dSize );
1557             // balls: color, size
1558             anActor->SetBallColor( ballColor.redF(), ballColor.greenF(), ballColor.blueF() );
1559             // anActor->SetBallSize( ballSize );
1560             anActor->SetBallScale( ballScale );
1561             // orientation: color, scale, 3d flag
1562             anActor->SetFacesOrientationColor( orientationColor.redF(), orientationColor.greenF(), orientationColor.blueF() );
1563             anActor->SetFacesOrientationScale( orientationScale );
1564             anActor->SetFacesOrientation3DVectors( orientation3d );
1565             // shrink factor
1566             anActor->SetShrinkFactor( shrinkCoef );
1567
1568             // for groups, set also proper color
1569             SMESH::SMESH_GroupBase_var aGroupObject = SMESH::IObjectToInterface<SMESH::SMESH_GroupBase>(IObject);
1570             if ( !aGroupObject->_is_nil() ) {
1571               SMESH::ElementType anElementType = aGroupObject->GetType();
1572               QColor aColor;
1573               switch( anElementType ) {
1574               case SMESH::NODE:
1575                 aColor = nodeColor; break;
1576               case SMESH::EDGE:
1577                 aColor = edgeColor; break;
1578               case SMESH::FACE: 
1579                 aColor = faceColor; break;
1580               case SMESH::VOLUME:
1581                 aColor = volumeColor; break;
1582               case SMESH::ELEM0D: 
1583                 aColor = elem0dColor; break;
1584               case SMESH::BALL: 
1585                 aColor = ballColor; break;
1586               default: break;
1587               }
1588               
1589               if ( aColor.isValid() ) {
1590                 SALOMEDS::Color aGroupColor;
1591                 aGroupColor.R = aColor.redF();
1592                 aGroupColor.G = aColor.greenF();
1593                 aGroupColor.B = aColor.blueF();
1594                 aGroupObject->SetColor( aGroupColor );
1595               }
1596             } // if ( !aGroupObject->_is_nil() )
1597           } // for ( ; It.More(); It.Next() )
1598           SMESH::RepaintCurrentView();
1599         } // if ( dlg.exec() )
1600         return;
1601       } // case SMESHOp::OpProperties:
1602       } // switch(theCommandID)
1603       SUIT_OverrideCursor wc;
1604       SALOME_ListIteratorOfListIO It( selected );
1605       for( ; It.More(); It.Next()){
1606         Handle(SALOME_InteractiveObject) IObject = It.Value();
1607         if(IObject->hasEntry()){
1608           if(SMESH_Actor *anActor = SMESH::FindActorByEntry(IObject->getEntry())){
1609             switch(theCommandID){
1610             case SMESHOp::OpDMWireframe:
1611               anActor->SetRepresentation(SMESH_Actor::eEdge);
1612               break;
1613             case SMESHOp::OpDMShading:
1614               anActor->SetRepresentation(SMESH_Actor::eSurface);
1615               break;
1616             case SMESHOp::OpDMShrink:
1617               if(anActor->IsShrunk())
1618                 anActor->UnShrink();
1619               else
1620                 anActor->SetShrink();
1621               break;
1622             case SMESHOp::OpDMNodes:
1623               anActor->SetRepresentation(SMESH_Actor::ePoint);
1624               break;
1625             case SMESHOp::OpRepresentationLines:
1626               if(anActor->GetQuadratic2DRepresentation() != SMESH_Actor::eLines)
1627                 anActor->SetQuadratic2DRepresentation(SMESH_Actor::eLines);
1628               break;
1629             case SMESHOp::OpRepresentationArcs:
1630               if(anActor->GetQuadratic2DRepresentation() != SMESH_Actor::eArcs)
1631                 anActor->SetQuadratic2DRepresentation(SMESH_Actor::eArcs);
1632               break;
1633             }
1634           }
1635         }
1636       }
1637       SMESH::RepaintCurrentView();
1638     }
1639   }
1640
1641   int ActionToControl( int theID, bool theReversed )
1642   {
1643     NCollection_DoubleMap<int,int> ActionControl;
1644     ActionControl.Bind( 0,                                SMESH_Actor::eNone );
1645     ActionControl.Bind( SMESHOp::OpFreeNode,              SMESH_Actor::eFreeNodes );
1646     ActionControl.Bind( SMESHOp::OpEqualNode,             SMESH_Actor::eCoincidentNodes );
1647     ActionControl.Bind( SMESHOp::OpNodeConnectivityNb,    SMESH_Actor::eNodeConnectivityNb );
1648     ActionControl.Bind( SMESHOp::OpFreeEdge,              SMESH_Actor::eFreeEdges );
1649     ActionControl.Bind( SMESHOp::OpFreeBorder,            SMESH_Actor::eFreeBorders );
1650     ActionControl.Bind( SMESHOp::OpLength,                SMESH_Actor::eLength );
1651     ActionControl.Bind( SMESHOp::OpConnection,            SMESH_Actor::eMultiConnection );
1652     ActionControl.Bind( SMESHOp::OpEqualEdge,             SMESH_Actor::eCoincidentElems1D );
1653     ActionControl.Bind( SMESHOp::OpFreeFace,              SMESH_Actor::eFreeFaces );
1654     ActionControl.Bind( SMESHOp::OpBareBorderFace,        SMESH_Actor::eBareBorderFace );
1655     ActionControl.Bind( SMESHOp::OpOverConstrainedFace,   SMESH_Actor::eOverConstrainedFace );
1656     ActionControl.Bind( SMESHOp::OpLength2D,              SMESH_Actor::eLength2D );
1657     ActionControl.Bind( SMESHOp::OpConnection2D,          SMESH_Actor::eMultiConnection2D );
1658     ActionControl.Bind( SMESHOp::OpArea,                  SMESH_Actor::eArea );
1659     ActionControl.Bind( SMESHOp::OpTaper,                 SMESH_Actor::eTaper );
1660     ActionControl.Bind( SMESHOp::OpAspectRatio,           SMESH_Actor::eAspectRatio );
1661     ActionControl.Bind( SMESHOp::OpMinimumAngle,          SMESH_Actor::eMinimumAngle );
1662     ActionControl.Bind( SMESHOp::OpWarpingAngle,          SMESH_Actor::eWarping );
1663     ActionControl.Bind( SMESHOp::OpSkew,                  SMESH_Actor::eSkew );
1664     ActionControl.Bind( SMESHOp::OpMaxElementLength2D,    SMESH_Actor::eMaxElementLength2D );
1665     ActionControl.Bind( SMESHOp::OpEqualFace,             SMESH_Actor::eCoincidentElems2D );
1666     ActionControl.Bind( SMESHOp::OpAspectRatio3D,         SMESH_Actor::eAspectRatio3D );
1667     ActionControl.Bind( SMESHOp::OpVolume,                SMESH_Actor::eVolume3D );
1668     ActionControl.Bind( SMESHOp::OpMaxElementLength3D,    SMESH_Actor::eMaxElementLength3D );
1669     ActionControl.Bind( SMESHOp::OpBareBorderVolume,      SMESH_Actor::eBareBorderVolume );
1670     ActionControl.Bind( SMESHOp::OpOverConstrainedVolume, SMESH_Actor::eOverConstrainedVolume );
1671     ActionControl.Bind( SMESHOp::OpEqualVolume,           SMESH_Actor::eCoincidentElems3D );
1672
1673     return theReversed ? ActionControl.Find2( theID ) : ActionControl.Find1( theID );
1674   }
1675
1676   void Control( int theCommandID )
1677   {
1678     SMESH_Actor::eControl aControl = SMESH_Actor::eControl( ActionToControl( theCommandID ));
1679     _PTR(Study) aStudy = SMESH::GetActiveStudyDocument();
1680
1681     SALOME_ListIO selected;
1682     if ( LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr() )
1683       aSel->selectedObjects( selected );
1684
1685     if ( !selected.IsEmpty() ) {
1686       SALOME_ListIteratorOfListIO It(selected);
1687       for ( ; It.More(); It.Next())
1688       {
1689         Handle(SALOME_InteractiveObject) anIO = It.Value();
1690         if ( !anIO.IsNull() ) {
1691           _PTR(SObject) SO = aStudy->FindObjectID( It.Value()->getEntry() );
1692           if ( SO ) {
1693             CORBA::Object_var         aObject = SMESH::SObjectToObject( SO );
1694             SMESH::SMESH_IDSource_var anIDSrc = SMESH::SMESH_IDSource::_narrow( aObject );
1695             if ( !anIDSrc->_is_nil() ) {
1696               SMESH_Actor *anActor = SMESH::FindActorByEntry( anIO->getEntry());
1697               if (( !anActor && selected.Extent() == 1 ) &&
1698                   ( anActor = SMESH::CreateActor( aStudy, anIO->getEntry() )))
1699               {
1700                 anActor->SetControlMode( aControl );
1701                 SMESH::DisplayActor( SMESH::GetCurrentVtkView(), anActor );
1702                 SMESH::UpdateView  ( SMESH::eDisplay, anIO->getEntry() );
1703               }
1704               if ( anActor )
1705               {
1706                 if ( anActor->GetControlMode() != aControl )
1707                   anActor->SetControlMode( aControl );
1708                 QString functorName = functorToString( anActor->GetFunctor() );
1709                 int anEntitiesCount = anActor->GetNumberControlEntities();
1710                 if (anEntitiesCount >= 0)
1711                   functorName = functorName + ": " + QString::number(anEntitiesCount);
1712                 anActor->GetScalarBarActor()->SetTitle( functorName.toLatin1().constData() );
1713                 SMESH::RepaintCurrentView();
1714 #ifndef DISABLE_PLOT2DVIEWER
1715                 if ( anActor->GetPlot2Histogram() ) {
1716                   SPlot2d_Histogram* aHistogram = anActor->UpdatePlot2Histogram();
1717                   QString aHistogramName("%1 : %2");
1718                   aHistogramName = aHistogramName.arg( anIO->getName() ).arg( functorName );
1719                   aHistogram->setName( aHistogramName );
1720                   aHistogram->setHorTitle( functorName );
1721                   SMESH::ProcessIn2DViewers( anActor );
1722                 }
1723 #endif
1724               }
1725             }
1726           }
1727         }
1728       }
1729     }
1730   }
1731
1732
1733   bool CheckOIType(const Handle(SALOME_InteractiveObject) & theIO,
1734                    SMESH::MeshObjectType                    theType,
1735                    const QString                            theInTypeName,
1736                    QString &                                theOutTypeName)
1737   {
1738     SMESH_TypeFilter aTypeFilter( theType );
1739     QString entry;
1740     if ( !theIO.IsNull() )
1741     {
1742       entry = theIO->getEntry();
1743       LightApp_DataOwner owner( entry );
1744       if ( aTypeFilter.isOk( &owner )) {
1745         theOutTypeName = theInTypeName;
1746         return true;
1747       }
1748     }
1749     return false;
1750   }
1751
1752
1753   QString CheckTypeObject(const Handle(SALOME_InteractiveObject) & theIO)
1754   {
1755     _PTR(Study)  aStudy = SMESH::GetActiveStudyDocument();
1756     _PTR(SObject) aSObj = aStudy->FindObjectID(theIO->getEntry());
1757     if (aSObj) {
1758       _PTR(SComponent) aSComp = aSObj->GetFatherComponent();
1759       CORBA::String_var  anID = aSComp->GetID().c_str();
1760       if ( !strcmp(anID.in(),theIO->getEntry()) )
1761         return "Component";
1762     }
1763
1764     QString aTypeName;
1765     if (
1766         CheckOIType ( theIO, SMESH::HYPOTHESIS,    "Hypothesis", aTypeName ) ||
1767         CheckOIType ( theIO, SMESH::ALGORITHM,     "Algorithm",  aTypeName ) ||
1768         CheckOIType ( theIO, SMESH::MESH,          "Mesh",       aTypeName ) ||
1769         CheckOIType ( theIO, SMESH::SUBMESH,       "SubMesh",    aTypeName ) ||
1770         CheckOIType ( theIO, SMESH::GROUP,         "Group",      aTypeName )
1771         )
1772       return aTypeName;
1773
1774     return "NoType";
1775   }
1776
1777
1778   // QString CheckHomogeneousSelection()
1779   // {
1780   //   LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
1781   //   SALOME_ListIO selected;
1782   //   if ( aSel )
1783   //     aSel->selectedObjects( selected );
1784
1785   //   QString RefType = CheckTypeObject(selected.First());
1786   //   SALOME_ListIteratorOfListIO It(selected);
1787   //   for ( ; It.More(); It.Next())
1788   //   {
1789   //     Handle(SALOME_InteractiveObject) IObject = It.Value();
1790   //     QString Type = CheckTypeObject(IObject);
1791   //     if ( Type.compare(RefType) != 0 )
1792   //       return "Heterogeneous Selection";
1793   //   }
1794
1795   //   return RefType;
1796   // }
1797
1798   uint randomize( uint size )
1799   {
1800     static bool initialized = false;
1801     if ( !initialized ) {
1802       qsrand( QDateTime::currentDateTime().toTime_t() );
1803       initialized = true;
1804     }
1805     uint v = qrand();
1806     v = uint( (double)( v ) / RAND_MAX * size );
1807     v = qMax( uint(0), qMin ( v, size-1 ) );
1808     return v;
1809   }
1810   
1811 } //namespace
1812
1813 void SMESHGUI::OnEditDelete()
1814 {
1815   // VSR 17/11/04: check if all objects selected belong to SMESH component --> start
1816   LightApp_SelectionMgr* aSel = SMESHGUI::selectionMgr();
1817   SALOME_ListIO selected; aSel->selectedObjects( selected, QString::null, false );
1818
1819   _PTR(Study) aStudy = SMESH::GetActiveStudyDocument();
1820   _PTR(StudyBuilder) aStudyBuilder = aStudy->NewBuilder();
1821   _PTR(GenericAttribute) anAttr;
1822   _PTR(AttributeIOR) anIOR;
1823
1824   int objectCount = 0;
1825   QString aNameList;
1826   QString aParentComponent = QString::null;
1827   Handle(SALOME_InteractiveObject) anIO;
1828   for( SALOME_ListIteratorOfListIO anIt( selected ); anIt.More(); anIt.Next() )
1829   {
1830     anIO = anIt.Value();
1831     QString cur = anIO->getComponentDataType();
1832     _PTR(SObject) aSO = aStudy->FindObjectID(anIO->getEntry());
1833     if (aSO) {
1834       // check if object is reference
1835       _PTR(SObject) aRefSObj;
1836       aNameList.append("\n    - ");
1837       if ( aSO->ReferencedObject( aRefSObj ) ) {
1838         QString aRefName = QString::fromStdString ( aRefSObj->GetName() );
1839         aNameList.append( aRefName );
1840         cur = QString::fromStdString ( aRefSObj->GetFatherComponent()->ComponentDataType() );
1841       }
1842       else
1843         aNameList.append(anIO->getName());
1844       objectCount++;
1845     }
1846
1847     if( aParentComponent.isNull() )
1848       aParentComponent = cur;
1849     else if( !aParentComponent.isEmpty() && aParentComponent!=cur )
1850       aParentComponent = "";
1851   }
1852
1853   if ( objectCount == 0 )
1854     return; // No Valid Objects Selected
1855
1856   if ( aParentComponent != SMESHGUI::GetSMESHGUI()->name() )  {
1857     SUIT_MessageBox::warning( SMESHGUI::desktop(),
1858                               QObject::tr("ERR_ERROR"),
1859                               QObject::tr("NON_SMESH_OBJECTS_SELECTED").arg( SMESHGUI::GetSMESHGUI()->moduleName() ) );
1860     return;
1861   }
1862   // VSR 17/11/04: check if all objects selected belong to SMESH component <-- finish
1863   if (SUIT_MessageBox::warning
1864       (SMESHGUI::desktop(),
1865        QObject::tr("SMESH_WRN_WARNING"),
1866        QObject::tr("SMESH_REALLY_DELETE").arg( objectCount ).arg( aNameList ),
1867        SUIT_MessageBox::Yes | SUIT_MessageBox::No,
1868        SUIT_MessageBox::Yes) != SUIT_MessageBox::Yes)
1869     return;
1870
1871   SalomeApp_Application* anApp = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
1872
1873   // Put the whole hierarchy of sub-objects of the selected SO's into a list and
1874   // then treat them all starting from the deepest objects (at list back)
1875   std::list< _PTR(SObject) > listSO;
1876   SALOME_ListIteratorOfListIO It(selected);
1877   for( ; It.More(); It.Next()) // loop on selected IO's
1878   {
1879     Handle(SALOME_InteractiveObject) IObject = It.Value();
1880     if(IObject->hasEntry()) {
1881       _PTR(SObject) aSO = aStudy->FindObjectID(IObject->getEntry());
1882
1883       // disable removal of "SMESH" component object
1884       if(aSO->FindAttribute(anAttr, "AttributeIOR")){
1885         anIOR = anAttr;
1886         if ( engineIOR() == anIOR->Value().c_str() )
1887           continue;
1888       }
1889       //Check the referenced object
1890       _PTR(SObject) aRefSObject;
1891       if ( aSO && aSO->ReferencedObject( aRefSObject ) )
1892         aSO = aRefSObject; // Delete main Object instead of reference
1893
1894       listSO.push_back( aSO );
1895       std::list< _PTR(SObject) >::iterator itSO = --listSO.end();
1896       for ( ; itSO != listSO.end(); ++itSO ) {
1897         _PTR(ChildIterator) it = aStudy->NewChildIterator( *itSO );
1898         for (it->InitEx(false); it->More(); it->Next())
1899           listSO.push_back( it->Value() );
1900       }
1901     }
1902   }
1903   // Check if none of objects to delete is referred from outside
1904   std::list< _PTR(SObject) >::reverse_iterator ritSO;
1905   for ( ritSO = listSO.rbegin(); ritSO != listSO.rend(); ++ritSO )
1906   {
1907     _PTR(SObject) SO = *ritSO;
1908     if ( !SO ) continue;
1909     std::vector<_PTR(SObject)> aReferences = aStudy->FindDependances( *ritSO  );
1910     for (size_t i = 0; i < aReferences.size(); i++) {
1911       _PTR(SComponent) aComponent = aReferences[i]->GetFatherComponent();
1912       std::string type = aComponent->ComponentDataType();
1913       if ( type != "SMESH" )
1914       {
1915         SUIT_MessageBox::warning( anApp->desktop(),
1916                                   QObject::tr("WRN_WARNING"),
1917                                   QObject::tr("DEP_OBJECT") );
1918         return; // outside SMESH, there is an object depending on a SMESH object
1919       }
1920     }
1921   }
1922
1923   // Call mesh->Clear() to prevent loading mesh from file caused by hypotheses removal
1924   for( It.Initialize( selected ); It.More(); It.Next()) // loop on selected IO's
1925   {
1926     Handle(SALOME_InteractiveObject) IObject = It.Value();
1927     SMESH::SMESH_Mesh_var mesh = SMESH::IObjectToInterface< SMESH::SMESH_Mesh >( IObject );
1928     if ( !mesh->_is_nil() )
1929       mesh->Clear();
1930   }
1931
1932   // Treat SO's in the list starting from the back
1933   aStudyBuilder->NewCommand();  // There is a transaction
1934   for ( ritSO = listSO.rbegin(); ritSO != listSO.rend(); ++ritSO )
1935   {
1936     _PTR(SObject) SO = *ritSO;
1937     if ( !SO ) continue;
1938     std::string anEntry = SO->GetID();
1939
1940     /** Erase graphical object and remove all its data **/
1941     if(SO->FindAttribute(anAttr, "AttributeIOR")) {
1942       SMESH::RemoveVisualObjectWithActors( anEntry.c_str(), true);
1943     }
1944     /** Remove an object from data structures **/
1945     SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( SMESH::SObjectToObject( SO ));
1946     SMESH::SMESH_subMesh_var   aSubMesh = SMESH::SMESH_subMesh::_narrow( SMESH::SObjectToObject( SO ));
1947     if ( !aGroup->_is_nil() ) {                          // DELETE GROUP
1948       SMESH::SMESH_Mesh_var aMesh = aGroup->GetMesh();
1949       aMesh->RemoveGroup( aGroup );
1950     }
1951     else if ( !aSubMesh->_is_nil() ) {                   // DELETE SUBMESH
1952       SMESH::SMESH_Mesh_var aMesh = aSubMesh->GetFather();
1953       aMesh->RemoveSubMesh( aSubMesh );
1954
1955       _PTR(SObject) aMeshSO = SMESH::FindSObject(aMesh);
1956       if (aMeshSO)
1957         SMESH::ModifiedMesh(aMeshSO, false, aMesh->NbNodes()==0);
1958     }
1959     else {
1960       Handle(SALOME_InteractiveObject) IObject = new SALOME_InteractiveObject
1961         ( anEntry.c_str(), engineIOR().toLatin1().data(), SO->GetName().c_str() );
1962       QString objType = CheckTypeObject(IObject);
1963       if ( objType == "Hypothesis" || objType == "Algorithm" ) {// DELETE HYPOTHESIS
1964         SMESH::RemoveHypothesisOrAlgorithmOnMesh(IObject);
1965         aStudyBuilder->RemoveObjectWithChildren( SO );
1966       }
1967       else {// default action: remove SObject from the study
1968         // san - it's no use opening a transaction here until UNDO/REDO is provided in SMESH
1969         //SUIT_Operation *op = new SALOMEGUI_ImportOperation(myActiveStudy);
1970         //op->start();
1971         aStudyBuilder->RemoveObjectWithChildren( SO );
1972         //op->finish();
1973       }
1974     }
1975   } /* listSO back loop */
1976
1977   aStudyBuilder->CommitCommand();
1978
1979   /* Clear any previous selection */
1980   SALOME_ListIO l1;
1981   aSel->setSelectedObjects( l1 );
1982
1983   SMESHGUI::GetSMESHGUI()->updateObjBrowser();
1984 }
1985
1986 extern "C" {
1987   SMESHGUI_EXPORT CAM_Module* createModule()
1988   {
1989     return new SMESHGUI();
1990   }
1991
1992   SMESHGUI_EXPORT  char* getModuleVersion() {
1993     return (char*)SMESH_VERSION_STR;
1994   }
1995 }
1996
1997 SMESH::SMESH_Gen_var SMESHGUI::myComponentSMESH = SMESH::SMESH_Gen::_nil();
1998
1999 //=============================================================================
2000 /*!
2001  *
2002  */
2003 //=============================================================================
2004 SMESHGUI::SMESHGUI() :
2005 SalomeApp_Module( "SMESH" )
2006 {
2007   if ( CORBA::is_nil( myComponentSMESH ) )
2008   {
2009     CORBA::Boolean anIsEmbeddedMode;
2010     myComponentSMESH = SMESH_Client::GetSMESHGen(getApp()->orb(),anIsEmbeddedMode);
2011     //MESSAGE("-------------------------------> anIsEmbeddedMode=" << anIsEmbeddedMode);
2012
2013     //  0019923: EDF 765 SMESH : default values of hypothesis
2014     SUIT_ResourceMgr* aResourceMgr = SMESH::GetResourceMgr(this);
2015     int nbSeg = aResourceMgr->integerValue( "SMESH", "segmentation", 10 );
2016     myComponentSMESH->SetBoundaryBoxSegmentation( nbSeg );
2017     nbSeg = aResourceMgr->integerValue( "SMESH", "nb_segments_per_edge", 15 );
2018     myComponentSMESH->SetDefaultNbSegments( nbSeg );
2019
2020     const char* options[] = { "historical_python_dump", "forget_mesh_on_hyp_modif", "default_grp_color" };
2021     for ( size_t i = 0; i < sizeof(options)/sizeof(char*); ++i )
2022       if ( aResourceMgr->hasValue( "SMESH", options[i] ))
2023       {
2024         QString val = aResourceMgr->stringValue( "SMESH", options[i] );
2025         myComponentSMESH->SetOption( options[i], val.toLatin1().constData() );
2026       }
2027   }
2028
2029   myActiveDialogBox = 0;
2030   myFilterLibraryDlg = 0;
2031   myState = -1;
2032   myDisplayer = 0;
2033
2034   myEventCallbackCommand = vtkCallbackCommand::New();
2035   myEventCallbackCommand->Delete();
2036   myEventCallbackCommand->SetClientData( this );
2037   myEventCallbackCommand->SetCallback( SMESHGUI::ProcessEvents );
2038   myPriority = 0.0;
2039
2040   /* load resources for all available meshers */
2041   SMESH::InitAvailableHypotheses();
2042 }
2043
2044 //=============================================================================
2045 /*!
2046  *
2047  */
2048 //=============================================================================
2049 SMESHGUI::~SMESHGUI()
2050 {
2051 }
2052
2053 //=============================================================================
2054 /*!
2055  *
2056  */
2057 //=============================================================================
2058 LightApp_SelectionMgr* SMESHGUI::selectionMgr()
2059 {
2060   SalomeApp_Application* anApp = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
2061   if( anApp )
2062     return dynamic_cast<LightApp_SelectionMgr*>( anApp->selectionMgr() );
2063   else
2064     return 0;
2065 }
2066
2067 //=============================================================================
2068 /*!
2069  *
2070  */
2071 //=============================================================================
2072 bool SMESHGUI::automaticUpdate(unsigned int requestedSize, bool* limitExceeded)
2073 {
2074   SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
2075   if ( !resMgr )
2076     return false;
2077
2078   bool autoUpdate  = resMgr->booleanValue( "SMESH", "auto_update",  false );
2079   long updateLimit = resMgr->integerValue( "SMESH", "update_limit", 500000 );
2080   bool exceeded = updateLimit > 0 && requestedSize > updateLimit;
2081   if ( limitExceeded ) *limitExceeded = autoUpdate && exceeded;
2082   return autoUpdate && !exceeded;
2083 }
2084
2085 //=============================================================================
2086 /*!
2087  *
2088  */
2089 //=============================================================================
2090 bool SMESHGUI::automaticUpdate( SMESH::SMESH_IDSource_ptr theMesh,
2091                                 int* entities, bool* limitExceeded, int* hidden, long* nbElements )
2092 {
2093   SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
2094   if ( !resMgr )
2095     return false;
2096
2097   bool autoUpdate  = resMgr->booleanValue( "SMESH", "auto_update", false );
2098   long updateLimit = resMgr->integerValue( "SMESH", "update_limit", 500000 );
2099   bool incrementalLimit = resMgr->booleanValue( "SMESH", "incremental_limit", false );
2100
2101   SMESH::long_array_var info = theMesh->GetMeshInfo();
2102   long nbOdElems = info[SMDSEntity_0D];
2103   long nbEdges   = info[SMDSEntity_Edge] + info[SMDSEntity_Quad_Edge];
2104   long nbFaces   = info[SMDSEntity_Triangle]   + info[SMDSEntity_Quad_Triangle]   + info[SMDSEntity_BiQuad_Triangle] + 
2105                    info[SMDSEntity_Quadrangle] + info[SMDSEntity_Quad_Quadrangle] + info[SMDSEntity_BiQuad_Quadrangle] + 
2106                    info[SMDSEntity_Polygon] + info[SMDSEntity_Quad_Polygon];
2107   long nbVolumes = info[SMDSEntity_Tetra]   + info[SMDSEntity_Quad_Tetra] + 
2108                    info[SMDSEntity_Hexa]    + info[SMDSEntity_Quad_Hexa] + info[SMDSEntity_TriQuad_Hexa] + 
2109                    info[SMDSEntity_Pyramid] + info[SMDSEntity_Quad_Pyramid] + 
2110                    info[SMDSEntity_Penta]   + info[SMDSEntity_Quad_Penta] + 
2111                    info[SMDSEntity_Polyhedra] + 
2112                    info[SMDSEntity_Hexagonal_Prism];
2113   long nbBalls   = info[SMDSEntity_Ball];
2114
2115   long requestedSize = nbOdElems + nbBalls + nbEdges + nbFaces + nbVolumes;
2116   *nbElements = requestedSize;
2117   
2118   *entities = SMESH_Actor::eAllEntity;
2119   *hidden   = 0;
2120
2121   bool exceeded = updateLimit > 0 && requestedSize > updateLimit;
2122
2123   if ( limitExceeded ) *limitExceeded = autoUpdate && exceeded;
2124
2125   if ( incrementalLimit ) {
2126     long total     = 0;
2127
2128     if ( nbOdElems > 0 ) {
2129       if ( total + nbOdElems > updateLimit ) {
2130         *entities = *entities & ~SMESH_Actor::e0DElements;
2131         *hidden = *hidden | SMESH_Actor::e0DElements;
2132       }
2133       else
2134         exceeded = false;
2135     }
2136     total += nbOdElems;
2137
2138     if ( nbEdges > 0 ) {
2139       if ( total + nbEdges > updateLimit ) {
2140         *entities = *entities & ~SMESH_Actor::eEdges;
2141         *hidden = *hidden | SMESH_Actor::eEdges;
2142       }
2143       else
2144         exceeded = false;
2145     }
2146     total += nbEdges;
2147
2148     if ( nbFaces > 0 ) {
2149       if ( total + nbFaces > updateLimit ) {
2150         *entities = *entities & ~SMESH_Actor::eFaces;
2151         *hidden = *hidden | SMESH_Actor::eFaces;
2152       }
2153       else
2154         exceeded = false;
2155     }
2156     total += nbFaces;
2157
2158     if ( nbVolumes > 0 ) {
2159       if ( total + nbVolumes > updateLimit ) {
2160         *entities = *entities & ~SMESH_Actor::eVolumes;
2161         *hidden = *hidden | SMESH_Actor::eVolumes;
2162       }
2163       else
2164         exceeded = false;
2165     }
2166     total += nbVolumes;
2167
2168     if ( nbBalls > 0 ) {
2169       if ( total + nbBalls > updateLimit ) {
2170         *entities = *entities & ~SMESH_Actor::eBallElem;
2171         *hidden = *hidden | SMESH_Actor::eBallElem;
2172       }
2173       else
2174         exceeded = false;
2175     }
2176     total += nbBalls;
2177   }
2178
2179   return autoUpdate && !exceeded;
2180 }
2181
2182 //=============================================================================
2183 /*!
2184  *
2185  */
2186 //=============================================================================
2187 SUIT_ResourceMgr* SMESHGUI::resourceMgr()
2188 {
2189   return dynamic_cast<SUIT_ResourceMgr*>( SUIT_Session::session()->resourceMgr() );
2190 }
2191
2192 //=============================================================================
2193 /*!
2194  *
2195  */
2196 //=============================================================================
2197 SMESHGUI* SMESHGUI::GetSMESHGUI()
2198 {
2199   SMESHGUI* smeshMod = 0;
2200   SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>(SUIT_Session::session()->activeApplication());
2201   if ( app )
2202   {
2203     CAM_Module* module = app->module( "Mesh" );
2204     smeshMod = dynamic_cast<SMESHGUI*>( module );
2205   }
2206
2207   if ( smeshMod && smeshMod->application() && smeshMod->application()->activeStudy() )
2208   {
2209     SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( smeshMod->application()->activeStudy() );
2210     if ( study )
2211     {
2212       _PTR(Study) aStudy = study->studyDS();
2213       if ( aStudy )
2214         GetSMESHGen()->SetCurrentStudy( _CAST(Study,aStudy)->GetStudy() );
2215     }
2216   }
2217
2218   return smeshMod;
2219 }
2220
2221 extern "C"
2222 {
2223   Standard_EXPORT SMESHGUI* GetComponentGUI()
2224   {
2225     return SMESHGUI::GetSMESHGUI();
2226   }
2227 }
2228
2229 //=============================================================================
2230 /*!
2231  *
2232  */
2233 //=============================================================================
2234 void SMESHGUI::SetState(int aState)
2235 {
2236   myState = aState;
2237 }
2238
2239 //=============================================================================
2240 /*!
2241  *
2242  */
2243 //=============================================================================
2244 void SMESHGUI::ResetState()
2245 {
2246   myState = -1;
2247 }
2248
2249 //=============================================================================
2250 /*!
2251  *
2252  */
2253 //=============================================================================
2254 void SMESHGUI::EmitSignalDeactivateDialog()
2255 {
2256   emit SignalDeactivateActiveDialog();
2257 }
2258
2259 //=============================================================================
2260 /*!
2261  *
2262  */
2263 //=============================================================================
2264 void SMESHGUI::EmitSignalStudyFrameChanged()
2265 {
2266   emit SignalStudyFrameChanged();
2267 }
2268
2269 //=============================================================================
2270 /*!
2271  *
2272  */
2273 //=============================================================================
2274 void SMESHGUI::EmitSignalCloseAllDialogs()
2275 {
2276   emit SignalCloseAllDialogs();
2277 }
2278
2279 //=============================================================================
2280 /*!
2281  *
2282  */
2283 //=============================================================================
2284 void SMESHGUI::EmitSignalVisibilityChanged()
2285 {
2286   emit SignalVisibilityChanged();
2287 }
2288
2289 //=============================================================================
2290 /*!
2291  *
2292  */
2293 //=============================================================================
2294 void SMESHGUI::EmitSignalCloseView()
2295 {
2296   emit SignalCloseView();
2297 }
2298
2299 //=============================================================================
2300 /*!
2301  *
2302  */
2303 //=============================================================================
2304 void SMESHGUI::EmitSignalActivatedViewManager()
2305 {
2306   emit SignalActivatedViewManager();
2307 }
2308
2309 //=============================================================================
2310 /*!
2311  *
2312  */
2313 //=============================================================================
2314 QDialog *SMESHGUI::GetActiveDialogBox()
2315 {
2316   return myActiveDialogBox;
2317 }
2318
2319 //=============================================================================
2320 /*!
2321  *
2322  */
2323 //=============================================================================
2324 void SMESHGUI::SetActiveDialogBox(QDialog * aDlg)
2325 {
2326   myActiveDialogBox = (QDialog *) aDlg;
2327   return;
2328 }
2329
2330 //=============================================================================
2331 /*!
2332  *
2333  */
2334 //=============================================================================
2335 SUIT_Desktop* SMESHGUI::desktop()
2336 {
2337   SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
2338   if( app )
2339     return app->desktop();
2340   else
2341     return 0;
2342 }
2343
2344 //=============================================================================
2345 /*!
2346  *
2347  */
2348 //=============================================================================
2349 SalomeApp_Study* SMESHGUI::activeStudy()
2350 {
2351   SUIT_Application* app = SUIT_Session::session()->activeApplication();
2352   if( app )
2353     return dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
2354   else
2355     return NULL;
2356 }
2357
2358 //=============================================================================
2359 /*!
2360  *
2361  */
2362 //=============================================================================
2363 void SMESHGUI::Modified( bool theIsUpdateActions )
2364 {
2365   if( SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() ) ) {
2366     if( SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() ) ) {
2367       appStudy->Modified();
2368       if( theIsUpdateActions )
2369         app->updateActions();
2370     }
2371   }
2372 }
2373
2374 //=============================================================================
2375 /*!
2376  *
2377  */
2378 //=============================================================================
2379 bool SMESHGUI::DefineDlgPosition(QWidget * aDlg, int &x, int &y)
2380 {
2381   /* Here the position is on the bottom right corner - 10 */
2382   // aDlg->resize(QSize().expandedTo(aDlg->minimumSizeHint()));
2383   aDlg->adjustSize();
2384   SUIT_Desktop *PP = desktop();
2385   x = abs(PP->x() + PP->size().width() - aDlg->size().width() - 10);
2386   y = abs(PP->y() + PP->size().height() - aDlg->size().height() - 10);
2387   return true;
2388 }
2389
2390 //=============================================================================
2391 /*!
2392  *
2393  */
2394 //=============================================================================
2395 static int isStudyLocked(_PTR(Study) theStudy){
2396   return theStudy->GetProperties()->IsLocked();
2397 }
2398
2399 static bool checkLock(_PTR(Study) theStudy) {
2400   if (isStudyLocked(theStudy)) {
2401     SUIT_MessageBox::warning( SMESHGUI::desktop(),
2402                               QObject::tr("WRN_WARNING"),
2403                               QObject::tr("WRN_STUDY_LOCKED") );
2404     return true;
2405   }
2406   return false;
2407 }
2408
2409 //=======================================================================
2410 //function : CheckActiveStudyLocked
2411 //purpose  :
2412 //=======================================================================
2413
2414 bool SMESHGUI::isActiveStudyLocked()
2415 {
2416   _PTR(Study) aStudy = activeStudy()->studyDS();
2417   return checkLock( aStudy );
2418 }
2419
2420 //=============================================================================
2421 /*!
2422  *
2423  */
2424 //=============================================================================
2425 bool SMESHGUI::OnGUIEvent( int theCommandID )
2426 {
2427   SalomeApp_Application* anApp = dynamic_cast<SalomeApp_Application*>( application() );
2428   if( !anApp )
2429     return false;
2430
2431   _PTR(Study) aStudy = SMESH::GetActiveStudyDocument(); //Document OCAF de l'etude active
2432   SUIT_ResourceMgr* mgr = resourceMgr();
2433   if( !mgr )
2434     return false;
2435
2436   if (CORBA::is_nil(GetSMESHGen()->GetCurrentStudy())) {
2437     GetSMESHGen()->SetCurrentStudy(_CAST(Study,aStudy)->GetStudy());
2438   }
2439
2440   SUIT_ViewWindow* view = application()->desktop()->activeWindow();
2441   SVTK_ViewWindow* vtkwnd = dynamic_cast<SVTK_ViewWindow*>( view );
2442
2443   //QAction* act = action( theCommandID );
2444
2445   switch (theCommandID) {
2446   case SMESHOp::OpDelete:
2447     if(checkLock(aStudy)) break;
2448     OnEditDelete();
2449     break;
2450   case SMESHOp::OpImportDAT:
2451   case SMESHOp::OpImportUNV:
2452   case SMESHOp::OpImportMED:
2453   case SMESHOp::OpImportSTL:
2454 #ifdef WITH_CGNS
2455   case SMESHOp::OpImportCGNS:
2456 #endif
2457   case SMESHOp::OpImportSAUV:
2458   case SMESHOp::OpImportGMF:
2459     {
2460       if(checkLock(aStudy)) break;
2461       ::ImportMeshesFromFile(GetSMESHGen(),theCommandID);
2462       break;
2463     }
2464
2465   case SMESHOp::OpFileInformation:
2466     {
2467       SALOME_ListIO selected;
2468       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2469       if( aSel )
2470         aSel->selectedObjects( selected );
2471       if( selected.Extent() )
2472       {
2473         Handle(SALOME_InteractiveObject) anIObject = selected.First();
2474         SMESH::SMESH_Mesh_var aMesh = SMESH::IObjectToInterface<SMESH::SMESH_Mesh>(anIObject);
2475         if ( !aMesh->_is_nil() )
2476         {
2477           SMESHGUI_FileInfoDlg dlg( desktop(), aMesh->GetMEDFileInfo() );
2478           dlg.exec();
2479         }
2480       }
2481       break;
2482     }
2483   case SMESHOp::OpExportDAT:
2484   case SMESHOp::OpExportMED:
2485   case SMESHOp::OpExportUNV:
2486   case SMESHOp::OpExportSTL:
2487 #ifdef WITH_CGNS
2488   case SMESHOp::OpExportCGNS:
2489 #endif
2490   case SMESHOp::OpExportSAUV:
2491   case SMESHOp::OpExportGMF:
2492   case SMESHOp::OpPopupExportDAT:
2493   case SMESHOp::OpPopupExportMED:
2494   case SMESHOp::OpPopupExportUNV:
2495   case SMESHOp::OpPopupExportSTL:
2496 #ifdef WITH_CGNS
2497   case SMESHOp::OpPopupExportCGNS:
2498 #endif
2499   case SMESHOp::OpPopupExportSAUV:
2500   case SMESHOp::OpPopupExportGMF:
2501     {
2502       ::ExportMeshToFile(theCommandID);
2503       break;
2504     }
2505
2506   case SMESHOp::OpReset:                      // SCALAR BAR
2507     {
2508       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2509       SALOME_ListIO selected;
2510       if( aSel )
2511         aSel->selectedObjects( selected );
2512
2513       SALOME_ListIteratorOfListIO it(selected);
2514       for( ; it.More(); it.Next()) {
2515         Handle(SALOME_InteractiveObject) anIO = it.Value();
2516         if( anIO->hasEntry() ) {
2517           if( SMESH_Actor* anActor = SMESH::FindActorByEntry( anIO->getEntry() ) ) {
2518             anActor->SetControlMode( SMESH_Actor::eNone );
2519 #ifndef DISABLE_PLOT2DVIEWER
2520             SMESH::ProcessIn2DViewers(anActor,SMESH::RemoveFrom2dViewer);
2521 #endif
2522           }
2523         }
2524       }
2525       SMESH::UpdateView();
2526       break;
2527     }
2528   case SMESHOp::OpScalarBarProperties:
2529     {
2530       SMESHGUI_Preferences_ScalarBarDlg::ScalarBarProperties( this );
2531       break;
2532     }
2533   case SMESHOp::OpShowScalarBar:
2534     {
2535       // show/hide scalar bar
2536       ::ShowElement(theCommandID);
2537       break;
2538     }
2539   case SMESHOp::OpSaveDistribution:
2540     {
2541       // dump control distribution data to the text file
2542       ::SaveDistribution();
2543       break;
2544     }
2545
2546   case SMESHOp::OpShowDistribution:
2547     {
2548       // show/hide distribution
2549       ::ShowElement(theCommandID);
2550       break;
2551     }
2552
2553 #ifndef DISABLE_PLOT2DVIEWER
2554   case SMESHOp::OpPlotDistribution:
2555     {
2556       // plot distribution
2557       ::PlotDistribution();
2558       break;
2559     }
2560 #endif
2561
2562     // Auto-color
2563   case SMESHOp::OpAutoColor:
2564     ::AutoColor();
2565   break;
2566
2567   case SMESHOp::OpDisableAutoColor:
2568     ::DisableAutoColor();
2569   break;
2570
2571   case SMESHOp::OpClipping:
2572   case SMESHOp::OpTransparency:
2573   case SMESHOp::OpProperties: // Display preferences (colors, shrink size, line width, ...)
2574
2575     // Display Mode
2576   case SMESHOp::OpDMWireframe:
2577   case SMESHOp::OpDMShading:
2578   case SMESHOp::OpDMNodes:
2579   case SMESHOp::OpDMShrink:
2580     ::SetDisplayMode(theCommandID, myMarkerMap);
2581   break;
2582
2583   //2D quadratic representation
2584   case SMESHOp::OpRepresentationLines:
2585   case SMESHOp::OpRepresentationArcs:
2586     ::SetDisplayMode(theCommandID, myMarkerMap);
2587   break;
2588
2589   // Display Entity
2590   case SMESHOp::OpDE0DElements:
2591   case SMESHOp::OpDEEdges:
2592   case SMESHOp::OpDEFaces:
2593   case SMESHOp::OpDEVolumes:
2594   case SMESHOp::OpDEBalls:
2595   case SMESHOp::OpDEAllEntity:
2596     ::SetDisplayEntity(theCommandID);
2597   break;
2598
2599   // Choose entities to be displayed
2600   case SMESHOp::OpDEChoose:
2601     {
2602       ( new SMESHGUI_DisplayEntitiesDlg( SMESHGUI::desktop() ) )->exec();
2603       break;
2604     }
2605
2606   case SMESHOp::OpOrientationOnFaces:
2607     {
2608       SUIT_OverrideCursor wc;
2609       LightApp_SelectionMgr* mgr = selectionMgr();
2610       SALOME_ListIO selected; mgr->selectedObjects( selected );
2611
2612       SALOME_ListIteratorOfListIO it(selected);
2613       for( ; it.More(); it.Next()) {
2614         Handle(SALOME_InteractiveObject) anIObject = it.Value();
2615         if(anIObject->hasEntry()) {
2616           if(SMESH_Actor *anActor = SMESH::FindActorByEntry(anIObject->getEntry())){
2617             anActor->SetFacesOriented( !anActor->GetFacesOriented() );
2618           }
2619         }
2620       }
2621       break;
2622     }
2623
2624   case SMESHOp::OpUpdate:
2625     {
2626       if(checkLock(aStudy)) break;
2627       SUIT_OverrideCursor wc;
2628       try {
2629 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
2630         OCC_CATCH_SIGNALS;
2631 #endif
2632         SMESH::UpdateView();
2633       }
2634       catch (std::bad_alloc) { // PAL16774 (Crash after display of many groups)
2635         SMESH::OnVisuException();
2636       }
2637       catch (...) { // PAL16774 (Crash after display of many groups)
2638         SMESH::OnVisuException();
2639       }
2640
2641       SALOME_ListIO l;
2642       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2643       aSel->selectedObjects( l );
2644       aSel->setSelectedObjects( l );
2645       break;
2646     }
2647
2648   case SMESHOp::OpHide:
2649   case SMESHOp::OpShow:
2650   case SMESHOp::OpShowOnly:
2651     {
2652       SUIT_OverrideCursor wc;
2653       SMESH::EDisplaing anAction;
2654       switch (theCommandID) {
2655       case SMESHOp::OpHide:     anAction = SMESH::eErase; break;
2656       case SMESHOp::OpShow:     anAction = SMESH::eDisplay; break;
2657       case SMESHOp::OpShowOnly: anAction = SMESH::eDisplayOnly; break;
2658       }
2659
2660       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2661       SALOME_ListIO sel_objects, to_process;
2662       if (aSel)
2663         aSel->selectedObjects( sel_objects );
2664
2665       if ( theCommandID==SMESHOp::OpShowOnly )
2666       {
2667         //MESSAGE("anAction = SMESH::eDisplayOnly");
2668         startOperation( myEraseAll );
2669       }
2670
2671       extractContainers( sel_objects, to_process );
2672
2673       try {
2674 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
2675         OCC_CATCH_SIGNALS;
2676 #endif
2677         if (vtkwnd) {
2678           SALOME_ListIteratorOfListIO It( to_process );
2679           for ( ; It.More(); It.Next())
2680           {
2681             Handle(SALOME_InteractiveObject) IOS = It.Value();
2682             if ( IOS->hasEntry() )
2683             {
2684               if ( !SMESH::UpdateView( anAction, IOS->getEntry() )) {
2685                 SMESHGUI::GetSMESHGUI()->EmitSignalVisibilityChanged();
2686                 break; // PAL16774 (Crash after display of many groups)
2687               }
2688               if (anAction == SMESH::eDisplayOnly)
2689                 anAction = SMESH::eDisplay;
2690             }
2691           }
2692         }
2693
2694         // PAL13338 + PAL15161 -->
2695         if ( ( theCommandID==SMESHOp::OpShow || theCommandID==SMESHOp::OpShowOnly ) && !checkLock(aStudy)) {
2696           SMESH::UpdateView();
2697           SMESHGUI::GetSMESHGUI()->EmitSignalVisibilityChanged();
2698         }
2699         // PAL13338 + PAL15161 <--
2700       }
2701       catch (...) { // PAL16774 (Crash after display of many groups)
2702         SMESH::OnVisuException();
2703       }
2704
2705       if (anAction == SMESH::eErase) {
2706         SALOME_ListIO l1;
2707         aSel->setSelectedObjects( l1 );
2708       }
2709       else
2710         aSel->setSelectedObjects( to_process );
2711
2712       break;
2713     }
2714
2715   case SMESHOp::OpNode:
2716     {
2717       if(checkLock(aStudy)) break;
2718
2719       if ( vtkwnd ) {
2720         EmitSignalDeactivateDialog();
2721
2722         ( new SMESHGUI_NodesDlg( this ) )->show();
2723       }
2724       else {
2725         SUIT_MessageBox::warning(desktop(),tr("SMESH_WRN_WARNING"),tr("SMESH_WRN_VIEWER_VTK"));
2726       }
2727       break;
2728     }
2729
2730   case SMESHOp::OpCreateMesh:
2731   case SMESHOp::OpCreateSubMesh:
2732   case SMESHOp::OpEditMeshOrSubMesh:
2733   case SMESHOp::OpEditMesh:
2734   case SMESHOp::OpEditSubMesh:
2735   case SMESHOp::OpCompute:
2736   case SMESHOp::OpComputeSubMesh:
2737   case SMESHOp::OpPreCompute:
2738   case SMESHOp::OpEvaluate:
2739   case SMESHOp::OpMeshOrder:
2740     startOperation( theCommandID );
2741     break;
2742   case SMESHOp::OpCopyMesh:
2743     {
2744       if (checkLock(aStudy)) break;
2745       EmitSignalDeactivateDialog();
2746       ( new SMESHGUI_CopyMeshDlg( this ) )->show();
2747     }
2748     break;
2749   case SMESHOp::OpBuildCompoundMesh:
2750     {
2751       if (checkLock(aStudy)) break;
2752       EmitSignalDeactivateDialog();
2753       ( new SMESHGUI_BuildCompoundDlg( this ) )->show();
2754     }
2755     break;
2756
2757   case SMESHOp::OpDiagonalInversion:
2758   case SMESHOp::OpUnionOfTwoTriangle:
2759     {
2760       if ( !vtkwnd )
2761       {
2762         SUIT_MessageBox::warning( desktop(), tr( "SMESH_WRN_WARNING" ), tr( "NOT_A_VTK_VIEWER" ) );
2763         break;
2764       }
2765
2766       if ( checkLock( aStudy ) )
2767         break;
2768
2769       /*Standard_Boolean aRes;
2770       SMESH::SMESH_Mesh_var aMesh = SMESH::IObjectToInterface<SMESH::SMESH_Mesh>(IObject);
2771       if ( aMesh->_is_nil() )
2772       {
2773         SUIT_MessageBox::warning(GetDesktop(), tr( "SMESH_WRN_WARNING" ),
2774           tr( "SMESH_BAD_SELECTION" ) );
2775         break;
2776       }
2777       */
2778       EmitSignalDeactivateDialog();
2779       if ( theCommandID == SMESHOp::OpDiagonalInversion )
2780         ( new SMESHGUI_TrianglesInversionDlg( this ) )->show();
2781       else
2782         ( new SMESHGUI_UnionOfTwoTrianglesDlg( this ) )->show();
2783       break;
2784     }
2785   case SMESHOp::OpOrientation:
2786   case SMESHOp::OpUnionOfTriangles:
2787   case SMESHOp::OpCuttingOfQuadrangles:
2788   case SMESHOp::OpSplitVolumes:
2789     {
2790       if ( !vtkwnd )
2791       {
2792         SUIT_MessageBox::warning( desktop(), tr( "SMESH_WRN_WARNING" ), tr( "NOT_A_VTK_VIEWER" ) );
2793         break;
2794       }
2795
2796       if ( checkLock( aStudy ) )
2797         break;
2798
2799       EmitSignalDeactivateDialog();
2800       SMESHGUI_MultiEditDlg* aDlg = NULL;
2801       if ( theCommandID == SMESHOp::OpOrientation )
2802         aDlg = new SMESHGUI_ChangeOrientationDlg(this);
2803       else if ( theCommandID == SMESHOp::OpUnionOfTriangles )
2804         aDlg = new SMESHGUI_UnionOfTrianglesDlg(this);
2805       else if ( theCommandID == SMESHOp::OpSplitVolumes )
2806         aDlg = new SMESHGUI_SplitVolumesDlg(this);
2807       else
2808         aDlg = new SMESHGUI_CuttingOfQuadsDlg(this);
2809
2810       aDlg->show();
2811       break;
2812     }
2813   case SMESHOp::OpSmoothing:
2814     {
2815       if(checkLock(aStudy)) break;
2816       if( vtkwnd ) {
2817         EmitSignalDeactivateDialog();
2818         ( new SMESHGUI_SmoothingDlg( this ) )->show();
2819       }
2820       else {
2821         SUIT_MessageBox::warning(desktop(), tr("SMESH_WRN_WARNING"), tr("SMESH_WRN_VIEWER_VTK"));
2822       }
2823       break;
2824     }
2825   case SMESHOp::OpExtrusion:
2826     {
2827       if (checkLock(aStudy)) break;
2828       if (vtkwnd) {
2829         EmitSignalDeactivateDialog();
2830         ( new SMESHGUI_ExtrusionDlg ( this ) )->show();
2831       } else {
2832         SUIT_MessageBox::warning(desktop(),tr("SMESH_WRN_WARNING"), tr("SMESH_WRN_VIEWER_VTK"));
2833       }
2834       break;
2835     }
2836   case SMESHOp::OpExtrusionAlongAPath:
2837     {
2838       if (checkLock(aStudy)) break;
2839       if (vtkwnd) {
2840         EmitSignalDeactivateDialog();
2841         ( new SMESHGUI_ExtrusionAlongPathDlg( this ) )->show();
2842       } else {
2843         SUIT_MessageBox::warning(desktop(),tr("SMESH_WRN_WARNING"), tr("SMESH_WRN_VIEWER_VTK"));
2844       }
2845       break;
2846     }
2847   case SMESHOp::OpRevolution:
2848     {
2849       if(checkLock(aStudy)) break;
2850       if( vtkwnd ) {
2851         EmitSignalDeactivateDialog();
2852         ( new SMESHGUI_RevolutionDlg( this ) )->show();
2853       }
2854       else {
2855         SUIT_MessageBox::warning(desktop(),tr("SMESH_WRN_WARNING"), tr("SMESH_WRN_VIEWER_VTK"));
2856       }
2857       break;
2858     }
2859   case SMESHOp::OpPatternMapping:
2860     {
2861       if ( checkLock( aStudy ) )
2862         break;
2863       if ( vtkwnd )
2864       {
2865         EmitSignalDeactivateDialog();
2866         ( new SMESHGUI_MeshPatternDlg( this ) )->show();
2867       }
2868       else {
2869         SUIT_MessageBox::warning(desktop(),tr("SMESH_WRN_WARNING"), tr("SMESH_WRN_VIEWER_VTK"));
2870       }
2871       break;
2872     }
2873   case SMESHOp::OpSplitBiQuadratic:
2874   case SMESHOp::OpConvertMeshToQuadratic:
2875   case SMESHOp::OpCreateBoundaryElements: // create 2D mesh from 3D
2876   case SMESHOp::OpReorientFaces:
2877   case SMESHOp::OpCreateGeometryGroup:
2878     {
2879       startOperation( theCommandID );
2880       break;
2881     }
2882   case SMESHOp::OpCreateGroup:
2883     {
2884       if ( !vtkwnd )
2885       {
2886         SUIT_MessageBox::warning( desktop(), tr( "SMESH_WRN_WARNING" ),tr( "NOT_A_VTK_VIEWER" ) );
2887         break;
2888       }
2889
2890       if(checkLock(aStudy)) break;
2891       EmitSignalDeactivateDialog();
2892       SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_nil();
2893
2894       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2895       SALOME_ListIO selected;
2896       if( aSel )
2897         aSel->selectedObjects( selected );
2898
2899       int nbSel = selected.Extent();
2900       if (nbSel == 1) {
2901         // check if mesh is selected
2902         aMesh = SMESH::GetMeshByIO( selected.First() );
2903       }
2904       SMESHGUI_GroupDlg *aDlg = new SMESHGUI_GroupDlg( this, aMesh);
2905       aDlg->show();
2906       break;
2907     }
2908
2909   case SMESHOp::OpConstructGroup:
2910     {
2911       if ( !vtkwnd )
2912       {
2913         SUIT_MessageBox::warning( desktop(), tr( "SMESH_WRN_WARNING" ),tr( "NOT_A_VTK_VIEWER" ) );
2914         break;
2915       }
2916
2917       if(checkLock(aStudy)) break;
2918       EmitSignalDeactivateDialog();
2919
2920       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2921       SALOME_ListIO selected;
2922       if( aSel )
2923         aSel->selectedObjects( selected );
2924
2925       int nbSel = selected.Extent();
2926       if (nbSel == 1) {
2927         // check if submesh is selected
2928         Handle(SALOME_InteractiveObject) IObject = selected.First();
2929         if (IObject->hasEntry()) {
2930           _PTR(SObject) aSObj = aStudy->FindObjectID(IObject->getEntry());
2931           if( aSObj ) {
2932             SMESH::SMESH_subMesh_var aSubMesh = SMESH::SMESH_subMesh::_narrow( SMESH::SObjectToObject( aSObj ) );
2933             if (!aSubMesh->_is_nil()) {
2934               try {
2935                 SMESH::SMESH_Mesh_var aMesh = aSubMesh->GetFather();
2936                 // get submesh elements list by types
2937                 SMESH::long_array_var aNodes = aSubMesh->GetElementsByType(SMESH::NODE);
2938                 SMESH::long_array_var aEdges = aSubMesh->GetElementsByType(SMESH::EDGE);
2939                 SMESH::long_array_var aFaces = aSubMesh->GetElementsByType(SMESH::FACE);
2940                 SMESH::long_array_var aVolumes = aSubMesh->GetElementsByType(SMESH::VOLUME);
2941                 // create group for each type o elements
2942                 QString aName = IObject->getName();
2943                 QStringList anEntryList;
2944                 if (aNodes->length() > 0) {
2945                   SMESH::SMESH_Group_var aGroup = SMESH::AddGroup(aMesh, SMESH::NODE, aName + "_Nodes");
2946                   aGroup->Add(aNodes.inout());
2947                   if( _PTR(SObject) aSObject = SMESH::ObjectToSObject( aGroup ) )
2948                     anEntryList.append( aSObject->GetID().c_str() );
2949                 }
2950                 if (aEdges->length() > 0) {
2951                   SMESH::SMESH_Group_var aGroup = SMESH::AddGroup(aMesh, SMESH::EDGE, aName + "_Edges");
2952                   aGroup->Add(aEdges.inout());
2953                   if( _PTR(SObject) aSObject = SMESH::ObjectToSObject( aGroup ) )
2954                     anEntryList.append( aSObject->GetID().c_str() );
2955                 }
2956                 if (aFaces->length() > 0) {
2957                   SMESH::SMESH_Group_var aGroup = SMESH::AddGroup(aMesh, SMESH::FACE, aName + "_Faces");
2958                   aGroup->Add(aFaces.inout());
2959                   if( _PTR(SObject) aSObject = SMESH::ObjectToSObject( aGroup ) )
2960                     anEntryList.append( aSObject->GetID().c_str() );
2961                 }
2962                 if (aVolumes->length() > 0) {
2963                   SMESH::SMESH_Group_var aGroup = SMESH::AddGroup(aMesh, SMESH::VOLUME, aName + "_Volumes");
2964                   aGroup->Add(aVolumes.inout());
2965                   if( _PTR(SObject) aSObject = SMESH::ObjectToSObject( aGroup ) )
2966                     anEntryList.append( aSObject->GetID().c_str() );
2967                 }
2968                 updateObjBrowser();
2969                 anApp->browseObjects( anEntryList );
2970               }
2971               catch(const SALOME::SALOME_Exception & S_ex){
2972                 SalomeApp_Tools::QtCatchCorbaException(S_ex);
2973               }
2974             }
2975           }
2976         }
2977       }
2978       else if(nbSel==0) {
2979         SUIT_MessageBox::warning(desktop(),
2980                                  tr("SMESH_WRN_WARNING"),
2981                                  tr("SMESH_WRN_NO_AVAILABLE_DATA"));
2982       }
2983       break;
2984     }
2985
2986   case SMESHOp::OpEditGroup:
2987     {
2988       if ( !vtkwnd )
2989       {
2990         SUIT_MessageBox::warning( desktop(), tr( "SMESH_WRN_WARNING" ),tr( "NOT_A_VTK_VIEWER" ) );
2991         break;
2992       }
2993
2994       if(checkLock(aStudy)) break;
2995       EmitSignalDeactivateDialog();
2996
2997       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2998       SALOME_ListIO selected;
2999       if( aSel )
3000         aSel->selectedObjects( selected );
3001
3002       SALOME_ListIteratorOfListIO It (selected);
3003       int nbSelectedGroups = 0;
3004       for ( ; It.More(); It.Next() )
3005       {
3006         SMESH::SMESH_GroupBase_var aGroup =
3007           SMESH::IObjectToInterface<SMESH::SMESH_GroupBase>(It.Value());
3008         if (!aGroup->_is_nil()) {
3009           nbSelectedGroups++;
3010           SMESHGUI_GroupDlg *aDlg = new SMESHGUI_GroupDlg( this, aGroup);
3011           aDlg->show();
3012         }
3013       }
3014       if (nbSelectedGroups == 0)
3015         {
3016           SMESHGUI_GroupDlg *aDlg = new SMESHGUI_GroupDlg( this, SMESH::SMESH_GroupBase::_nil());
3017           aDlg->show();
3018         }
3019       break;
3020     }
3021
3022   case SMESHOp::OpAddElemGroupPopup:     // Add elements to group
3023     {
3024       if(checkLock(aStudy)) break;
3025       if (myState == 800) {
3026         SMESHGUI_GroupDlg *aDlg = (SMESHGUI_GroupDlg*) myActiveDialogBox;
3027         if (aDlg) aDlg->onAdd();
3028       }
3029       break;
3030     }
3031
3032   case SMESHOp::OpRemoveElemGroupPopup:  // Remove elements from group
3033     {
3034       if(checkLock(aStudy)) break;
3035       if (myState == 800) {
3036         SMESHGUI_GroupDlg *aDlg = (SMESHGUI_GroupDlg*) myActiveDialogBox;
3037         if (aDlg) aDlg->onRemove();
3038       }
3039       break;
3040     }
3041
3042   case SMESHOp::OpEditGeomGroupAsGroup:
3043     {
3044       if ( !vtkwnd )
3045       {
3046         SUIT_MessageBox::warning( desktop(), tr( "SMESH_WRN_WARNING" ),tr( "NOT_A_VTK_VIEWER" ) );
3047         break;
3048       }
3049
3050       if(checkLock(aStudy)) break;
3051       EmitSignalDeactivateDialog();
3052
3053       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
3054       SALOME_ListIO selected;
3055       if( aSel )
3056         aSel->selectedObjects( selected );
3057
3058       SALOME_ListIteratorOfListIO It (selected);
3059       for ( ; It.More(); It.Next() )
3060       {
3061         SMESH::SMESH_GroupOnGeom_var aGroup =
3062           SMESH::IObjectToInterface<SMESH::SMESH_GroupOnGeom>(It.Value());
3063         if (!aGroup->_is_nil()) {
3064           SMESHGUI_GroupDlg *aDlg = new SMESHGUI_GroupDlg( this, aGroup, true );
3065