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