Salome HOME
Debug
[modules/smesh.git] / src / SMESHGUI / SMESHGUI_MeshPatternDlg.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 // SMESH SMESHGUI : GUI for SMESH component
23 // File   : SMESHGUI_MeshPatternDlg.cxx
24 // Author : Sergey LITONIN, Open CASCADE S.A.S.
25 // SMESH includes
26 //
27 #include "SMESHGUI_MeshPatternDlg.h"
28
29 #include "SMESHGUI.h"
30 #include "SMESHGUI_CreatePatternDlg.h"
31 #include "SMESHGUI_PatternWidget.h"
32 #include "SMESHGUI_Utils.h"
33 #include "SMESHGUI_VTKUtils.h"
34 #include "SMESHGUI_PatternUtils.h"
35 #include "SMESHGUI_GEOMGenUtils.h"
36
37 #include <SMESH_Actor.h>
38 #include <SMESH_ActorUtils.h>
39 #include <SMESH_NumberFilter.hxx>
40
41 #include <SMDS_Mesh.hxx>
42 #include <SMDS_MeshElement.hxx>
43
44 // SALOME GUI includes
45 #include <SUIT_ResourceMgr.h>
46 #include <SUIT_Desktop.h>
47 #include <SUIT_FileDlg.h>
48 #include <SUIT_Session.h>
49 #include <SUIT_MessageBox.h>
50
51 #include <LightApp_SelectionMgr.h>
52 #include <SalomeApp_Notebook.h>
53 #include <SalomeApp_Tools.h>
54 #include <LightApp_Application.h>
55 #include <SalomeApp_IntSpinBox.h>
56
57 #include <SALOME_ListIO.hxx>
58
59 #include <SVTK_ViewModel.h>
60 #include <SVTK_ViewWindow.h>
61 #include <VTKViewer_CellLocationsArray.h>
62
63 // SALOME KERNEL includes 
64 #include <SALOMEDS_SObject.hxx>
65
66 // OCCT includes
67 #include <TColStd_MapOfInteger.hxx>
68
69 // Qt includes
70 #include <QFrame>
71 #include <QVBoxLayout>
72 #include <QHBoxLayout>
73 #include <QGridLayout>
74 #include <QLineEdit>
75 #include <QPushButton>
76 #include <QGroupBox>
77 #include <QLabel>
78 #include <QRadioButton>
79 #include <QCheckBox>
80 #include <QButtonGroup>
81 #include <QList>
82 #include <QDir>
83 #include <QFileDialog>
84 #include <QFileInfo>
85 #include <QFile>
86 #include <QKeyEvent>
87
88 // VTK includes
89 #include <vtkIdList.h>
90 #include <vtkCellArray.h>
91 #include <vtkUnsignedCharArray.h>
92 #include <vtkUnstructuredGrid.h>
93 #include <vtkDataSetMapper.h>
94 #include <vtkProperty.h>
95
96 #define SPACING 6
97 #define MARGIN  11
98
99 /*!
100  *  Class       : SMESHGUI_MeshPatternDlg
101  *  Description : Dialog to specify filters for VTK viewer
102  */
103
104 //=======================================================================
105 // name    : SMESHGUI_MeshPatternDlg::SMESHGUI_MeshPatternDlg
106 // Purpose : Constructor
107 //=======================================================================
108 SMESHGUI_MeshPatternDlg::SMESHGUI_MeshPatternDlg( SMESHGUI* theModule )
109   : QDialog( SMESH::GetDesktop( theModule ) ),
110     SMESHGUI_Helper( theModule ),
111     mySMESHGUI( theModule ),
112     mySelectionMgr( SMESH::GetSelectionMgr( theModule ) ),
113     myBusy( false ),
114     myCreationDlg( 0 )
115 {
116   setModal( false );
117   setWindowTitle( tr( "CAPTION" ) );
118
119   QVBoxLayout* aDlgLay = new QVBoxLayout( this );
120   aDlgLay->setMargin( MARGIN );
121   aDlgLay->setSpacing( SPACING );
122
123   QWidget* aMainFrame = createMainFrame  ( this );
124   QWidget* aBtnFrame  = createButtonFrame( this );
125
126   aDlgLay->addWidget( aMainFrame );
127   aDlgLay->addWidget( aBtnFrame );
128
129   aDlgLay->setStretchFactor( aMainFrame, 1 );
130
131   mySelector = (SMESH::GetViewWindow( mySMESHGUI ))->GetSelector();
132
133   myHelpFileName = "pattern_mapping_page.html";
134
135   Init();
136 }
137
138 //=======================================================================
139 // name    : SMESHGUI_MeshPatternDlg::createMainFrame
140 // Purpose : Create frame containing dialog's input fields
141 //=======================================================================
142 QWidget* SMESHGUI_MeshPatternDlg::createMainFrame (QWidget* theParent)
143 {
144   SUIT_ResourceMgr* mgr = SMESH::GetResourceMgr( mySMESHGUI );
145   QPixmap iconSlct ( mgr->loadPixmap( "SMESH", tr( "ICON_SELECT" ) ) );
146   QPixmap icon2d   ( mgr->loadPixmap( "SMESH", tr( "ICON_PATTERN_2d" ) ) );
147   QPixmap icon3d   ( mgr->loadPixmap( "SMESH", tr( "ICON_PATTERN_3d" ) ) );
148   QPixmap iconOpen ( mgr->loadPixmap( "STD",   tr( "ICON_FILE_OPEN" ) ) );
149
150   QPixmap iconSample2d ( mgr->loadPixmap( "SMESH", tr( "ICON_PATTERN_SAMPLE_2D" ) ) );
151   QPixmap iconSample3d ( mgr->loadPixmap( "SMESH", tr( "ICON_PATTERN_SAMPLE_3D" ) ) );
152
153   QWidget* aMainGrp = new QWidget( theParent );
154
155   QVBoxLayout* aMainGrpLayout = new QVBoxLayout( aMainGrp );
156   aMainGrpLayout->setMargin( 0 );
157   aMainGrpLayout->setSpacing( SPACING );
158
159   // Pattern type group
160
161   QGroupBox* aTypeGrp = new QGroupBox( tr( "PATTERN_TYPE" ), aMainGrp );
162   QHBoxLayout* aTypeGrpLayout = new QHBoxLayout( aTypeGrp );
163   aTypeGrpLayout->setMargin( MARGIN );
164   aTypeGrpLayout->setSpacing( SPACING );
165
166   mySwitch2d = new QRadioButton( aTypeGrp );
167   mySwitch3d = new QRadioButton( aTypeGrp );
168   mySwitch2d->setIcon( icon2d );
169   mySwitch3d->setIcon( icon3d );
170
171   myTypeGrp = new QButtonGroup( aMainGrp );
172   myTypeGrp->addButton( mySwitch2d, Type_2d );
173   myTypeGrp->addButton( mySwitch3d, Type_3d );
174
175   // ... layout widgets
176
177   aTypeGrpLayout->addWidget( mySwitch2d );
178   aTypeGrpLayout->addWidget( mySwitch3d );
179
180   // Mesh group
181
182   QGroupBox* aMeshGrp = new QGroupBox( tr( "SMESH_MESH" ), aMainGrp );
183   QHBoxLayout* aMeshGrpLayout = new QHBoxLayout( aMeshGrp );
184   aMeshGrpLayout->setMargin( MARGIN );
185   aMeshGrpLayout->setSpacing( SPACING );
186
187   QLabel* aMeshLab = new QLabel( tr( "SMESH_MESH" ), aMeshGrp );
188   mySelBtn[ Mesh ] = new QPushButton( aMeshGrp );
189   mySelBtn[ Mesh ]->setIcon( iconSlct );
190   mySelEdit[ Mesh ] = new QLineEdit( aMeshGrp );
191   mySelEdit[ Mesh ]->setReadOnly( true );
192
193   // ... layout widgets
194
195   aMeshGrpLayout->addWidget( aMeshLab );
196   aMeshGrpLayout->addWidget( mySelBtn[ Mesh ] );
197   aMeshGrpLayout->addWidget( mySelEdit[ Mesh ] );
198
199   // Pattern group
200
201   QGroupBox* aPatGrp = new QGroupBox( tr( "PATTERN" ), aMainGrp );
202   QGridLayout* aPatGrpLayout = new QGridLayout( aPatGrp );
203   aPatGrpLayout->setMargin( MARGIN );
204   aPatGrpLayout->setSpacing( SPACING );
205
206   // ... Pattern name
207
208   QLabel* aNameLab = new QLabel( tr( "PATTERN" ), aPatGrp );
209   myName = new QLineEdit( aPatGrp );
210   myName->setReadOnly( true );
211   myOpenBtn = new QPushButton( aPatGrp );
212   myOpenBtn->setIcon( iconOpen );
213   myNewBtn = new QPushButton( tr( "NEW" ), aPatGrp );
214
215   // ... Mode selection check box
216   myRefine = new QCheckBox( tr( "REFINE" ), aPatGrp );
217
218   // ... selection widgets for Apply to geom mode
219   myGeomGrp = new QFrame( aPatGrp );
220   myGeomGrp->setFrameStyle( QFrame::NoFrame );
221   QGridLayout* myGeomGrpLayout = new QGridLayout( myGeomGrp );
222   myGeomGrpLayout->setMargin( 0 );
223   myGeomGrpLayout->setSpacing( SPACING );
224
225   for ( int i = Object; i <= Vertex2; i++ ) {
226     mySelLbl[ i ] = new QLabel( myGeomGrp );
227     mySelBtn[ i ] = new QPushButton( myGeomGrp );
228     mySelBtn[ i ]->setIcon( iconSlct );
229     mySelEdit[ i ] = new QLineEdit( myGeomGrp );
230     mySelEdit[ i ]->setReadOnly( true );
231     myGeomGrpLayout->addWidget( mySelLbl[ i ],  i - Object, 0 );
232     myGeomGrpLayout->addWidget( mySelBtn[ i ],  i - Object, 1 );
233     myGeomGrpLayout->addWidget( mySelEdit[ i ], i - Object, 2 );
234   }
235
236   // ... Widgets for refinement of existing mesh elements
237
238   myRefineGrp = new QFrame( aPatGrp );
239   myRefineGrp->setFrameStyle( QFrame::NoFrame );
240
241   QGridLayout* myRefineGrpLayout = new QGridLayout( myRefineGrp );
242   myRefineGrpLayout->setMargin( 0 );
243   myRefineGrpLayout->setSpacing( SPACING );
244
245   mySelLbl[ Ids ] = new QLabel( myRefineGrp );
246   mySelBtn[ Ids ] = new QPushButton( myRefineGrp );
247   mySelBtn[ Ids ]->setIcon( iconSlct );
248   mySelEdit[ Ids ] = new QLineEdit( myRefineGrp );
249
250   QLabel* aNodeLbl = new QLabel( tr( "NODE_1" ), myRefineGrp );
251   myNode1          = new SalomeApp_IntSpinBox( myRefineGrp );
252   myNode2Lbl       = new QLabel( tr( "NODE_2" ), myRefineGrp );
253   myNode2          = new SalomeApp_IntSpinBox( myRefineGrp );
254
255   myRefineGrpLayout->addWidget( mySelLbl[ Ids ],  0, 0 );
256   myRefineGrpLayout->addWidget( mySelBtn[ Ids ],  0, 1 );
257   myRefineGrpLayout->addWidget( mySelEdit[ Ids ], 0, 2 );
258   myRefineGrpLayout->addWidget( aNodeLbl,         1, 0 );
259   myRefineGrpLayout->addWidget( myNode1,          1, 1, 1, 2 );
260   myRefineGrpLayout->addWidget( myNode2Lbl,       2, 0 );
261   myRefineGrpLayout->addWidget( myNode2,          2, 1, 1, 2 );
262
263   // ... reverse check box
264   myReverseChk = new QCheckBox( tr( "REVERSE" ), aPatGrp );
265
266   // ... CreatePoly check box
267   myCreatePolygonsChk = new QCheckBox( tr( "CREATE_POLYGONS_NEAR_BOUNDARY" ), aPatGrp );
268   myCreatePolyedrsChk = new QCheckBox( tr( "CREATE_POLYEDRS_NEAR_BOUNDARY" ), aPatGrp );
269
270   // ... Pictures 2d and 3d
271
272   myPicture2d = new SMESHGUI_PatternWidget( aPatGrp );
273   myPicture2d->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) );
274
275   myPicture3d = new QLabel( aPatGrp );
276   myPicture3d->setPixmap( iconSample3d );
277   myPicture3d->setScaledContents( false );
278   myPicture3d->setAlignment( Qt::AlignCenter );
279   myPicture3d->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) );
280
281   // ... preview check box
282
283   myPreviewChk = new QCheckBox( tr( "PREVIEW" ), aPatGrp );
284
285   // ... layout widgets 
286
287   aPatGrpLayout->addWidget( aNameLab,            0, 0 );
288   aPatGrpLayout->addWidget( myName,              0, 1 );
289   aPatGrpLayout->addWidget( myOpenBtn,           0, 2 );
290   aPatGrpLayout->addWidget( myNewBtn,            0, 3 );
291   aPatGrpLayout->addWidget( myRefine,            1, 0, 1, 4 );
292   aPatGrpLayout->addWidget( myRefine,            1, 0, 1, 4 );
293   aPatGrpLayout->addWidget( myGeomGrp,           2, 0, 1, 4 );
294   aPatGrpLayout->addWidget( myRefineGrp,         3, 0, 1, 4 );
295   aPatGrpLayout->addWidget( myReverseChk,        4, 0, 1, 4 );
296   aPatGrpLayout->addWidget( myCreatePolygonsChk, 5, 0, 1, 4 );
297   aPatGrpLayout->addWidget( myCreatePolyedrsChk, 6, 0, 1, 4 );
298   aPatGrpLayout->addWidget( myPicture2d,         7, 0, 1, 4 );
299   aPatGrpLayout->addWidget( myPicture3d,         8, 0, 1, 4 );
300   aPatGrpLayout->addWidget( myPreviewChk,        9, 0, 1, 4 );
301
302   // main layout
303   
304   aMainGrpLayout->addWidget( aTypeGrp );
305   aMainGrpLayout->addWidget( aMeshGrp );
306   aMainGrpLayout->addWidget( aPatGrp );
307
308   // Connect signals and slots
309
310   connect(myTypeGrp, SIGNAL(buttonClicked(int)), SLOT(onTypeChanged(int)));
311   connect(myOpenBtn, SIGNAL(clicked()),    SLOT(onOpen()));
312   connect(myNewBtn,  SIGNAL(clicked()),    SLOT(onNew()));
313
314   connect(myReverseChk, SIGNAL(toggled(bool)), SLOT(onReverse(bool)));
315   connect(myPreviewChk, SIGNAL(toggled(bool)), SLOT(onPreview(bool)));
316   connect(myRefine,     SIGNAL(toggled(bool)), SLOT(onModeToggled(bool)));
317
318   connect(myNode1, SIGNAL(valueChanged(int)), SLOT(onNodeChanged(int)));
319   connect(myNode2, SIGNAL(valueChanged(int)), SLOT(onNodeChanged(int)));
320
321   connect(mySelEdit[Ids], SIGNAL(textChanged(const QString&)), SLOT(onTextChanged(const QString&)));
322
323   QMap< int, QPushButton* >::iterator anIter;
324   for (anIter = mySelBtn.begin(); anIter != mySelBtn.end(); ++anIter)
325     connect(*anIter, SIGNAL(clicked()), SLOT(onSelInputChanged()));
326
327   return aMainGrp;
328 }
329
330 //=======================================================================
331 // name    : SMESHGUI_MeshPatternDlg::createButtonFrame
332 // Purpose : Create frame containing buttons
333 //=======================================================================
334 QWidget* SMESHGUI_MeshPatternDlg::createButtonFrame (QWidget* theParent)
335 {
336   QFrame* aFrame = new QFrame(theParent);
337   aFrame->setFrameStyle(QFrame::Box | QFrame::Sunken);
338
339   myOkBtn     = new QPushButton(tr("SMESH_BUT_APPLY_AND_CLOSE"), aFrame);
340   myApplyBtn  = new QPushButton(tr("SMESH_BUT_APPLY"), aFrame);
341   myCloseBtn  = new QPushButton(tr("SMESH_BUT_CLOSE"), aFrame);
342   myHelpBtn   = new QPushButton(tr("SMESH_BUT_HELP"),  aFrame);
343
344   QHBoxLayout* aLay = new QHBoxLayout( aFrame );
345   aLay->setMargin( MARGIN );
346   aLay->setSpacing( SPACING );
347
348   aLay->addWidget(myOkBtn);
349   aLay->addWidget(myApplyBtn);
350   aLay->addSpacing( 10 );
351   aLay->addStretch();
352   aLay->addWidget(myCloseBtn);
353   aLay->addWidget(myHelpBtn);
354
355   connect(myOkBtn,    SIGNAL(clicked()), SLOT(onOk()));
356   connect(myCloseBtn, SIGNAL(clicked()), SLOT(onClose()));
357   connect(myApplyBtn, SIGNAL(clicked()), SLOT(onApply()));
358   connect(myHelpBtn,  SIGNAL(clicked()), SLOT(onHelp()));
359
360   return aFrame;
361 }
362
363 //=======================================================================
364 // name    : SMESHGUI_MeshPatternDlg::~SMESHGUI_MeshPatternDlg
365 // Purpose : Destructor
366 //=======================================================================
367 SMESHGUI_MeshPatternDlg::~SMESHGUI_MeshPatternDlg()
368 {
369 }
370
371 //=======================================================================
372 // name    : SMESHGUI_MeshPatternDlg::Init
373 // Purpose : Init dialog fields, connect signals and slots, show dialog
374 //=======================================================================
375 void SMESHGUI_MeshPatternDlg::Init()
376 {
377   myPattern = SMESH::GetPattern();
378   myPreviewActor = 0;
379   myIsCreateDlgOpen = false;
380   mySelInput = Mesh;
381   myType = -1;
382   myNbPoints = -1;
383   mySMESHGUI->SetActiveDialogBox((QDialog*)this);
384   myMesh = SMESH::SMESH_Mesh::_nil();
385
386   myMeshShape = GEOM::GEOM_Object::_nil();
387   myGeomObj[ Object  ] = GEOM::GEOM_Object::_nil();
388   myGeomObj[ Vertex1 ] = GEOM::GEOM_Object::_nil();
389   myGeomObj[ Vertex2 ] = GEOM::GEOM_Object::_nil();
390
391   // selection and SMESHGUI
392   connect(mySelectionMgr, SIGNAL(currentSelectionChanged()), SLOT(onSelectionDone()));
393   connect(mySMESHGUI, SIGNAL(SignalDeactivateActiveDialog()), SLOT(onDeactivate()));
394   connect(mySMESHGUI, SIGNAL(SignalCloseAllDialogs()), SLOT(onClose()));
395
396   myTypeGrp->button(Type_2d)->setChecked(true);
397   onTypeChanged(Type_2d);
398   onModeToggled(isRefine());
399
400   updateGeometry();
401
402   resize(100,100);
403
404   activateSelection();
405   onSelectionDone();
406
407   this->show();
408 }
409
410 //=======================================================================
411 // name    : SMESHGUI_MeshPatternDlg::isValid
412 // Purpose : Verify validity of entry data
413 //=======================================================================
414 bool SMESHGUI_MeshPatternDlg::isValid (const bool theMess)
415 {
416   if (isRefine())
417   {
418     QList<QAbstractSpinBox*> aSpinBoxList;
419     aSpinBoxList << myNode1;
420     if( myType == Type_3d )
421       aSpinBoxList << myNode2;
422     if( !checkParameters( theMess, aSpinBoxList ) )
423       return false;
424   }
425
426   QList<int> ids;
427   if ((isRefine() &&
428        (myMesh->_is_nil() || !getIds(ids) || getNode(false) < 0 ||
429         myType == Type_3d && (getNode(true) < 0 || getNode(false) == getNode(true))))
430       ||
431       (!isRefine() &&
432        (myMesh->_is_nil() || myMeshShape->_is_nil() || myGeomObj[ Object ]->_is_nil() ||
433         myGeomObj[ Vertex1 ]->_is_nil() || myType == Type_3d && myGeomObj[ Vertex2 ]->_is_nil())))
434   {
435     if (theMess)
436       SUIT_MessageBox::information(this, tr("SMESH_INSUFFICIENT_DATA"),
437                                    tr("SMESHGUI_INVALID_PARAMETERS"));
438     return false;
439   }
440
441   if ( myName->text().isEmpty() ) {
442     if (theMess)
443       SUIT_MessageBox::information(this, tr("SMESH_INSUFFICIENT_DATA"),
444                                    tr("SMESHGUI_INVALID_PARAMETERS"));
445     return false;
446   }
447
448   return true;
449 }
450
451 //=======================================================================
452 // name    : SMESHGUI_MeshPatternDlg::onApply
453 // Purpose : SLOT called when "Apply" button pressed.
454 //=======================================================================
455 bool SMESHGUI_MeshPatternDlg::onApply()
456 {
457   try {
458     if (!isValid())
459       return false;
460
461     erasePreview();
462
463     if (isRefine()) { // Refining existing mesh elements
464       QList<int> ids;
465       getIds(ids);
466       SMESH::long_array_var varIds = new SMESH::long_array();
467       varIds->length(ids.count());
468       int i = 0;
469       for (QList<int>::iterator it = ids.begin(); it != ids.end(); ++it)
470         varIds[i++] = *it;
471       myType == Type_2d
472         ? myPattern->ApplyToMeshFaces  (myMesh, varIds, getNode(false), myReverseChk->isChecked())
473         : myPattern->ApplyToHexahedrons(myMesh, varIds, getNode(false), getNode(true));
474
475       QStringList aParameters;
476       aParameters << myNode1->text();
477       if(myType == Type_3d )
478         aParameters << myNode2->text();
479       getNotebook()->setParameters( myMesh, aParameters );
480
481     } else { // Applying a pattern to geometrical object
482       if (myType == Type_2d)
483         myPattern->ApplyToFace(myGeomObj[Object], myGeomObj[Vertex1], myReverseChk->isChecked());
484       else
485         myPattern->ApplyTo3DBlock(myGeomObj[Object], myGeomObj[Vertex1], myGeomObj[Vertex2]);
486     }
487
488     bool toCreatePolygons = myCreatePolygonsChk->isChecked();
489     bool toCreatePolyedrs = myCreatePolyedrsChk->isChecked();
490     if ( myPattern->MakeMesh( myMesh, toCreatePolygons, toCreatePolyedrs ) ) {
491       //mySelectionMgr->clearSelected();
492       bool autoUpdate = SMESHGUI::automaticUpdate();
493       if (!isRefine() && autoUpdate) {
494         _PTR(SObject) aSO = SMESH::FindSObject(myMesh.in());
495         SMESH_Actor* anActor = SMESH::FindActorByEntry(aSO->GetID().c_str());
496         if (!anActor) {
497           anActor = SMESH::CreateActor(aSO->GetStudy(), aSO->GetID().c_str());
498           if (anActor) {
499             SMESH::DisplayActor(SMESH::GetActiveWindow(), anActor);
500             SMESH::FitAll();
501           }
502         }
503       }
504       mySelectionMgr->clearSelected();
505       SMESH::UpdateView();
506
507       mySMESHGUI->updateObjBrowser(true);
508
509       mySelEdit[ Ids ]->setText("");
510
511       return true;
512     } else {
513       SUIT_MessageBox::information(this, tr("SMESH_ERROR"),
514                                    tr("SMESH_OPERATION_FAILED"));
515       return false;
516     }
517   } catch (const SALOME::SALOME_Exception& S_ex) {
518     SalomeApp_Tools::QtCatchCorbaException(S_ex);
519   } catch (...) {
520   }
521
522   return false;
523 }
524
525 //=======================================================================
526 // name    : SMESHGUI_MeshPatternDlg::onOk
527 // Purpose : SLOT called when "Ok" button pressed.
528 //=======================================================================
529 void SMESHGUI_MeshPatternDlg::onOk()
530 {
531   if (onApply())
532     onClose();
533 }
534
535 //=======================================================================
536 // name    : SMESHGUI_MeshPatternDlg::onClose
537 // Purpose : SLOT called when "Close" button pressed. Close dialog
538 //=======================================================================
539 void SMESHGUI_MeshPatternDlg::onClose()
540 {
541   mySelectionMgr->clearFilters();
542   SMESH::SetPickable();
543   if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
544     aViewWindow->SetSelectionMode(ActorSelection);
545   disconnect(mySelectionMgr, 0, this, 0);
546   disconnect(mySMESHGUI, 0, this, 0);
547   mySMESHGUI->ResetState();
548   erasePreview();
549   reject();
550 }
551
552 //=================================================================================
553 // function : onHelp()
554 // purpose  :
555 //=================================================================================
556 void SMESHGUI_MeshPatternDlg::onHelp()
557 {
558   LightApp_Application* app = (LightApp_Application*)(SUIT_Session::session()->activeApplication());
559   if (app) 
560     app->onHelpContextModule(mySMESHGUI ? app->moduleName(mySMESHGUI->moduleName()) : QString(""), myHelpFileName);
561   else {
562                 QString platform;
563 #ifdef WIN32
564                 platform = "winapplication";
565 #else
566                 platform = "application";
567 #endif
568     SUIT_MessageBox::warning(this, tr("WRN_WARNING"),
569                              tr("EXTERNAL_BROWSER_CANNOT_SHOW_PAGE").
570                              arg(app->resourceMgr()->stringValue("ExternalBrowser", 
571                                                                  platform)).
572                              arg(myHelpFileName));
573   }
574 }
575
576 //=======================================================================
577 // name    : SMESHGUI_MeshPatternDlg::onSelectionDone
578 // Purpose : SLOT called when selection changed
579 //=======================================================================
580 void SMESHGUI_MeshPatternDlg::onSelectionDone()
581 {
582   if (myBusy)
583     return;
584
585   try {
586     if (mySelInput == Mesh) {
587       SALOME_ListIO aList;
588       mySelectionMgr->selectedObjects(aList,SVTK_Viewer::Type());
589       if (aList.Extent() != 1)
590         return;
591
592       // Retrieve mesh from selection
593       Handle(SALOME_InteractiveObject) anIO = aList.First();
594       SMESH::SMESH_Mesh_var aMesh = SMESH::IObjectToInterface<SMESH::SMESH_Mesh>(anIO);
595       if (aMesh->_is_nil())
596         return;
597
598       // Get geom object corresponding to the mesh
599       _PTR(SObject) aSO = SMESH::FindSObject(aMesh.in());
600       myMeshShape = SMESH::GetGeom(aSO);
601
602       // Clear fields of geom objects if mesh was changed
603       if (myMesh != aMesh) {
604         for (int i = Object; i <= Ids; i++) {
605           myGeomObj[ i ] = GEOM::GEOM_Object::_nil();
606           mySelEdit[ i ]->setText("");
607         }
608       }
609
610       myMesh = aMesh;
611
612       // Set name of mesh in line edit
613       QString aName;
614       SMESH::GetNameOfSelectedIObjects(mySelectionMgr, aName);
615       mySelEdit[ Mesh ]->setText(aName);
616
617     } else if (mySelInput == Ids) {
618       SALOME_ListIO aList;
619       mySelectionMgr->selectedObjects(aList,SVTK_Viewer::Type());
620       if (aList.Extent() != 1)
621         return;
622
623       QString anIds;
624       if (!SMESH::GetNameOfSelectedElements(mySelector, aList.First(), anIds))
625         anIds = "";
626
627       myBusy = true;
628       mySelEdit[ Ids ]->setText(anIds);
629       myBusy = false;
630
631     } else {
632       SALOME_ListIO aList;
633       mySelectionMgr->selectedObjects(aList, SVTK_Viewer::Type());
634       if (aList.Extent() != 1)
635         return;
636
637       // Get geom object from selection
638       Handle(SALOME_InteractiveObject) anIO = aList.First();
639       GEOM::GEOM_Object_var anObj = SMESH::IObjectToInterface<GEOM::GEOM_Object>(anIO);
640       if (anObj->_is_nil())
641         return;
642
643       // Clear fields of vertexes if face or 3d block was changed
644       if (anObj != myGeomObj[ mySelInput ] && mySelInput == Object) {
645         for (int i = Vertex1; i <= Vertex2; i++) {
646           myGeomObj[ i ] = GEOM::GEOM_Object::_nil();
647           mySelEdit[ i ]->setText("");
648         }
649       }
650
651       myGeomObj[ mySelInput ] = anObj;
652
653       // Set name of geom object in line edit
654       QString aName;
655       SMESH::GetNameOfSelectedIObjects(mySelectionMgr, aName);
656       mySelEdit[ mySelInput ]->setText(aName);
657     }
658   } catch (const SALOME::SALOME_Exception& S_ex) {
659     SalomeApp_Tools::QtCatchCorbaException(S_ex);
660     resetSelInput();
661   } catch (...) {
662     resetSelInput();
663   }
664
665   updateWgState();
666   displayPreview();
667 }
668
669 //=======================================================================
670 // name    : SMESHGUI_MeshPatternDlg::resetSelInput
671 // Purpose : Reset fields corresponding to the current selection input
672 //=======================================================================
673 void SMESHGUI_MeshPatternDlg::resetSelInput()
674 {
675   if (mySelInput == Mesh)
676   {
677     myMesh = SMESH::SMESH_Mesh::_nil();
678     myMeshShape = GEOM::GEOM_Object::_nil();
679   }
680
681   else
682     myGeomObj[ mySelInput ] = GEOM::GEOM_Object::_nil();
683
684   mySelEdit[ mySelInput ]->setText("");
685 }
686
687 //=======================================================================
688 // name    : SMESHGUI_MeshPatternDlg::onDeactivate
689 // Purpose : SLOT called when dialog must be deativated
690 //=======================================================================
691 void SMESHGUI_MeshPatternDlg::onDeactivate()
692 {
693   mySelectionMgr->clearFilters();
694   //if (myReverseChk->isChecked())
695   //  erasePreview();
696   disconnect(mySelectionMgr, 0, this, 0);
697   setEnabled(false);
698 }
699
700 //=======================================================================
701 // name    : SMESHGUI_MeshPatternDlg::enterEvent
702 // Purpose : Event filter
703 //=======================================================================
704 void SMESHGUI_MeshPatternDlg::enterEvent (QEvent*)
705 {
706   if (myIsCreateDlgOpen)
707     return;
708
709   if (myReverseChk->isChecked())
710     displayPreview();
711   mySMESHGUI->EmitSignalDeactivateDialog();
712   setEnabled(true);
713   activateSelection();
714   connect(mySelectionMgr, SIGNAL(currentSelectionChanged()), SLOT(onSelectionDone()));
715   onTextChanged(mySelEdit[Ids]->text());
716 }
717
718 //=======================================================================
719 // name    : SMESHGUI_MeshPatternDlg::closeEvent
720 // Purpose :
721 //=======================================================================
722 void SMESHGUI_MeshPatternDlg::closeEvent (QCloseEvent*)
723 {
724   onClose();
725 }
726
727 //=======================================================================
728 // name    : SMESHGUI_MeshPatternDlg::onSelInputChanged
729 // Purpose : SLOT. Called when -> button clicked.
730 //           Change current selection input field
731 //=======================================================================
732 void SMESHGUI_MeshPatternDlg::onSelInputChanged()
733 {
734   const QObject* aSender = sender();
735   for (int i = Mesh; i <= Ids; i++)
736     if (aSender == mySelBtn[ i ])
737       mySelInput = i;
738
739   activateSelection();
740   onSelectionDone();
741 }
742
743 //=======================================================================
744 // name    : SMESHGUI_MeshPatternDlg::prepareFilters
745 // Purpose : Prepare filters for dialog
746 //=======================================================================
747 QStringList SMESHGUI_MeshPatternDlg::prepareFilters() const
748 {
749   static QStringList aList;
750   if (aList.isEmpty())
751   {
752     aList.append(tr("PATTERN_FILT"));
753     //aList.append(tr("ALL_FILES_FILTER"));
754   }
755
756   return aList;
757 }
758
759 //=======================================================================
760 // name    : SMESHGUI_MeshPatternDlg::autoExtension
761 // Purpose : Append extension to the file name
762 //=======================================================================
763 QString SMESHGUI_MeshPatternDlg::autoExtension (const QString& theFileName) const
764 {
765   QString anExt = theFileName.section('.', -1);
766   return anExt != "smp" && anExt != "SMP" ? theFileName + ".smp" : theFileName;
767 }
768
769 //=======================================================================
770 // name    : SMESHGUI_MeshPatternDlg::onOpen
771 // Purpose : SLOT. Called when "Open" button clicked.
772 //           Displays file open dialog
773 //=======================================================================
774 void SMESHGUI_MeshPatternDlg::onOpen()
775 {
776   SUIT_FileDlg* aDlg = new SUIT_FileDlg (this, true);
777   aDlg->setWindowTitle(tr("LOAD_PATTERN"));
778   aDlg->setFileMode(QFileDialog::ExistingFile);
779   aDlg->setFilters(prepareFilters());
780   if (!myName->text().isEmpty())
781     aDlg->selectFile(myName->text() + ".smp");
782   QPushButton* anOkBtn = qFindChild<QPushButton*>( aDlg, "OK" );
783   if (anOkBtn != 0)
784     anOkBtn->setText(tr("SMESH_BUT_OK"));
785
786   if (aDlg->exec() != Accepted)
787     return;
788
789   QString fName = aDlg->selectedFile();
790   if (fName.isEmpty())
791     return;
792
793   if (QFileInfo(fName).suffix().isEmpty())
794     fName = autoExtension(fName);
795
796   fName = QDir::convertSeparators(fName);
797
798   QString prev = QDir::convertSeparators(myName->text());
799   if (prev == fName)
800     return;
801
802   // Read string from file
803   QFile aFile(fName);
804   if (!aFile.open(QIODevice::ReadOnly)) {
805     SUIT_MessageBox::information(this, tr("SMESH_ERROR"),
806                                  tr("ERROR_OF_OPENING"));
807     return;
808   }
809
810   QByteArray aDataArray = aFile.readAll();
811   if (aDataArray.isEmpty()) {
812     SUIT_MessageBox::information(this, tr("SMESH_ERROR"),
813                                  tr("ERROR_OF_READING"));
814     return;
815   }
816
817   if (loadFromFile(aDataArray))
818     myName->setText(QFileInfo(fName).completeBaseName());
819
820   updateWgState();
821   displayPreview();
822 }
823
824 //=======================================================================
825 // name    : SMESHGUI_MeshPatternDlg::onCloseCreationDlg
826 // Purpose : SLOT. Called when "Pattern creation" dialog closed with "Close"
827 //=======================================================================
828 void SMESHGUI_MeshPatternDlg::onCloseCreationDlg()
829 {
830   setEnabled(true);
831   myIsCreateDlgOpen = false;
832 }
833
834 //=======================================================================
835 // name    : SMESHGUI_MeshPatternDlg::onOkCreationDlg
836 // Purpose : SLOT. Called when "Pattern creation" dialog closed with OK
837 //           or SAVE buttons. Initialize myPattern field. Redisplay preview
838 //=======================================================================
839 void SMESHGUI_MeshPatternDlg::onOkCreationDlg()
840 {
841   myPattern = SMESH::SMESH_Pattern::_duplicate(myCreationDlg->GetPattern());
842   myName->setText(myCreationDlg->GetPatternName());
843
844   updateWgState();
845   displayPreview();
846
847   setEnabled(true);
848   myIsCreateDlgOpen = false;
849 }
850
851 //=======================================================================
852 // name    : SMESHGUI_MeshPatternDlg::onNew
853 // Purpose : SLOT. Called when "New..." button clicked. Create new pattern
854 //=======================================================================
855 void SMESHGUI_MeshPatternDlg::onNew()
856 {
857   setEnabled(false);
858   myIsCreateDlgOpen = true;
859   if (myCreationDlg == 0)
860   {
861     myCreationDlg = new SMESHGUI_CreatePatternDlg( mySMESHGUI, myType);
862     connect(myCreationDlg, SIGNAL(NewPattern()), SLOT(onOkCreationDlg()));
863     connect(myCreationDlg, SIGNAL(Close()), SLOT(onCloseCreationDlg()));
864   }
865   else
866     myCreationDlg->Init(myType);
867
868   myCreationDlg->SetMesh(myMesh);
869   myCreationDlg->show();
870 }
871
872 //=======================================================================
873 // name    : SMESHGUI_MeshPatternDlg::onReverse
874 // Purpose : SLOT. Called when state of "Reverse order..." checkbox chaged
875 //           Calculate new points of the mesh to be created. Redisplay preview
876 //=======================================================================
877 void SMESHGUI_MeshPatternDlg::onReverse (bool)
878 {
879   displayPreview();
880 }
881
882 //=======================================================================
883
884 // name    : SMESHGUI_MeshPatternDlg::onPreview
885 // Purpose : SLOT. Called when state of "Preview" checkbox changed
886 //           Display/Erase preview
887 //=======================================================================
888 void SMESHGUI_MeshPatternDlg::onPreview (bool)
889 {
890   displayPreview();
891 }
892
893 //=======================================================================
894 // name    : SMESHGUI_MeshPatternDlg::displayPreview
895 // Purpose : Display preview
896 //=======================================================================
897 void SMESHGUI_MeshPatternDlg::displayPreview()
898 {
899   try {
900     // Redisplay preview in dialog
901     SMESH::point_array_var pnts = myPattern->GetPoints();
902     SMESH::long_array_var keyPoints = myPattern->GetKeyPoints();
903     SMESH::array_of_long_array_var elemPoints = myPattern->GetElementPoints(false);
904
905     if (pnts->length()       == 0 ||
906         keyPoints->length()  == 0 ||
907         elemPoints->length() == 0) {
908       erasePreview();
909       return;
910     } else {
911       PointVector aPoints(pnts->length());
912       QVector<int> aKeyPoints(keyPoints->length());
913       ConnectivityVector anElemPoints(elemPoints->length());
914
915       for (int i = 0, n = pnts->length(); i < n; i++)
916         aPoints[ i ] = pnts[ i ];
917
918       for (int i2 = 0, n2 = keyPoints->length(); i2 < n2; i2++)
919         aKeyPoints[ i2 ] = keyPoints[ i2 ];
920
921       for (int i3 = 0, n3 = elemPoints->length(); i3 < n3; i3++) {
922         QVector<int> aVec(elemPoints[ i3 ].length());
923         for (int i4 = 0, n4 = elemPoints[ i3 ].length(); i4 < n4; i4++)
924           aVec[ i4 ] = elemPoints[ i3 ][ i4 ];
925
926         anElemPoints[ i3 ] = aVec;
927       }
928
929       myPicture2d->SetPoints(aPoints, aKeyPoints, anElemPoints);
930     }
931
932     // Redisplay preview in 3D viewer
933     if (myPreviewActor != 0) {
934       if (SVTK_ViewWindow* vf = SMESH::GetCurrentVtkView()) {
935         vf->RemoveActor(myPreviewActor);
936         vf->Repaint();
937       }
938       myPreviewActor->Delete();
939       myPreviewActor = 0;
940     }
941
942     if (!myPreviewChk->isChecked() || !isValid(false))
943       return;
944
945     vtkUnstructuredGrid* aGrid = getGrid();
946     if (aGrid == 0)
947       return;
948
949     // Create and display actor
950     vtkDataSetMapper* aMapper = vtkDataSetMapper::New();
951     aMapper->SetInput(aGrid);
952
953     myPreviewActor = SALOME_Actor::New();
954     myPreviewActor->PickableOff();
955     myPreviewActor->SetMapper(aMapper);
956
957     vtkProperty* aProp = vtkProperty::New();
958     aProp->SetRepresentationToWireframe();
959     aProp->SetColor(250, 0, 250);
960     if (SMESH::FindActorByObject(myMesh))
961       aProp->SetLineWidth( SMESH::GetFloat( "SMESH:element_width", 1 ) + 1 );
962     else
963       aProp->SetLineWidth(1);
964     myPreviewActor->SetProperty(aProp);
965
966     myPreviewActor->SetRepresentation(3);
967
968     SMESH::GetCurrentVtkView()->AddActor(myPreviewActor);
969     SMESH::GetCurrentVtkView()->Repaint();
970
971     aProp->Delete();
972     aGrid->Delete();
973   } catch (const SALOME::SALOME_Exception& S_ex) {
974     SalomeApp_Tools::QtCatchCorbaException(S_ex);
975     erasePreview();
976   } catch (...) {
977     erasePreview();
978   }
979 }
980
981 //=======================================================================
982 // name    : SMESHGUI_MeshPatternDlg::erasePreview
983 // Purpose : Erase preview
984 //=======================================================================
985 void SMESHGUI_MeshPatternDlg::erasePreview()
986 {
987   // Erase preview in 2D viewer
988   myPicture2d->SetPoints(PointVector(), QVector<int>(), ConnectivityVector());
989
990   // Erase preview in 3D viewer
991   if (myPreviewActor == 0)
992     return;
993
994
995   if (SVTK_ViewWindow* vf = SMESH::GetCurrentVtkView())
996   {
997     vf->RemoveActor(myPreviewActor);
998     vf->Repaint();
999   }
1000   myPreviewActor->Delete();
1001   myPreviewActor = 0;
1002 }
1003
1004 //=======================================================================
1005 // name    : SMESHGUI_MeshPatternDlg::updateWgState
1006 // Purpose : Enable/disable selection widgets
1007 //=======================================================================
1008 void SMESHGUI_MeshPatternDlg::updateWgState()
1009 {
1010   if (myMesh->_is_nil()) {
1011     for (int i = Object; i <= Ids; i++) {
1012       mySelBtn [ i ]->setEnabled(false);
1013       mySelEdit[ i ]->setEnabled(false);
1014       mySelEdit[ i ]->setText("");
1015     }
1016     myNode1->setEnabled(false);
1017     myNode2->setEnabled(false);
1018     myNode1->setRange(0, 0);
1019     myNode2->setRange(0, 0);
1020   } else {
1021     mySelBtn [ Object ]->setEnabled(true);
1022     mySelEdit[ Object ]->setEnabled(true);
1023     mySelBtn [ Ids ]   ->setEnabled(true);
1024     mySelEdit[ Ids ]   ->setEnabled(true);
1025
1026     if (myGeomObj[ Object ]->_is_nil()) {
1027       for (int i = Vertex1; i <= Vertex2; i++) {
1028         mySelBtn [ i ]->setEnabled(false);
1029         mySelEdit[ i ]->setEnabled(false);
1030         mySelEdit[ i ]->setText("");
1031       }
1032     } else {
1033       for (int i = Object; i <= Vertex2; i++) {
1034         mySelBtn [ i ]->setEnabled(true);
1035         mySelEdit[ i ]->setEnabled(true);
1036       }
1037     }
1038
1039     QList<int> ids;
1040     if (!CORBA::is_nil(myPattern)/* && getIds(ids)*/) {
1041       SMESH::long_array_var keyPoints = myPattern->GetKeyPoints();
1042       if (keyPoints->length()) {
1043         myNode1->setEnabled(true);
1044         myNode2->setEnabled(true);
1045         myNode1->setRange(1, keyPoints->length());
1046         myNode2->setRange(1, keyPoints->length());
1047         return;
1048       }
1049     }
1050
1051     myNode1->setEnabled(false);
1052     myNode2->setEnabled(false);
1053     myNode1->setRange(0, 0);
1054     myNode2->setRange(0, 0);
1055   }
1056 }
1057
1058 //=======================================================================
1059 // name    : SMESHGUI_MeshPatternDlg::activateSelection
1060 // Purpose : Activate selection in accordance with current selection input
1061 //=======================================================================
1062 void SMESHGUI_MeshPatternDlg::activateSelection()
1063 {
1064   mySelectionMgr->clearFilters();
1065   if (mySelInput == Ids) {
1066     SMESH_Actor* anActor = SMESH::FindActorByObject(myMesh);
1067     if (anActor)
1068       SMESH::SetPickable(anActor);
1069
1070     if (myType == Type_2d)
1071       {
1072         if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
1073           aViewWindow->SetSelectionMode(FaceSelection);
1074       }
1075     else
1076       {
1077         if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
1078           aViewWindow->SetSelectionMode(CellSelection);
1079       }
1080   }
1081   else {
1082     SMESH::SetPickable();
1083     //mySelectionMgr->setSelectionModes(ActorSelection);
1084     if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
1085       aViewWindow->SetSelectionMode(ActorSelection);
1086   }
1087
1088   if (mySelInput == Object && !myMeshShape->_is_nil()) {
1089     if (myType == Type_2d) {
1090       if (myNbPoints > 0)
1091         mySelectionMgr->installFilter
1092           (new SMESH_NumberFilter ("GEOM", TopAbs_VERTEX, myNbPoints, TopAbs_FACE, myMeshShape));
1093       else
1094         mySelectionMgr->installFilter
1095           (new SMESH_NumberFilter ("GEOM", TopAbs_SHAPE, myNbPoints, TopAbs_FACE, myMeshShape));
1096     } else {
1097       TColStd_MapOfInteger aTypes;
1098       aTypes.Add(TopAbs_SHELL);
1099       aTypes.Add(TopAbs_SOLID);
1100       mySelectionMgr->installFilter
1101         (new SMESH_NumberFilter ("GEOM", TopAbs_FACE, 6, aTypes, myMeshShape, true));
1102     }
1103   } else if ((mySelInput == Vertex1 || mySelInput == Vertex2) && !myGeomObj[ Object ]->_is_nil()) {
1104     mySelectionMgr->installFilter
1105       (new SMESH_NumberFilter ("GEOM", TopAbs_SHAPE, 1, TopAbs_VERTEX, myGeomObj[ Object ]));
1106   } else {
1107   }
1108 }
1109
1110 //=======================================================================
1111 // name    : SMESHGUI_MeshPatternDlg::loadFromFile
1112 // Purpose : Load pattern from file
1113 //=======================================================================
1114 bool SMESHGUI_MeshPatternDlg::loadFromFile (const QString& theName)
1115 {
1116   try {
1117     SMESH::SMESH_Pattern_var aPattern = SMESH::GetPattern();
1118
1119     if (!aPattern->LoadFromFile(theName.toLatin1().data()) ||
1120         myType == Type_2d && !aPattern->Is2D()) {
1121       SMESH::SMESH_Pattern::ErrorCode aCode = aPattern->GetErrorCode();
1122       QString aMess;
1123       if      (aCode == SMESH::SMESH_Pattern::ERR_READ_NB_POINTS     ) aMess = tr("ERR_READ_NB_POINTS");
1124       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_POINT_COORDS  ) aMess = tr("ERR_READ_POINT_COORDS");
1125       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_TOO_FEW_POINTS) aMess = tr("ERR_READ_TOO_FEW_POINTS");
1126       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_3D_COORD      ) aMess = tr("ERR_READ_3D_COORD");
1127       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_NO_KEYPOINT   ) aMess = tr("ERR_READ_NO_KEYPOINT");
1128       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_BAD_INDEX     ) aMess = tr("ERR_READ_BAD_INDEX");
1129       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_ELEM_POINTS   ) aMess = tr("ERR_READ_ELEM_POINTS");
1130       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_NO_ELEMS      ) aMess = tr("ERR_READ_NO_ELEMS");
1131       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_BAD_KEY_POINT ) aMess = tr("ERR_READ_BAD_KEY_POINT");
1132       else                                                             aMess = tr("ERROR_OF_LOADING");
1133
1134       SUIT_MessageBox::information(this, tr("SMESH_ERROR"), aMess);
1135       return false;
1136     } else {
1137       myPattern = aPattern;
1138       return true;
1139     }
1140   } catch (const SALOME::SALOME_Exception& S_ex) {
1141     SalomeApp_Tools::QtCatchCorbaException(S_ex);
1142     SUIT_MessageBox::information(this, tr("SMESH_ERROR"),
1143                                  tr("ERROR_OF_LOADING") );
1144     return false;
1145   }
1146 }
1147
1148 //=======================================================================
1149 // name    : SMESHGUI_MeshPatternDlg::onTypeChanged
1150 // Purpose : SLOT. Called when pattern type changed.
1151 //           Change dialog's look and feel
1152 //=======================================================================
1153 void SMESHGUI_MeshPatternDlg::onTypeChanged (int theType)
1154 {
1155   if (myType == theType)
1156     return;
1157
1158   myType = theType;
1159
1160   myNbPoints = -1;
1161   myGeomObj[ Object  ] = GEOM::GEOM_Object::_nil();
1162   myGeomObj[ Vertex1 ] = GEOM::GEOM_Object::_nil();
1163   myGeomObj[ Vertex2 ] = GEOM::GEOM_Object::_nil();
1164   myPattern = SMESH::GetPattern();
1165
1166   myName->setText("");
1167   mySelEdit[ Object  ]->setText("");
1168   mySelEdit[ Vertex1 ]->setText("");
1169   mySelEdit[ Vertex2 ]->setText("");
1170   mySelEdit[ Ids ]    ->setText("");
1171   myCreatePolygonsChk->show();
1172   myCreatePolyedrsChk->show();
1173
1174   if (theType == Type_2d) {
1175     // Geom widgets
1176     mySelLbl [ Vertex2 ]->hide();
1177     mySelBtn [ Vertex2 ]->hide();
1178     mySelEdit[ Vertex2 ]->hide();
1179     myReverseChk->show();
1180     myPicture2d->show();
1181     myPicture3d->hide();
1182     mySelLbl[ Object  ]->setText(tr("FACE"));
1183     mySelLbl[ Vertex1 ]->setText(tr("VERTEX"));
1184     // Refine widgets
1185     mySelLbl[ Ids ]->setText(tr("MESH_FACES"));
1186     myNode2Lbl->hide();
1187     myNode2   ->hide();
1188   } else {
1189     // Geom widgets
1190     mySelLbl [ Vertex2 ]->show();
1191     mySelBtn [ Vertex2 ]->show();
1192     mySelEdit[ Vertex2 ]->show();
1193     myReverseChk->hide();
1194     myPicture2d->hide();
1195     myPicture3d->show();
1196     mySelLbl[ Object  ]->setText(tr("3D_BLOCK"));
1197     mySelLbl[ Vertex1 ]->setText(tr("VERTEX1"));
1198     mySelLbl[ Vertex2 ]->setText(tr("VERTEX2"));
1199     // Refine widgets
1200     mySelLbl[ Ids ]->setText(tr("MESH_VOLUMES"));
1201     myNode2Lbl->show();
1202     myNode2   ->show();
1203   }
1204
1205   mySelInput = Mesh;
1206   activateSelection();
1207   updateWgState();
1208   displayPreview();
1209 }
1210
1211 //=======================================================================
1212 // name    : SMESHGUI_MeshPatternDlg::getGrid
1213 // Purpose : Get unstructured grid for pattern
1214 //=======================================================================
1215 vtkUnstructuredGrid* SMESHGUI_MeshPatternDlg::getGrid()
1216 {
1217   try {
1218     // Get points from pattern
1219     SMESH::point_array_var pnts;
1220     QList<int> ids;
1221     if (isRefine() && getIds(ids)) {
1222       SMESH::long_array_var varIds = new SMESH::long_array();
1223       varIds->length(ids.count());
1224       int i = 0;
1225       for (QList<int>::iterator it = ids.begin(); it != ids.end(); ++it)
1226         varIds[i++] = *it;
1227       pnts = myType == Type_2d
1228         ? myPattern->ApplyToMeshFaces  (myMesh, varIds, getNode(false), myReverseChk->isChecked())
1229         : myPattern->ApplyToHexahedrons(myMesh, varIds, getNode(false), getNode(true));
1230     } else {
1231       pnts = myType == Type_2d
1232         ? myPattern->ApplyToFace   (myGeomObj[ Object ], myGeomObj[ Vertex1 ], myReverseChk->isChecked())
1233       : myPattern->ApplyTo3DBlock(myGeomObj[ Object ], myGeomObj[ Vertex1 ], myGeomObj[ Vertex2 ]);
1234     }
1235
1236     SMESH::array_of_long_array_var elemPoints = myPattern->GetElementPoints(true);
1237
1238     if (pnts->length() == 0 || elemPoints->length() == 0)
1239       return 0;
1240
1241     // to do : to be removed /////////////////////////////////////////////
1242
1243 #ifdef DEB_SLN
1244     for (int i1 = 0, n1 = pnts->length(); i1 < n1; i1++)
1245       printf("%d: %g %g %g\n", i1, pnts[ i1 ].x, pnts[ i1 ].y, pnts[ i1 ].z);
1246
1247     printf("\nELEMENTS : \n");
1248     for (int i2 = 0, n2 = elemPoints->length(); i2 < n2; i2++)
1249     {
1250
1251       printf("%d: ", i2);
1252       for (int i3 = 0, n3 = elemPoints[ i2 ].length(); i3 < n3; i3++)
1253         printf("%d ", elemPoints[ i2 ][ i3 ]);
1254
1255       printf("\n");
1256
1257     }
1258 #endif
1259     //////////////////////////////////////////////////////////////////////
1260
1261     // Calculate number of points used for cell
1262     vtkIdType aNbCells = elemPoints->length();
1263     vtkIdType aCellsSize = 0;
1264     for (int i = 0, n = elemPoints->length(); i < n; i++)
1265       aCellsSize += elemPoints[ i ].length();
1266
1267     // Create unstructured grid and other  usefull arrays
1268     vtkUnstructuredGrid* aGrid = vtkUnstructuredGrid::New();
1269
1270     vtkCellArray* aConnectivity = vtkCellArray::New();
1271     aConnectivity->Allocate(aCellsSize, 0);
1272
1273     vtkPoints* aPoints = vtkPoints::New();
1274     aPoints->SetNumberOfPoints(pnts->length());
1275
1276     vtkUnsignedCharArray* aCellTypesArray = vtkUnsignedCharArray::New();
1277     aCellTypesArray->SetNumberOfComponents(1);
1278     aCellTypesArray->Allocate(aNbCells * aCellTypesArray->GetNumberOfComponents());
1279
1280     vtkIdList *anIdList = vtkIdList::New();
1281
1282     // Fill array of points
1283     for (int p = 0, nbPnt = pnts->length(); p < nbPnt; p++)
1284       aPoints->SetPoint(p, pnts[ p ].x, pnts[ p ].y, pnts[ p ].z);
1285
1286     for (int e = 0, nbElem = elemPoints->length(); e < nbElem; e++) {
1287       int nbPoints = elemPoints[ e ].length();
1288       anIdList->SetNumberOfIds(nbPoints);
1289       for (int i = 0; i < nbPoints; i++)
1290         anIdList->SetId(i, elemPoints[ e ][ i ]);
1291
1292       aConnectivity->InsertNextCell(anIdList);
1293
1294       if      (nbPoints == 3) aCellTypesArray->InsertNextValue(VTK_TRIANGLE);
1295       else if (nbPoints == 5) aCellTypesArray->InsertNextValue(VTK_PYRAMID);
1296       else if (nbPoints == 6) aCellTypesArray->InsertNextValue(VTK_WEDGE);
1297       else if (nbPoints == 8) aCellTypesArray->InsertNextValue(VTK_HEXAHEDRON);
1298       else if (nbPoints == 4 && myType == Type_2d) aCellTypesArray->InsertNextValue(VTK_QUAD);
1299       else if (nbPoints == 4 && myType == Type_3d) aCellTypesArray->InsertNextValue(VTK_TETRA);
1300       else aCellTypesArray->InsertNextValue(VTK_EMPTY_CELL);
1301     }
1302
1303     VTKViewer_CellLocationsArray* aCellLocationsArray = VTKViewer_CellLocationsArray::New();
1304     aCellLocationsArray->SetNumberOfComponents(1);
1305     aCellLocationsArray->SetNumberOfTuples(aNbCells);
1306
1307     aConnectivity->InitTraversal();
1308     for (vtkIdType idType = 0, *pts, npts; aConnectivity->GetNextCell(npts, pts); idType++)
1309       aCellLocationsArray->SetValue(idType, aConnectivity->GetTraversalLocation(npts));
1310
1311     aGrid->SetPoints(aPoints);
1312     aGrid->SetCells(aCellTypesArray, aCellLocationsArray,aConnectivity);
1313
1314     aConnectivity->Delete();
1315     aPoints->Delete();
1316     aCellTypesArray->Delete();
1317     anIdList->Delete();
1318     aCellLocationsArray->Delete();
1319
1320     return aGrid;
1321   } catch (...) {
1322     return 0;
1323   }
1324 }
1325
1326 //=======================================================================
1327 // name    : onModeToggled
1328 // Purpose :
1329 //=======================================================================
1330 void SMESHGUI_MeshPatternDlg::onModeToggled (bool on)
1331 {
1332   on ? myRefineGrp->show() : myRefineGrp->hide();
1333   on ? myGeomGrp->hide()   : myGeomGrp->show();
1334
1335   displayPreview();
1336 }
1337
1338 //=======================================================================
1339 // name    : isRefine
1340 // Purpose :
1341 //=======================================================================
1342 bool SMESHGUI_MeshPatternDlg::isRefine() const
1343 {
1344   return myRefine->isChecked();
1345 }
1346
1347 //=======================================================================
1348 // name    : onTextChanged
1349 // Purpose :
1350 //=======================================================================
1351 void SMESHGUI_MeshPatternDlg::onTextChanged (const QString& theNewText)
1352 {
1353   if (myBusy || !isRefine())
1354     return;
1355
1356   myBusy = true;
1357
1358   if (mySelInput != Ids) {
1359     mySelInput = Ids;
1360     activateSelection();
1361   }
1362
1363   // hilight entered elements/nodes
1364   SMDS_Mesh* aMesh = 0;
1365   SMESH_Actor* anActor = SMESH::FindActorByObject(myMesh);
1366   if (anActor)
1367     aMesh = anActor->GetObject()->GetMesh();
1368
1369   if (aMesh) {
1370     QStringList aListId = theNewText.split(" ", QString::SkipEmptyParts);
1371
1372     TColStd_MapOfInteger newIndices;
1373
1374     for (int i = 0; i < aListId.count(); i++) {
1375       const SMDS_MeshElement * e = aMesh->FindElement(aListId[ i ].toInt());
1376       if (e && e->GetType() == (myType == Type_2d ? SMDSAbs_Face : SMDSAbs_Volume))
1377         newIndices.Add(e->GetID());
1378     }
1379     mySelector->AddOrRemoveIndex( anActor->getIO(), newIndices, false);
1380     if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
1381       aViewWindow->highlight( anActor->getIO(), true, true );
1382   }
1383
1384   myBusy = false;
1385
1386   displayPreview();
1387 }
1388
1389 //=======================================================================
1390 // name    : onNodeChanged
1391 // Purpose :
1392 //=======================================================================
1393 void SMESHGUI_MeshPatternDlg::onNodeChanged (int value)
1394 {
1395   if (myType == Type_3d) {
1396     SalomeApp_IntSpinBox* first = (SalomeApp_IntSpinBox*)sender();
1397     SalomeApp_IntSpinBox* second = first == myNode1 ? myNode2 : myNode1;
1398     int secondVal = second->value();
1399     if (secondVal == value) {
1400       secondVal = value == second->maximum() ? second->minimum() : value + 1;
1401       bool blocked = second->signalsBlocked();
1402       second->blockSignals(true);
1403       second->setValue(secondVal);
1404       second->blockSignals(blocked);
1405     }
1406   }
1407
1408   displayPreview();
1409 }
1410
1411 //=======================================================================
1412 // name    : getIds
1413 // Purpose :
1414 //=======================================================================
1415 bool SMESHGUI_MeshPatternDlg::getIds (QList<int>& ids) const
1416 {
1417   ids.clear();
1418   QStringList strIds = mySelEdit[Ids]->text().split(" ", QString::SkipEmptyParts );
1419   bool isOk;
1420   int val;
1421   for (QStringList::iterator it = strIds.begin(); it != strIds.end(); ++it) {
1422     val = (*it).toInt(&isOk);
1423     if (isOk)
1424       ids.append(val);
1425   }
1426
1427   return ids.count();
1428 }
1429
1430 //=======================================================================
1431 // name    : getNode1
1432 // Purpose :
1433 //=======================================================================
1434 int SMESHGUI_MeshPatternDlg::getNode (bool second) const
1435 {
1436   return second ? myNode2->value() - 1 : myNode1->value() - 1;
1437 }
1438
1439 //=================================================================================
1440 // function : keyPressEvent()
1441 // purpose  :
1442 //=================================================================================
1443 void SMESHGUI_MeshPatternDlg::keyPressEvent( QKeyEvent* e )
1444 {
1445   QDialog::keyPressEvent( e );
1446   if ( e->isAccepted() )
1447     return;
1448
1449   if ( e->key() == Qt::Key_F1 )
1450     {
1451       e->accept();
1452       onHelp();
1453     }
1454 }