Salome HOME
Merge from V7_3_BR (09/01/2014)
[modules/smesh.git] / src / SMESHGUI / SMESHGUI_ComputeDlg.cxx
1 // Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File   : SMESHGUI_ComputeDlg.cxx
21 // Author : Edward AGAPOV, Open CASCADE S.A.S.
22 // SMESH includes
23 //
24 #include "SMESHGUI_ComputeDlg.h"
25
26 #include "SMESHGUI.h"
27 #include "SMESHGUI_GEOMGenUtils.h"
28 #include "SMESHGUI_MeshUtils.h"
29 #include "SMESHGUI_VTKUtils.h"
30 #include "SMESHGUI_MeshInfosBox.h"
31 #include "SMESHGUI_HypothesesUtils.h"
32 #include "SMESHGUI_MeshEditPreview.h"
33 #include "SMESHGUI_MeshOrderOp.h"
34 #include "SMESHGUI_MeshOrderDlg.h"
35
36 #include "SMESH_Actor.h"
37 #include "SMESH_ActorUtils.h"
38
39 #include <SMDS_SetIterator.hxx>
40 #include <SMDS_Mesh.hxx>
41
42 // SALOME GEOM includes
43 #include <GEOMBase.h>
44 #include <GEOM_Actor.h>
45 #include <GEOM_wrap.hxx>
46
47 // SALOME GUI includes
48 #include <LightApp_SelectionMgr.h>
49 #include <LightApp_UpdateFlags.h>
50 #include <SALOME_ListIO.hxx>
51 #include <SVTK_ViewWindow.h>
52 #include <SVTK_ViewModel.h>
53 #include <SalomeApp_Application.h>
54 #include <SUIT_ResourceMgr.h>
55 #include <SUIT_OverrideCursor.h>
56 #include <SUIT_MessageBox.h>
57 #include <SUIT_Desktop.h>
58 #include <QtxComboBox.h>
59
60 // SALOME KERNEL includes
61 #include <SALOMEDS_SObject.hxx>
62 #include <SALOMEDSClient_SObject.hxx>
63 #include <SALOMEDS_wrap.hxx>
64
65 #include CORBA_SERVER_HEADER(SMESH_Group)
66
67 // OCCT includes
68 #include <BRep_Tool.hxx>
69 #include <TopExp.hxx>
70 #include <TopExp_Explorer.hxx>
71 #include <TopTools_IndexedMapOfShape.hxx>
72 #include <TopoDS.hxx>
73
74 #include <TopLoc_Location.hxx>
75 #include <Poly_Triangulation.hxx>
76 #include <Bnd_Box.hxx>
77 #include <BRepBndLib.hxx>
78 #include <BRepMesh_IncrementalMesh.hxx>
79
80 #include <Standard_ErrorHandler.hxx>
81
82 // Qt includes
83 #include <QFrame>
84 #include <QPushButton>
85 #include <QLabel>
86 #include <QRadioButton>
87 #include <QTableWidget>
88 #include <QHeaderView>
89 #include <QGridLayout>
90 #include <QHBoxLayout>
91 #include <QVBoxLayout>
92 #include <QButtonGroup>
93 #include <QCloseEvent>
94 #include <QTimerEvent>
95 #include <QProgressBar>
96
97 // VTK includes
98 #include <vtkProperty.h>
99
100 // STL includes
101 #include <vector>
102 #include <set>
103
104 #ifndef WIN32
105 #include <sys/sysinfo.h>
106 #endif
107
108 #define SPACING 6
109 #define MARGIN  11
110
111 #define COLONIZE(str)   (QString(str).contains(":") > 0 ? QString(str) : QString(str) + " :" )
112
113 enum TCol {
114   COL_ALGO = 0, COL_SHAPE, COL_ERROR, COL_SHAPEID, COL_PUBLISHED, COL_BAD_MESH, NB_COLUMNS
115 };
116
117 //using namespace SMESH;
118
119 namespace SMESH
120 {
121   //=============================================================================
122   /*!
123    * \brief Allocate some memory at construction and release it at destruction.
124    * Is used to be able to continue working after mesh generation or visualization
125    * break due to lack of memory
126    */
127   //=============================================================================
128
129   struct MemoryReserve
130   {
131     char* myBuf;
132     MemoryReserve(): myBuf( new char[1024*1024*1] ){} // 1M
133     void release() { delete [] myBuf; myBuf = 0; }
134     ~MemoryReserve() { release(); }
135   };
136
137   // =========================================================================================
138   /*!
139    * \brief Class showing shapes without publishing
140    */
141   // =========================================================================================
142
143   class TShapeDisplayer
144   {
145   public:
146     // -----------------------------------------------------------------------
147     TShapeDisplayer(): myViewWindow(0)
148     {
149       myProperty = vtkProperty::New();
150       myProperty->SetRepresentationToWireframe();
151       myProperty->SetColor( 250, 0, 250 );
152       myProperty->SetAmbientColor( 250, 0, 250 );
153       myProperty->SetDiffuseColor( 250, 0, 250 );
154       //myProperty->SetSpecularColor( 250, 0, 250 );
155       myProperty->SetLineWidth( 5 );
156     }
157     // -----------------------------------------------------------------------
158     ~TShapeDisplayer()
159     {
160       DeleteActors();
161       myProperty->Delete();
162     }
163     // -----------------------------------------------------------------------
164     void DeleteActors()
165     {
166       if ( hasViewWindow() ) {
167         TActorIterator actorIt = actorIterator();
168         while ( actorIt.more() )
169           if (VTKViewer_Actor* anActor = actorIt.next()) {
170             myViewWindow->RemoveActor( anActor );
171             //anActor->Delete();
172           }
173       }
174       myIndexToShape.Clear();
175       myActors.clear();
176       myShownActors.clear();
177       myBuiltSubs.clear();
178     }
179     // -----------------------------------------------------------------------
180     void SetVisibility (bool theVisibility)
181     {
182       TActorIterator actorIt = shownIterator();
183       while ( actorIt.more() )
184         if (VTKViewer_Actor* anActor = actorIt.next())
185           anActor->SetVisibility(theVisibility);
186       SMESH::RepaintCurrentView();
187     }
188     // -----------------------------------------------------------------------
189     bool HasReadyActorsFor (int subShapeID, GEOM::GEOM_Object_var aMainShape )
190     {
191       std::string mainEntry;
192       if ( !aMainShape->_is_nil() )
193         mainEntry = aMainShape->GetStudyEntry();
194       return ( myMainEntry == mainEntry &&
195                myBuiltSubs.find( subShapeID ) != myBuiltSubs.end() );
196     }
197     // -----------------------------------------------------------------------
198     void Show( int subShapeID, GEOM::GEOM_Object_var aMainShape, bool only = false)
199     {
200       SVTK_ViewWindow* aViewWindow  = SMESH::GetViewWindow( SMESHGUI::GetSMESHGUI() );
201       SUIT_ResourceMgr* resMgr = SMESH::GetResourceMgr( SMESHGUI::GetSMESHGUI() );
202       std::string mainEntry;
203       if ( !aMainShape->_is_nil() )
204         mainEntry = aMainShape->GetStudyEntry();
205       if ( myMainEntry != mainEntry || aViewWindow != myViewWindow ) { // remove actors
206         DeleteActors();
207         TopoDS_Shape aShape;
208         if ( !aMainShape->_is_nil() && GEOMBase::GetShape(aMainShape, aShape)) {
209           checkTriangulation( aShape );
210           TopExp::MapShapes(aShape, myIndexToShape);
211           myActors.resize( myIndexToShape.Extent(), 0 );
212           myShownActors.reserve( myIndexToShape.Extent() );
213         }
214         myMainEntry  = mainEntry;
215         myViewWindow = aViewWindow;
216       }
217       if ( only ) { // hide shown actors
218         TActorIterator actorIt = shownIterator();
219         while ( actorIt.more() )
220           if (VTKViewer_Actor* anActor = actorIt.next())
221             anActor->SetVisibility(false);
222         myShownActors.clear();
223       }
224       // find actors to show
225       TopoDS_Shape aShape = myIndexToShape( subShapeID );
226       if ( !aShape.IsNull() ) {
227         TopAbs_ShapeEnum type( aShape.ShapeType() >= TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE );
228         for ( TopExp_Explorer exp( aShape, type ); exp.More(); exp.Next() ) {
229           //checkTriangulation( exp.Current() );
230           if ( GEOM_Actor* anActor = getActor( exp.Current() ) ) {
231             int UNbIsos = resMgr->integerValue( "Geometry", "iso_number_u", 1);
232             int VNbIsos = resMgr->integerValue( "Geometry", "iso_number_v", 1);
233             int aNbIsos[2] = { UNbIsos ? UNbIsos : 1, VNbIsos ? VNbIsos : 1 };
234             anActor->SetNbIsos( aNbIsos );
235             myShownActors.push_back( anActor );
236           }
237         }
238         if ( type == TopAbs_FACE ) {
239           for ( TopExp_Explorer exp( aShape, TopAbs_EDGE ); exp.More(); exp.Next() ) {
240             const TopoDS_Edge & edge = TopoDS::Edge( exp.Current() );
241             if ( !BRep_Tool::Degenerated( edge ))
242               if ( GEOM_Actor* anActor = getActor( exp.Current() ))
243                 myShownActors.push_back( anActor );
244           }
245         }
246       }
247       myBuiltSubs.insert( subShapeID );
248       SetVisibility(true);
249     }
250     // -----------------------------------------------------------------------
251
252   private:
253
254     typedef std::vector<GEOM_Actor*> TActorVec;
255     TActorVec                  myActors;
256     TActorVec                  myShownActors;
257     TopTools_IndexedMapOfShape myIndexToShape;
258     std::string                myMainEntry;
259     SVTK_ViewWindow*           myViewWindow;
260     vtkProperty*               myProperty;
261     std::set<int>              myBuiltSubs;
262
263     // -----------------------------------------------------------------------
264     typedef SMDS_SetIterator< GEOM_Actor*, TActorVec::const_iterator> TActorIterator;
265     TActorIterator actorIterator() {
266       return TActorIterator( myActors.begin(), myActors.end() );
267     }
268     TActorIterator shownIterator() {
269       return TActorIterator( myShownActors.begin(), myShownActors.end() );
270     }
271     // -----------------------------------------------------------------------
272     GEOM_Actor* getActor(const TopoDS_Shape& shape)
273     {
274       int index = myIndexToShape.FindIndex( shape ) - 1;
275       if ( index < 0 || index >= myActors.size() )
276         return 0;
277       GEOM_Actor* & actor = myActors[ index ];
278       if ( !actor ) {
279         actor = GEOM_Actor::New();
280         if ( actor ) {
281           actor->SetShape(shape,0,0);
282           actor->SetProperty(myProperty);
283           actor->SetShadingProperty(myProperty);
284           actor->SetWireframeProperty(myProperty);
285           actor->SetPreviewProperty(myProperty);
286           actor->PickableOff();
287           //         if ( shape.ShapeType() == TopAbs_EDGE )
288           //           actor->SubShapeOn();
289           myViewWindow->AddActor( actor );
290         }
291       }
292       return actor;
293     }
294     // -----------------------------------------------------------------------
295     void checkTriangulation(const TopoDS_Shape& shape)
296     {
297       TopLoc_Location aLoc;
298       Standard_Boolean alreadymesh = Standard_True;
299       TopExp_Explorer ex(shape, TopAbs_FACE);
300       if ( ex.More() )
301         for ( ; ex.More(); ex.Next()) {
302           const TopoDS_Face& aFace = TopoDS::Face(ex.Current());
303           Handle(Poly_Triangulation) aPoly = BRep_Tool::Triangulation(aFace,aLoc);
304           if(aPoly.IsNull()) { alreadymesh = Standard_False; break; }
305         }
306       else
307         for (ex.Init(shape, TopAbs_EDGE); ex.More(); ex.Next()) {
308           const TopoDS_Edge& edge = TopoDS::Edge(ex.Current());
309           Handle(Poly_Polygon3D) aPoly = BRep_Tool::Polygon3D(edge, aLoc);
310           if(aPoly.IsNull()) { alreadymesh = Standard_False; break; }
311         }
312       if (alreadymesh) return;
313       // Compute default deflection
314       Bnd_Box B;
315       BRepBndLib::Add(shape, B);
316       Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
317       B.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
318       double deflection = Max( aXmax-aXmin, Max ( aYmax-aYmin, aZmax-aZmin)) * 0.01 *4;
319       BRepMesh_IncrementalMesh MESH(shape,deflection);
320     }
321     // -----------------------------------------------------------------------
322     bool hasViewWindow() const
323     {
324       if ( !myViewWindow ) return false;
325
326       if ( SalomeApp_Application* anApp = SMESHGUI::GetSMESHGUI()->getApp() )
327         return FindVtkViewWindow( anApp->getViewManager(SVTK_Viewer::Type(), false ),
328                                   myViewWindow );
329       return false;
330     }
331   };
332
333   // =========================================================================================
334   /*!
335    * \brief Return text describing an error
336    */
337 #define CASE2TEXT(enum) case SMESH::enum: text = QObject::tr( #enum ); break;
338   QString errorText(int errCode, const char* comment)
339   {
340     QString text;
341     switch ( errCode ) {
342       CASE2TEXT( COMPERR_OK               );
343       CASE2TEXT( COMPERR_BAD_INPUT_MESH   );
344       CASE2TEXT( COMPERR_STD_EXCEPTION    );
345       CASE2TEXT( COMPERR_OCC_EXCEPTION    );
346     case SMESH::COMPERR_SLM_EXCEPTION: break; // avoid double "Salome exception"
347       CASE2TEXT( COMPERR_EXCEPTION        );
348       CASE2TEXT( COMPERR_MEMORY_PB        );
349       CASE2TEXT( COMPERR_BAD_SHAPE        );
350       CASE2TEXT( COMPERR_CANCELED         );
351       CASE2TEXT( COMPERR_NO_MESH_ON_SHAPE );
352       CASE2TEXT( COMPERR_BAD_PARMETERS    );
353     case SMESH::COMPERR_ALGO_FAILED:
354       if ( strlen(comment) == 0 )
355         text = QObject::tr("COMPERR_ALGO_FAILED");
356       break;
357     case SMESH::COMPERR_WARNING:
358       text = QObject::tr( (comment && strlen(comment)) ? "COMPERR_WARNING" : "COMPERR_UNKNOWN");
359       break;
360     default:
361       text = QString("#%1").arg( -errCode );
362     }
363     if ( text.length() > 0 ) text += ". ";
364     return text + comment;
365   }
366   // -----------------------------------------------------------------------
367   /*!
368    * \brief Return SO of a sub-shape
369    */
370   _PTR(SObject) getSubShapeSO( int subShapeID, GEOM::GEOM_Object_var aMainShape)
371   {
372     _PTR(SObject) so = SMESH::FindSObject(aMainShape);
373     if ( subShapeID == 1 || !so )
374       return so;
375     _PTR(ChildIterator) it;
376     if (_PTR(Study) study = SMESH::GetActiveStudyDocument())
377       it =  study->NewChildIterator(so);
378     _PTR(SObject) subSO;
379     if ( it ) {
380       for ( it->InitEx(true); !subSO && it->More(); it->Next() ) {
381         GEOM::GEOM_Object_var geom = SMESH::SObjectToInterface<GEOM::GEOM_Object>( it->Value() );
382         if ( !geom->_is_nil() ) {
383           GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
384           if ( list->length() == 1 && list[0] == subShapeID )
385             subSO = it->Value();
386         }
387       }
388     }
389     return subSO;
390   }
391   // -----------------------------------------------------------------------
392   /*!
393    * \brief Return sub-shape by ID. WARNING: UnRegister() must be called on a result
394    */
395   GEOM::GEOM_Object_ptr getSubShape( int subShapeID, GEOM::GEOM_Object_var aMainShape)
396   {
397     GEOM::GEOM_Object_var aSubShape;
398     if ( subShapeID == 1 ) {
399       aSubShape = aMainShape;
400       aSubShape->Register();
401     }
402     else if ( _PTR(SObject) so = getSubShapeSO( subShapeID, aMainShape )) {
403       aSubShape = SMESH::SObjectToInterface<GEOM::GEOM_Object>( so );
404       aSubShape->Register();
405     }
406     else {
407       aSubShape = SMESH::GetSubShape( aMainShape, subShapeID );
408       // future call of UnRegister() will delete a servant of this new object
409     }
410     return aSubShape._retn();
411   }
412   // -----------------------------------------------------------------------
413   /*!
414    * \brief Return shape type name
415    */
416 #define CASE2NAME(enum) case GEOM::enum: name = QObject::tr( "GEOM_" #enum ); break;
417   QString shapeTypeName(GEOM::GEOM_Object_var aShape, const char* dflt = "" )
418   {
419     QString name = dflt;
420     if ( !aShape->_is_nil() ) {
421       switch ( aShape->GetShapeType() ) {
422       CASE2NAME( VERTEX    );
423       CASE2NAME( EDGE      );
424       CASE2NAME( WIRE      );
425       CASE2NAME( FACE      );
426       CASE2NAME( SHELL     );
427       CASE2NAME( SOLID     );
428       CASE2NAME( COMPSOLID );
429       CASE2NAME( COMPOUND  );
430       default:;
431       }
432     }
433     return name;
434   }
435   // -----------------------------------------------------------------------
436   /*!
437    * \brief Return text describing a sub-shape
438    */
439   QString shapeText(int subShapeID, GEOM::GEOM_Object_var aMainShape )
440   {
441     QString text;
442     if ( _PTR(SObject) aSO = getSubShapeSO( subShapeID, aMainShape ))
443       text = aSO->GetName().c_str();
444     else {
445       text = QString("#%1").arg( subShapeID );
446       GEOM::GEOM_Object_wrap shape = getSubShape( subShapeID, aMainShape );
447       QString typeName = shapeTypeName( shape );
448       if ( typeName.length() )
449         text += QString(" (%1)").arg(typeName);
450     }
451     return text;
452   }
453   // -----------------------------------------------------------------------
454   /*!
455    * \brief Return a list of selected rows
456    */
457   int getSelectedRows(QTableWidget* table, QList<int>& rows)
458   {
459     rows.clear();
460     QList<QTableWidgetSelectionRange> selRanges = table->selectedRanges();
461     QTableWidgetSelectionRange range;
462     foreach( range, selRanges )
463     {
464       for ( int row = range.topRow(); row <= range.bottomRow(); ++row )
465         if ( !rows.count( row ))
466              rows.append( row );
467     }
468     if ( rows.isEmpty() && table->currentRow() > -1 )
469       if ( !rows.count( table->currentRow() ))
470         rows.append( table->currentRow() );
471
472     return rows.count();
473   }
474
475 } // namespace SMESH
476
477
478 // =========================================================================================
479 /*!
480  * \brief Dialog to compute a mesh and show computation errors
481  */
482 //=======================================================================
483
484 SMESHGUI_ComputeDlg::SMESHGUI_ComputeDlg( QWidget* parent, bool ForEval )
485  : SMESHGUI_Dialog( parent, false, true, Close/* | Help*/ )
486 {
487   QVBoxLayout* aDlgLay = new QVBoxLayout (mainFrame());
488   aDlgLay->setMargin( 0 );
489   aDlgLay->setSpacing( SPACING );
490
491   QFrame* aMainFrame = createMainFrame(mainFrame(),ForEval);
492
493   aDlgLay->addWidget(aMainFrame);
494
495   aDlgLay->setStretchFactor(aMainFrame, 1);
496 }
497
498 // =========================================================================================
499 /*!
500  * \brief Destructor
501  */
502 //=======================================================================
503
504 SMESHGUI_ComputeDlg::~SMESHGUI_ComputeDlg()
505 {
506 }
507
508 //=======================================================================
509 // function : createMainFrame()
510 // purpose  : Create frame containing dialog's fields
511 //=======================================================================
512
513 QFrame* SMESHGUI_ComputeDlg::createMainFrame (QWidget* theParent, bool ForEval)
514 {
515   QFrame* aFrame = new QFrame(theParent);
516
517   SUIT_ResourceMgr* rm = resourceMgr();
518   QPixmap iconCompute (rm->loadPixmap("SMESH", tr("ICON_COMPUTE")));
519
520   // constructor
521
522   QGroupBox* aPixGrp;
523   if(ForEval) {
524     aPixGrp = new QGroupBox(tr("EVAL_DLG"), aFrame);
525   }
526   else {
527     aPixGrp = new QGroupBox(tr("CONSTRUCTOR"), aFrame);
528   }
529   QButtonGroup* aBtnGrp = new QButtonGroup(this);
530   QHBoxLayout* aPixGrpLayout = new QHBoxLayout(aPixGrp);
531   aPixGrpLayout->setMargin(MARGIN); aPixGrpLayout->setSpacing(SPACING);
532
533   QRadioButton* aRBut = new QRadioButton(aPixGrp);
534   aRBut->setIcon(iconCompute);
535   aRBut->setChecked(true);
536   aPixGrpLayout->addWidget(aRBut);
537   aBtnGrp->addButton(aRBut, 0);
538
539   // Mesh name
540
541   QGroupBox* nameBox = new QGroupBox(tr("SMESH_MESHINFO_NAME"), aFrame );
542   QHBoxLayout* nameBoxLayout = new QHBoxLayout(nameBox);
543   nameBoxLayout->setMargin(MARGIN); nameBoxLayout->setSpacing(SPACING);
544   myMeshName = new QLabel(nameBox);
545   nameBoxLayout->addWidget(myMeshName);
546
547   // Mesh Info
548
549   myBriefInfo = new SMESHGUI_MeshInfosBox(false, aFrame);
550   myFullInfo  = new SMESHGUI_MeshInfosBox(true,  aFrame);
551
552   // Computation errors
553
554   myCompErrorGroup = new QGroupBox(tr("ERRORS"), aFrame);
555   myWarningLabel = new QLabel(QString("<b>%1</b>").arg(tr("COMPUTE_WARNING")), myCompErrorGroup);
556   myTable        = new QTableWidget( 1, NB_COLUMNS, myCompErrorGroup);
557   myShowBtn      = new QPushButton(tr("SHOW_SHAPE"), myCompErrorGroup);
558   myPublishBtn   = new QPushButton(tr("PUBLISH_SHAPE"), myCompErrorGroup);
559   myBadMeshBtn   = new QPushButton(tr("SHOW_BAD_MESH"), myCompErrorGroup);
560   myBadMeshToGroupBtn = new QPushButton(tr("GROUP_OF_BAD_MESH"), myCompErrorGroup);
561
562   //myTable->setReadOnly( true ); // VSR: check
563   myTable->setEditTriggers( QAbstractItemView::NoEditTriggers );
564   myTable->hideColumn( COL_PUBLISHED );
565   myTable->hideColumn( COL_SHAPEID );
566   myTable->hideColumn( COL_BAD_MESH );
567   myTable->horizontalHeader()->setResizeMode( COL_ERROR, QHeaderView::Interactive );
568   myTable->setWordWrap( true );
569   myTable->horizontalHeader()->setStretchLastSection( true );
570   myTable->setMinimumWidth( 500 );
571
572   QStringList headers;
573   headers << tr( "COL_ALGO_HEADER" );
574   headers << tr( "COL_SHAPE_HEADER" );
575   headers << tr( "COL_ERROR_HEADER" );
576   headers << tr( "COL_SHAPEID_HEADER" );
577   headers << tr( "COL_PUBLISHED_HEADER" );
578
579   myTable->setHorizontalHeaderLabels( headers );
580
581   // layouting
582   QGridLayout* grpLayout = new QGridLayout(myCompErrorGroup);
583   grpLayout->setSpacing(SPACING);
584   grpLayout->setMargin(MARGIN);
585   grpLayout->addWidget( myWarningLabel,      0, 0, 1, 4 );
586   grpLayout->addWidget( myTable,             1, 0, 1, 4 );
587   grpLayout->addWidget( myShowBtn,           2, 0 );
588   grpLayout->addWidget( myPublishBtn,        2, 1 );
589   grpLayout->addWidget( myBadMeshBtn,        2, 2 );
590   grpLayout->addWidget( myBadMeshToGroupBtn, 2, 3 );
591   grpLayout->setColumnStretch( 3, 1 );
592
593   // Hypothesis definition errors
594
595   myHypErrorGroup = new QGroupBox(tr("SMESH_WRN_MISSING_PARAMETERS"), aFrame);
596   QHBoxLayout* myHypErrorGroupLayout = new QHBoxLayout(myHypErrorGroup);
597   myHypErrorGroupLayout->setMargin(MARGIN);
598   myHypErrorGroupLayout->setSpacing(SPACING);
599   myHypErrorLabel = new QLabel(myHypErrorGroup);
600   myHypErrorGroupLayout->addWidget(myHypErrorLabel);
601
602   // Memory Lack Label
603
604   myMemoryLackGroup = new QGroupBox(tr("ERRORS"), aFrame);
605   QVBoxLayout* myMemoryLackGroupLayout = new QVBoxLayout(myMemoryLackGroup);
606   myMemoryLackGroupLayout->setMargin(MARGIN);
607   myMemoryLackGroupLayout->setSpacing(SPACING);
608   QLabel* memLackLabel = new QLabel(tr("MEMORY_LACK"), myMemoryLackGroup);
609   QFont bold = memLackLabel->font(); bold.setBold(true);
610   memLackLabel->setFont( bold );
611   memLackLabel->setMinimumWidth(300);
612   myMemoryLackGroupLayout->addWidget(memLackLabel);
613
614   // add all widgets to aFrame
615   QVBoxLayout* aLay = new QVBoxLayout(aFrame);
616   aLay->setMargin( 0 );
617   aLay->setSpacing( 0 );
618   aLay->addWidget( aPixGrp );
619   aLay->addWidget( nameBox );
620   aLay->addWidget( myBriefInfo );
621   aLay->addWidget( myFullInfo );
622   aLay->addWidget( myHypErrorGroup );
623   aLay->addWidget( myCompErrorGroup );
624   aLay->addWidget( myMemoryLackGroup );
625   aLay->setStretchFactor( myCompErrorGroup, 1 );
626
627   ((QPushButton*) button( OK ))->setDefault( true );
628
629   return aFrame;
630 }
631
632 //================================================================================
633 /*!
634  * \brief Constructor
635 */
636 //================================================================================
637
638 SMESHGUI_BaseComputeOp::SMESHGUI_BaseComputeOp()
639   : SMESHGUI_Operation(), myCompDlg( 0 )
640 {
641   myTShapeDisplayer = new SMESH::TShapeDisplayer();
642   myBadMeshDisplayer = 0;
643
644   //myHelpFileName = "/files/about_meshes.htm"; // V3
645   myHelpFileName = "about_meshes_page.html"; // V4
646 }
647
648 SMESH::SMESH_Mesh_ptr SMESHGUI_BaseComputeOp::getMesh()
649 {
650   LightApp_SelectionMgr* Sel = selectionMgr();
651   SALOME_ListIO selected; Sel->selectedObjects( selected );
652   Handle(SALOME_InteractiveObject) anIO = selected.First();
653   SMESH::SMESH_Mesh_var aMesh = SMESH::GetMeshByIO(anIO);
654   return myMesh->_is_nil() ? aMesh._retn() : SMESH::SMESH_Mesh::_duplicate( myMesh );
655 }
656
657 //================================================================================
658 /*!
659  * \brief Start operation
660  * \purpose Init dialog fields, connect signals and slots, show dialog
661  */
662 //================================================================================
663
664 void SMESHGUI_BaseComputeOp::startOperation()
665 {
666   // create compute dialog if not created before
667   computeDlg();
668
669   myMesh      = SMESH::SMESH_Mesh::_nil();
670   myMainShape = GEOM::GEOM_Object::_nil();
671
672   // check selection
673   LightApp_SelectionMgr *Sel = selectionMgr();
674   SALOME_ListIO selected; Sel->selectedObjects( selected );
675
676   int nbSel = selected.Extent();
677   if (nbSel != 1) {
678     SUIT_MessageBox::warning(desktop(),
679                              tr("SMESH_WRN_WARNING"),
680                              tr("SMESH_WRN_NO_AVAILABLE_DATA"));
681     onCancel();
682     return;
683   }
684
685   myIObject = selected.First();
686   myMesh = SMESH::GetMeshByIO(myIObject);
687   if (myMesh->_is_nil()) {
688     SUIT_MessageBox::warning(desktop(),
689                              tr("SMESH_WRN_WARNING"),
690                              tr("SMESH_WRN_NO_AVAILABLE_DATA"));
691     onCancel();
692     return;
693   }
694   myMainShape = myMesh->GetShapeToMesh();
695
696   SMESHGUI_Operation::startOperation();
697 }
698
699 //================================================================================
700 //================================================================================
701
702 SMESHGUI_ComputeDlg_QThread::SMESHGUI_ComputeDlg_QThread(SMESH::SMESH_Gen_var gen,
703                                                          SMESH::SMESH_Mesh_var mesh,
704                                                          GEOM::GEOM_Object_var mainShape)
705 {
706   myResult = false;
707   myGen = gen;
708   myMesh = mesh;
709   myMainShape = mainShape;
710 }
711
712 void SMESHGUI_ComputeDlg_QThread::run()
713 {
714   myResult = myGen->Compute(myMesh, myMainShape);
715 }
716
717 bool SMESHGUI_ComputeDlg_QThread::result()
718 {
719   return myResult;
720 }
721
722 void SMESHGUI_ComputeDlg_QThread::cancel()
723 {
724   myGen->CancelCompute(myMesh, myMainShape);
725 }
726
727 //================================================================================
728 //================================================================================
729
730 SMESHGUI_ComputeDlg_QThreadQDialog::SMESHGUI_ComputeDlg_QThreadQDialog(QWidget             * parent,
731                                                                        SMESH::SMESH_Gen_var  gen,
732                                                                        SMESH::SMESH_Mesh_var mesh,
733                                                                        GEOM::GEOM_Object_var mainShape)
734   : QDialog(parent,
735             Qt::WindowSystemMenuHint |
736             Qt::WindowCloseButtonHint |
737             Qt::Dialog |
738             Qt::WindowMaximizeButtonHint),
739     qthread(gen, mesh, mainShape)
740 {
741   // --
742   setWindowTitle(tr("TITLE"));
743   setMinimumWidth( 200 );
744
745   cancelButton = new QPushButton(tr("CANCEL"));
746   cancelButton->setDefault(true);
747   cancelButton->setCheckable(true);
748
749   QLabel * nbNodesName = new QLabel(tr("SMESH_MESHINFO_NODES"), this );
750   QLabel * nbElemsName = new QLabel(tr("SMESH_MESHINFO_ELEMENTS"), this );
751   nbNodesLabel = new QLabel("0", this );
752   nbElemsLabel = new QLabel("0", this );
753 #ifndef WIN32
754   QLabel * freeRAMName = new QLabel(tr("SMESH_FREERAM"), this );
755   freeRAMLabel = new QLabel("", this );
756 #endif
757   progressBar  = new QProgressBar(this);
758   progressBar->setMinimum( 0 );
759   progressBar->setMaximum( 1000 );
760
761   QGridLayout* layout = new QGridLayout(this);
762   layout->setMargin( MARGIN );
763   layout->setSpacing( SPACING );
764   int row = 0;
765   layout->addWidget(nbNodesName,  row,   0);
766   layout->addWidget(nbNodesLabel, row++, 1);
767   layout->addWidget(nbElemsName,  row,   0);
768   layout->addWidget(nbElemsLabel, row++, 1);
769 #ifndef WIN32
770   layout->addWidget(freeRAMName,  row,   0);
771   layout->addWidget(freeRAMLabel, row++, 1);
772 #endif
773   layout->addWidget(progressBar,  row++, 0, 1, 2);
774   layout->addWidget(cancelButton, row++, 0, 1, 2);
775   adjustSize();
776   update();
777
778   connect(cancelButton, SIGNAL(clicked()), this, SLOT(onCancel()));
779   // --
780   startTimer(300); // millisecs
781   qthread.start();
782 }
783
784 bool SMESHGUI_ComputeDlg_QThreadQDialog::result()
785 {
786   return qthread.result();
787 }
788
789 void SMESHGUI_ComputeDlg_QThreadQDialog::onCancel()
790 {
791   qthread.cancel();
792   cancelButton->setText( tr("CANCELING"));
793   cancelButton->setEnabled(false);
794 }
795
796 void SMESHGUI_ComputeDlg_QThreadQDialog::timerEvent(QTimerEvent *event)
797 {
798   if ( !cancelButton->isChecked() ) // not yet cancelled
799     progressBar->setValue( progressBar->maximum() * qthread.getMesh()->GetComputeProgress() );
800
801   if(qthread.isFinished())
802   {
803     close();
804   }
805   else
806   {
807     nbNodesLabel->setText( QString("%1").arg( qthread.getMesh()->NbNodes() ));
808     nbElemsLabel->setText( QString("%1").arg( qthread.getMesh()->NbElements() ));
809 #ifndef WIN32
810     struct sysinfo si;
811     const int err = sysinfo( &si );
812     if ( err )
813       freeRAMLabel->setText("");
814     else
815       freeRAMLabel->setText( tr("SMESH_GIGABYTE").arg
816                              ( si.freeram * si.mem_unit /1024./1024./1024., 0, 'f', 2 ));
817 #endif
818   }
819   event->accept();
820 }
821
822 void SMESHGUI_ComputeDlg_QThreadQDialog::closeEvent(QCloseEvent *event)
823 {
824   if(qthread.isRunning())
825   {
826       event->ignore();
827       return;
828     }
829   event->accept();
830 }
831
832 //================================================================================
833 /*!
834  * \brief computeMesh()
835 */
836 //================================================================================
837
838 void SMESHGUI_BaseComputeOp::computeMesh()
839 {
840   // COMPUTE MESH
841
842   SMESH::MemoryReserve aMemoryReserve;
843
844   SMESH::compute_error_array_var aCompErrors;
845   QString                        aHypErrors;
846
847   bool computeFailed = true, memoryLack = false;
848
849   _PTR(SObject) aMeshSObj = SMESH::FindSObject(myMesh);
850   if ( !aMeshSObj ) // IPAL 21340
851     return;
852   bool hasShape = myMesh->HasShapeToMesh();
853   bool shapeOK = myMainShape->_is_nil() ? !hasShape : hasShape;
854   if ( shapeOK )
855   {
856     myCompDlg->myMeshName->setText( aMeshSObj->GetName().c_str() );
857     SMESH::SMESH_Gen_var gen = getSMESHGUI()->GetSMESHGen();
858     SMESH::algo_error_array_var errors = gen->GetAlgoState(myMesh,myMainShape);
859     if ( errors->length() > 0 ) {
860       aHypErrors = SMESH::GetMessageOnAlgoStateErrors( errors.in() );
861     }
862     if ( myMesh->HasModificationsToDiscard() && // issue 0020693
863          SUIT_MessageBox::question( desktop(), tr( "SMESH_WARNING" ),
864                                     tr( "FULL_RECOMPUTE_QUESTION" ),
865                                     tr( "SMESH_BUT_YES" ), tr( "SMESH_BUT_NO" ), 1, 0 ) == 0 )
866       myMesh->Clear();
867     SUIT_OverrideCursor aWaitCursor;
868     try {
869 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
870       OCC_CATCH_SIGNALS;
871 #endif
872       SMESHGUI_ComputeDlg_QThreadQDialog qthreaddialog(desktop(), gen, myMesh, myMainShape);
873       qthreaddialog.exec();
874       computeFailed = !qthreaddialog.result();
875     }
876     catch(const SALOME::SALOME_Exception & S_ex) {
877       memoryLack = true;
878     }
879     try {
880 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
881       OCC_CATCH_SIGNALS;
882 #endif
883       aCompErrors = gen->GetComputeErrors( myMesh, myMainShape );
884       // check if there are memory problems
885       for ( int i = 0; (i < aCompErrors->length()) && !memoryLack; ++i )
886         memoryLack = ( aCompErrors[ i ].code == SMESH::COMPERR_MEMORY_PB );
887     }
888     catch(const SALOME::SALOME_Exception & S_ex) {
889       memoryLack = true;
890     }
891
892     if ( !memoryLack && !SMDS_Mesh::CheckMemory(true) ) { // has memory to show dialog boxes?
893       memoryLack = true;
894     }
895
896     // NPAL16631: if ( !memoryLack )
897     {
898       SMESH::ModifiedMesh(aMeshSObj, !computeFailed, myMesh->NbNodes() == 0);
899       update( UF_ObjBrowser | UF_Model );
900
901       // SHOW MESH
902       // NPAL16631: if ( getSMESHGUI()->automaticUpdate() )
903       SUIT_ResourceMgr* resMgr = SMESH::GetResourceMgr( SMESHGUI::GetSMESHGUI() );
904       bool limitExceeded;
905       long limitSize = resMgr->integerValue( "SMESH", "update_limit", 500000 );
906       int entities = SMESH_Actor::eAllEntity;
907       int hidden = 0;
908       if ( !memoryLack )
909       {
910         if ( getSMESHGUI()->automaticUpdate( myMesh, &entities, &limitExceeded, &hidden ) )
911         {
912           try {
913 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
914             OCC_CATCH_SIGNALS;
915 #endif
916             SMESH_Actor *anActor = SMESH::FindActorByObject( myMesh );
917             if ( !anActor ) anActor = SMESH::CreateActor( aMeshSObj->GetStudy(), aMeshSObj->GetID().c_str(), true );    
918             if ( anActor ) // actor is not created for an empty mesh
919             {
920               anActor->SetEntityMode( entities );
921               SMESH::DisplayActor( SMESH::GetActiveWindow(), anActor );
922             }
923             SMESH::Update(myIObject, true);
924
925             if ( limitExceeded )
926             {
927               QStringList hiddenMsg;
928               if ( hidden & SMESH_Actor::e0DElements ) hiddenMsg << tr( "SMESH_ELEMS0D" );
929               if ( hidden & SMESH_Actor::eEdges )      hiddenMsg << tr( "SMESH_EDGES" );
930               if ( hidden & SMESH_Actor::eFaces )      hiddenMsg << tr( "SMESH_FACES" );
931               if ( hidden & SMESH_Actor::eVolumes )    hiddenMsg << tr( "SMESH_VOLUMES" );
932               if ( hidden & SMESH_Actor::eBallElem )   hiddenMsg << tr( "SMESH_BALLS" );
933               SUIT_MessageBox::warning( desktop(),
934                                         tr( "SMESH_WRN_WARNING" ),
935                                         tr( "SMESH_WRN_SIZE_INC_LIMIT_EXCEEDED" ).arg( myMesh->NbElements() ).arg( limitSize ).arg( hiddenMsg.join(", ") ) );
936             }
937           }
938           catch (...) {
939 #ifdef _DEBUG_
940             MESSAGE ( "Exception thrown during mesh visualization" );
941 #endif
942             if ( SMDS_Mesh::CheckMemory(true) ) { // has memory to show warning?
943               SMESH::OnVisuException();
944             }
945             else {
946               memoryLack = true;
947             }
948           }
949         }
950         else if ( limitExceeded )
951         {
952           SUIT_MessageBox::warning( desktop(),
953                                     tr( "SMESH_WRN_WARNING" ),
954                                     tr( "SMESH_WRN_SIZE_LIMIT_EXCEEDED" ).arg( myMesh->NbElements() ).arg( limitSize ) );
955         }
956       }
957       LightApp_SelectionMgr *Sel = selectionMgr();
958       if ( Sel )
959       {
960         SALOME_ListIO selected;
961         selected.Append( myIObject );
962         Sel->setSelectedObjects( selected );
963       }
964     }
965   }
966
967   if ( memoryLack )
968     aMemoryReserve.release();
969
970   myCompDlg->setWindowTitle(tr( computeFailed ? "SMESH_WRN_COMPUTE_FAILED" : "SMESH_COMPUTE_SUCCEED"));
971
972   // SHOW ERRORS
973   
974   bool noCompError = ( !aCompErrors.operator->() || aCompErrors->length() == 0 );
975   bool noHypoError = ( aHypErrors.isEmpty() );
976
977   SUIT_ResourceMgr* resMgr = SMESH::GetResourceMgr( SMESHGUI::GetSMESHGUI() );
978   int aNotifyMode = resMgr->integerValue( "SMESH", "show_result_notification" );
979
980   bool isShowResultDlg = true;
981   switch( aNotifyMode ) {
982   case 0: // show the mesh computation result dialog NEVER
983     isShowResultDlg = false;
984     commit();
985     break;
986   case 1: // show the mesh computation result dialog if there are some errors
987     if ( memoryLack || !noCompError || !noHypoError )
988       isShowResultDlg = true;
989     else
990     {
991       isShowResultDlg = false;
992       commit();
993     }
994     break;
995   default: // show the result dialog after each mesh computation
996     isShowResultDlg = true;
997   }
998
999   // SHOW RESULTS
1000   if ( isShowResultDlg )
1001     showComputeResult( memoryLack, noCompError,aCompErrors, noHypoError, aHypErrors );
1002 }
1003
1004 void SMESHGUI_BaseComputeOp::showComputeResult( const bool theMemoryLack,
1005                                                 const bool theNoCompError,
1006                                                 SMESH::compute_error_array_var& theCompErrors,
1007                                                 const bool theNoHypoError,
1008                                                 const QString& theHypErrors )
1009 {
1010   bool hasShape = myMesh->HasShapeToMesh();
1011   SMESHGUI_ComputeDlg* aCompDlg = computeDlg();
1012   aCompDlg->myMemoryLackGroup->hide();
1013
1014   if ( theMemoryLack )
1015   {
1016     aCompDlg->myMemoryLackGroup->show();
1017     aCompDlg->myFullInfo->hide();
1018     aCompDlg->myBriefInfo->hide();
1019     aCompDlg->myHypErrorGroup->hide();
1020     aCompDlg->myCompErrorGroup->hide();
1021   }
1022   else if ( theNoCompError && theNoHypoError )
1023   {
1024     SMESH::long_array_var aRes = myMesh->GetMeshInfo();
1025     aCompDlg->myFullInfo->SetMeshInfo( aRes );
1026     aCompDlg->myFullInfo->show();
1027     aCompDlg->myBriefInfo->hide();
1028     aCompDlg->myHypErrorGroup->hide();
1029     aCompDlg->myCompErrorGroup->hide();
1030   }
1031   else
1032   {
1033     bool onlyWarnings = !theNoCompError; // == valid mesh computed but there are errors reported
1034     for ( int i = 0; i < theCompErrors->length() && onlyWarnings; ++i )
1035       onlyWarnings = ( theCompErrors[ i ].code == SMESH::COMPERR_WARNING ||
1036                        theCompErrors[ i ].code == SMESH::COMPERR_NO_MESH_ON_SHAPE );
1037
1038     // full or brief mesh info
1039     SMESH::long_array_var aRes = myMesh->GetMeshInfo();
1040     if ( onlyWarnings ) {
1041       aCompDlg->myFullInfo->SetMeshInfo( aRes );
1042       aCompDlg->myFullInfo->show();
1043       aCompDlg->myBriefInfo->hide();
1044     } else {
1045       aCompDlg->myBriefInfo->SetMeshInfo( aRes );
1046       aCompDlg->myBriefInfo->show();
1047       aCompDlg->myFullInfo->hide();
1048     }
1049
1050     // pbs of hypo dfinitions
1051     if ( theNoHypoError ) {
1052       aCompDlg->myHypErrorGroup->hide();
1053     } else {
1054       aCompDlg->myHypErrorGroup->show();
1055       aCompDlg->myHypErrorLabel->setText( theHypErrors );
1056     }
1057
1058     // table of errors
1059     if ( theNoCompError )
1060     {
1061       aCompDlg->myCompErrorGroup->hide();
1062     }
1063     else
1064     {
1065       aCompDlg->myCompErrorGroup->show();
1066
1067       if ( onlyWarnings )
1068         aCompDlg->myWarningLabel->show();
1069       else
1070         aCompDlg->myWarningLabel->hide();
1071
1072       if ( !hasShape ) {
1073         aCompDlg->myPublishBtn->hide();
1074         aCompDlg->myShowBtn->hide();
1075       }
1076       else {
1077         aCompDlg->myPublishBtn->show();
1078         aCompDlg->myShowBtn->show();
1079       }
1080
1081       // fill table of errors
1082       QTableWidget* tbl = aCompDlg->myTable;
1083       tbl->setRowCount( theCompErrors->length() );
1084       if ( !hasShape ) tbl->hideColumn( COL_SHAPE );
1085       else             tbl->showColumn( COL_SHAPE );
1086       tbl->setColumnWidth( COL_ERROR, 200 );
1087
1088       bool hasBadMesh = false;
1089       for ( int row = 0; row < theCompErrors->length(); ++row )
1090       {
1091         SMESH::ComputeError & err = theCompErrors[ row ];
1092
1093         QString text = err.algoName.in();
1094         if ( !tbl->item( row, COL_ALGO ) ) tbl->setItem( row, COL_ALGO, new QTableWidgetItem( text ) );
1095         else tbl->item( row, COL_ALGO )->setText( text );
1096
1097         text = SMESH::errorText( err.code, err.comment.in() );
1098         if ( !tbl->item( row, COL_ERROR ) ) tbl->setItem( row, COL_ERROR, new QTableWidgetItem( text ) );
1099         else tbl->item( row, COL_ERROR )->setText( text );
1100
1101         text = QString("%1").arg( err.subShapeID );
1102         if ( !tbl->item( row, COL_SHAPEID ) ) tbl->setItem( row, COL_SHAPEID, new QTableWidgetItem( text ) );
1103         else tbl->item( row, COL_SHAPEID )->setText( text );
1104
1105         text = hasShape ? SMESH::shapeText( err.subShapeID, myMainShape ) : QString("");
1106         if ( !tbl->item( row, COL_SHAPE ) ) tbl->setItem( row, COL_SHAPE, new QTableWidgetItem( text ) );
1107         else tbl->item( row, COL_SHAPE )->setText( text );
1108
1109         text = ( !hasShape || SMESH::getSubShapeSO( err.subShapeID, myMainShape )) ? "PUBLISHED" : "";
1110         if ( !tbl->item( row, COL_PUBLISHED ) ) tbl->setItem( row, COL_PUBLISHED, new QTableWidgetItem( text ) );
1111         else tbl->item( row, COL_PUBLISHED )->setText( text ); // if text=="", "PUBLISH" button enabled
1112
1113         text = err.hasBadMesh ? "hasBadMesh" : "";
1114         if ( !tbl->item( row, COL_BAD_MESH ) ) tbl->setItem( row, COL_BAD_MESH, new QTableWidgetItem( text ) );
1115         else tbl->item( row, COL_BAD_MESH )->setText( text );
1116         if ( err.hasBadMesh ) hasBadMesh = true;
1117
1118         //tbl->item( row, COL_ERROR )->setWordWrap( true ); // VSR: TODO ???
1119         tbl->resizeRowToContents( row );
1120       }
1121       tbl->resizeColumnToContents( COL_ALGO );
1122       tbl->resizeColumnToContents( COL_SHAPE );
1123       tbl->setWordWrap( true );
1124
1125       if ( hasBadMesh ) {
1126         aCompDlg->myBadMeshBtn->show();
1127         aCompDlg->myBadMeshToGroupBtn->show();
1128       }
1129       else {
1130         aCompDlg->myBadMeshBtn->hide();
1131         aCompDlg->myBadMeshToGroupBtn->hide();
1132       }
1133       tbl->setCurrentCell(0,0);
1134       currentCellChanged(); // to update buttons
1135     }
1136   }
1137   // show dialog and wait, becase Compute can be invoked from Preview operation
1138   //aCompDlg->exec(); // this way it becomes modal - impossible to rotate model in the Viewer
1139   aCompDlg->show();
1140 }
1141
1142 //================================================================================
1143 /*!
1144  * \brief Stops operation
1145  */
1146 //================================================================================
1147
1148 void SMESHGUI_BaseComputeOp::stopOperation()
1149 {
1150   SMESHGUI_Operation::stopOperation();
1151   if ( myTShapeDisplayer )
1152     myTShapeDisplayer->SetVisibility( false );
1153   if ( myBadMeshDisplayer ) {
1154     myBadMeshDisplayer->SetVisibility( false );
1155     // delete it in order not to have problems at its destruction when the viewer
1156     // where it worked is dead due to e.g. study closing
1157     delete myBadMeshDisplayer;
1158     myBadMeshDisplayer = 0;
1159   }
1160   myIObject.Nullify();
1161 }
1162
1163 //================================================================================
1164 /*!
1165  * \brief publish selected sub-shape
1166  */
1167 //================================================================================
1168
1169 void SMESHGUI_BaseComputeOp::onPublishShape()
1170 {
1171   GEOM::GEOM_Gen_var geomGen = SMESH::GetGEOMGen();
1172   SALOMEDS::Study_var study = SMESHGUI::GetSMESHGen()->GetCurrentStudy();
1173
1174   QList<int> rows;
1175   SMESH::getSelectedRows( table(), rows );
1176   int row;
1177   foreach ( row, rows )
1178   {
1179     int curSub = table()->item(row, COL_SHAPEID)->text().toInt();
1180     GEOM::GEOM_Object_wrap shape = SMESH::getSubShape( curSub, myMainShape );
1181     if ( !shape->_is_nil() && ! SMESH::getSubShapeSO( curSub, myMainShape ))
1182     {
1183       if ( !SMESH::getSubShapeSO( 1, myMainShape )) // the main shape not published
1184       {
1185         QString name = GEOMBase::GetDefaultName( SMESH::shapeTypeName( myMainShape, "MAIN_SHAPE" ));
1186         SALOMEDS::SObject_wrap so =
1187           geomGen->AddInStudy( study, myMainShape, name.toLatin1().data(), GEOM::GEOM_Object::_nil());
1188         // look for myMainShape in the table
1189         for ( int r = 0, nr = table()->rowCount(); r < nr; ++r ) {
1190           if ( table()->item( r, COL_SHAPEID )->text() == "1" ) {
1191             if ( so->_is_nil() ) {
1192               CORBA::String_var name  = so->GetName();
1193               CORBA::String_var entry = so->GetID();
1194               table()->item( r, COL_SHAPE     )->setText( name.in() );
1195               table()->item( r, COL_PUBLISHED )->setText( entry.in() );
1196             }
1197             break;
1198           }
1199         }
1200         if ( curSub == 1 ) continue;
1201       }
1202       QString name = GEOMBase::GetDefaultName( SMESH::shapeTypeName( shape, "ERROR_SHAPE" ));
1203       SALOMEDS::SObject_wrap so = geomGen->AddInStudy( study, shape, name.toLatin1().data(), myMainShape);
1204       if ( !so->_is_nil() ) {
1205         CORBA::String_var name  = so->GetName();
1206         CORBA::String_var entry = so->GetID();
1207         table()->item( row, COL_SHAPE     )->setText( name.in() );
1208         table()->item( row, COL_PUBLISHED )->setText( entry.in() );
1209       }
1210     }
1211   }
1212   getSMESHGUI()->getApp()->updateObjectBrowser();
1213   currentCellChanged(); // to update buttons
1214 }
1215
1216 //================================================================================
1217 /*!
1218  * \brief show mesh elements preventing computation of a submesh of current row
1219  */
1220 //================================================================================
1221
1222 void SMESHGUI_BaseComputeOp::onShowBadMesh()
1223 {
1224   myTShapeDisplayer->SetVisibility( false );
1225   QList<int> rows;
1226   if ( SMESH::getSelectedRows( table(), rows ) == 1 ) {
1227     bool hasBadMesh = ( !table()->item(rows.front(), COL_BAD_MESH)->text().isEmpty() );
1228     if ( hasBadMesh ) {
1229       int curSub = table()->item(rows.front(), COL_SHAPEID)->text().toInt();
1230       SMESHGUI* gui = getSMESHGUI();
1231       SMESH::SMESH_Gen_var gen = gui->GetSMESHGen();
1232       SVTK_ViewWindow*    view = SMESH::GetViewWindow( gui );
1233       if ( myBadMeshDisplayer ) delete myBadMeshDisplayer;
1234       myBadMeshDisplayer = new SMESHGUI_MeshEditPreview( view );
1235       SMESH::MeshPreviewStruct_var aMeshData = gen->GetBadInputElements(myMesh,curSub);
1236       double aPointSize = SMESH::GetFloat("SMESH:node_size",3);
1237       double aLineWidth = SMESH::GetFloat("SMESH:element_width",1);
1238       vtkProperty* prop = vtkProperty::New();
1239       prop->SetLineWidth( aLineWidth * 3 );
1240       prop->SetPointSize( aPointSize * 3 );
1241       prop->SetColor( 250, 0, 250 );
1242       myBadMeshDisplayer->GetActor()->SetProperty( prop );
1243       myBadMeshDisplayer->SetData( aMeshData._retn() );
1244       prop->Delete();
1245     }
1246   }
1247 }
1248
1249 //================================================================================
1250 /*!
1251  * \brief create groups of bad mesh elements preventing computation of a submesh of current row
1252  */
1253 //================================================================================
1254
1255 void SMESHGUI_BaseComputeOp::onGroupOfBadMesh()
1256 {
1257   QList<int> rows;
1258   SMESH::getSelectedRows( table(), rows );
1259   int row;
1260   foreach ( row, rows )
1261   {
1262     bool hasBadMesh = ( !table()->item(row, COL_BAD_MESH)->text().isEmpty() );
1263     if ( hasBadMesh ) {
1264       int     curSub = table()->item(rows.front(), COL_SHAPEID)->text().toInt();
1265       QString grName = table()->item(rows.front(), COL_SHAPE)->text();
1266       if ( grName.isEmpty() ) grName = "bad mesh";
1267       else                    grName = "bad mesh of " + grName;
1268       SMESH::SMESH_Gen_var gen = getSMESHGUI()->GetSMESHGen();
1269       SMESH::ListOfGroups_var groups
1270         ( gen->MakeGroupsOfBadInputElements(myMesh,curSub,grName.toLatin1().data()) );
1271       update( UF_ObjBrowser | UF_Model );
1272       if( LightApp_Application* anApp = dynamic_cast<LightApp_Application*>( application() ))
1273       {
1274         QStringList anEntryList;
1275         for ( size_t i = 0; i < groups->length(); ++i )
1276           if ( _PTR(SObject) so = SMESH::FindSObject( groups[i] ))
1277             anEntryList.append( so->GetID().c_str() );
1278
1279         if ( !anEntryList.isEmpty())
1280           anApp->browseObjects( anEntryList, true, false );
1281       }
1282     }
1283   }
1284 }
1285
1286 //================================================================================
1287 /*!
1288  * \brief SLOT called when a selected cell in table() changed
1289  */
1290 //================================================================================
1291
1292 void SMESHGUI_BaseComputeOp::currentCellChanged()
1293 {
1294   myTShapeDisplayer->SetVisibility( false );
1295   if ( myBadMeshDisplayer )
1296     myBadMeshDisplayer->SetVisibility( false );
1297
1298   bool publishEnable = 0, showEnable = 0, showOnly = 1, hasBadMesh = 0;
1299   QList<int> rows;
1300   int nbSelected = SMESH::getSelectedRows( table(), rows );
1301   int row;
1302   foreach ( row, rows )
1303   {
1304     bool hasData     = ( !table()->item( row, COL_SHAPE )->text().isEmpty() );
1305     bool isPublished = ( !table()->item( row, COL_PUBLISHED )->text().isEmpty() );
1306     if ( hasData && !isPublished )
1307       publishEnable = true;
1308
1309     int curSub = table()->item( row, COL_SHAPEID )->text().toInt();
1310     bool prsReady = myTShapeDisplayer->HasReadyActorsFor( curSub, myMainShape );
1311     if ( prsReady ) {
1312       myTShapeDisplayer->Show( curSub, myMainShape, showOnly );
1313       showOnly = false;
1314     }
1315     else {
1316       showEnable = true;
1317     }
1318
1319     if ( !table()->item(row, COL_BAD_MESH)->text().isEmpty() )
1320       hasBadMesh = true;
1321   }
1322   myCompDlg->myPublishBtn->setEnabled( publishEnable );
1323   myCompDlg->myShowBtn   ->setEnabled( showEnable );
1324   myCompDlg->myBadMeshBtn->setEnabled( hasBadMesh && ( nbSelected == 1 ));
1325   myCompDlg->myBadMeshToGroupBtn->setEnabled( hasBadMesh && ( nbSelected == 1 ));
1326 }
1327
1328 //================================================================================
1329 /*!
1330  * \brief update preview
1331  */
1332 //================================================================================
1333
1334 void SMESHGUI_BaseComputeOp::onPreviewShape()
1335 {
1336   if ( myTShapeDisplayer )
1337   {
1338     SUIT_OverrideCursor aWaitCursor;
1339     QList<int> rows;
1340     SMESH::getSelectedRows( table(), rows );
1341
1342     bool showOnly = true;
1343     int row;
1344     foreach ( row, rows )
1345     {
1346       int curSub = table()->item( row, COL_SHAPEID )->text().toInt();
1347       if ( curSub > 0 ) {
1348         myTShapeDisplayer->Show( curSub, myMainShape, showOnly );
1349         showOnly = false;
1350       }
1351     }
1352     currentCellChanged(); // to update buttons
1353   }
1354 }
1355
1356 //================================================================================
1357 /*!
1358  * \brief Destructor
1359  */
1360 //================================================================================
1361
1362 SMESHGUI_BaseComputeOp::~SMESHGUI_BaseComputeOp()
1363 {
1364   delete myCompDlg;
1365   myCompDlg = 0;
1366   delete myTShapeDisplayer;
1367   if ( myBadMeshDisplayer )
1368     delete myBadMeshDisplayer;
1369 }
1370
1371 //================================================================================
1372 /*!
1373  * \brief Gets dialog of compute operation
1374  * \retval SMESHGUI_ComputeDlg* - pointer to dialog of this operation
1375  */
1376 //================================================================================
1377
1378 SMESHGUI_ComputeDlg* SMESHGUI_BaseComputeOp::computeDlg() const
1379 {
1380   if ( !myCompDlg )
1381   {
1382     SMESHGUI_BaseComputeOp* me = (SMESHGUI_BaseComputeOp*)this;
1383     me->myCompDlg = new SMESHGUI_ComputeDlg( desktop(), false );
1384     // connect signals and slots
1385     connect(myCompDlg->myShowBtn,           SIGNAL (clicked()), SLOT(onPreviewShape()));
1386     connect(myCompDlg->myPublishBtn,        SIGNAL (clicked()), SLOT(onPublishShape()));
1387     connect(myCompDlg->myBadMeshBtn,        SIGNAL (clicked()), SLOT(onShowBadMesh()));
1388     connect(myCompDlg->myBadMeshToGroupBtn, SIGNAL (clicked()), SLOT(onGroupOfBadMesh()));
1389
1390     QTableWidget* aTable = me->table();
1391     connect(aTable, SIGNAL(itemSelectionChanged()), SLOT(currentCellChanged()));
1392     connect(aTable, SIGNAL(currentCellChanged(int,int,int,int)), SLOT(currentCellChanged()));
1393   }
1394   return myCompDlg;
1395 }
1396
1397 //================================================================================
1398 /*!
1399  * \brief returns from compute mesh result dialog
1400  */
1401 //================================================================================
1402
1403 bool SMESHGUI_BaseComputeOp::onApply()
1404 {
1405   return true;
1406 }
1407
1408 //================================================================================
1409 /*!
1410  * \brief Return a table
1411  */
1412 //================================================================================
1413
1414 QTableWidget* SMESHGUI_BaseComputeOp::table()
1415 {
1416   return myCompDlg->myTable;
1417 }
1418
1419
1420 //================================================================================
1421 /*!
1422  * \brief Constructor
1423 */
1424 //================================================================================
1425
1426 SMESHGUI_ComputeOp::SMESHGUI_ComputeOp()
1427  : SMESHGUI_BaseComputeOp()
1428 {
1429 }
1430
1431
1432 //================================================================================
1433 /*!
1434  * \brief Desctructor
1435 */
1436 //================================================================================
1437
1438 SMESHGUI_ComputeOp::~SMESHGUI_ComputeOp()
1439 {
1440 }
1441
1442 //================================================================================
1443 /*!
1444  * \brief perform it's intention action: compute mesh
1445  */
1446 //================================================================================
1447
1448 void SMESHGUI_ComputeOp::startOperation()
1449 {
1450   SMESHGUI_BaseComputeOp::startOperation();
1451   if (myMesh->_is_nil())
1452     return;
1453   computeMesh();
1454 }
1455
1456 //================================================================================
1457 /*!
1458  * \brief check the same operations on the same mesh
1459  */
1460 //================================================================================
1461
1462 bool SMESHGUI_BaseComputeOp::isValid(  SUIT_Operation* theOp  ) const
1463 {
1464   SMESHGUI_BaseComputeOp* baseOp = dynamic_cast<SMESHGUI_BaseComputeOp*>( theOp );
1465   bool ret = true;
1466   if ( !myMesh->_is_nil() && baseOp ) {
1467     SMESH::SMESH_Mesh_var aMesh = baseOp->getMesh();
1468     if ( !aMesh->_is_nil() && aMesh->GetId() == myMesh->GetId() ) ret = false;
1469   }
1470   return ret;
1471 }
1472
1473 //================================================================================
1474 /*!
1475  * \brief Gets dialog of this operation
1476  * \retval LightApp_Dialog* - pointer to dialog of this operation
1477  */
1478 //================================================================================
1479
1480 LightApp_Dialog* SMESHGUI_ComputeOp::dlg() const
1481 {
1482   return computeDlg();
1483 }
1484
1485 //================================================================================
1486 /*!
1487  * \brief Constructor
1488 */
1489 //================================================================================
1490
1491 SMESHGUI_PrecomputeOp::SMESHGUI_PrecomputeOp()
1492  : SMESHGUI_BaseComputeOp(),
1493  myDlg( 0 ),
1494  myOrderMgr( 0 ),
1495  myActiveDlg( 0 ),
1496  myPreviewDisplayer( 0 )
1497 {
1498   myHelpFileName = "constructing_meshes_page.html#preview_mesh_anchor";
1499 }
1500
1501 //================================================================================
1502 /*!
1503  * \brief Destructor
1504  */
1505 //================================================================================
1506
1507 SMESHGUI_PrecomputeOp::~SMESHGUI_PrecomputeOp()
1508 {
1509   delete myDlg;
1510   myDlg = 0;
1511   delete myOrderMgr;
1512   myOrderMgr = 0;
1513   myActiveDlg = 0;
1514   if ( myPreviewDisplayer )
1515     delete myPreviewDisplayer;
1516   myPreviewDisplayer = 0;
1517 }
1518
1519 //================================================================================
1520 /*!
1521  * \brief Gets current dialog of this operation
1522  * \retval LightApp_Dialog* - pointer to dialog of this operation
1523  */
1524 //================================================================================
1525
1526 LightApp_Dialog* SMESHGUI_PrecomputeOp::dlg() const
1527 {
1528   return myActiveDlg;
1529 }
1530
1531 //================================================================================
1532 /*!
1533  * \brief perform it's intention action: prepare data
1534  */
1535 //================================================================================
1536
1537 void SMESHGUI_PrecomputeOp::startOperation()
1538 {
1539   if ( !myDlg )
1540   {
1541     myDlg = new SMESHGUI_PrecomputeDlg( desktop() );
1542     
1543     // connect signals
1544     connect( myDlg, SIGNAL( preview() ), this, SLOT( onPreview() ) );
1545     connect( myDlg, SIGNAL( dlgOk() ), this, SLOT( onCompute() ) );
1546     connect( myDlg, SIGNAL( dlgApply() ), this, SLOT( onCompute() ) );
1547   }
1548   myActiveDlg = myDlg;
1549
1550   // connect signal to compute dialog. which will be shown after Compute mesh operation
1551   SMESHGUI_ComputeDlg* cmpDlg = computeDlg();
1552   if ( cmpDlg )
1553   {
1554     // disconnect signals
1555     disconnect( cmpDlg, SIGNAL( dlgOk() ), this, SLOT( onOk() ) );
1556     disconnect( cmpDlg, SIGNAL( dlgApply() ), this, SLOT( onApply() ) );
1557     disconnect( cmpDlg, SIGNAL( dlgCancel() ), this, SLOT( onCancel() ) );
1558     disconnect( cmpDlg, SIGNAL( dlgClose() ), this, SLOT( onCancel() ) );
1559     disconnect( cmpDlg, SIGNAL( dlgHelp() ), this, SLOT( onHelp() ) );
1560
1561     // connect signals
1562     if( cmpDlg->testButtonFlags( QtxDialog::OK ) )
1563       connect( cmpDlg, SIGNAL( dlgOk() ), this, SLOT( onOk() ) );
1564     if( cmpDlg->testButtonFlags( QtxDialog::Apply ) )
1565       connect( cmpDlg, SIGNAL( dlgApply() ), this, SLOT( onApply() ) );
1566     if( cmpDlg->testButtonFlags( QtxDialog::Help ) )
1567       connect( cmpDlg, SIGNAL( dlgHelp() ), this, SLOT( onHelp() ) );
1568     if( cmpDlg->testButtonFlags( QtxDialog::Cancel ) )
1569       connect( cmpDlg, SIGNAL( dlgCancel() ), this, SLOT( onCancel() ) );
1570     if( cmpDlg->testButtonFlags( QtxDialog::Close ) )
1571       connect( cmpDlg, SIGNAL( dlgClose() ), this, SLOT( onCancel() ) );
1572   }
1573
1574   SMESHGUI_BaseComputeOp::startOperation();
1575   if (myMesh->_is_nil())
1576     return;
1577
1578   if (myDlg->getPreviewMode() == -1)
1579   {
1580     // nothing to preview
1581     SUIT_MessageBox::warning(desktop(),
1582                              tr("SMESH_WRN_WARNING"),
1583                              tr("SMESH_WRN_NOTHING_PREVIEW"));
1584     onCancel();
1585     return;
1586   }
1587
1588   // disconnect slot from preview dialog to have Apply from results of compute operation only 
1589   disconnect( myDlg, SIGNAL( dlgOk() ), this, SLOT( onOk() ) );
1590   disconnect( myDlg, SIGNAL( dlgApply() ), this, SLOT( onApply() ) );
1591
1592   myDlg->show();
1593 }
1594
1595 //================================================================================
1596 /*!
1597  * \brief Stops operation
1598  */
1599 //================================================================================
1600
1601 void SMESHGUI_PrecomputeOp::stopOperation()
1602 {
1603   if ( myPreviewDisplayer )
1604   {
1605     myPreviewDisplayer->SetVisibility( false );
1606     delete myPreviewDisplayer;
1607     myPreviewDisplayer = 0;
1608   }
1609   myMapShapeId.clear();
1610   SMESHGUI_BaseComputeOp::stopOperation();
1611 }
1612
1613 //================================================================================
1614 /*!
1615  * \brief reinitialize dialog after operaiton become active again
1616  */
1617 //================================================================================
1618
1619 void SMESHGUI_PrecomputeOp::resumeOperation()
1620 {
1621   if ( myActiveDlg == myDlg )
1622     initDialog();
1623   SMESHGUI_BaseComputeOp::resumeOperation();
1624 }
1625
1626 //================================================================================
1627 /*!
1628  * \brief perform it's intention action: reinitialise dialog
1629  */
1630 //================================================================================
1631
1632 void SMESHGUI_PrecomputeOp::initDialog()
1633 {
1634   QList<int> modes;
1635
1636   QMap<int, int> modeMap;
1637   _PTR(SObject)  pMesh = studyDS()->FindObjectID( myIObject->getEntry() );
1638   getAssignedAlgos( pMesh, modeMap );
1639   if ( modeMap.contains( SMESH::DIM_3D ) )
1640   {
1641     if ( modeMap.contains( SMESH::DIM_2D ) )
1642       modes.append( SMESH::DIM_2D );
1643     if ( modeMap.contains( SMESH::DIM_1D ) )
1644       modes.append( SMESH::DIM_1D );
1645   }
1646   else if ( modeMap.contains( SMESH::DIM_2D ) )
1647   {
1648     if ( modeMap.contains( SMESH::DIM_1D ) )
1649       modes.append( SMESH::DIM_1D );
1650   }
1651
1652   myOrderMgr = new SMESHGUI_MeshOrderMgr( myDlg->getMeshOrderBox() );
1653   myOrderMgr->SetMesh( myMesh );
1654   bool isOrder = myOrderMgr->GetMeshOrder(myPrevOrder);
1655   myDlg->getMeshOrderBox()->setShown(isOrder);
1656   if ( !isOrder ) {
1657     delete myOrderMgr;
1658     myOrderMgr = 0;
1659   }
1660
1661   myDlg->setPreviewModes( modes );
1662 }
1663
1664 //================================================================================
1665 /*!
1666  * \brief detect asigned mesh algorithms
1667  */
1668 //================================================================================
1669
1670 void SMESHGUI_PrecomputeOp::getAssignedAlgos(_PTR(SObject) theMesh,
1671                                              QMap<int,int>& theModeMap)
1672 {
1673   _PTR(SObject)          aHypRoot;
1674   _PTR(GenericAttribute) anAttr;
1675   int aPart = SMESH::Tag_RefOnAppliedAlgorithms;
1676   if ( theMesh && theMesh->FindSubObject( aPart, aHypRoot ) )
1677   {
1678     _PTR(ChildIterator) anIter =
1679       SMESH::GetActiveStudyDocument()->NewChildIterator( aHypRoot );
1680     for ( ; anIter->More(); anIter->Next() )
1681     {
1682       _PTR(SObject) anObj = anIter->Value();
1683       _PTR(SObject) aRefObj;
1684       if ( anObj->ReferencedObject( aRefObj ) )
1685         anObj = aRefObj;
1686       else
1687         continue;
1688       
1689       if ( anObj->FindAttribute( anAttr, "AttributeName" ) )
1690       {
1691         CORBA::Object_var aVar = _CAST(SObject,anObj)->GetObject();
1692         if ( CORBA::is_nil( aVar ) )
1693           continue;
1694         
1695         for( int dim = SMESH::DIM_1D; dim <= SMESH::DIM_3D; dim++ )
1696         {
1697           SMESH::SMESH_Algo_var algo;
1698           switch(dim) {
1699           case SMESH::DIM_1D: algo = SMESH::SMESH_1D_Algo::_narrow( aVar ); break;
1700           case SMESH::DIM_2D: algo = SMESH::SMESH_2D_Algo::_narrow( aVar ); break;
1701           case SMESH::DIM_3D: algo = SMESH::SMESH_3D_Algo::_narrow( aVar ); break;
1702           default: break;
1703           }
1704           if ( !algo->_is_nil() )
1705             theModeMap[ dim ] = 0;
1706         }
1707       }
1708     }
1709   }
1710 }
1711
1712 //================================================================================
1713 /*!
1714  * \brief perform it's intention action: compute mesh
1715  */
1716 //================================================================================
1717
1718 void SMESHGUI_PrecomputeOp::onCompute()
1719 {
1720   myDlg->hide();
1721   if (myOrderMgr && myOrderMgr->IsOrderChanged())
1722     myOrderMgr->SetMeshOrder();
1723   myMapShapeId.clear();
1724   myActiveDlg = computeDlg();
1725   computeMesh();
1726 }
1727
1728 //================================================================================
1729 /*!
1730  * \brief perform it's intention action: compute mesh
1731  */
1732 //================================================================================
1733
1734 void SMESHGUI_PrecomputeOp::onCancel()
1735 {
1736   QObject* curDlg = sender();
1737   if ( curDlg == computeDlg() && myActiveDlg == myDlg )
1738   {
1739     // return from error messages
1740     myDlg->show();
1741     return;
1742   }
1743
1744   bool isRestoreOrder = false;
1745   if ( myActiveDlg == myDlg  && !myMesh->_is_nil() && myMapShapeId.count() )
1746   {
1747     // ask to remove already computed mesh elements
1748     if ( SUIT_MessageBox::question( desktop(), tr( "SMESH_WARNING" ),
1749                                     tr( "CLEAR_SUBMESH_QUESTION" ),
1750                                     tr( "SMESH_BUT_DELETE" ), tr( "SMESH_BUT_NO" ), 0, 1 ) == 0 )
1751     {
1752       // remove all submeshes for collected shapes
1753       QMap<int,int>::const_iterator it = myMapShapeId.constBegin();
1754       for ( ; it != myMapShapeId.constEnd(); ++it )
1755         myMesh->ClearSubMesh( *it );
1756       isRestoreOrder = true;
1757     }
1758   }
1759
1760   // return previous mesh order
1761   if (myOrderMgr && myOrderMgr->IsOrderChanged()) {
1762     if (!isRestoreOrder)
1763       isRestoreOrder = 
1764         (SUIT_MessageBox::question( desktop(), tr( "SMESH_WARNING" ),
1765                                     tr( "SMESH_REJECT_MESH_ORDER" ),
1766                                     tr( "SMESH_BUT_YES" ), tr( "SMESH_BUT_NO" ), 0, 1 ) == 0);
1767     if (isRestoreOrder)
1768       myOrderMgr->SetMeshOrder(myPrevOrder);
1769   }
1770
1771   delete myOrderMgr;
1772   myOrderMgr = 0;
1773
1774   myMapShapeId.clear();
1775   SMESHGUI_BaseComputeOp::onCancel();
1776 }
1777
1778 //================================================================================
1779 /*!
1780  * \brief perform it's intention action: preview mesh
1781  */
1782 //================================================================================
1783
1784 void SMESHGUI_PrecomputeOp::onPreview()
1785 {
1786   if ( !myDlg || myMesh->_is_nil() || myMainShape->_is_nil() )
1787     return;
1788
1789   _PTR(SObject) aMeshSObj = SMESH::FindSObject(myMesh);
1790   if ( !aMeshSObj )
1791     return;
1792
1793   // set modified submesh priority if any
1794   if (myOrderMgr && myOrderMgr->IsOrderChanged())
1795     myOrderMgr->SetMeshOrder();
1796
1797   // Compute preview of mesh, 
1798   // i.e. compute mesh till indicated dimension
1799   int dim = myDlg->getPreviewMode();
1800   
1801   SMESH::MemoryReserve aMemoryReserve;
1802   
1803   SMESH::compute_error_array_var aCompErrors;
1804   QString                        aHypErrors;
1805
1806   bool computeFailed = true, memoryLack = false;
1807
1808   SMESHGUI_ComputeDlg* aCompDlg = computeDlg();
1809     aCompDlg->myMeshName->setText( aMeshSObj->GetName().c_str() );
1810
1811   SMESHGUI* gui = getSMESHGUI();
1812   SMESH::SMESH_Gen_var gen = gui->GetSMESHGen();
1813   SMESH::algo_error_array_var errors = gen->GetAlgoState(myMesh,myMainShape);
1814   if ( errors->length() > 0 ) {
1815     aHypErrors = SMESH::GetMessageOnAlgoStateErrors( errors.in() );
1816   }
1817
1818   SUIT_OverrideCursor aWaitCursor;
1819
1820   SVTK_ViewWindow*    view = SMESH::GetViewWindow( gui );
1821   if ( myPreviewDisplayer ) delete myPreviewDisplayer;
1822   myPreviewDisplayer = new SMESHGUI_MeshEditPreview( view );
1823   
1824   SMESH::long_array_var aShapesId = new SMESH::long_array();
1825   try {
1826 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
1827     OCC_CATCH_SIGNALS;
1828 #endif
1829       
1830     SMESH::MeshPreviewStruct_var previewData =
1831       gen->Precompute(myMesh, myMainShape, (SMESH::Dimension)dim, aShapesId);
1832
1833     SMESH::MeshPreviewStruct* previewRes = previewData._retn();
1834     if ( previewRes && previewRes->nodesXYZ.length() > 0 )
1835     {
1836       computeFailed = false;
1837       myPreviewDisplayer->SetData( previewRes );
1838       // append shape indeces with computed mesh entities
1839       for ( int i = 0, n = aShapesId->length(); i < n; i++ )
1840         myMapShapeId[ aShapesId[ i ] ] = 0;
1841     }
1842     else
1843       myPreviewDisplayer->SetVisibility(false);
1844   }
1845   catch(const SALOME::SALOME_Exception & S_ex){
1846     memoryLack = true;
1847     myPreviewDisplayer->SetVisibility(false);
1848   }
1849
1850   try {
1851 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
1852     OCC_CATCH_SIGNALS;
1853 #endif
1854     aCompErrors = gen->GetComputeErrors( myMesh, myMainShape );
1855     // check if there are memory problems
1856     for ( int i = 0; (i < aCompErrors->length()) && !memoryLack; ++i )
1857       memoryLack = ( aCompErrors[ i ].code == SMESH::COMPERR_MEMORY_PB );
1858   }
1859   catch(const SALOME::SALOME_Exception & S_ex){
1860     memoryLack = true;
1861   }
1862
1863   if ( memoryLack )
1864     aMemoryReserve.release();
1865
1866   bool noCompError = ( !aCompErrors.operator->() || aCompErrors->length() == 0 );
1867   bool noHypoError = ( aHypErrors.isEmpty() );
1868
1869   SUIT_ResourceMgr* resMgr = SMESH::GetResourceMgr( gui );
1870   int aNotifyMode = resMgr->integerValue( "SMESH", "show_result_notification" );
1871
1872   bool isShowError = true;
1873   switch( aNotifyMode ) {
1874   case 0: // show the mesh computation result dialog NEVER
1875     isShowError = false;
1876     break;
1877   case 1: // show the mesh computation result dialog if there are some errors
1878   default: // show the result dialog after each mesh computation
1879     if ( !computeFailed && !memoryLack && noCompError && noHypoError )
1880       isShowError = false;
1881     break;
1882   }
1883
1884   aWaitCursor.suspend();
1885   // SHOW ERRORS
1886   if ( isShowError )
1887   {
1888     myDlg->hide();
1889     aCompDlg->setWindowTitle(tr( computeFailed ? "SMESH_WRN_COMPUTE_FAILED" : "SMESH_COMPUTE_SUCCEED"));
1890     showComputeResult( memoryLack, noCompError, aCompErrors, noHypoError, aHypErrors );
1891   }
1892 }
1893
1894
1895 //================================================================================
1896 /*!
1897  * \brief Constructor
1898 */
1899 //================================================================================
1900
1901 SMESHGUI_PrecomputeDlg::SMESHGUI_PrecomputeDlg( QWidget* parent )
1902  : SMESHGUI_Dialog( parent, false, false, OK | Cancel | Help ),
1903    myOrderBox(0)
1904 {
1905   setWindowTitle( tr( "CAPTION" ) );
1906
1907   setButtonText( OK, tr( "COMPUTE" ) );
1908   QFrame* main = mainFrame();
1909
1910   QVBoxLayout* layout = new QVBoxLayout( main );
1911
1912   myOrderBox = new SMESHGUI_MeshOrderBox( main );
1913   layout->addWidget(myOrderBox);
1914
1915   QFrame* frame = new QFrame( main );
1916   layout->setMargin(0); layout->setSpacing(0);
1917   layout->addWidget( frame );
1918
1919   QHBoxLayout* frameLay = new QHBoxLayout( frame );
1920   frameLay->setMargin(0); frameLay->setSpacing(SPACING);
1921   
1922   myPreviewMode = new QtxComboBox( frame );
1923   frameLay->addWidget( myPreviewMode );
1924
1925   myPreviewBtn = new QPushButton( tr( "PREVIEW" ), frame );
1926   frameLay->addWidget( myPreviewBtn );
1927
1928   connect( myPreviewBtn, SIGNAL( clicked( bool ) ), this, SIGNAL( preview() ) );
1929 }
1930
1931 //================================================================================
1932 /*!
1933  * \brief Destructor
1934 */
1935 //================================================================================
1936
1937 SMESHGUI_PrecomputeDlg::~SMESHGUI_PrecomputeDlg()
1938 {
1939 }
1940
1941 //================================================================================
1942 /*!
1943  * \brief Sets available preview modes
1944 */
1945 //================================================================================
1946
1947 void SMESHGUI_PrecomputeDlg::setPreviewModes( const QList<int>& theModes )
1948 {
1949   myPreviewMode->clear();
1950   QList<int>::const_iterator it = theModes.constBegin();
1951   for ( int i = 0; it != theModes.constEnd(); ++it, i++ )
1952   {
1953     QString mode = QString( "PREVIEW_%1" ).arg( *it );
1954     myPreviewMode->addItem( tr( mode.toLatin1().data() ) );
1955     myPreviewMode->setId( i, *it );
1956   }
1957   myPreviewBtn->setEnabled( !theModes.isEmpty() );
1958 }
1959
1960 //================================================================================
1961 /*!
1962  * \brief Returns current preview mesh mode
1963 */
1964 //================================================================================
1965
1966 int SMESHGUI_PrecomputeDlg::getPreviewMode() const
1967 {
1968   return myPreviewMode->currentId();
1969 }
1970
1971 //================================================================================
1972 /*!
1973  * \brief Returns current preview mesh mode
1974 */
1975 //================================================================================
1976
1977 SMESHGUI_MeshOrderBox* SMESHGUI_PrecomputeDlg::getMeshOrderBox() const
1978 {
1979   return myOrderBox;
1980 }
1981
1982
1983 //================================================================================
1984 /*!
1985  * \brief Constructor
1986 */
1987 //================================================================================
1988
1989 SMESHGUI_EvaluateOp::SMESHGUI_EvaluateOp()
1990  : SMESHGUI_BaseComputeOp()
1991 {
1992 }
1993
1994
1995 //================================================================================
1996 /*!
1997  * \brief Desctructor
1998 */
1999 //================================================================================
2000
2001 SMESHGUI_EvaluateOp::~SMESHGUI_EvaluateOp()
2002 {
2003 }
2004
2005 //================================================================================
2006 /*!
2007  * \brief perform it's intention action: compute mesh
2008  */
2009 //================================================================================
2010
2011 void SMESHGUI_EvaluateOp::startOperation()
2012 {
2013   SMESHGUI_BaseComputeOp::evaluateDlg();
2014   SMESHGUI_BaseComputeOp::startOperation();
2015   if (myMesh->_is_nil())
2016     return;
2017   evaluateMesh();
2018 }
2019
2020 //================================================================================
2021 /*!
2022  * \brief Gets dialog of this operation
2023  * \retval LightApp_Dialog* - pointer to dialog of this operation
2024  */
2025 //================================================================================
2026
2027 LightApp_Dialog* SMESHGUI_EvaluateOp::dlg() const
2028 {
2029   return evaluateDlg();
2030 }
2031
2032 //================================================================================
2033 /*!
2034  * \brief evaluateMesh()
2035 */
2036 //================================================================================
2037
2038 void SMESHGUI_BaseComputeOp::evaluateMesh()
2039 {
2040   // EVALUATE MESH
2041
2042   SMESH::MemoryReserve aMemoryReserve;
2043
2044   SMESH::compute_error_array_var aCompErrors;
2045   QString                        aHypErrors;
2046
2047   bool evaluateFailed = true, memoryLack = false;
2048   SMESH::long_array_var aRes;
2049
2050   _PTR(SObject) aMeshSObj = SMESH::FindSObject(myMesh);
2051   if ( !aMeshSObj ) //  IPAL21340
2052     return;
2053
2054   bool hasShape = myMesh->HasShapeToMesh();
2055   bool shapeOK = myMainShape->_is_nil() ? !hasShape : hasShape;
2056   if ( shapeOK )
2057   {
2058     myCompDlg->myMeshName->setText( aMeshSObj->GetName().c_str() );
2059     SMESH::SMESH_Gen_var gen = getSMESHGUI()->GetSMESHGen();
2060     SMESH::algo_error_array_var errors = gen->GetAlgoState(myMesh,myMainShape);
2061     if ( errors->length() > 0 ) {
2062       aHypErrors = SMESH::GetMessageOnAlgoStateErrors( errors.in() );
2063     }
2064     SUIT_OverrideCursor aWaitCursor;
2065     try {
2066 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
2067       OCC_CATCH_SIGNALS;
2068 #endif
2069       aRes = gen->Evaluate(myMesh, myMainShape);
2070     }
2071     catch(const SALOME::SALOME_Exception & S_ex){
2072       memoryLack = true;
2073     }
2074
2075     try {
2076 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
2077       OCC_CATCH_SIGNALS;
2078 #endif
2079       aCompErrors = gen->GetComputeErrors( myMesh, myMainShape );
2080     }
2081     catch(const SALOME::SALOME_Exception & S_ex){
2082       memoryLack = true;
2083     }
2084   }
2085
2086   if ( memoryLack )
2087     aMemoryReserve.release();
2088
2089   evaluateFailed =  ( aCompErrors->length() > 0 );
2090   myCompDlg->setWindowTitle(tr( evaluateFailed ? "SMESH_WRN_EVALUATE_FAILED" : "SMESH_EVALUATE_SUCCEED"));
2091
2092   // SHOW ERRORS
2093   
2094   bool noCompError = ( !aCompErrors.operator->() || aCompErrors->length() == 0 );
2095   bool noHypoError = ( aHypErrors.isEmpty() );
2096
2097   //SUIT_ResourceMgr* resMgr = SMESH::GetResourceMgr( SMESHGUI::GetSMESHGUI() );
2098   //int aNotifyMode = resMgr->integerValue( "SMESH", "show_result_notification" );
2099
2100   bool isShowResultDlg = true;
2101   //if( noHypoError )
2102   //switch( aNotifyMode ) {
2103   //case 0: // show the mesh computation result dialog NEVER
2104   //isShowResultDlg = false;
2105   //commit();
2106   //break;
2107   //case 1: // show the mesh computation result dialog if there are some errors
2108   //if ( memoryLack || !noHypoError )
2109   //  isShowResultDlg = true;
2110   //else
2111   //{
2112   //  isShowResultDlg = false;
2113   //  commit();
2114   //}
2115   //break;
2116   //default: // show the result dialog after each mesh computation
2117   //isShowResultDlg = true;
2118   //}
2119
2120   // SHOW RESULTS
2121   if ( isShowResultDlg )
2122     showEvaluateResult( aRes, memoryLack, noCompError, aCompErrors,
2123                         noHypoError, aHypErrors);
2124 }
2125
2126
2127 void SMESHGUI_BaseComputeOp::showEvaluateResult(const SMESH::long_array& theRes,
2128                                                 const bool theMemoryLack,
2129                                                 const bool theNoCompError,
2130                                                 SMESH::compute_error_array_var& theCompErrors,
2131                                                 const bool theNoHypoError,
2132                                                 const QString& theHypErrors)
2133 {
2134   bool hasShape = myMesh->HasShapeToMesh();
2135   SMESHGUI_ComputeDlg* aCompDlg = evaluateDlg();
2136   aCompDlg->myMemoryLackGroup->hide();
2137
2138   if ( theMemoryLack )
2139   {
2140     aCompDlg->myMemoryLackGroup->show();
2141     aCompDlg->myFullInfo->hide();
2142     aCompDlg->myBriefInfo->hide();
2143     aCompDlg->myHypErrorGroup->hide();
2144     aCompDlg->myCompErrorGroup->hide();
2145   }
2146   else if ( theNoCompError && theNoHypoError )
2147   {
2148     aCompDlg->myFullInfo->SetMeshInfo( theRes );
2149     aCompDlg->myFullInfo->show();
2150     aCompDlg->myBriefInfo->hide();
2151     aCompDlg->myHypErrorGroup->hide();
2152     aCompDlg->myCompErrorGroup->hide();
2153   }
2154   else
2155   {
2156     QTableWidget* tbl = aCompDlg->myTable;
2157     aCompDlg->myBriefInfo->SetMeshInfo( theRes );
2158     aCompDlg->myBriefInfo->show();
2159     aCompDlg->myFullInfo->hide();
2160
2161     if ( theNoHypoError ) {
2162       aCompDlg->myHypErrorGroup->hide();
2163     }
2164     else {
2165       aCompDlg->myHypErrorGroup->show();
2166       aCompDlg->myHypErrorLabel->setText( theHypErrors );
2167     }
2168
2169     if ( theNoCompError ) {
2170       aCompDlg->myCompErrorGroup->hide();
2171     }
2172     else {
2173       aCompDlg->myCompErrorGroup->show();
2174
2175       aCompDlg->myPublishBtn->hide();
2176       aCompDlg->myShowBtn->hide();
2177
2178       // fill table of errors
2179       tbl->setRowCount( theCompErrors->length() );
2180       if ( !hasShape ) tbl->hideColumn( COL_SHAPE );
2181       else             tbl->showColumn( COL_SHAPE );
2182       tbl->setColumnWidth( COL_ERROR, 200 );
2183
2184       bool hasBadMesh = false;
2185       for ( int row = 0; row < theCompErrors->length(); ++row )
2186       {
2187         SMESH::ComputeError & err = theCompErrors[ row ];
2188
2189         QString text = err.algoName.in();
2190         if ( !tbl->item( row, COL_ALGO ) ) tbl->setItem( row, COL_ALGO, new QTableWidgetItem( text ) );
2191         else tbl->item( row, COL_ALGO )->setText( text );
2192
2193         text = SMESH::errorText( err.code, err.comment.in() );
2194         if ( !tbl->item( row, COL_ERROR ) ) tbl->setItem( row, COL_ERROR, new QTableWidgetItem( text ) );
2195         else tbl->item( row, COL_ERROR )->setText( text );
2196
2197         text = QString("%1").arg( err.subShapeID );
2198         if ( !tbl->item( row, COL_SHAPEID ) ) tbl->setItem( row, COL_SHAPEID, new QTableWidgetItem( text ) );
2199         else tbl->item( row, COL_SHAPEID )->setText( text );
2200
2201         text = hasShape ? SMESH::shapeText( err.subShapeID, myMainShape ) : QString("");
2202         if ( !tbl->item( row, COL_SHAPE ) ) tbl->setItem( row, COL_SHAPE, new QTableWidgetItem( text ) );
2203         else tbl->item( row, COL_SHAPE )->setText( text );
2204
2205         text = ( !hasShape || SMESH::getSubShapeSO( err.subShapeID, myMainShape )) ? "PUBLISHED" : "";
2206         if ( !tbl->item( row, COL_PUBLISHED ) ) tbl->setItem( row, COL_PUBLISHED, new QTableWidgetItem( text ) );
2207         else tbl->item( row, COL_PUBLISHED )->setText( text ); // if text=="", "PUBLISH" button enabled
2208
2209         text = err.hasBadMesh ? "hasBadMesh" : "";
2210         if ( !tbl->item( row, COL_BAD_MESH ) ) tbl->setItem( row, COL_BAD_MESH, new QTableWidgetItem( text ) );
2211         else tbl->item( row, COL_BAD_MESH )->setText( text );
2212         if ( err.hasBadMesh ) hasBadMesh = true;
2213
2214         //tbl->item( row, COL_ERROR )->setWordWrap( true ); // VSR: TODO ???
2215         tbl->resizeRowToContents( row );
2216       }
2217       tbl->resizeColumnToContents( COL_ALGO );
2218       tbl->resizeColumnToContents( COL_SHAPE );
2219       tbl->setWordWrap( true );
2220
2221       if ( hasBadMesh )
2222       {
2223         aCompDlg->myBadMeshBtn->show();
2224         aCompDlg->myBadMeshToGroupBtn->show();
2225       }
2226       else
2227       {
2228         aCompDlg->myBadMeshBtn->hide();
2229         aCompDlg->myBadMeshToGroupBtn->hide();
2230       }
2231       tbl->setCurrentCell(0,0);
2232       currentCellChanged(); // to update buttons
2233     }
2234   }
2235   // show dialog and wait, becase Compute can be invoked from Preview operation
2236   //aCompDlg->exec(); // this way it becomes modal - impossible to rotate model in the Viewer
2237   aCompDlg->show();
2238 }
2239
2240
2241 //================================================================================
2242 /*!
2243  * \brief Gets dialog of evaluate operation
2244  * \retval SMESHGUI_ComputeDlg* - pointer to dialog of this operation
2245  */
2246 //================================================================================
2247
2248 SMESHGUI_ComputeDlg* SMESHGUI_BaseComputeOp::evaluateDlg() const
2249 {
2250   if ( !myCompDlg )
2251   {
2252     SMESHGUI_BaseComputeOp* me = (SMESHGUI_BaseComputeOp*)this;
2253     me->myCompDlg = new SMESHGUI_ComputeDlg( desktop(), true );
2254     // connect signals and slots
2255     connect(myCompDlg->myShowBtn,    SIGNAL (clicked()), SLOT(onPreviewShape()));
2256     connect(myCompDlg->myPublishBtn, SIGNAL (clicked()), SLOT(onPublishShape()));
2257     connect(myCompDlg->myBadMeshBtn, SIGNAL (clicked()), SLOT(onShowBadMesh()));
2258     QTableWidget* aTable = me->table();
2259     connect(aTable, SIGNAL(itemSelectionChanged()), SLOT(currentCellChanged()));
2260     connect(aTable, SIGNAL(currentCellChanged(int,int,int,int)), SLOT(currentCellChanged()));
2261   }
2262   return myCompDlg;
2263 }
2264