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