Salome HOME
Merge branch 'V8_4_BR'
[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   
1860   for( SALOME_ListIteratorOfListIO anIt( selected ); anIt.More(); anIt.Next() )
1861   {
1862     Handle(SALOME_InteractiveObject) anIO = anIt.Value();
1863     if ( anIO.IsNull() ) continue;
1864     
1865     QString father = "unknown";
1866
1867     _PTR(SObject) aSO = aStudy->FindObjectID( anIO->getEntry() );
1868     if (aSO) {
1869       father = QString::fromStdString( aSO->GetFatherComponent()->ComponentDataType() );
1870       // check if object is reference
1871       _PTR(SObject) aRefSObj;
1872       aNameList.append("\n    - ");
1873       if ( aSO->ReferencedObject( aRefSObj ) ) {
1874         QString aRefName = QString::fromStdString ( aRefSObj->GetName() );
1875         aNameList.append( aRefName );
1876         father = QString::fromStdString ( aRefSObj->GetFatherComponent()->ComponentDataType() );
1877       }
1878       else
1879         aNameList.append(anIO->getName());
1880       objectCount++;
1881     }
1882
1883     if( aParentComponent.isNull() )
1884       aParentComponent = father;
1885     else if( !aParentComponent.isEmpty() && aParentComponent!=father )
1886       aParentComponent = "";
1887   }
1888
1889   if ( objectCount == 0 )
1890     return; // No Valid Objects Selected
1891
1892   if ( aParentComponent != SMESHGUI::GetSMESHGUI()->name() )  {
1893     SUIT_MessageBox::warning( SMESHGUI::desktop(),
1894                               QObject::tr("ERR_ERROR"),
1895                               QObject::tr("NON_SMESH_OBJECTS_SELECTED").arg( SMESHGUI::GetSMESHGUI()->moduleName() ) );
1896     return;
1897   }
1898   // VSR 17/11/04: check if all objects selected belong to SMESH component <-- finish
1899   if (SUIT_MessageBox::warning
1900       (SMESHGUI::desktop(),
1901        QObject::tr("SMESH_WRN_WARNING"),
1902        QObject::tr("SMESH_REALLY_DELETE").arg( objectCount ).arg( aNameList ),
1903        SUIT_MessageBox::Yes | SUIT_MessageBox::No,
1904        SUIT_MessageBox::Yes) != SUIT_MessageBox::Yes)
1905     return;
1906
1907   SalomeApp_Application* anApp = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
1908
1909   // Put the whole hierarchy of sub-objects of the selected SO's into a list and
1910   // then treat them all starting from the deepest objects (at list back)
1911   std::list< _PTR(SObject) > listSO;
1912   SALOME_ListIteratorOfListIO It(selected);
1913   for( ; It.More(); It.Next()) // loop on selected IO's
1914   {
1915     Handle(SALOME_InteractiveObject) IObject = It.Value();
1916     if(IObject->hasEntry()) {
1917       _PTR(SObject) aSO = aStudy->FindObjectID(IObject->getEntry());
1918
1919       // disable removal of "SMESH" component object
1920       if(aSO->FindAttribute(anAttr, "AttributeIOR")){
1921         anIOR = anAttr;
1922         if ( engineIOR() == anIOR->Value().c_str() )
1923           continue;
1924       }
1925       //Check the referenced object
1926       _PTR(SObject) aRefSObject;
1927       if ( aSO && aSO->ReferencedObject( aRefSObject ) )
1928         aSO = aRefSObject; // Delete main Object instead of reference
1929
1930       listSO.push_back( aSO );
1931       std::list< _PTR(SObject) >::iterator itSO = --listSO.end();
1932       for ( ; itSO != listSO.end(); ++itSO ) {
1933         _PTR(ChildIterator) it = aStudy->NewChildIterator( *itSO );
1934         for (it->InitEx(false); it->More(); it->Next())
1935           listSO.push_back( it->Value() );
1936       }
1937     }
1938   }
1939   // Check if none of objects to delete is referred from outside
1940   std::list< _PTR(SObject) >::reverse_iterator ritSO;
1941   for ( ritSO = listSO.rbegin(); ritSO != listSO.rend(); ++ritSO )
1942   {
1943     _PTR(SObject) SO = *ritSO;
1944     if ( !SO ) continue;
1945     std::vector<_PTR(SObject)> aReferences = aStudy->FindDependances( *ritSO  );
1946     for (size_t i = 0; i < aReferences.size(); i++) {
1947       _PTR(SComponent) aComponent = aReferences[i]->GetFatherComponent();
1948       std::string type = aComponent->ComponentDataType();
1949       if ( type != "SMESH" )
1950       {
1951         SUIT_MessageBox::warning( anApp->desktop(),
1952                                   QObject::tr("WRN_WARNING"),
1953                                   QObject::tr("DEP_OBJECT") );
1954         return; // outside SMESH, there is an object depending on a SMESH object
1955       }
1956     }
1957   }
1958
1959   // Call mesh->Clear() to prevent loading mesh from file caused by hypotheses removal
1960   for( It.Initialize( selected ); It.More(); It.Next()) // loop on selected IO's
1961   {
1962     Handle(SALOME_InteractiveObject) IObject = It.Value();
1963     SMESH::SMESH_Mesh_var mesh = SMESH::IObjectToInterface< SMESH::SMESH_Mesh >( IObject );
1964     if ( !mesh->_is_nil() )
1965       mesh->Clear();
1966   }
1967
1968   // Treat SO's in the list starting from the back
1969   aStudyBuilder->NewCommand();  // There is a transaction
1970   for ( ritSO = listSO.rbegin(); ritSO != listSO.rend(); ++ritSO )
1971   {
1972     _PTR(SObject) SO = *ritSO;
1973     if ( !SO ) continue;
1974     std::string anEntry = SO->GetID();
1975
1976     /** Erase graphical object and remove all its data **/
1977     if(SO->FindAttribute(anAttr, "AttributeIOR")) {
1978       SMESH::RemoveVisualObjectWithActors( anEntry.c_str(), true);
1979     }
1980     /** Remove an object from data structures **/
1981     SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( SMESH::SObjectToObject( SO ));
1982     SMESH::SMESH_subMesh_var   aSubMesh = SMESH::SMESH_subMesh::_narrow( SMESH::SObjectToObject( SO ));
1983     if ( !aGroup->_is_nil() ) {                          // DELETE GROUP
1984       SMESH::SMESH_Mesh_var aMesh = aGroup->GetMesh();
1985       aMesh->RemoveGroup( aGroup );
1986     }
1987     else if ( !aSubMesh->_is_nil() ) {                   // DELETE SUBMESH
1988       SMESH::SMESH_Mesh_var aMesh = aSubMesh->GetFather();
1989       aMesh->RemoveSubMesh( aSubMesh );
1990
1991       _PTR(SObject) aMeshSO = SMESH::FindSObject(aMesh);
1992       if (aMeshSO)
1993         SMESH::ModifiedMesh(aMeshSO, false, aMesh->NbNodes()==0);
1994     }
1995     else {
1996       Handle(SALOME_InteractiveObject) IObject = new SALOME_InteractiveObject
1997         ( anEntry.c_str(), engineIOR().toLatin1().data(), SO->GetName().c_str() );
1998       QString objType = CheckTypeObject(IObject);
1999       if ( objType == "Hypothesis" || objType == "Algorithm" ) {// DELETE HYPOTHESIS
2000         SMESH::RemoveHypothesisOrAlgorithmOnMesh(IObject);
2001         aStudyBuilder->RemoveObjectWithChildren( SO );
2002       }
2003       else {// default action: remove SObject from the study
2004         // san - it's no use opening a transaction here until UNDO/REDO is provided in SMESH
2005         //SUIT_Operation *op = new SALOMEGUI_ImportOperation(myActiveStudy);
2006         //op->start();
2007         aStudyBuilder->RemoveObjectWithChildren( SO );
2008         //op->finish();
2009       }
2010     }
2011   } /* listSO back loop */
2012
2013   aStudyBuilder->CommitCommand();
2014
2015   /* Clear any previous selection */
2016   SALOME_ListIO l1;
2017   aSel->setSelectedObjects( l1 );
2018
2019   SMESHGUI::GetSMESHGUI()->updateObjBrowser();
2020 }
2021
2022 extern "C" {
2023   SMESHGUI_EXPORT CAM_Module* createModule()
2024   {
2025     return new SMESHGUI();
2026   }
2027
2028   SMESHGUI_EXPORT  char* getModuleVersion() {
2029     return (char*)SMESH_VERSION_STR;
2030   }
2031 }
2032
2033 SMESH::SMESH_Gen_var SMESHGUI::myComponentSMESH = SMESH::SMESH_Gen::_nil();
2034
2035 //=============================================================================
2036 /*!
2037  *
2038  */
2039 //=============================================================================
2040 SMESHGUI::SMESHGUI() :
2041 SalomeApp_Module( "SMESH" )
2042 {
2043   if ( CORBA::is_nil( myComponentSMESH ) )
2044   {
2045     CORBA::Boolean anIsEmbeddedMode;
2046     myComponentSMESH = SMESH_Client::GetSMESHGen(getApp()->orb(),anIsEmbeddedMode);
2047     //MESSAGE("-------------------------------> anIsEmbeddedMode=" << anIsEmbeddedMode);
2048
2049     //  0019923: EDF 765 SMESH : default values of hypothesis
2050     SUIT_ResourceMgr* aResourceMgr = SMESH::GetResourceMgr(this);
2051     int nbSeg = aResourceMgr->integerValue( "SMESH", "segmentation", 10 );
2052     myComponentSMESH->SetBoundaryBoxSegmentation( nbSeg );
2053     nbSeg = aResourceMgr->integerValue( "SMESH", "nb_segments_per_edge", 15 );
2054     myComponentSMESH->SetDefaultNbSegments( nbSeg );
2055
2056     const char* options[] = { "historical_python_dump", "forget_mesh_on_hyp_modif", "default_grp_color" };
2057     for ( size_t i = 0; i < sizeof(options)/sizeof(char*); ++i )
2058       if ( aResourceMgr->hasValue( "SMESH", options[i] ))
2059       {
2060         QString val = aResourceMgr->stringValue( "SMESH", options[i] );
2061         myComponentSMESH->SetOption( options[i], val.toLatin1().constData() );
2062       }
2063   }
2064
2065   myActiveDialogBox = 0;
2066   myFilterLibraryDlg = 0;
2067   myState = -1;
2068   myDisplayer = 0;
2069
2070   myEventCallbackCommand = vtkCallbackCommand::New();
2071   myEventCallbackCommand->Delete();
2072   myEventCallbackCommand->SetClientData( this );
2073   myEventCallbackCommand->SetCallback( SMESHGUI::ProcessEvents );
2074   myPriority = 0.0;
2075
2076   /* load resources for all available meshers */
2077   SMESH::InitAvailableHypotheses();
2078 }
2079
2080 //=============================================================================
2081 /*!
2082  *
2083  */
2084 //=============================================================================
2085 SMESHGUI::~SMESHGUI()
2086 {
2087 }
2088
2089 //=============================================================================
2090 /*!
2091  *
2092  */
2093 //=============================================================================
2094 LightApp_SelectionMgr* SMESHGUI::selectionMgr()
2095 {
2096   SalomeApp_Application* anApp = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
2097   if( anApp )
2098     return dynamic_cast<LightApp_SelectionMgr*>( anApp->selectionMgr() );
2099   else
2100     return 0;
2101 }
2102
2103 //=============================================================================
2104 /*!
2105  *
2106  */
2107 //=============================================================================
2108 bool SMESHGUI::automaticUpdate(unsigned int requestedSize, bool* limitExceeded)
2109 {
2110   SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
2111   if ( !resMgr )
2112     return false;
2113
2114   bool autoUpdate  = resMgr->booleanValue( "SMESH", "auto_update",  false );
2115   long updateLimit = resMgr->integerValue( "SMESH", "update_limit", 500000 );
2116   bool exceeded = updateLimit > 0 && requestedSize > updateLimit;
2117   if ( limitExceeded ) *limitExceeded = autoUpdate && exceeded;
2118   return autoUpdate && !exceeded;
2119 }
2120
2121 //=============================================================================
2122 /*!
2123  *
2124  */
2125 //=============================================================================
2126 bool SMESHGUI::automaticUpdate( SMESH::SMESH_IDSource_ptr theMesh,
2127                                 int* entities, bool* limitExceeded, int* hidden, long* nbElements )
2128 {
2129   SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
2130   if ( !resMgr )
2131     return false;
2132
2133   bool autoUpdate  = resMgr->booleanValue( "SMESH", "auto_update", false );
2134   long updateLimit = resMgr->integerValue( "SMESH", "update_limit", 500000 );
2135   bool incrementalLimit = resMgr->booleanValue( "SMESH", "incremental_limit", false );
2136
2137   SMESH::long_array_var info = theMesh->GetMeshInfo();
2138   long nbOdElems = info[SMDSEntity_0D];
2139   long nbEdges   = info[SMDSEntity_Edge] + info[SMDSEntity_Quad_Edge];
2140   long nbFaces   = info[SMDSEntity_Triangle]   + info[SMDSEntity_Quad_Triangle]   + info[SMDSEntity_BiQuad_Triangle] + 
2141                    info[SMDSEntity_Quadrangle] + info[SMDSEntity_Quad_Quadrangle] + info[SMDSEntity_BiQuad_Quadrangle] + 
2142                    info[SMDSEntity_Polygon] + info[SMDSEntity_Quad_Polygon];
2143   long nbVolumes = info[SMDSEntity_Tetra]   + info[SMDSEntity_Quad_Tetra] + 
2144                    info[SMDSEntity_Hexa]    + info[SMDSEntity_Quad_Hexa] + info[SMDSEntity_TriQuad_Hexa] + 
2145                    info[SMDSEntity_Pyramid] + info[SMDSEntity_Quad_Pyramid] + 
2146                    info[SMDSEntity_Penta]   + info[SMDSEntity_Quad_Penta] + info[SMDSEntity_BiQuad_Penta] +
2147                    info[SMDSEntity_Polyhedra] + 
2148                    info[SMDSEntity_Hexagonal_Prism];
2149   long nbBalls   = info[SMDSEntity_Ball];
2150
2151   long requestedSize = nbOdElems + nbBalls + nbEdges + nbFaces + nbVolumes;
2152   *nbElements = requestedSize;
2153   
2154   *entities = SMESH_Actor::eAllEntity;
2155   *hidden   = 0;
2156
2157   bool exceeded = updateLimit > 0 && requestedSize > updateLimit;
2158
2159   if ( limitExceeded ) *limitExceeded = autoUpdate && exceeded;
2160
2161   if ( incrementalLimit ) {
2162     long total     = 0;
2163
2164     if ( nbOdElems > 0 ) {
2165       if ( total + nbOdElems > updateLimit ) {
2166         *entities = *entities & ~SMESH_Actor::e0DElements;
2167         *hidden = *hidden | SMESH_Actor::e0DElements;
2168       }
2169       else
2170         exceeded = false;
2171     }
2172     total += nbOdElems;
2173
2174     if ( nbEdges > 0 ) {
2175       if ( total + nbEdges > updateLimit ) {
2176         *entities = *entities & ~SMESH_Actor::eEdges;
2177         *hidden = *hidden | SMESH_Actor::eEdges;
2178       }
2179       else
2180         exceeded = false;
2181     }
2182     total += nbEdges;
2183
2184     if ( nbFaces > 0 ) {
2185       if ( total + nbFaces > updateLimit ) {
2186         *entities = *entities & ~SMESH_Actor::eFaces;
2187         *hidden = *hidden | SMESH_Actor::eFaces;
2188       }
2189       else
2190         exceeded = false;
2191     }
2192     total += nbFaces;
2193
2194     if ( nbVolumes > 0 ) {
2195       if ( total + nbVolumes > updateLimit ) {
2196         *entities = *entities & ~SMESH_Actor::eVolumes;
2197         *hidden = *hidden | SMESH_Actor::eVolumes;
2198       }
2199       else
2200         exceeded = false;
2201     }
2202     total += nbVolumes;
2203
2204     if ( nbBalls > 0 ) {
2205       if ( total + nbBalls > updateLimit ) {
2206         *entities = *entities & ~SMESH_Actor::eBallElem;
2207         *hidden = *hidden | SMESH_Actor::eBallElem;
2208       }
2209       else
2210         exceeded = false;
2211     }
2212     total += nbBalls;
2213   }
2214
2215   return autoUpdate && !exceeded;
2216 }
2217
2218 //=============================================================================
2219 /*!
2220  *
2221  */
2222 //=============================================================================
2223 SUIT_ResourceMgr* SMESHGUI::resourceMgr()
2224 {
2225   return dynamic_cast<SUIT_ResourceMgr*>( SUIT_Session::session()->resourceMgr() );
2226 }
2227
2228 //=============================================================================
2229 /*!
2230  *
2231  */
2232 //=============================================================================
2233 SMESHGUI* SMESHGUI::GetSMESHGUI()
2234 {
2235   SMESHGUI* smeshMod = 0;
2236   SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>(SUIT_Session::session()->activeApplication());
2237   if ( app )
2238   {
2239     CAM_Module* module = app->module( "Mesh" );
2240     smeshMod = dynamic_cast<SMESHGUI*>( module );
2241   }
2242
2243   if ( smeshMod && smeshMod->application() && smeshMod->application()->activeStudy() )
2244   {
2245     SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>( smeshMod->application()->activeStudy() );
2246     if ( study )
2247     {
2248       _PTR(Study) aStudy = study->studyDS();
2249       if ( aStudy )
2250         GetSMESHGen()->SetCurrentStudy( _CAST(Study,aStudy)->GetStudy() );
2251     }
2252   }
2253
2254   return smeshMod;
2255 }
2256
2257 extern "C"
2258 {
2259   Standard_EXPORT SMESHGUI* GetComponentGUI()
2260   {
2261     return SMESHGUI::GetSMESHGUI();
2262   }
2263 }
2264
2265 //=============================================================================
2266 /*!
2267  *
2268  */
2269 //=============================================================================
2270 void SMESHGUI::SetState(int aState)
2271 {
2272   myState = aState;
2273 }
2274
2275 //=============================================================================
2276 /*!
2277  *
2278  */
2279 //=============================================================================
2280 void SMESHGUI::ResetState()
2281 {
2282   myState = -1;
2283 }
2284
2285 //=============================================================================
2286 /*!
2287  *
2288  */
2289 //=============================================================================
2290 void SMESHGUI::EmitSignalDeactivateDialog()
2291 {
2292   emit SignalDeactivateActiveDialog();
2293 }
2294
2295 //=============================================================================
2296 /*!
2297  *
2298  */
2299 //=============================================================================
2300 void SMESHGUI::EmitSignalStudyFrameChanged()
2301 {
2302   emit SignalStudyFrameChanged();
2303 }
2304
2305 //=============================================================================
2306 /*!
2307  *
2308  */
2309 //=============================================================================
2310 void SMESHGUI::EmitSignalCloseAllDialogs()
2311 {
2312   emit SignalCloseAllDialogs();
2313 }
2314
2315 //=============================================================================
2316 /*!
2317  *
2318  */
2319 //=============================================================================
2320 void SMESHGUI::EmitSignalVisibilityChanged()
2321 {
2322   emit SignalVisibilityChanged();
2323 }
2324
2325 //=============================================================================
2326 /*!
2327  *
2328  */
2329 //=============================================================================
2330 void SMESHGUI::EmitSignalCloseView()
2331 {
2332   emit SignalCloseView();
2333 }
2334
2335 //=============================================================================
2336 /*!
2337  *
2338  */
2339 //=============================================================================
2340 void SMESHGUI::EmitSignalActivatedViewManager()
2341 {
2342   emit SignalActivatedViewManager();
2343 }
2344
2345 //=============================================================================
2346 /*!
2347  *
2348  */
2349 //=============================================================================
2350 QDialog *SMESHGUI::GetActiveDialogBox()
2351 {
2352   return myActiveDialogBox;
2353 }
2354
2355 //=============================================================================
2356 /*!
2357  *
2358  */
2359 //=============================================================================
2360 void SMESHGUI::SetActiveDialogBox(QDialog * aDlg)
2361 {
2362   myActiveDialogBox = (QDialog *) aDlg;
2363   return;
2364 }
2365
2366 //=============================================================================
2367 /*!
2368  *
2369  */
2370 //=============================================================================
2371 SUIT_Desktop* SMESHGUI::desktop()
2372 {
2373   SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
2374   if( app )
2375     return app->desktop();
2376   else
2377     return 0;
2378 }
2379
2380 //=============================================================================
2381 /*!
2382  *
2383  */
2384 //=============================================================================
2385 SalomeApp_Study* SMESHGUI::activeStudy()
2386 {
2387   SUIT_Application* app = SUIT_Session::session()->activeApplication();
2388   if( app )
2389     return dynamic_cast<SalomeApp_Study*>( app->activeStudy() );
2390   else
2391     return NULL;
2392 }
2393
2394 //=============================================================================
2395 /*!
2396  *
2397  */
2398 //=============================================================================
2399 void SMESHGUI::Modified( bool theIsUpdateActions )
2400 {
2401   if( SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() ) ) {
2402     if( SalomeApp_Study* appStudy = dynamic_cast<SalomeApp_Study*>( app->activeStudy() ) ) {
2403       appStudy->Modified();
2404       if( theIsUpdateActions )
2405         app->updateActions();
2406     }
2407   }
2408 }
2409
2410 //=============================================================================
2411 /*!
2412  *
2413  */
2414 //=============================================================================
2415 bool SMESHGUI::DefineDlgPosition(QWidget * aDlg, int &x, int &y)
2416 {
2417   /* Here the position is on the bottom right corner - 10 */
2418   // aDlg->resize(QSize().expandedTo(aDlg->minimumSizeHint()));
2419   aDlg->adjustSize();
2420   SUIT_Desktop *PP = desktop();
2421   x = abs(PP->x() + PP->size().width() - aDlg->size().width() - 10);
2422   y = abs(PP->y() + PP->size().height() - aDlg->size().height() - 10);
2423   return true;
2424 }
2425
2426 //=============================================================================
2427 /*!
2428  *
2429  */
2430 //=============================================================================
2431 static int isStudyLocked(_PTR(Study) theStudy){
2432   return theStudy->GetProperties()->IsLocked();
2433 }
2434
2435 static bool checkLock(_PTR(Study) theStudy) {
2436   if (isStudyLocked(theStudy)) {
2437     SUIT_MessageBox::warning( SMESHGUI::desktop(),
2438                               QObject::tr("WRN_WARNING"),
2439                               QObject::tr("WRN_STUDY_LOCKED") );
2440     return true;
2441   }
2442   return false;
2443 }
2444
2445 //=======================================================================
2446 //function : CheckActiveStudyLocked
2447 //purpose  :
2448 //=======================================================================
2449
2450 bool SMESHGUI::isActiveStudyLocked()
2451 {
2452   _PTR(Study) aStudy = activeStudy()->studyDS();
2453   return checkLock( aStudy );
2454 }
2455
2456 //=============================================================================
2457 /*!
2458  *
2459  */
2460 //=============================================================================
2461 bool SMESHGUI::OnGUIEvent( int theCommandID )
2462 {
2463   SalomeApp_Application* anApp = dynamic_cast<SalomeApp_Application*>( application() );
2464   if( !anApp )
2465     return false;
2466
2467   _PTR(Study) aStudy = SMESH::GetActiveStudyDocument(); //Document OCAF de l'etude active
2468   SUIT_ResourceMgr* mgr = resourceMgr();
2469   if( !mgr )
2470     return false;
2471
2472   if (CORBA::is_nil(GetSMESHGen()->GetCurrentStudy())) {
2473     GetSMESHGen()->SetCurrentStudy(_CAST(Study,aStudy)->GetStudy());
2474   }
2475
2476   SUIT_ViewWindow* view = application()->desktop()->activeWindow();
2477   SVTK_ViewWindow* vtkwnd = dynamic_cast<SVTK_ViewWindow*>( view );
2478
2479   //QAction* act = action( theCommandID );
2480
2481   switch (theCommandID) {
2482   case SMESHOp::OpDelete:
2483     if(checkLock(aStudy)) break;
2484     OnEditDelete();
2485     break;
2486   case SMESHOp::OpImportDAT:
2487   case SMESHOp::OpImportUNV:
2488   case SMESHOp::OpImportMED:
2489   case SMESHOp::OpImportSTL:
2490   case SMESHOp::OpImportCGNS:
2491   case SMESHOp::OpImportSAUV:
2492   case SMESHOp::OpImportGMF:
2493   case SMESHOp::OpPopupImportDAT:
2494   case SMESHOp::OpPopupImportUNV:
2495   case SMESHOp::OpPopupImportMED:
2496   case SMESHOp::OpPopupImportSTL:
2497   case SMESHOp::OpPopupImportCGNS:
2498   case SMESHOp::OpPopupImportSAUV:
2499   case SMESHOp::OpPopupImportGMF:
2500     {
2501       if(checkLock(aStudy)) break;
2502       ::ImportMeshesFromFile(GetSMESHGen(),theCommandID);
2503       break;
2504     }
2505
2506   case SMESHOp::OpFileInformation:
2507     {
2508       SALOME_ListIO selected;
2509       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2510       if( aSel )
2511         aSel->selectedObjects( selected );
2512       if( selected.Extent() )
2513       {
2514         Handle(SALOME_InteractiveObject) anIObject = selected.First();
2515         SMESH::SMESH_Mesh_var aMesh = SMESH::IObjectToInterface<SMESH::SMESH_Mesh>(anIObject);
2516         if ( !aMesh->_is_nil() )
2517         {
2518           SMESHGUI_FileInfoDlg dlg( desktop(), aMesh->GetMEDFileInfo() );
2519           dlg.exec();
2520         }
2521       }
2522       break;
2523     }
2524   case SMESHOp::OpExportDAT:
2525   case SMESHOp::OpExportMED:
2526   case SMESHOp::OpExportUNV:
2527   case SMESHOp::OpExportSTL:
2528   case SMESHOp::OpExportCGNS:
2529   case SMESHOp::OpExportSAUV:
2530   case SMESHOp::OpExportGMF:
2531   case SMESHOp::OpPopupExportDAT:
2532   case SMESHOp::OpPopupExportMED:
2533   case SMESHOp::OpPopupExportUNV:
2534   case SMESHOp::OpPopupExportSTL:
2535   case SMESHOp::OpPopupExportCGNS:
2536   case SMESHOp::OpPopupExportSAUV:
2537   case SMESHOp::OpPopupExportGMF:
2538     {
2539       ::ExportMeshToFile(theCommandID);
2540       break;
2541     }
2542
2543   case SMESHOp::OpReset:                      // SCALAR BAR
2544     {
2545       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2546       SALOME_ListIO selected;
2547       if( aSel )
2548         aSel->selectedObjects( selected );
2549
2550       SALOME_ListIteratorOfListIO it(selected);
2551       for( ; it.More(); it.Next()) {
2552         Handle(SALOME_InteractiveObject) anIO = it.Value();
2553         if( anIO->hasEntry() ) {
2554           if( SMESH_Actor* anActor = SMESH::FindActorByEntry( anIO->getEntry() ) ) {
2555             anActor->SetControlMode( SMESH_Actor::eNone );
2556 #ifndef DISABLE_PLOT2DVIEWER
2557             SMESH::ProcessIn2DViewers(anActor,SMESH::RemoveFrom2dViewer);
2558 #endif
2559           }
2560         }
2561       }
2562       SMESH::UpdateView();
2563       break;
2564     }
2565   case SMESHOp::OpScalarBarProperties:
2566     {
2567       SMESHGUI_Preferences_ScalarBarDlg::ScalarBarProperties( this );
2568       break;
2569     }
2570   case SMESHOp::OpShowScalarBar:
2571     {
2572       // show/hide scalar bar
2573       ::ShowElement(theCommandID);
2574       break;
2575     }
2576   case SMESHOp::OpSaveDistribution:
2577     {
2578       // dump control distribution data to the text file
2579       ::SaveDistribution();
2580       break;
2581     }
2582
2583   case SMESHOp::OpShowDistribution:
2584     {
2585       // show/hide distribution
2586       ::ShowElement(theCommandID);
2587       break;
2588     }
2589
2590 #ifndef DISABLE_PLOT2DVIEWER
2591   case SMESHOp::OpPlotDistribution:
2592     {
2593       // plot distribution
2594       ::PlotDistribution();
2595       break;
2596     }
2597 #endif
2598
2599     // Auto-color
2600   case SMESHOp::OpAutoColor:
2601     ::AutoColor();
2602   break;
2603
2604   case SMESHOp::OpDisableAutoColor:
2605     ::DisableAutoColor();
2606   break;
2607
2608   case SMESHOp::OpClipping:
2609   case SMESHOp::OpTransparency:
2610   case SMESHOp::OpProperties: // Display preferences (colors, shrink size, line width, ...)
2611
2612     // Display Mode
2613   case SMESHOp::OpDMWireframe:
2614   case SMESHOp::OpDMShading:
2615   case SMESHOp::OpDMNodes:
2616   case SMESHOp::OpDMShrink:
2617     ::SetDisplayMode(theCommandID, myMarkerMap);
2618   break;
2619
2620   //2D quadratic representation
2621   case SMESHOp::OpRepresentationLines:
2622   case SMESHOp::OpRepresentationArcs:
2623     ::SetDisplayMode(theCommandID, myMarkerMap);
2624   break;
2625
2626   // Display Entity
2627   case SMESHOp::OpDE0DElements:
2628   case SMESHOp::OpDEEdges:
2629   case SMESHOp::OpDEFaces:
2630   case SMESHOp::OpDEVolumes:
2631   case SMESHOp::OpDEBalls:
2632   case SMESHOp::OpDEAllEntity:
2633     ::SetDisplayEntity(theCommandID);
2634   break;
2635
2636   // Choose entities to be displayed
2637   case SMESHOp::OpDEChoose:
2638     {
2639       ( new SMESHGUI_DisplayEntitiesDlg( SMESHGUI::desktop() ) )->exec();
2640       break;
2641     }
2642
2643   case SMESHOp::OpOrientationOnFaces:
2644     {
2645       SUIT_OverrideCursor wc;
2646       LightApp_SelectionMgr* mgr = selectionMgr();
2647       SALOME_ListIO selected; mgr->selectedObjects( selected );
2648
2649       SALOME_ListIteratorOfListIO it(selected);
2650       for( ; it.More(); it.Next()) {
2651         Handle(SALOME_InteractiveObject) anIObject = it.Value();
2652         if(anIObject->hasEntry()) {
2653           if(SMESH_Actor *anActor = SMESH::FindActorByEntry(anIObject->getEntry())){
2654             anActor->SetFacesOriented( !anActor->GetFacesOriented() );
2655           }
2656         }
2657       }
2658       break;
2659     }
2660
2661   case SMESHOp::OpUpdate:
2662     {
2663       if(checkLock(aStudy)) break;
2664       SUIT_OverrideCursor wc;
2665       try {
2666         OCC_CATCH_SIGNALS;
2667         SMESH::UpdateView();
2668       }
2669       catch (std::bad_alloc) { // PAL16774 (Crash after display of many groups)
2670         SMESH::OnVisuException();
2671       }
2672       catch (...) { // PAL16774 (Crash after display of many groups)
2673         SMESH::OnVisuException();
2674       }
2675
2676       SALOME_ListIO l;
2677       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2678       aSel->selectedObjects( l );
2679       aSel->setSelectedObjects( l );
2680       break;
2681     }
2682
2683   case SMESHOp::OpHide:
2684   case SMESHOp::OpShow:
2685   case SMESHOp::OpShowOnly:
2686     {
2687       SUIT_OverrideCursor wc;
2688       SMESH::EDisplaing anAction;
2689       switch (theCommandID) {
2690       case SMESHOp::OpHide:     anAction = SMESH::eErase; break;
2691       case SMESHOp::OpShow:     anAction = SMESH::eDisplay; break;
2692       case SMESHOp::OpShowOnly: anAction = SMESH::eDisplayOnly; break;
2693       }
2694
2695       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2696       SALOME_ListIO sel_objects, to_process;
2697       if (aSel)
2698         aSel->selectedObjects( sel_objects );
2699
2700       if ( theCommandID==SMESHOp::OpShowOnly )
2701       {
2702         //MESSAGE("anAction = SMESH::eDisplayOnly");
2703         startOperation( myEraseAll );
2704       }
2705
2706       extractContainers( sel_objects, to_process );
2707
2708       try {
2709         OCC_CATCH_SIGNALS;
2710         if (vtkwnd) {
2711           SALOME_ListIteratorOfListIO It( to_process );
2712           for ( ; It.More(); It.Next())
2713           {
2714             Handle(SALOME_InteractiveObject) IOS = It.Value();
2715             if ( IOS->hasEntry() )
2716             {
2717               if ( !SMESH::UpdateView( anAction, IOS->getEntry() )) {
2718                 SMESHGUI::GetSMESHGUI()->EmitSignalVisibilityChanged();
2719                 break; // PAL16774 (Crash after display of many groups)
2720               }
2721               if (anAction == SMESH::eDisplayOnly)
2722                 anAction = SMESH::eDisplay;
2723             }
2724           }
2725         }
2726
2727         // PAL13338 + PAL15161 -->
2728         if ( ( theCommandID==SMESHOp::OpShow || theCommandID==SMESHOp::OpShowOnly ) && !checkLock(aStudy)) {
2729           SMESH::UpdateView();
2730           SMESHGUI::GetSMESHGUI()->EmitSignalVisibilityChanged();
2731         }
2732         // PAL13338 + PAL15161 <--
2733       }
2734       catch (...) { // PAL16774 (Crash after display of many groups)
2735         SMESH::OnVisuException();
2736       }
2737
2738       if (anAction == SMESH::eErase) {
2739         SALOME_ListIO l1;
2740         aSel->setSelectedObjects( l1 );
2741       }
2742       else
2743         aSel->setSelectedObjects( to_process );
2744
2745       break;
2746     }
2747
2748   case SMESHOp::OpNode:
2749     {
2750       if(checkLock(aStudy)) break;
2751
2752       if ( vtkwnd ) {
2753         EmitSignalDeactivateDialog();
2754
2755         ( new SMESHGUI_NodesDlg( this ) )->show();
2756       }
2757       else {
2758         SUIT_MessageBox::warning(desktop(),tr("SMESH_WRN_WARNING"),tr("SMESH_WRN_VIEWER_VTK"));
2759       }
2760       break;
2761     }
2762
2763   case SMESHOp::OpCreateMesh:
2764   case SMESHOp::OpCreateSubMesh:
2765   case SMESHOp::OpEditMeshOrSubMesh:
2766   case SMESHOp::OpEditMesh:
2767   case SMESHOp::OpEditSubMesh:
2768   case SMESHOp::OpCompute:
2769   case SMESHOp::OpComputeSubMesh:
2770   case SMESHOp::OpPreCompute:
2771   case SMESHOp::OpEvaluate:
2772   case SMESHOp::OpMeshOrder:
2773     startOperation( theCommandID );
2774     break;
2775   case SMESHOp::OpCopyMesh:
2776     {
2777       if (checkLock(aStudy)) break;
2778       EmitSignalDeactivateDialog();
2779       ( new SMESHGUI_CopyMeshDlg( this ) )->show();
2780     }
2781     break;
2782   case SMESHOp::OpBuildCompoundMesh:
2783     {
2784       if (checkLock(aStudy)) break;
2785       EmitSignalDeactivateDialog();
2786       ( new SMESHGUI_BuildCompoundDlg( this ) )->show();
2787     }
2788     break;
2789
2790   case SMESHOp::OpDiagonalInversion:
2791   case SMESHOp::OpUnionOfTwoTriangle:
2792     {
2793       if ( !vtkwnd )
2794       {
2795         SUIT_MessageBox::warning( desktop(), tr( "SMESH_WRN_WARNING" ), tr( "NOT_A_VTK_VIEWER" ) );
2796         break;
2797       }
2798
2799       if ( checkLock( aStudy ) )
2800         break;
2801
2802       /*Standard_Boolean aRes;
2803       SMESH::SMESH_Mesh_var aMesh = SMESH::IObjectToInterface<SMESH::SMESH_Mesh>(IObject);
2804       if ( aMesh->_is_nil() )
2805       {
2806         SUIT_MessageBox::warning(GetDesktop(), tr( "SMESH_WRN_WARNING" ),
2807           tr( "SMESH_BAD_SELECTION" ) );
2808         break;
2809       }
2810       */
2811       EmitSignalDeactivateDialog();
2812       if ( theCommandID == SMESHOp::OpDiagonalInversion )
2813         ( new SMESHGUI_TrianglesInversionDlg( this ) )->show();
2814       else
2815         ( new SMESHGUI_UnionOfTwoTrianglesDlg( this ) )->show();
2816       break;
2817     }
2818   case SMESHOp::OpOrientation:
2819   case SMESHOp::OpUnionOfTriangles:
2820   case SMESHOp::OpCuttingOfQuadrangles:
2821   case SMESHOp::OpSplitVolumes:
2822     {
2823       if ( !vtkwnd )
2824       {
2825         SUIT_MessageBox::warning( desktop(), tr( "SMESH_WRN_WARNING" ), tr( "NOT_A_VTK_VIEWER" ) );
2826         break;
2827       }
2828
2829       if ( checkLock( aStudy ) )
2830         break;
2831
2832       EmitSignalDeactivateDialog();
2833       SMESHGUI_MultiEditDlg* aDlg = NULL;
2834       if ( theCommandID == SMESHOp::OpOrientation )
2835         aDlg = new SMESHGUI_ChangeOrientationDlg(this);
2836       else if ( theCommandID == SMESHOp::OpUnionOfTriangles )
2837         aDlg = new SMESHGUI_UnionOfTrianglesDlg(this);
2838       else if ( theCommandID == SMESHOp::OpSplitVolumes )
2839         aDlg = new SMESHGUI_SplitVolumesDlg(this);
2840       else
2841         aDlg = new SMESHGUI_CuttingOfQuadsDlg(this);
2842
2843       aDlg->show();
2844       break;
2845     }
2846   case SMESHOp::OpSmoothing:
2847     {
2848       if(checkLock(aStudy)) break;
2849       if( vtkwnd ) {
2850         EmitSignalDeactivateDialog();
2851         ( new SMESHGUI_SmoothingDlg( this ) )->show();
2852       }
2853       else {
2854         SUIT_MessageBox::warning(desktop(), tr("SMESH_WRN_WARNING"), tr("SMESH_WRN_VIEWER_VTK"));
2855       }
2856       break;
2857     }
2858   case SMESHOp::OpExtrusion:
2859     {
2860       if (checkLock(aStudy)) break;
2861       if (vtkwnd) {
2862         EmitSignalDeactivateDialog();
2863         ( new SMESHGUI_ExtrusionDlg ( this ) )->show();
2864       } else {
2865         SUIT_MessageBox::warning(desktop(),tr("SMESH_WRN_WARNING"), tr("SMESH_WRN_VIEWER_VTK"));
2866       }
2867       break;
2868     }
2869   case SMESHOp::OpExtrusionAlongAPath:
2870     {
2871       if (checkLock(aStudy)) break;
2872       if (vtkwnd) {
2873         EmitSignalDeactivateDialog();
2874         ( new SMESHGUI_ExtrusionAlongPathDlg( this ) )->show();
2875       } else {
2876         SUIT_MessageBox::warning(desktop(),tr("SMESH_WRN_WARNING"), tr("SMESH_WRN_VIEWER_VTK"));
2877       }
2878       break;
2879     }
2880   case SMESHOp::OpRevolution:
2881     {
2882       if(checkLock(aStudy)) break;
2883       if( vtkwnd ) {
2884         EmitSignalDeactivateDialog();
2885         ( new SMESHGUI_RevolutionDlg( this ) )->show();
2886       }
2887       else {
2888         SUIT_MessageBox::warning(desktop(),tr("SMESH_WRN_WARNING"), tr("SMESH_WRN_VIEWER_VTK"));
2889       }
2890       break;
2891     }
2892   case SMESHOp::OpPatternMapping:
2893     {
2894       if ( checkLock( aStudy ) )
2895         break;
2896       if ( vtkwnd )
2897       {
2898         EmitSignalDeactivateDialog();
2899         ( new SMESHGUI_MeshPatternDlg( this ) )->show();
2900       }
2901       else {
2902         SUIT_MessageBox::warning(desktop(),tr("SMESH_WRN_WARNING"), tr("SMESH_WRN_VIEWER_VTK"));
2903       }
2904       break;
2905     }
2906   case SMESHOp::OpSplitBiQuadratic:
2907   case SMESHOp::OpConvertMeshToQuadratic:
2908   case SMESHOp::OpCreateBoundaryElements: // create 2D mesh from 3D
2909   case SMESHOp::OpReorientFaces:
2910   case SMESHOp::OpCreateGeometryGroup:
2911     {
2912       startOperation( theCommandID );
2913       break;
2914     }
2915   case SMESHOp::OpCreateGroup:
2916     {
2917       if ( !vtkwnd )
2918       {
2919         SUIT_MessageBox::warning( desktop(), tr( "SMESH_WRN_WARNING" ),tr( "NOT_A_VTK_VIEWER" ) );
2920         break;
2921       }
2922
2923       if(checkLock(aStudy)) break;
2924       EmitSignalDeactivateDialog();
2925       SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_nil();
2926
2927       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2928       SALOME_ListIO selected;
2929       if( aSel )
2930         aSel->selectedObjects( selected );
2931
2932       int nbSel = selected.Extent();
2933       if (nbSel == 1) {
2934         // check if mesh is selected
2935         aMesh = SMESH::GetMeshByIO( selected.First() );
2936       }
2937       SMESHGUI_GroupDlg *aDlg = new SMESHGUI_GroupDlg( this, aMesh);
2938       aDlg->show();
2939       break;
2940     }
2941
2942   case SMESHOp::OpConstructGroup:
2943     {
2944       if ( !vtkwnd )
2945       {
2946         SUIT_MessageBox::warning( desktop(), tr( "SMESH_WRN_WARNING" ),tr( "NOT_A_VTK_VIEWER" ) );
2947         break;
2948       }
2949
2950       if(checkLock(aStudy)) break;
2951       EmitSignalDeactivateDialog();
2952
2953       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
2954       SALOME_ListIO selected;
2955       if( aSel )
2956         aSel->selectedObjects( selected );
2957
2958       int nbSel = selected.Extent();
2959       if (nbSel == 1) {
2960         // check if submesh is selected
2961         Handle(SALOME_InteractiveObject) IObject = selected.First();
2962         if (IObject->hasEntry()) {
2963           _PTR(SObject) aSObj = aStudy->FindObjectID(IObject->getEntry());
2964           if( aSObj ) {
2965             SMESH::SMESH_subMesh_var aSubMesh = SMESH::SMESH_subMesh::_narrow( SMESH::SObjectToObject( aSObj ) );
2966             if (!aSubMesh->_is_nil()) {
2967               try {
2968                 SMESH::SMESH_Mesh_var aMesh = aSubMesh->GetFather();
2969                 // get submesh elements list by types
2970                 SMESH::long_array_var aNodes = aSubMesh->GetElementsByType(SMESH::NODE);
2971                 SMESH::long_array_var aEdges = aSubMesh->GetElementsByType(SMESH::EDGE);
2972                 SMESH::long_array_var aFaces = aSubMesh->GetElementsByType(SMESH::FACE);
2973                 SMESH::long_array_var aVolumes = aSubMesh->GetElementsByType(SMESH::VOLUME);
2974                 // create group for each type o elements
2975                 QString aName = IObject->getName();
2976                 QStringList anEntryList;
2977                 if (aNodes->length() > 0) {
2978                   SMESH::SMESH_Group_var aGroup = SMESH::AddGroup(aMesh, SMESH::NODE, aName + "_Nodes");
2979                   aGroup->Add(aNodes.inout());
2980                   if( _PTR(SObject) aSObject = SMESH::ObjectToSObject( aGroup ) )
2981                     anEntryList.append( aSObject->GetID().c_str() );
2982                 }
2983                 if (aEdges->length() > 0) {
2984                   SMESH::SMESH_Group_var aGroup = SMESH::AddGroup(aMesh, SMESH::EDGE, aName + "_Edges");
2985                   aGroup->Add(aEdges.inout());
2986                   if( _PTR(SObject) aSObject = SMESH::ObjectToSObject( aGroup ) )
2987                     anEntryList.append( aSObject->GetID().c_str() );
2988                 }
2989                 if (aFaces->length() > 0) {
2990                   SMESH::SMESH_Group_var aGroup = SMESH::AddGroup(aMesh, SMESH::FACE, aName + "_Faces");
2991                   aGroup->Add(aFaces.inout());
2992                   if( _PTR(SObject) aSObject = SMESH::ObjectToSObject( aGroup ) )
2993                     anEntryList.append( aSObject->GetID().c_str() );
2994                 }
2995                 if (aVolumes->length() > 0) {
2996                   SMESH::SMESH_Group_var aGroup = SMESH::AddGroup(aMesh, SMESH::VOLUME, aName + "_Volumes");
2997                   aGroup->Add(aVolumes.inout());
2998                   if( _PTR(SObject) aSObject = SMESH::ObjectToSObject( aGroup ) )
2999                     anEntryList.append( aSObject->GetID().c_str() );
3000                 }
3001                 updateObjBrowser();
3002                 anApp->browseObjects( anEntryList );
3003               }
3004               catch(const SALOME::SALOME_Exception & S_ex){
3005                 SalomeApp_Tools::QtCatchCorbaException(S_ex);
3006               }
3007             }
3008           }
3009         }
3010       }
3011       else if(nbSel==0) {
3012         SUIT_MessageBox::warning(desktop(),
3013                                  tr("SMESH_WRN_WARNING"),
3014                                  tr("SMESH_WRN_NO_AVAILABLE_DATA"));
3015       }
3016       break;
3017     }
3018
3019   case SMESHOp::OpEditGroup:
3020     {
3021       if ( !vtkwnd )
3022       {
3023         SUIT_MessageBox::warning( desktop(), tr( "SMESH_WRN_WARNING" ),tr( "NOT_A_VTK_VIEWER" ) );
3024         break;
3025       }
3026
3027       if(checkLock(aStudy)) break;
3028       EmitSignalDeactivateDialog();
3029
3030       LightApp_SelectionMgr *aSel = SMESHGUI::selectionMgr();
3031       SALOME_ListIO selected;
3032       if( aSel )
3033         aSel->selectedObjects( selected );
3034
3035       SALOME_ListIteratorOfListIO It (selected);
3036       int nbSelectedGroups = 0;
3037       for ( ; It.More(); It.Next() )
3038       {
3039         SMESH::SMESH_GroupBase_var aGroup =
3040           SMESH::IObjectToInterface<SMESH::SMESH_GroupBase>(It.Value());
3041         if (!aGroup->_is_nil()) {
3042           nbSelectedGroups++;
3043           SMESHGUI_GroupDlg *aDlg = new SMESHGUI_GroupDlg( this, aGroup);
3044           aDlg->show();
3045         }
3046       }
3047       if (nbSelectedGroups == 0)
3048         {
3049           SMESHGUI_GroupDlg *aDlg = new SMESHGUI_GroupDlg( this, SMESH::SMESH_GroupBase::_nil());
3050           aDlg->show();
3051         }
3052       break;
3053     }
3054
3055   case SMESHOp::OpAddElemGroupPopup:     // Add elements to group
3056     {
3057       if(checkLock(aStudy)) break;
3058       if (myState == 800) {