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