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