Salome HOME
Update copyright
[modules/smesh.git] / src / SMESHGUI / SMESHGUI_MeshPatternDlg.cxx
1 // Copyright (C) 2007-2011  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
23 // SMESH SMESHGUI : GUI for SMESH component
24 // File   : SMESHGUI_MeshPatternDlg.cxx
25 // Author : Sergey LITONIN, Open CASCADE S.A.S.
26 // SMESH includes
27 //
28 #include "SMESHGUI_MeshPatternDlg.h"
29
30 #include "SMESHGUI.h"
31 #include "SMESHGUI_CreatePatternDlg.h"
32 #include "SMESHGUI_PatternWidget.h"
33 #include "SMESHGUI_Utils.h"
34 #include "SMESHGUI_VTKUtils.h"
35 #include "SMESHGUI_PatternUtils.h"
36 #include "SMESHGUI_GEOMGenUtils.h"
37
38 #include <SMESH_Actor.h>
39 #include <SMESH_ActorUtils.h>
40 #include <SMESH_NumberFilter.hxx>
41
42 #include <SMDS_Mesh.hxx>
43 #include <SMDS_MeshElement.hxx>
44
45 // SALOME GUI includes
46 #include <SUIT_ResourceMgr.h>
47 #include <SUIT_Desktop.h>
48 #include <SUIT_FileDlg.h>
49 #include <SUIT_Session.h>
50 #include <SUIT_MessageBox.h>
51
52 #include <LightApp_SelectionMgr.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     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     QString msg;
418     bool ok = true;
419     ok = myNode1->isValid( msg, theMess ) && ok;
420     if (myType == Type_3d)
421       ok = myNode2->isValid( msg, theMess ) && ok;
422     if( !ok ) {
423       if( theMess ) {
424         QString str( tr( "SMESH_INCORRECT_INPUT" ) );
425         if ( !msg.isEmpty() )
426           str += "\n" + msg;
427         SUIT_MessageBox::critical( this, tr( "SMESH_ERROR" ), str );
428       }
429       return false;
430     }
431   }
432
433   QList<int> ids;
434   if ((isRefine() &&
435        (myMesh->_is_nil() || !getIds(ids) || getNode(false) < 0 ||
436         (myType == Type_3d && (getNode(true) < 0 || getNode(false) == getNode(true)))))
437       ||
438       (!isRefine() &&
439        (myMesh->_is_nil() || myMeshShape->_is_nil() || myGeomObj[ Object ]->_is_nil() ||
440         myGeomObj[ Vertex1 ]->_is_nil() || (myType == Type_3d && myGeomObj[ Vertex2 ]->_is_nil()))))
441   {
442     if (theMess)
443       SUIT_MessageBox::information(this, tr("SMESH_INSUFFICIENT_DATA"),
444                                    tr("SMESHGUI_INVALID_PARAMETERS"));
445     return false;
446   }
447
448   if ( myName->text().isEmpty() ) {
449     if (theMess)
450       SUIT_MessageBox::information(this, tr("SMESH_INSUFFICIENT_DATA"),
451                                    tr("SMESHGUI_INVALID_PARAMETERS"));
452     return false;
453   }
454
455   return true;
456 }
457
458 //=======================================================================
459 // name    : SMESHGUI_MeshPatternDlg::onApply
460 // Purpose : SLOT called when "Apply" button pressed.
461 //=======================================================================
462 bool SMESHGUI_MeshPatternDlg::onApply()
463 {
464   try {
465     if (!isValid())
466       return false;
467
468     erasePreview();
469
470     if (isRefine()) { // Refining existing mesh elements
471       QList<int> ids;
472       getIds(ids);
473       SMESH::long_array_var varIds = new SMESH::long_array();
474       varIds->length(ids.count());
475       int i = 0;
476       for (QList<int>::iterator it = ids.begin(); it != ids.end(); ++it)
477         varIds[i++] = *it;
478       myType == Type_2d
479         ? myPattern->ApplyToMeshFaces  (myMesh, varIds, getNode(false), myReverseChk->isChecked())
480         : myPattern->ApplyToHexahedrons(myMesh, varIds, getNode(false), getNode(true));
481
482       QStringList aParameters;
483       aParameters << myNode1->text();
484       if(myType == Type_3d )
485         aParameters << myNode2->text();
486       myMesh->SetParameters( aParameters.join(":").toLatin1().constData() );
487
488     } else { // Applying a pattern to geometrical object
489       if (myType == Type_2d)
490         myPattern->ApplyToFace(myGeomObj[Object], myGeomObj[Vertex1], myReverseChk->isChecked());
491       else
492         myPattern->ApplyTo3DBlock(myGeomObj[Object], myGeomObj[Vertex1], myGeomObj[Vertex2]);
493     }
494
495     bool toCreatePolygons = myCreatePolygonsChk->isChecked();
496     bool toCreatePolyedrs = myCreatePolyedrsChk->isChecked();
497     if ( myPattern->MakeMesh( myMesh, toCreatePolygons, toCreatePolyedrs ) ) {
498       //mySelectionMgr->clearSelected();
499       bool autoUpdate = SMESHGUI::automaticUpdate();
500       if (!isRefine() && autoUpdate) {
501         _PTR(SObject) aSO = SMESH::FindSObject(myMesh.in());
502         SMESH_Actor* anActor = SMESH::FindActorByEntry(aSO->GetID().c_str());
503         if (!anActor) {
504           anActor = SMESH::CreateActor(aSO->GetStudy(), aSO->GetID().c_str());
505           if (anActor) {
506             SMESH::DisplayActor(SMESH::GetActiveWindow(), anActor);
507             SMESH::FitAll();
508           }
509         }
510       }
511       mySelectionMgr->clearSelected();
512       SMESH::UpdateView();
513       SMESHGUI::Modified();
514
515       mySMESHGUI->updateObjBrowser(true);
516
517       mySelEdit[ Ids ]->setText("");
518
519       return true;
520     } else {
521       SUIT_MessageBox::information(this, tr("SMESH_ERROR"),
522                                    tr("SMESH_OPERATION_FAILED"));
523       return false;
524     }
525   } catch (const SALOME::SALOME_Exception& S_ex) {
526     SalomeApp_Tools::QtCatchCorbaException(S_ex);
527   } catch (...) {
528   }
529
530   return false;
531 }
532
533 //=======================================================================
534 // name    : SMESHGUI_MeshPatternDlg::onOk
535 // Purpose : SLOT called when "Ok" button pressed.
536 //=======================================================================
537 void SMESHGUI_MeshPatternDlg::onOk()
538 {
539   if (onApply())
540     onClose();
541 }
542
543 //=======================================================================
544 // name    : SMESHGUI_MeshPatternDlg::onClose
545 // Purpose : SLOT called when "Close" button pressed. Close dialog
546 //=======================================================================
547 void SMESHGUI_MeshPatternDlg::onClose()
548 {
549   mySelectionMgr->clearFilters();
550   SMESH::SetPickable();
551   if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
552     aViewWindow->SetSelectionMode(ActorSelection);
553   disconnect(mySelectionMgr, 0, this, 0);
554   disconnect(mySMESHGUI, 0, this, 0);
555   mySMESHGUI->ResetState();
556   erasePreview();
557   reject();
558 }
559
560 //=================================================================================
561 // function : onHelp()
562 // purpose  :
563 //=================================================================================
564 void SMESHGUI_MeshPatternDlg::onHelp()
565 {
566   LightApp_Application* app = (LightApp_Application*)(SUIT_Session::session()->activeApplication());
567   if (app) 
568     app->onHelpContextModule(mySMESHGUI ? app->moduleName(mySMESHGUI->moduleName()) : QString(""), myHelpFileName);
569   else {
570                 QString platform;
571 #ifdef WIN32
572                 platform = "winapplication";
573 #else
574                 platform = "application";
575 #endif
576     SUIT_MessageBox::warning(this, tr("WRN_WARNING"),
577                              tr("EXTERNAL_BROWSER_CANNOT_SHOW_PAGE").
578                              arg(app->resourceMgr()->stringValue("ExternalBrowser", 
579                                                                  platform)).
580                              arg(myHelpFileName));
581   }
582 }
583
584 //=======================================================================
585 // name    : SMESHGUI_MeshPatternDlg::onSelectionDone
586 // Purpose : SLOT called when selection changed
587 //=======================================================================
588 void SMESHGUI_MeshPatternDlg::onSelectionDone()
589 {
590   if (myBusy)
591     return;
592
593   try {
594     if (mySelInput == Mesh) {
595       SALOME_ListIO aList;
596       mySelectionMgr->selectedObjects(aList,SVTK_Viewer::Type());
597       if (aList.Extent() != 1)
598         return;
599
600       // Retrieve mesh from selection
601       Handle(SALOME_InteractiveObject) anIO = aList.First();
602       SMESH::SMESH_Mesh_var aMesh = SMESH::IObjectToInterface<SMESH::SMESH_Mesh>(anIO);
603       if (aMesh->_is_nil())
604         return;
605
606       // Get geom object corresponding to the mesh
607       _PTR(SObject) aSO = SMESH::FindSObject(aMesh.in());
608       myMeshShape = SMESH::GetGeom(aSO);
609
610       // Clear fields of geom objects if mesh was changed
611       if (myMesh != aMesh) {
612         for (int i = Object; i <= Ids; i++) {
613           myGeomObj[ i ] = GEOM::GEOM_Object::_nil();
614           mySelEdit[ i ]->setText("");
615         }
616       }
617
618       myMesh = aMesh;
619
620       // Set name of mesh in line edit
621       QString aName;
622       SMESH::GetNameOfSelectedIObjects(mySelectionMgr, aName);
623       mySelEdit[ Mesh ]->setText(aName);
624
625     } else if (mySelInput == Ids) {
626       SALOME_ListIO aList;
627       mySelectionMgr->selectedObjects(aList,SVTK_Viewer::Type());
628       if (aList.Extent() != 1)
629         return;
630
631       QString anIds;
632       if (!SMESH::GetNameOfSelectedElements(mySelector, aList.First(), anIds))
633         anIds = "";
634
635       myBusy = true;
636       mySelEdit[ Ids ]->setText(anIds);
637       myBusy = false;
638
639     } else {
640       SALOME_ListIO aList;
641       mySelectionMgr->selectedObjects(aList, SVTK_Viewer::Type());
642       if (aList.Extent() != 1)
643         return;
644
645       // Get geom object from selection
646       Handle(SALOME_InteractiveObject) anIO = aList.First();
647       GEOM::GEOM_Object_var anObj = SMESH::IObjectToInterface<GEOM::GEOM_Object>(anIO);
648       if (anObj->_is_nil())
649         return;
650
651       // Clear fields of vertexes if face or 3d block was changed
652       if (anObj != myGeomObj[ mySelInput ] && mySelInput == Object) {
653         for (int i = Vertex1; i <= Vertex2; i++) {
654           myGeomObj[ i ] = GEOM::GEOM_Object::_nil();
655           mySelEdit[ i ]->setText("");
656         }
657       }
658
659       myGeomObj[ mySelInput ] = anObj;
660
661       // Set name of geom object in line edit
662       QString aName;
663       SMESH::GetNameOfSelectedIObjects(mySelectionMgr, aName);
664       mySelEdit[ mySelInput ]->setText(aName);
665     }
666   } catch (const SALOME::SALOME_Exception& S_ex) {
667     SalomeApp_Tools::QtCatchCorbaException(S_ex);
668     resetSelInput();
669   } catch (...) {
670     resetSelInput();
671   }
672
673   updateWgState();
674   displayPreview();
675 }
676
677 //=======================================================================
678 // name    : SMESHGUI_MeshPatternDlg::resetSelInput
679 // Purpose : Reset fields corresponding to the current selection input
680 //=======================================================================
681 void SMESHGUI_MeshPatternDlg::resetSelInput()
682 {
683   if (mySelInput == Mesh)
684   {
685     myMesh = SMESH::SMESH_Mesh::_nil();
686     myMeshShape = GEOM::GEOM_Object::_nil();
687   }
688
689   else
690     myGeomObj[ mySelInput ] = GEOM::GEOM_Object::_nil();
691
692   mySelEdit[ mySelInput ]->setText("");
693 }
694
695 //=======================================================================
696 // name    : SMESHGUI_MeshPatternDlg::onDeactivate
697 // Purpose : SLOT called when dialog must be deativated
698 //=======================================================================
699 void SMESHGUI_MeshPatternDlg::onDeactivate()
700 {
701   mySelectionMgr->clearFilters();
702   //if (myReverseChk->isChecked())
703   //  erasePreview();
704   disconnect(mySelectionMgr, 0, this, 0);
705   setEnabled(false);
706 }
707
708 //=======================================================================
709 // name    : SMESHGUI_MeshPatternDlg::enterEvent
710 // Purpose : Event filter
711 //=======================================================================
712 void SMESHGUI_MeshPatternDlg::enterEvent (QEvent*)
713 {
714   if (myIsCreateDlgOpen)
715     return;
716
717   if (myReverseChk->isChecked())
718     displayPreview();
719   mySMESHGUI->EmitSignalDeactivateDialog();
720   setEnabled(true);
721   activateSelection();
722   connect(mySelectionMgr, SIGNAL(currentSelectionChanged()), SLOT(onSelectionDone()));
723   onTextChanged(mySelEdit[Ids]->text());
724 }
725
726 //=======================================================================
727 // name    : SMESHGUI_MeshPatternDlg::closeEvent
728 // Purpose :
729 //=======================================================================
730 void SMESHGUI_MeshPatternDlg::closeEvent (QCloseEvent*)
731 {
732   onClose();
733 }
734
735 //=======================================================================
736 // name    : SMESHGUI_MeshPatternDlg::onSelInputChanged
737 // Purpose : SLOT. Called when -> button clicked.
738 //           Change current selection input field
739 //=======================================================================
740 void SMESHGUI_MeshPatternDlg::onSelInputChanged()
741 {
742   const QObject* aSender = sender();
743   for (int i = Mesh; i <= Ids; i++)
744     if (aSender == mySelBtn[ i ])
745       mySelInput = i;
746
747   activateSelection();
748   onSelectionDone();
749 }
750
751 //=======================================================================
752 // name    : SMESHGUI_MeshPatternDlg::prepareFilters
753 // Purpose : Prepare filters for dialog
754 //=======================================================================
755 QStringList SMESHGUI_MeshPatternDlg::prepareFilters() const
756 {
757   static QStringList aList;
758   if (aList.isEmpty())
759   {
760     aList.append(tr("PATTERN_FILT"));
761     //aList.append(tr("ALL_FILES_FILTER"));
762   }
763
764   return aList;
765 }
766
767 //=======================================================================
768 // name    : SMESHGUI_MeshPatternDlg::autoExtension
769 // Purpose : Append extension to the file name
770 //=======================================================================
771 QString SMESHGUI_MeshPatternDlg::autoExtension (const QString& theFileName) const
772 {
773   QString anExt = theFileName.section('.', -1);
774   return anExt != "smp" && anExt != "SMP" ? theFileName + ".smp" : theFileName;
775 }
776
777 //=======================================================================
778 // name    : SMESHGUI_MeshPatternDlg::onOpen
779 // Purpose : SLOT. Called when "Open" button clicked.
780 //           Displays file open dialog
781 //=======================================================================
782 void SMESHGUI_MeshPatternDlg::onOpen()
783 {
784   SUIT_FileDlg* aDlg = new SUIT_FileDlg (this, true);
785   aDlg->setWindowTitle(tr("LOAD_PATTERN"));
786   aDlg->setFileMode(QFileDialog::ExistingFile);
787   aDlg->setFilters(prepareFilters());
788   if (!myName->text().isEmpty())
789     aDlg->selectFile(myName->text() + ".smp");
790   QPushButton* anOkBtn = qFindChild<QPushButton*>( aDlg, "OK" );
791   if (anOkBtn != 0)
792     anOkBtn->setText(tr("SMESH_BUT_OK"));
793
794   if (aDlg->exec() != Accepted)
795     return;
796
797   QString fName = aDlg->selectedFile();
798   if (fName.isEmpty())
799     return;
800
801   if (QFileInfo(fName).suffix().isEmpty())
802     fName = autoExtension(fName);
803
804   fName = QDir::convertSeparators(fName);
805
806   QString prev = QDir::convertSeparators(myName->text());
807   if (prev == fName)
808     return;
809
810   // Read string from file
811   QFile aFile(fName);
812   if (!aFile.open(QIODevice::ReadOnly)) {
813     SUIT_MessageBox::information(this, tr("SMESH_ERROR"),
814                                  tr("ERROR_OF_OPENING"));
815     return;
816   }
817
818   QByteArray aDataArray = aFile.readAll();
819   if (aDataArray.isEmpty()) {
820     SUIT_MessageBox::information(this, tr("SMESH_ERROR"),
821                                  tr("ERROR_OF_READING"));
822     return;
823   }
824
825   if (loadFromFile(aDataArray))
826     myName->setText(QFileInfo(fName).completeBaseName());
827
828   updateWgState();
829   displayPreview();
830 }
831
832 //=======================================================================
833 // name    : SMESHGUI_MeshPatternDlg::onCloseCreationDlg
834 // Purpose : SLOT. Called when "Pattern creation" dialog closed with "Close"
835 //=======================================================================
836 void SMESHGUI_MeshPatternDlg::onCloseCreationDlg()
837 {
838   setEnabled(true);
839   myIsCreateDlgOpen = false;
840 }
841
842 //=======================================================================
843 // name    : SMESHGUI_MeshPatternDlg::onOkCreationDlg
844 // Purpose : SLOT. Called when "Pattern creation" dialog closed with OK
845 //           or SAVE buttons. Initialize myPattern field. Redisplay preview
846 //=======================================================================
847 void SMESHGUI_MeshPatternDlg::onOkCreationDlg()
848 {
849   myPattern = SMESH::SMESH_Pattern::_duplicate(myCreationDlg->GetPattern());
850   myName->setText(myCreationDlg->GetPatternName());
851
852   updateWgState();
853   displayPreview();
854
855   setEnabled(true);
856   myIsCreateDlgOpen = false;
857 }
858
859 //=======================================================================
860 // name    : SMESHGUI_MeshPatternDlg::onNew
861 // Purpose : SLOT. Called when "New..." button clicked. Create new pattern
862 //=======================================================================
863 void SMESHGUI_MeshPatternDlg::onNew()
864 {
865   setEnabled(false);
866   myIsCreateDlgOpen = true;
867   if (myCreationDlg == 0)
868   {
869     myCreationDlg = new SMESHGUI_CreatePatternDlg( mySMESHGUI, myType);
870     connect(myCreationDlg, SIGNAL(NewPattern()), SLOT(onOkCreationDlg()));
871     connect(myCreationDlg, SIGNAL(Close()), SLOT(onCloseCreationDlg()));
872   }
873   else
874     myCreationDlg->Init(myType);
875
876   myCreationDlg->SetMesh(myMesh);
877   myCreationDlg->show();
878 }
879
880 //=======================================================================
881 // name    : SMESHGUI_MeshPatternDlg::onReverse
882 // Purpose : SLOT. Called when state of "Reverse order..." checkbox chaged
883 //           Calculate new points of the mesh to be created. Redisplay preview
884 //=======================================================================
885 void SMESHGUI_MeshPatternDlg::onReverse (bool)
886 {
887   displayPreview();
888 }
889
890 //=======================================================================
891
892 // name    : SMESHGUI_MeshPatternDlg::onPreview
893 // Purpose : SLOT. Called when state of "Preview" checkbox changed
894 //           Display/Erase preview
895 //=======================================================================
896 void SMESHGUI_MeshPatternDlg::onPreview (bool)
897 {
898   displayPreview();
899 }
900
901 //=======================================================================
902 // name    : SMESHGUI_MeshPatternDlg::displayPreview
903 // Purpose : Display preview
904 //=======================================================================
905 void SMESHGUI_MeshPatternDlg::displayPreview()
906 {
907   try {
908     // Redisplay preview in dialog
909     SMESH::point_array_var pnts = myPattern->GetPoints();
910     SMESH::long_array_var keyPoints = myPattern->GetKeyPoints();
911     SMESH::array_of_long_array_var elemPoints = myPattern->GetElementPoints(false);
912
913     if (pnts->length()       == 0 ||
914         keyPoints->length()  == 0 ||
915         elemPoints->length() == 0) {
916       erasePreview();
917       return;
918     } else {
919       PointVector aPoints(pnts->length());
920       QVector<int> aKeyPoints(keyPoints->length());
921       ConnectivityVector anElemPoints(elemPoints->length());
922
923       for (int i = 0, n = pnts->length(); i < n; i++)
924         aPoints[ i ] = pnts[ i ];
925
926       for (int i2 = 0, n2 = keyPoints->length(); i2 < n2; i2++)
927         aKeyPoints[ i2 ] = keyPoints[ i2 ];
928
929       for (int i3 = 0, n3 = elemPoints->length(); i3 < n3; i3++) {
930         QVector<int> aVec(elemPoints[ i3 ].length());
931         for (int i4 = 0, n4 = elemPoints[ i3 ].length(); i4 < n4; i4++)
932           aVec[ i4 ] = elemPoints[ i3 ][ i4 ];
933
934         anElemPoints[ i3 ] = aVec;
935       }
936
937       myPicture2d->SetPoints(aPoints, aKeyPoints, anElemPoints);
938     }
939
940     // Redisplay preview in 3D viewer
941     if (myPreviewActor != 0) {
942       if (SVTK_ViewWindow* vf = SMESH::GetCurrentVtkView()) {
943         vf->RemoveActor(myPreviewActor);
944         vf->Repaint();
945       }
946       myPreviewActor->Delete();
947       myPreviewActor = 0;
948     }
949
950     if (!myPreviewChk->isChecked() || !isValid(false))
951       return;
952
953     vtkUnstructuredGrid* aGrid = getGrid();
954     if (aGrid == 0)
955       return;
956
957     // Create and display actor
958     vtkDataSetMapper* aMapper = vtkDataSetMapper::New();
959     aMapper->SetInput(aGrid);
960
961     myPreviewActor = SALOME_Actor::New();
962     myPreviewActor->PickableOff();
963     myPreviewActor->SetMapper(aMapper);
964
965     vtkProperty* aProp = vtkProperty::New();
966     aProp->SetRepresentationToWireframe();
967     aProp->SetColor(250, 0, 250);
968     if (SMESH::FindActorByObject(myMesh))
969       aProp->SetLineWidth( SMESH::GetFloat( "SMESH:element_width", 1 ) + 1 );
970     else
971       aProp->SetLineWidth(1);
972     myPreviewActor->SetProperty(aProp);
973
974     myPreviewActor->SetRepresentation(3);
975
976     SMESH::GetCurrentVtkView()->AddActor(myPreviewActor);
977     SMESH::GetCurrentVtkView()->Repaint();
978
979     aProp->Delete();
980     aGrid->Delete();
981   } catch (const SALOME::SALOME_Exception& S_ex) {
982     SalomeApp_Tools::QtCatchCorbaException(S_ex);
983     erasePreview();
984   } catch (...) {
985     erasePreview();
986   }
987 }
988
989 //=======================================================================
990 // name    : SMESHGUI_MeshPatternDlg::erasePreview
991 // Purpose : Erase preview
992 //=======================================================================
993 void SMESHGUI_MeshPatternDlg::erasePreview()
994 {
995   // Erase preview in 2D viewer
996   myPicture2d->SetPoints(PointVector(), QVector<int>(), ConnectivityVector());
997
998   // Erase preview in 3D viewer
999   if (myPreviewActor == 0)
1000     return;
1001
1002
1003   if (SVTK_ViewWindow* vf = SMESH::GetCurrentVtkView())
1004   {
1005     vf->RemoveActor(myPreviewActor);
1006     vf->Repaint();
1007   }
1008   myPreviewActor->Delete();
1009   myPreviewActor = 0;
1010 }
1011
1012 //=======================================================================
1013 // name    : SMESHGUI_MeshPatternDlg::updateWgState
1014 // Purpose : Enable/disable selection widgets
1015 //=======================================================================
1016 void SMESHGUI_MeshPatternDlg::updateWgState()
1017 {
1018   if (myMesh->_is_nil()) {
1019     for (int i = Object; i <= Ids; i++) {
1020       mySelBtn [ i ]->setEnabled(false);
1021       mySelEdit[ i ]->setEnabled(false);
1022       mySelEdit[ i ]->setText("");
1023     }
1024     myNode1->setEnabled(false);
1025     myNode2->setEnabled(false);
1026     myNode1->setRange(0, 0);
1027     myNode2->setRange(0, 0);
1028   } else {
1029     mySelBtn [ Object ]->setEnabled(true);
1030     mySelEdit[ Object ]->setEnabled(true);
1031     mySelBtn [ Ids ]   ->setEnabled(true);
1032     mySelEdit[ Ids ]   ->setEnabled(true);
1033
1034     if (myGeomObj[ Object ]->_is_nil()) {
1035       for (int i = Vertex1; i <= Vertex2; i++) {
1036         mySelBtn [ i ]->setEnabled(false);
1037         mySelEdit[ i ]->setEnabled(false);
1038         mySelEdit[ i ]->setText("");
1039       }
1040     } else {
1041       for (int i = Object; i <= Vertex2; i++) {
1042         mySelBtn [ i ]->setEnabled(true);
1043         mySelEdit[ i ]->setEnabled(true);
1044       }
1045     }
1046
1047     QList<int> ids;
1048     if (!CORBA::is_nil(myPattern)/* && getIds(ids)*/) {
1049       SMESH::long_array_var keyPoints = myPattern->GetKeyPoints();
1050       if (keyPoints->length()) {
1051         myNode1->setEnabled(true);
1052         myNode2->setEnabled(true);
1053         myNode1->setRange(1, keyPoints->length());
1054         myNode2->setRange(1, keyPoints->length());
1055         return;
1056       }
1057     }
1058
1059     myNode1->setEnabled(false);
1060     myNode2->setEnabled(false);
1061     myNode1->setRange(0, 0);
1062     myNode2->setRange(0, 0);
1063   }
1064 }
1065
1066 //=======================================================================
1067 // name    : SMESHGUI_MeshPatternDlg::activateSelection
1068 // Purpose : Activate selection in accordance with current selection input
1069 //=======================================================================
1070 void SMESHGUI_MeshPatternDlg::activateSelection()
1071 {
1072   mySelectionMgr->clearFilters();
1073   if (mySelInput == Ids) {
1074     SMESH_Actor* anActor = SMESH::FindActorByObject(myMesh);
1075     if (anActor)
1076       SMESH::SetPickable(anActor);
1077
1078     if (myType == Type_2d)
1079       {
1080         if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
1081           aViewWindow->SetSelectionMode(FaceSelection);
1082       }
1083     else
1084       {
1085         if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
1086           aViewWindow->SetSelectionMode(CellSelection);
1087       }
1088   }
1089   else {
1090     SMESH::SetPickable();
1091     //mySelectionMgr->setSelectionModes(ActorSelection);
1092     if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
1093       aViewWindow->SetSelectionMode(ActorSelection);
1094   }
1095
1096   if (mySelInput == Object && !myMeshShape->_is_nil()) {
1097     if (myType == Type_2d) {
1098       if (myNbPoints > 0)
1099         mySelectionMgr->installFilter
1100           (new SMESH_NumberFilter ("GEOM", TopAbs_VERTEX, myNbPoints, TopAbs_FACE, myMeshShape));
1101       else
1102         mySelectionMgr->installFilter
1103           (new SMESH_NumberFilter ("GEOM", TopAbs_SHAPE, myNbPoints, TopAbs_FACE, myMeshShape));
1104     } else {
1105       TColStd_MapOfInteger aTypes;
1106       aTypes.Add(TopAbs_SHELL);
1107       aTypes.Add(TopAbs_SOLID);
1108       mySelectionMgr->installFilter
1109         (new SMESH_NumberFilter ("GEOM", TopAbs_FACE, 6, aTypes, myMeshShape, true));
1110     }
1111   } else if ((mySelInput == Vertex1 || mySelInput == Vertex2) && !myGeomObj[ Object ]->_is_nil()) {
1112     mySelectionMgr->installFilter
1113       (new SMESH_NumberFilter ("GEOM", TopAbs_SHAPE, 1, TopAbs_VERTEX, myGeomObj[ Object ]));
1114   } else {
1115   }
1116 }
1117
1118 //=======================================================================
1119 // name    : SMESHGUI_MeshPatternDlg::loadFromFile
1120 // Purpose : Load pattern from file
1121 //=======================================================================
1122 bool SMESHGUI_MeshPatternDlg::loadFromFile (const QString& theName)
1123 {
1124   try {
1125     SMESH::SMESH_Pattern_var aPattern = SMESH::GetPattern();
1126
1127     if (!aPattern->LoadFromFile(theName.toLatin1().data()) ||
1128         (myType == Type_2d && !aPattern->Is2D())) {
1129       SMESH::SMESH_Pattern::ErrorCode aCode = aPattern->GetErrorCode();
1130       QString aMess;
1131       if      (aCode == SMESH::SMESH_Pattern::ERR_READ_NB_POINTS     ) aMess = tr("ERR_READ_NB_POINTS");
1132       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_POINT_COORDS  ) aMess = tr("ERR_READ_POINT_COORDS");
1133       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_TOO_FEW_POINTS) aMess = tr("ERR_READ_TOO_FEW_POINTS");
1134       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_3D_COORD      ) aMess = tr("ERR_READ_3D_COORD");
1135       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_NO_KEYPOINT   ) aMess = tr("ERR_READ_NO_KEYPOINT");
1136       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_BAD_INDEX     ) aMess = tr("ERR_READ_BAD_INDEX");
1137       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_ELEM_POINTS   ) aMess = tr("ERR_READ_ELEM_POINTS");
1138       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_NO_ELEMS      ) aMess = tr("ERR_READ_NO_ELEMS");
1139       else if (aCode == SMESH::SMESH_Pattern::ERR_READ_BAD_KEY_POINT ) aMess = tr("ERR_READ_BAD_KEY_POINT");
1140       else                                                             aMess = tr("ERROR_OF_LOADING");
1141
1142       SUIT_MessageBox::information(this, tr("SMESH_ERROR"), aMess);
1143       return false;
1144     } else {
1145       myPattern = aPattern;
1146       return true;
1147     }
1148   } catch (const SALOME::SALOME_Exception& S_ex) {
1149     SalomeApp_Tools::QtCatchCorbaException(S_ex);
1150     SUIT_MessageBox::information(this, tr("SMESH_ERROR"),
1151                                  tr("ERROR_OF_LOADING") );
1152     return false;
1153   }
1154 }
1155
1156 //=======================================================================
1157 // name    : SMESHGUI_MeshPatternDlg::onTypeChanged
1158 // Purpose : SLOT. Called when pattern type changed.
1159 //           Change dialog's look and feel
1160 //=======================================================================
1161 void SMESHGUI_MeshPatternDlg::onTypeChanged (int theType)
1162 {
1163   if (myType == theType)
1164     return;
1165
1166   myType = theType;
1167
1168   myNbPoints = -1;
1169   myGeomObj[ Object  ] = GEOM::GEOM_Object::_nil();
1170   myGeomObj[ Vertex1 ] = GEOM::GEOM_Object::_nil();
1171   myGeomObj[ Vertex2 ] = GEOM::GEOM_Object::_nil();
1172   myPattern = SMESH::GetPattern();
1173
1174   myName->setText("");
1175   mySelEdit[ Object  ]->setText("");
1176   mySelEdit[ Vertex1 ]->setText("");
1177   mySelEdit[ Vertex2 ]->setText("");
1178   mySelEdit[ Ids ]    ->setText("");
1179   myCreatePolygonsChk->show();
1180   myCreatePolyedrsChk->show();
1181
1182   if (theType == Type_2d) {
1183     // Geom widgets
1184     mySelLbl [ Vertex2 ]->hide();
1185     mySelBtn [ Vertex2 ]->hide();
1186     mySelEdit[ Vertex2 ]->hide();
1187     myReverseChk->show();
1188     myPicture2d->show();
1189     myPicture3d->hide();
1190     mySelLbl[ Object  ]->setText(tr("FACE"));
1191     mySelLbl[ Vertex1 ]->setText(tr("VERTEX"));
1192     // Refine widgets
1193     mySelLbl[ Ids ]->setText(tr("MESH_FACES"));
1194     myNode2Lbl->hide();
1195     myNode2   ->hide();
1196   } else {
1197     // Geom widgets
1198     mySelLbl [ Vertex2 ]->show();
1199     mySelBtn [ Vertex2 ]->show();
1200     mySelEdit[ Vertex2 ]->show();
1201     myReverseChk->hide();
1202     myPicture2d->hide();
1203     myPicture3d->show();
1204     mySelLbl[ Object  ]->setText(tr("3D_BLOCK"));
1205     mySelLbl[ Vertex1 ]->setText(tr("VERTEX1"));
1206     mySelLbl[ Vertex2 ]->setText(tr("VERTEX2"));
1207     // Refine widgets
1208     mySelLbl[ Ids ]->setText(tr("MESH_VOLUMES"));
1209     myNode2Lbl->show();
1210     myNode2   ->show();
1211   }
1212
1213   mySelInput = Mesh;
1214   activateSelection();
1215   updateWgState();
1216   displayPreview();
1217 }
1218
1219 //=======================================================================
1220 // name    : SMESHGUI_MeshPatternDlg::getGrid
1221 // Purpose : Get unstructured grid for pattern
1222 //=======================================================================
1223 vtkUnstructuredGrid* SMESHGUI_MeshPatternDlg::getGrid()
1224 {
1225   try {
1226     // Get points from pattern
1227     SMESH::point_array_var pnts;
1228     QList<int> ids;
1229     if (isRefine() && getIds(ids)) {
1230       SMESH::long_array_var varIds = new SMESH::long_array();
1231       varIds->length(ids.count());
1232       int i = 0;
1233       for (QList<int>::iterator it = ids.begin(); it != ids.end(); ++it)
1234         varIds[i++] = *it;
1235       pnts = myType == Type_2d
1236         ? myPattern->ApplyToMeshFaces  (myMesh, varIds, getNode(false), myReverseChk->isChecked())
1237         : myPattern->ApplyToHexahedrons(myMesh, varIds, getNode(false), getNode(true));
1238     } else {
1239       pnts = myType == Type_2d
1240         ? myPattern->ApplyToFace   (myGeomObj[ Object ], myGeomObj[ Vertex1 ], myReverseChk->isChecked())
1241       : myPattern->ApplyTo3DBlock(myGeomObj[ Object ], myGeomObj[ Vertex1 ], myGeomObj[ Vertex2 ]);
1242     }
1243
1244     SMESH::array_of_long_array_var elemPoints = myPattern->GetElementPoints(true);
1245
1246     if (pnts->length() == 0 || elemPoints->length() == 0)
1247       return 0;
1248
1249     // to do : to be removed /////////////////////////////////////////////
1250
1251 #ifdef DEB_SLN
1252     for (int i1 = 0, n1 = pnts->length(); i1 < n1; i1++)
1253       printf("%d: %g %g %g\n", i1, pnts[ i1 ].x, pnts[ i1 ].y, pnts[ i1 ].z);
1254
1255     printf("\nELEMENTS : \n");
1256     for (int i2 = 0, n2 = elemPoints->length(); i2 < n2; i2++)
1257     {
1258
1259       printf("%d: ", i2);
1260       for (int i3 = 0, n3 = elemPoints[ i2 ].length(); i3 < n3; i3++)
1261         printf("%d ", elemPoints[ i2 ][ i3 ]);
1262
1263       printf("\n");
1264
1265     }
1266 #endif
1267     //////////////////////////////////////////////////////////////////////
1268
1269     // Calculate number of points used for cell
1270     vtkIdType aNbCells = elemPoints->length();
1271     vtkIdType aCellsSize = 0;
1272     for (int i = 0, n = elemPoints->length(); i < n; i++)
1273       aCellsSize += elemPoints[ i ].length();
1274
1275     // Create unstructured grid and other  usefull arrays
1276     vtkUnstructuredGrid* aGrid = vtkUnstructuredGrid::New();
1277
1278     vtkCellArray* aConnectivity = vtkCellArray::New();
1279     aConnectivity->Allocate(aCellsSize, 0);
1280
1281     vtkPoints* aPoints = vtkPoints::New();
1282     aPoints->SetNumberOfPoints(pnts->length());
1283
1284     vtkUnsignedCharArray* aCellTypesArray = vtkUnsignedCharArray::New();
1285     aCellTypesArray->SetNumberOfComponents(1);
1286     aCellTypesArray->Allocate(aNbCells * aCellTypesArray->GetNumberOfComponents());
1287
1288     vtkIdList *anIdList = vtkIdList::New();
1289
1290     // Fill array of points
1291     for (int p = 0, nbPnt = pnts->length(); p < nbPnt; p++)
1292       aPoints->SetPoint(p, pnts[ p ].x, pnts[ p ].y, pnts[ p ].z);
1293
1294     for (int e = 0, nbElem = elemPoints->length(); e < nbElem; e++) {
1295       int nbPoints = elemPoints[ e ].length();
1296       anIdList->SetNumberOfIds(nbPoints);
1297       for (int i = 0; i < nbPoints; i++)
1298         anIdList->SetId(i, elemPoints[ e ][ i ]);
1299
1300       aConnectivity->InsertNextCell(anIdList);
1301
1302       if      (nbPoints == 3) aCellTypesArray->InsertNextValue(VTK_TRIANGLE);
1303       else if (nbPoints == 5) aCellTypesArray->InsertNextValue(VTK_PYRAMID);
1304       else if (nbPoints == 6) aCellTypesArray->InsertNextValue(VTK_WEDGE);
1305       else if (nbPoints == 8) aCellTypesArray->InsertNextValue(VTK_HEXAHEDRON);
1306       else if (nbPoints == 4 && myType == Type_2d) aCellTypesArray->InsertNextValue(VTK_QUAD);
1307       else if (nbPoints == 4 && myType == Type_3d) aCellTypesArray->InsertNextValue(VTK_TETRA);
1308       else aCellTypesArray->InsertNextValue(VTK_EMPTY_CELL);
1309     }
1310
1311     VTKViewer_CellLocationsArray* aCellLocationsArray = VTKViewer_CellLocationsArray::New();
1312     aCellLocationsArray->SetNumberOfComponents(1);
1313     aCellLocationsArray->SetNumberOfTuples(aNbCells);
1314
1315     aConnectivity->InitTraversal();
1316     for (vtkIdType idType = 0, *pts, npts; aConnectivity->GetNextCell(npts, pts); idType++)
1317       aCellLocationsArray->SetValue(idType, aConnectivity->GetTraversalLocation(npts));
1318
1319     aGrid->SetPoints(aPoints);
1320     aGrid->SetCells(aCellTypesArray, aCellLocationsArray,aConnectivity);
1321
1322     aConnectivity->Delete();
1323     aPoints->Delete();
1324     aCellTypesArray->Delete();
1325     anIdList->Delete();
1326     aCellLocationsArray->Delete();
1327
1328     return aGrid;
1329   } catch (...) {
1330     return 0;
1331   }
1332 }
1333
1334 //=======================================================================
1335 // name    : onModeToggled
1336 // Purpose :
1337 //=======================================================================
1338 void SMESHGUI_MeshPatternDlg::onModeToggled (bool on)
1339 {
1340   on ? myRefineGrp->show() : myRefineGrp->hide();
1341   on ? myGeomGrp->hide()   : myGeomGrp->show();
1342
1343   displayPreview();
1344 }
1345
1346 //=======================================================================
1347 // name    : isRefine
1348 // Purpose :
1349 //=======================================================================
1350 bool SMESHGUI_MeshPatternDlg::isRefine() const
1351 {
1352   return myRefine->isChecked();
1353 }
1354
1355 //=======================================================================
1356 // name    : onTextChanged
1357 // Purpose :
1358 //=======================================================================
1359 void SMESHGUI_MeshPatternDlg::onTextChanged (const QString& theNewText)
1360 {
1361   if (myBusy || !isRefine())
1362     return;
1363
1364   myBusy = true;
1365
1366   if (mySelInput != Ids) {
1367     mySelInput = Ids;
1368     activateSelection();
1369   }
1370
1371   // hilight entered elements/nodes
1372   SMDS_Mesh* aMesh = 0;
1373   SMESH_Actor* anActor = SMESH::FindActorByObject(myMesh);
1374   if (anActor)
1375     aMesh = anActor->GetObject()->GetMesh();
1376
1377   if (aMesh) {
1378     QStringList aListId = theNewText.split(" ", QString::SkipEmptyParts);
1379
1380     TColStd_MapOfInteger newIndices;
1381
1382     for (int i = 0; i < aListId.count(); i++) {
1383       const SMDS_MeshElement * e = aMesh->FindElement(aListId[ i ].toInt());
1384       if (e && e->GetType() == (myType == Type_2d ? SMDSAbs_Face : SMDSAbs_Volume))
1385         newIndices.Add(e->GetID());
1386     }
1387     mySelector->AddOrRemoveIndex( anActor->getIO(), newIndices, false);
1388     if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
1389       aViewWindow->highlight( anActor->getIO(), true, true );
1390   }
1391
1392   myBusy = false;
1393
1394   displayPreview();
1395 }
1396
1397 //=======================================================================
1398 // name    : onNodeChanged
1399 // Purpose :
1400 //=======================================================================
1401 void SMESHGUI_MeshPatternDlg::onNodeChanged (int value)
1402 {
1403   if (myType == Type_3d) {
1404     SalomeApp_IntSpinBox* first = (SalomeApp_IntSpinBox*)sender();
1405     SalomeApp_IntSpinBox* second = first == myNode1 ? myNode2 : myNode1;
1406     int secondVal = second->value();
1407     if (secondVal == value) {
1408       secondVal = value == second->maximum() ? second->minimum() : value + 1;
1409       bool blocked = second->signalsBlocked();
1410       second->blockSignals(true);
1411       second->setValue(secondVal);
1412       second->blockSignals(blocked);
1413     }
1414   }
1415
1416   displayPreview();
1417 }
1418
1419 //=======================================================================
1420 // name    : getIds
1421 // Purpose :
1422 //=======================================================================
1423 bool SMESHGUI_MeshPatternDlg::getIds (QList<int>& ids) const
1424 {
1425   ids.clear();
1426   QStringList strIds = mySelEdit[Ids]->text().split(" ", QString::SkipEmptyParts );
1427   bool isOk;
1428   int val;
1429   for (QStringList::iterator it = strIds.begin(); it != strIds.end(); ++it) {
1430     val = (*it).toInt(&isOk);
1431     if (isOk)
1432       ids.append(val);
1433   }
1434
1435   return ids.count();
1436 }
1437
1438 //=======================================================================
1439 // name    : getNode1
1440 // Purpose :
1441 //=======================================================================
1442 int SMESHGUI_MeshPatternDlg::getNode (bool second) const
1443 {
1444   return second ? myNode2->value() - 1 : myNode1->value() - 1;
1445 }
1446
1447 //=================================================================================
1448 // function : keyPressEvent()
1449 // purpose  :
1450 //=================================================================================
1451 void SMESHGUI_MeshPatternDlg::keyPressEvent( QKeyEvent* e )
1452 {
1453   QDialog::keyPressEvent( e );
1454   if ( e->isAccepted() )
1455     return;
1456
1457   if ( e->key() == Qt::Key_F1 )
1458     {
1459       e->accept();
1460       onHelp();
1461     }
1462 }