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