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