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