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