Salome HOME
PAL19566, PAL19567, PAL19571, PAL19572
[modules/smesh.git] / src / SMESHGUI / SMESHGUI_FilterLibraryDlg.cxx
1 // SMESH SMESHGUI : GUI for SMESH component
2 //
3 // Copyright (C) 2003  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 // File   : SMESHGUI_FilterLibraryDlg.cxx
23 // Author : Sergey LITONIN, Open CASCADE S.A.S.
24 //
25
26 // SMESH includes
27 #include "SMESHGUI_FilterLibraryDlg.h"
28
29 #include "SMESHGUI.h"
30 #include "SMESHGUI_FilterUtils.h"
31 #include "SMESHGUI_FilterDlg.h"
32
33 // SALOME GUI includes
34 #include <SUIT_Session.h>
35 #include <SUIT_Desktop.h>
36 #include <SUIT_FileDlg.h>
37 #include <SUIT_MessageBox.h>
38 #include <SUIT_ResourceMgr.h>
39
40 #include <LightApp_Application.h>
41
42 // Qt includes
43 #include <QApplication>
44 #include <QVBoxLayout>
45 #include <QHBoxLayout>
46 #include <QGridLayout>
47 #include <QLineEdit>
48 #include <QPushButton>
49 #include <QGroupBox>
50 #include <QLabel>
51 #include <QListWidget>
52 #include <QFileInfo>
53 #include <QDir>
54 #include <QKeyEvent>
55
56 #define SPACING 6
57 #define MARGIN  11
58
59 /*!
60  *  Class       : SMESHGUI_FilterLibraryDlg::Dialog
61  *  Description : Dialog for opening filter library
62  */
63
64 class SMESHGUI_FilterLibraryDlg::Dialog : public SUIT_FileDlg
65 {
66 public:
67   Dialog(QWidget* theParent, const bool theToOpen);
68   virtual ~Dialog();
69
70 protected:
71   virtual bool acceptData();
72 };
73
74 SMESHGUI_FilterLibraryDlg::Dialog::Dialog (QWidget*   theParent,
75                                            const bool theToOpen)
76   : SUIT_FileDlg(theParent, theToOpen)
77 {
78 }
79
80 SMESHGUI_FilterLibraryDlg::Dialog::~Dialog()
81 {
82 }
83
84 bool SMESHGUI_FilterLibraryDlg::Dialog::acceptData()
85 {
86 //  if (mode() != QFileDialogP::AnyFile)
87 //    return SUIT_FileDlg::acceptData();
88
89   return true;
90 }
91
92 /*!
93  *  Class       : SMESHGUI_FilterLibraryDlg
94  *  Description : Dialog to specify filters for VTK viewer
95  */
96
97 //=======================================================================
98 // name    : SMESHGUI_FilterLibraryDlg::SMESHGUI_FilterLibraryDlg
99 // Purpose : Constructor
100 //=======================================================================
101 SMESHGUI_FilterLibraryDlg::SMESHGUI_FilterLibraryDlg (SMESHGUI* theModule,
102                                                       QWidget* parent,
103                                                       const QList<int>& theTypes,
104                                                       const int theMode)
105   : QDialog( parent ),
106     mySMESHGUI( theModule )
107 {
108   setModal(false);
109   construct(theTypes, theMode);
110 }
111
112 //=======================================================================
113 // name    : SMESHGUI_FilterLibraryDlg::SMESHGUI_FilterLibraryDlg
114 // Purpose : Constructor
115 //=======================================================================
116 SMESHGUI_FilterLibraryDlg::SMESHGUI_FilterLibraryDlg (SMESHGUI* theModule,
117                                                       QWidget* parent,
118                                                       const int   theType,
119                                                       const int   theMode)
120   : QDialog( parent ),
121     mySMESHGUI( theModule )
122 {
123   setModal(true);
124   QList<int> aTypes;
125   aTypes.append(theType);
126   construct(aTypes, theMode);
127 }
128
129 //=======================================================================
130 // name    : SMESHGUI_FilterLibraryDlg::construct
131 // Purpose : Construct dialog (called by constructor)
132 //=======================================================================
133 void SMESHGUI_FilterLibraryDlg::construct (const QList<int>& theTypes,
134                                            const int theMode)
135 {
136   myTypes = theTypes;
137   myMode  = theMode;
138
139   QVBoxLayout* aDlgLay = new QVBoxLayout(this);
140   aDlgLay->setMargin(MARGIN);
141   aDlgLay->setSpacing(SPACING);
142
143   myMainFrame        = createMainFrame  (this);
144   QWidget* aBtnFrame = createButtonFrame(this);
145
146   aDlgLay->addWidget(myMainFrame);
147   aDlgLay->addWidget(aBtnFrame);
148
149   aDlgLay->setStretchFactor(myMainFrame, 1);
150
151   myHelpFileName = "selection_filter_library_page.html";
152   
153   Init(myTypes, myMode);
154 }
155
156 //=======================================================================
157 // name    : SMESHGUI_FilterLibraryDlg::createMainFrame
158 // Purpose : Create frame containing dialog's input fields
159 //=======================================================================
160 QWidget* SMESHGUI_FilterLibraryDlg::createMainFrame (QWidget* theParent)
161 {
162   QWidget* aMainFrame = new QWidget(theParent);
163   QGridLayout* aMainLay = new QGridLayout(aMainFrame);
164   aMainLay->setMargin(0);
165   aMainLay->setSpacing(SPACING);
166
167   // library name
168
169   QLabel* aFileLab = new QLabel(tr("LIBRARY_FILE"), aMainFrame);
170   myFileName = new QLineEdit(aMainFrame);
171   myOpenBtn = new QPushButton(aMainFrame);
172   myOpenBtn->setIcon(SUIT_Session::session()->resourceMgr()->loadPixmap(
173     "SUIT", tr("ICON_FILE_OPEN")));
174
175   // filters list box
176
177   QGroupBox* aFiltersGrp = new QGroupBox(tr("FILTER_NAMES"), aMainFrame);
178   QGridLayout* aLay = new QGridLayout(aFiltersGrp);
179   aLay->setMargin(MARGIN);
180   aLay->setSpacing(SPACING);
181
182   myListBox = new QListWidget(aFiltersGrp);
183
184   myAddBtn    = new QPushButton(tr("ADD"), aFiltersGrp);
185   myDeleteBtn = new QPushButton(tr("DELETE"), aFiltersGrp);
186
187   aLay->addWidget(myListBox,   0, 0, 3, 1);
188   aLay->addWidget(myAddBtn,    0, 1);
189   aLay->addWidget(myDeleteBtn, 1, 1);
190   aLay->setRowStretch(2, 5);
191
192   // filter name
193
194   myNameGrp = new QWidget(aMainFrame);
195   QHBoxLayout* myNameGrpLayout = new QHBoxLayout(myNameGrp);
196   myNameGrpLayout->setMargin(0);
197   myNameGrpLayout->setSpacing(SPACING);
198
199   myNameGrpLayout->addWidget( new QLabel(tr("FILTER_NAME"), myNameGrp) );
200   myNameGrpLayout->addWidget( myName = new QLineEdit(myNameGrp) );
201
202   // table
203
204   myTable = new SMESHGUI_FilterTable( mySMESHGUI, aMainFrame, myTypes);
205   myTable->SetEditable(myMode == EDIT);
206   myTable->SetLibsEnabled(false);
207
208   myListBox->setMinimumHeight((int)(myTable->sizeHint().height() * 0.5));
209   //myListBox->setRowMode(QListWidget::FitToWidth); //VSR : TODO ???
210   myListBox->setSelectionMode(QListWidget::SingleSelection);
211
212   myOpenBtn->setAutoDefault(false);
213   myAddBtn->setAutoDefault(false);
214   myDeleteBtn->setAutoDefault(false);
215
216   aMainLay->addWidget(aFileLab,    0, 0);
217   aMainLay->addWidget(myFileName,  0, 1);
218   aMainLay->addWidget(myOpenBtn,   0, 2);
219   aMainLay->addWidget(aFiltersGrp, 1, 0, 1, 3);
220   aMainLay->addWidget(myNameGrp,   2, 0, 1, 3);
221   aMainLay->addWidget(myTable,     3, 0, 1, 3);
222
223   // connect signals and slots
224
225   connect(myFileName, SIGNAL(returnPressed()), this, SLOT(onReturnPressed()));
226   connect(myOpenBtn, SIGNAL(clicked()), this, SLOT(onBrowse()));
227
228   connect(myListBox, SIGNAL( currentItemChanged( QListWidgetItem*, QListWidgetItem* ) ),
229           this, SLOT( onFilterChanged( QListWidgetItem*, QListWidgetItem* ) ) );
230
231   connect(myAddBtn, SIGNAL(clicked()), this, SLOT(onAddBtnPressed()));
232   connect(myDeleteBtn, SIGNAL(clicked()), this, SLOT(onDeleteBtnPressed()));
233
234   connect(myName, SIGNAL(textChanged(const QString&)),
235            this, SLOT(onFilterNameChanged(const QString&)));
236
237   connect(myTable, SIGNAL(EntityTypeChanged(const int)),
238            this, SLOT(onEntityTypeChanged(const int)));
239
240   connect(myTable, SIGNAL(NeedValidation()), this, SLOT(onNeedValidation()));
241
242   return aMainFrame;
243 }
244
245 //=======================================================================
246 // name    : SMESHGUI_FilterLibraryDlg::createButtonFrame
247 // Purpose : Create frame containing buttons
248 //=======================================================================
249 QWidget* SMESHGUI_FilterLibraryDlg::createButtonFrame (QWidget* theParent)
250 {
251   QGroupBox* aGrp = new QGroupBox(theParent);
252   QHBoxLayout* aLay = new QHBoxLayout(aGrp);
253   aLay->setMargin(MARGIN);
254   aLay->setSpacing(SPACING);
255
256   myButtons[ BTN_OK    ] = new QPushButton(tr("SMESH_BUT_OK"   ), aGrp);
257   myButtons[ BTN_Apply ] = new QPushButton(tr("SMESH_BUT_APPLY"), aGrp);
258
259   QLabel* aLbl = new QLabel(aGrp);
260   aLbl->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
261
262   myButtons[ BTN_Cancel ] = new QPushButton(tr("SMESH_BUT_CANCEL"), aGrp);
263   myButtons[ BTN_Close  ] = new QPushButton(tr("SMESH_BUT_CLOSE"),  aGrp);
264   myButtons[ BTN_Help   ] = new QPushButton(tr("SMESH_BUT_HELP"),   aGrp);
265
266   aLay->addWidget(myButtons[ BTN_OK     ]);
267   aLay->addSpacing(10);
268   aLay->addWidget(myButtons[ BTN_Apply  ]);
269   aLay->addSpacing(10);
270   aLay->addStretch();
271   aLay->addWidget(myButtons[ BTN_Cancel ]);
272   aLay->addWidget(myButtons[ BTN_Close  ]);
273   aLay->addWidget(myButtons[ BTN_Help   ]);
274
275   connect(myButtons[ BTN_OK     ], SIGNAL(clicked()), SLOT(onOk()));
276   connect(myButtons[ BTN_Cancel ], SIGNAL(clicked()), SLOT(onClose()));
277   connect(myButtons[ BTN_Close  ], SIGNAL(clicked()), SLOT(onClose()));
278   connect(myButtons[ BTN_Apply  ], SIGNAL(clicked()), SLOT(onApply()));
279   connect(myButtons[ BTN_Help   ], SIGNAL(clicked()), SLOT(onHelp()));
280
281   QMap<int, QPushButton*>::iterator anIter;
282   for (anIter = myButtons.begin(); anIter != myButtons.end(); ++anIter)
283     anIter.value()->setAutoDefault(false);
284
285   updateMainButtons();
286
287   return aGrp;
288 }
289
290 //=======================================================================
291 // name    : SMESHGUI_FilterLibraryDlg::updateMainButtons
292 // Purpose : Update visibility of main buttons (OK, Cancel, Close ...)
293 //=======================================================================
294 void SMESHGUI_FilterLibraryDlg::updateMainButtons()
295 {
296   if (myTypes.count() == 1) {
297     myButtons[ BTN_Cancel ]->show();
298     myButtons[ BTN_Apply  ]->hide();
299     myButtons[ BTN_Close  ]->hide();
300   } else {
301     myButtons[ BTN_Cancel ]->hide();
302     myButtons[ BTN_Apply  ]->show();
303     myButtons[ BTN_Close  ]->show();
304   }
305 }
306
307 //=======================================================================
308 // name    : SMESHGUI_FilterLibraryDlg::~SMESHGUI_FilterLibraryDlg
309 // Purpose : Destructor
310 //=======================================================================
311 SMESHGUI_FilterLibraryDlg::~SMESHGUI_FilterLibraryDlg()
312 {
313 }
314
315 //=======================================================================
316 // name    : SMESHGUI_FilterLibraryDlg::Init
317 // Purpose : Init dialog fields, connect signals and slots, show dialog
318 //=======================================================================
319 void SMESHGUI_FilterLibraryDlg::Init (const int type, const int theMode)
320 {
321   QList<int> aTypes;
322   aTypes.append(type);
323   Init(aTypes, theMode);
324 }
325
326 //=======================================================================
327 // name    : SMESHGUI_FilterLibraryDlg::Init
328 // Purpose : Init dialog fields, connect signals and slots, show dialog
329 //=======================================================================
330 void SMESHGUI_FilterLibraryDlg::Init (const QList<int>& theTypes,
331                                       const int theMode)
332 {
333   myMode = theMode;
334   myTypes = theTypes;
335   myTable->Init(theTypes);
336   myCurrFilterName = "";
337   myCurrFilter = -1;
338   myListBox->blockSignals(true);
339   myListBox->clear();
340   myListBox->blockSignals(false);
341   myName->clear();
342   myTable->Clear();
343
344   updateControlsVisibility();
345   setEnabled(true);
346
347   connect( mySMESHGUI, SIGNAL(SignalDeactivateActiveDialog()), SLOT(onDeactivate()));
348   connect( mySMESHGUI, SIGNAL(SignalCloseAllDialogs()), SLOT(onClose()));
349
350   if (myMode == ADD_TO)
351   {
352     setWindowTitle(tr("ADD_TO_TLT"));
353     if (myFileName->text().isEmpty())
354       myFileName->setText(getDefaultLibraryName());
355     processNewLibrary();
356   }
357   else if (myMode == COPY_FROM)
358   {
359     setWindowTitle(tr("COPY_FROM_TLT"));
360     if (myFileName->text().isEmpty())
361       myFileName->setText(getDefaultLibraryName());
362     processNewLibrary();
363     if (myListBox->count() > 0)
364       myListBox->setCurrentItem(0);
365   }
366   else
367   {
368     setWindowTitle(tr("EDIT_LIB_TLT"));
369     if (myFileName->text().isEmpty())
370       myFileName->setText(getDefaultLibraryName());
371     processNewLibrary();
372     if (myListBox->count() > 0)
373       myListBox->setCurrentItem(0);
374   }
375
376   this->show();
377
378   updateMainButtons();
379   isPermissionValid(false);
380 }
381
382 //=======================================================================
383 // name    : SMESHGUI_FilterLibraryDlg::updateControlsVisibility
384 // Purpose : Update visibility of controls in accordance with myMode
385 //=======================================================================
386 void SMESHGUI_FilterLibraryDlg::updateControlsVisibility()
387 {
388   if (myMode == ADD_TO)
389   {
390     myNameGrp->show();
391     myNameGrp->setEnabled(true);
392     myAddBtn->hide();
393     myDeleteBtn->hide();
394     myTable->SetEditable(false);
395   }
396   else if (myMode == COPY_FROM)
397   {
398     myNameGrp->hide();
399     myNameGrp->setEnabled(false);
400     myAddBtn->hide();
401     myDeleteBtn->hide();
402     myTable->SetEditable(false);
403   }
404   else if (myMode == EDIT)
405   {
406     myNameGrp->show();
407     myNameGrp->setEnabled(true);
408     myAddBtn->show();
409     myDeleteBtn->show();
410     myTable->SetEditable(true);
411   }
412
413   qApp->processEvents();
414   updateGeometry();
415   adjustSize();
416 }
417
418 //=======================================================================
419 // name    : SMESHGUI_FilterLibraryDlg::onApply
420 // Purpose : SLOT called when "Apply" button pressed.
421 //=======================================================================
422 bool SMESHGUI_FilterLibraryDlg::onApply()
423 {
424   if (!isValid(true) || !isPermissionValid(false))
425     return false;
426
427   if (myLibrary->_is_nil()) {
428     SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_WRN_WARNING"),
429                                  tr("LIBRARY_IS_NOT_LOADED"));
430     return false;
431   }
432
433   if (myFileName->text() != myLibrary->GetFileName())
434     myLibrary->SetFileName(myFileName->text().toLatin1().data());
435
436   bool aResult = false;
437
438   if (myMode == COPY_FROM || myListBox->count() == 0) {
439     aResult = true;
440   } else if (myMode == EDIT || myMode == ADD_TO) {
441     SMESH::Filter_var aFilter = createFilter();
442     if (!myLibrary->Replace(myCurrFilterName.toLatin1().data(),
443                             myName->text().toLatin1().data(),
444                             aFilter.in())) {
445       SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_ERROR"),
446                                    tr("ERROR_OF_EDITING"));
447       aResult = false;
448     }
449     else
450       aResult = true;
451   }
452
453   if (aResult && myMode != COPY_FROM)
454     aResult = myLibrary->Save();
455
456   if (aResult) {
457     char* aFileName = myLibrary->GetFileName();
458     getDefaultLibraryName() = QString(aFileName);
459     delete aFileName;
460   } else if (myMode != COPY_FROM) {
461     SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_ERROR"),
462                                  tr("ERROR_OF_SAVING"));
463   } else {
464   }
465
466   return aResult;
467 }
468
469 //=======================================================================
470 // name    : SMESHGUI_FilterLibraryDlg::onOk
471 // Purpose : SLOT called when "Ok" button pressed.
472 //           Assign filters VTK viewer and close dialog
473 //=======================================================================
474 void SMESHGUI_FilterLibraryDlg::onOk()
475 {
476   if (onApply())
477   {
478     disconnect( mySMESHGUI, 0, this, 0);
479     mySMESHGUI->ResetState();
480     accept();
481   }
482 }
483
484 //=======================================================================
485 // name    : SMESHGUI_FilterLibraryDlg::onClose
486 // Purpose : SLOT called when "Close" button pressed. Close dialog
487 //=======================================================================
488 void SMESHGUI_FilterLibraryDlg::onClose()
489 {
490   disconnect( mySMESHGUI, 0, this, 0);
491   mySMESHGUI->ResetState();
492   reject();
493 }
494
495 //=================================================================================
496 // function : onHelp()
497 // purpose  :
498 //=================================================================================
499 void SMESHGUI_FilterLibraryDlg::onHelp()
500 {
501   LightApp_Application* app = (LightApp_Application*)(SUIT_Session::session()->activeApplication());
502   if (app) 
503     app->onHelpContextModule(mySMESHGUI ? app->moduleName(mySMESHGUI->moduleName()) : QString(""), myHelpFileName);
504   else {
505     QString platform;
506 #ifdef WIN32
507     platform = "winapplication";
508 #else
509     platform = "application";
510 #endif
511     SUIT_MessageBox::warning(this, tr("WRN_WARNING"),
512                              tr("EXTERNAL_BROWSER_CANNOT_SHOW_PAGE").
513                              arg(app->resourceMgr()->stringValue("ExternalBrowser", 
514                                                                  platform)).
515                              arg(myHelpFileName));
516   }
517 }
518
519 //=======================================================================
520 // name    : SMESHGUI_FilterLibraryDlg::onDeactivate
521 // Purpose : SLOT called when dialog must be deativated
522 //=======================================================================
523 void SMESHGUI_FilterLibraryDlg::onDeactivate()
524 {
525   setEnabled(false);
526 }
527
528 //=======================================================================
529 // name    : SMESHGUI_FilterLibraryDlg::enterEvent
530 // Purpose : Event filter
531 //=======================================================================
532 void SMESHGUI_FilterLibraryDlg::enterEvent(QEvent*)
533 {
534   setEnabled(true);
535 }
536
537 //=================================================================================
538 // function : closeEvent()
539 // purpose  : Close dialog
540 //=================================================================================
541 void SMESHGUI_FilterLibraryDlg::closeEvent(QCloseEvent* e)
542 {
543   onClose();
544 }
545
546 //=======================================================================
547 // name    : SMESHGUI_FilterLibraryDlg::getFileName
548 // Purpose : Get file name
549 //=======================================================================
550 QString SMESHGUI_FilterLibraryDlg::getFileName() const
551 {
552   return myFileName != 0 ? myFileName->text() : QString("");
553 }
554
555 //================================================================
556 // Function : setFileName
557 // Purpose  : Set file name to line edit
558 //================================================================
559 void SMESHGUI_FilterLibraryDlg::setFileName(const QString& txt, const bool autoExt)
560 {
561   if (myFileName == 0)
562     return;
563   myFileName->setText(autoExt ? autoExtension(txt) : txt);
564 }
565
566 //================================================================
567 // Function : autoExtension
568 // Purpose  : Append extension to the file name
569 //================================================================
570 QString SMESHGUI_FilterLibraryDlg::autoExtension(const QString& theFileName) const
571 {
572   QString anExt = theFileName.section('.', -1);
573   return anExt != "xml" && anExt != "XML" ? theFileName + ".xml" : theFileName;
574 }
575
576 //================================================================
577 // Function : filterWildCards
578 // Purpose  :
579 //================================================================
580 QStringList SMESHGUI_FilterLibraryDlg::filterWildCards(const QString& theFilter) const
581 {
582   QStringList res;
583
584   int b = theFilter.lastIndexOf("(");
585   int e = theFilter.lastIndexOf(")");
586   if (b != -1 && e != -1)
587   {
588     QString content = theFilter.mid(b + 1, e - b - 1).trimmed();
589     QStringList lst = content.split(" ", QString::SkipEmptyParts);
590     for (QStringList::const_iterator it = lst.begin(); it != lst.end(); ++it)
591       if ((*it).indexOf(".") != -1)
592         res.append((*it).trimmed());
593   }
594   return res;
595 }
596
597 //=======================================================================
598 // name    : SMESHGUI_FilterLibraryDlg::prepareFilters
599 // Purpose : Prepare filters for dialog
600 //=======================================================================
601 QStringList SMESHGUI_FilterLibraryDlg::prepareFilters() const
602 {
603   static QStringList aList;
604   if (aList.isEmpty())
605   {
606     aList.append(tr("XML_FILT"));
607     //aList.append(tr("ALL_FILES_FILTER"));
608   }
609
610   return aList;
611 }
612
613 //================================================================
614 // Function : onBrowse
615 // Purpose  : SLOT. Display "Open file" dialog for chosing library name
616 //================================================================
617 void SMESHGUI_FilterLibraryDlg::onBrowse()
618 {
619   Dialog* aDlg = new Dialog(this, true);
620   aDlg->setWindowTitle(tr("OPEN_LIBRARY"));
621
622   //aDlg->setMode(myMode == COPY_FROM ? QFileDialogP::ExistingFile : QFileDialogP::AnyFile);
623   aDlg->setFileMode(myMode == COPY_FROM ? QFileDialog::ExistingFile : QFileDialog::AnyFile);
624   aDlg->setFilters(prepareFilters());
625   aDlg->selectFile(getFileName());
626
627   QPushButton* anOkBtn = (QPushButton*)aDlg->findChild<QPushButton*>("OK");
628   if (anOkBtn != 0)
629     anOkBtn->setText(tr("SMESH_BUT_OK"));
630
631   if (aDlg->exec() != Accepted)
632     return;
633
634   QString fName = aDlg->selectedFile();
635
636   if (fName.isEmpty())
637     return;
638
639   if (QFileInfo(fName).suffix().isEmpty())
640     fName = autoExtension(fName);
641
642   fName = QDir::convertSeparators(fName);
643   QString prev = QDir::convertSeparators(getFileName());
644
645   if (prev == fName)
646     return;
647
648   setFileName(fName);
649
650   QListWidgetItem* item = myListBox->item( myListBox->count()-1 );
651   QString aName = item ? item->text() : QString::null;
652   processNewLibrary();
653
654   if (myMode == ADD_TO)
655   {
656     myTable->Copy((SMESHGUI_FilterTable*)parentWidget());
657     myCurrFilterName = "";
658     myCurrFilter = -1;
659     addFilterToLib(aName);
660   }
661
662   isPermissionValid(false);
663 }
664
665 //=======================================================================
666 // name    : SMESHGUI_FilterLibraryDlg::processNewLibrary
667 // Purpose : SLOT. Calleds when file name changed
668 //=======================================================================
669 void SMESHGUI_FilterLibraryDlg::processNewLibrary()
670 {
671   SMESH::FilterManager_var aFilterMgr = SMESH::GetFilterManager();
672   if (aFilterMgr->_is_nil())
673     return;
674
675   myLibrary = aFilterMgr->LoadLibrary(autoExtension(getFileName()).toLatin1().data());
676   if (myLibrary->_is_nil()) {
677     if (myMode == COPY_FROM) {
678       SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_ERROR"),
679                                    tr("ERROR_LOAD"));
680       return;
681     } else {
682       myLibrary = aFilterMgr->CreateLibrary();
683       myLibrary->SetFileName(getFileName().toLatin1().data());
684     }
685   }
686
687   updateList();
688 }
689
690 //=======================================================================
691 // name    : SMESHGUI_FilterLibraryDlg::updateList
692 // Purpose : Fill list box with filter names
693 //=======================================================================
694 void SMESHGUI_FilterLibraryDlg::updateList()
695 {
696   QStringList aList;
697   SMESH::string_array_var aNames = myLibrary->GetNames((SMESH::ElementType)myTable->GetType());
698   for (int i = 0, n = aNames->length(); i < n; i++)
699     aList.append(QString(aNames[ i ]));
700   myListBox->blockSignals(true);
701   myListBox->clear();
702   myListBox->blockSignals(false);
703   myListBox->addItems(aList);
704   if (myListBox->count() == 0)
705   {
706     myTable->Clear(myTable->GetType());
707     myName->clear();
708     myName->setEnabled(false);
709     myTable->SetEnabled(false);
710   }
711   else
712   {
713     myName->setEnabled(true);
714     myTable->SetEnabled(true);
715     if (myListBox->count())
716     {
717       myCurrFilterName = "";
718       myListBox->setCurrentItem(0);
719     }
720   }
721 }
722
723 //=======================================================================
724 // name    : SMESHGUI_FilterLibraryDlg::isNameValid
725 // Purpose : Verify validity if entered data
726 //=======================================================================
727 bool SMESHGUI_FilterLibraryDlg::isNameValid(const bool theMess) const
728 {
729   // verify validity of filter name
730   if (myName->isEnabled() && !myCurrFilterName.isEmpty()) {
731     QString aCurrName = myName->text();
732     if (aCurrName.isEmpty()) {
733       if (theMess)
734         SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
735                                      tr("EMPTY_FILTER_NAME"));
736       return false;
737     }
738
739     SMESH::string_array_var aNames = myLibrary->GetAllNames();
740     for (int f = 0, n = aNames->length(); f < n; f++) {
741       if (aNames[ f ] == aCurrName && aNames[ f ] != myCurrFilterName) {
742         if (theMess)
743           SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
744                                        tr("ERROR_FILTER_NAME"));
745         return false;
746       }
747     }
748   }
749
750   return true;
751 }
752
753 //=======================================================================
754 // name    : SMESHGUI_FilterLibraryDlg::isPermissionValid
755 // Purpose : Verify write permission on file
756 //=======================================================================
757 bool SMESHGUI_FilterLibraryDlg::isPermissionValid(const bool theIsExistingOnly)
758 {
759   if (myMode == COPY_FROM)
760     return true;
761
762   // Verify write permission
763   bool isWritable = false;
764
765   QString fName(myFileName->text());
766   if (QFileInfo(fName).suffix().isEmpty())
767     fName = autoExtension(fName);
768
769   fName = QDir::convertSeparators(fName);
770
771   if (QFileInfo(fName).exists()) {
772     isWritable = QFileInfo(fName).isWritable();
773   } else if (!theIsExistingOnly) {
774     QFileInfo aDirInfo(QFileInfo(fName).absolutePath());
775     isWritable = aDirInfo.isWritable();
776     /*if (QDir(QFileInfo(fName).dirPath(true)).exists() ||
777          QDir().mkdir(QFileInfo(fName).dirPath(true)))
778     {
779       QFile aFile(fName);
780       if (aFile.open(IO_WriteOnly))
781         isWritable = true;
782       else
783         aFile.close();
784     }
785     */
786   } else {
787     isWritable = true;
788   }
789
790   if (!isWritable) {
791     SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_WRN_WARNING"),
792                                  tr("NO_PERMISSION"));
793     return false;
794   }
795
796   return true;
797 }
798
799 //=======================================================================
800 // name    : SMESHGUI_FilterLibraryDlg::isValid
801 // Purpose : Verify validity if entered data
802 //=======================================================================
803 bool SMESHGUI_FilterLibraryDlg::isValid(const bool theMess) const
804 {
805   // verify validity of table
806   if (!myTable->IsValid(theMess) || !isNameValid(theMess))
807     return false;
808   else
809     return true;
810 }
811
812 //=======================================================================
813 // name    : SMESHGUI_FilterLibraryDlg::onFilterChanged
814 // Purpose : SLOT. Called when selected filter of library  changed
815 //=======================================================================
816 void SMESHGUI_FilterLibraryDlg::onFilterChanged( QListWidgetItem* item, QListWidgetItem* )
817 {
818   QString theName = item->text();
819   if (myLibrary->_is_nil())
820     return;
821
822   // Save parameters of filter if it was changed
823
824   if (!myCurrFilterName.isEmpty() && myTable->IsEditable())
825   {
826     if (!isValid(true))
827     {
828       myListBox->blockSignals(true);
829       myListBox->setCurrentRow(myCurrFilter);
830       myListBox->blockSignals(false);
831       return;
832     }
833
834     SMESH::Filter_var aFilter = createFilter();
835     myLibrary->Replace(myCurrFilterName.toLatin1().data(), 
836                        myName->text().toLatin1().data(), 
837                        aFilter);
838   }
839
840   // Fill table with filter parameters
841
842   SMESH::Filter_var aFilter = myLibrary->Copy(theName.toLatin1().data());
843   myCurrFilterName = theName;
844   myCurrFilter = myListBox->currentRow();
845   myName->setText(theName);
846
847
848   SMESH::Filter::Criteria_var aCriteria;
849
850   myTable->Clear(myTable->GetType());
851
852   if (CORBA::is_nil( aFilter ) || !aFilter->GetCriteria(aCriteria))
853     return;
854
855   for (int i = 0, n = aCriteria->length(); i < n; i++)
856     myTable->AddCriterion(aCriteria[ i ], myTable->GetType());
857
858   myTable->Update();
859 }
860
861 //=======================================================================
862 // name    : SMESHGUI_FilterLibraryDlg::onReturnPressed
863 // Purpose : SLOT. Called when enter button is pressed in library name field
864 //           Reload library
865 //=======================================================================
866 void SMESHGUI_FilterLibraryDlg::onReturnPressed()
867 {
868   QListWidgetItem* item = myListBox->item( myListBox->count()-1 );
869   QString aName = item ? item->text() : QString::null;
870
871   processNewLibrary();
872
873   if (myMode == ADD_TO)
874   {
875     myTable->Copy((SMESHGUI_FilterTable*)parentWidget());
876     myCurrFilterName = "";
877     myCurrFilter = -1;
878     addFilterToLib(aName);
879   }
880
881   isPermissionValid(false);
882 }
883
884 //=======================================================================
885 // name    : SMESHGUI_FilterLibraryDlg::enableMainButtons
886 // Purpose : Update state of "OK", "Cancel" buttons
887 //=======================================================================
888 void SMESHGUI_FilterLibraryDlg::enableMainButtons()
889 {
890   /*bool isEnabled = isValid(false);
891   if (myButtons.contains(BTN_OK))
892     myButtons[ BTN_OK ]->setEnabled(isEnabled);
893   else if (myButtons.contains(BTN_Apply))
894     myButtons[ BTN_OK ]->setEnabled(isEnabled);
895   if (myButtons.contains(BTN_Cancel))
896     myButtons[ BTN_Cancel ]->setEnabled(isEnabled);
897   else if (myButtons.contains(BTN_Close))
898     myButtons[ BTN_Cancel ]->setEnabled(isEnabled);
899     */
900 }
901
902 //=======================================================================
903 // name    : SMESHGUI_FilterLibraryDlg::createFilter
904 // Purpose : Cerate filter in accordance with library
905 //=======================================================================
906 SMESH::Filter_ptr SMESHGUI_FilterLibraryDlg::createFilter(const int theType)
907 {
908   int n = myTable->NumRows(theType);
909
910   SMESH::Filter::Criteria_var aCriteria = new SMESH::Filter::Criteria;
911   aCriteria->length(n);
912
913   for (int i = 0; i < n; i++)
914   {
915     SMESH::Filter::Criterion aCriterion = SMESHGUI_FilterDlg::createCriterion();
916     myTable->GetCriterion(i, aCriterion);
917     aCriteria[ i ] = aCriterion;
918   }
919
920   SMESH::FilterManager_var aFilterMgr = SMESH::GetFilterManager();
921   SMESH::Filter_var aFilter = aFilterMgr->CreateFilter();
922   aFilter->SetCriteria(aCriteria.in());
923
924   return aFilter._retn();
925 }
926
927 //=======================================================================
928 // name    : SMESHGUI_FilterLibraryDlg::onAddBtnPressed
929 // Purpose : SLOT. Called when "Add" button pressed
930 //           Add new filter to the end of library
931 //=======================================================================
932 void SMESHGUI_FilterLibraryDlg::onAddBtnPressed()
933 {
934   // Save parameters of filter if it was changed
935   if (!myCurrFilterName.isEmpty() && myTable->IsEditable())
936   {
937     if (!isValid(true))
938       return;
939   }
940   {
941     SMESH::Filter_var aFilter = createFilter();
942     myLibrary->Replace(myCurrFilterName.toLatin1().constData(), 
943                        myName->text().toLatin1().constData(), 
944                        aFilter);
945   }
946
947   addFilterToLib(getDefaultFilterName());
948 }
949
950 //=======================================================================
951 // name    : onAddBtnPressed()
952 // Purpose : SLOT. Called when "Add" button pressed
953 //           Add new filter to the end of library
954 //=======================================================================
955 void SMESHGUI_FilterLibraryDlg::addFilterToLib (const QString& theName)
956 {
957   if (myLibrary->_is_nil()) {
958     SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_WRN_WARNING"),
959                                  tr("LIBRARY_IS_NOT_LOADED"));
960     return;
961   }
962
963   // create filter
964   SMESH::Filter_var aFilter = createFilter();
965
966   // if name of filter already exist in the library assign default name for the filter
967   QString aName(theName);
968   SMESH::string_array_var aNames = myLibrary->GetAllNames();
969   for (int i = 0, n = aNames->length(); i < n; i++)
970     if (aName == QString(aNames[ i ]))
971     {
972       aName = getDefaultFilterName();
973       break;
974     }
975
976   // add new filter in library
977   bool aResult = !aFilter->GetPredicate()->_is_nil()
978     ? myLibrary->Add(aName.toLatin1().data(), aFilter)
979     : myLibrary->AddEmpty(aName.toLatin1().data(), (SMESH::ElementType)myTable->GetType());
980
981   if (!aResult) {
982     SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_ERROR"),
983                                  tr("ERROR_OF_ADDING"));
984   }
985
986   updateList();
987   myCurrFilterName = "";
988   myCurrFilter = -1;
989   setSelected(aName);
990
991   if (theName != aName)
992     SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_WARNING"),
993                                  tr("ASSIGN_NEW_NAME").arg(theName).arg(aName));
994 }
995
996 //=======================================================================
997 // name    : SMESHGUI_FilterLibraryDlg::getDefaultLibraryName
998 // Purpose : Get default library name
999 //=======================================================================
1000 QString& SMESHGUI_FilterLibraryDlg::getDefaultLibraryName() const
1001 {
1002   static QString aName;
1003   if (aName.isEmpty())
1004   {
1005     QString aHomeDir = QDir(QDir::home()).absolutePath();
1006     aName = aHomeDir + "/" + tr ("LIB_NAME");
1007   }
1008   return aName;
1009 }
1010
1011 //=======================================================================
1012 // name    : SMESHGUI_FilterLibraryDlg::getDefaultFilterName
1013 // Purpose : Create default filter name
1014 //=======================================================================
1015 QString SMESHGUI_FilterLibraryDlg::getDefaultFilterName() const
1016 {
1017   QString aName;
1018
1019   if (myTable->GetType() == SMESH::NODE)
1020     aName = tr("NODE");
1021   else if (myTable->GetType() == SMESH::EDGE)
1022     aName = tr("EDGE");
1023   else if (myTable->GetType() == SMESH::FACE)
1024     aName = tr("FACE");
1025   else if (myTable->GetType() == SMESH::VOLUME)
1026     aName = tr("VOLUME");
1027   else if (myTable->GetType() == SMESH::ALL)
1028     aName = tr("ELEMENT");
1029   else
1030     aName = tr("SELECTION");
1031
1032   aName += tr("FILTER");
1033
1034
1035   QMap< QString, int > anAllNames;
1036   SMESH::string_array_var aNames = myLibrary->GetAllNames();
1037   for(int i = 0, n = aNames->length(); i < n; i++)
1038     anAllNames[ QString(aNames[ i ]) ] = -1;
1039
1040   bool isNotValid = true;
1041   int k = 1;
1042   QString aNewName;
1043   while (isNotValid)
1044   {
1045     isNotValid = false;
1046     aNewName = aName + "_" + QString("%1").arg(k);
1047     if (anAllNames.contains(aNewName))
1048     {
1049       isNotValid = true;
1050       k++;
1051     }
1052   }
1053
1054   return aNewName;
1055 }
1056
1057 //=======================================================================
1058 // name    : SMESHGUI_FilterLibraryDlg::setSelected
1059 // Purpose : set selected item in list box containing filters
1060 //=======================================================================
1061 bool SMESHGUI_FilterLibraryDlg::setSelected(const QString& theName)
1062 {
1063   int anIndex = getIndex(theName);
1064   if (anIndex != -1)
1065   {
1066     myListBox->setCurrentRow(anIndex);
1067     myCurrFilterName = theName;
1068     myCurrFilter = anIndex;
1069   }
1070   return anIndex != -1;
1071 }
1072
1073 //=======================================================================
1074 // name    : SMESHGUI_FilterLibraryDlg::getIndex
1075 // Purpose : Get index of the filter in list box
1076 //=======================================================================
1077 int SMESHGUI_FilterLibraryDlg::getIndex(const QString& theName) const
1078 {
1079   for (int i = 0, n = myListBox->count(); i < n; i++)
1080     if (myListBox->item(i)->text() == theName)
1081       return i;
1082   return -1;
1083 }
1084
1085 //=======================================================================
1086 // name    : SMESHGUI_FilterLibraryDlg::onDeleteBtnPressed
1087 // Purpose : SLOT. Called when "Delete" button pressed
1088 //=======================================================================
1089 void SMESHGUI_FilterLibraryDlg::onDeleteBtnPressed()
1090 {
1091   if (myLibrary->_is_nil()) {
1092     SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_WRN_WARNING"),
1093                                  tr("LIBRARY_IS_NOT_LOADED"));
1094     return;
1095   }
1096
1097   int anIndex = getIndex(myCurrFilterName);
1098
1099   if (anIndex == -1 || !myLibrary->Delete(myCurrFilterName.toLatin1().data())) {
1100     SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_ERROR"),
1101                                  tr("ERROR_OF_DELETING"));
1102   } else {
1103     myCurrFilterName = "";
1104     myCurrFilter = -1;
1105     delete myListBox->item(anIndex);
1106
1107     if (anIndex >= 1)
1108       myListBox->item(anIndex - 1)->setSelected(true);
1109     else if (anIndex == 0 && myListBox->count() > 0)
1110       myListBox->item(0)->setSelected(true);
1111     else
1112       myTable->Clear();
1113   }
1114
1115   myTable->SetEnabled(myListBox->count() > 0);
1116   if (myListBox->count() == 0) {
1117     myName->setText("");
1118     myName->setEnabled(false);
1119   }
1120 }
1121
1122 //=======================================================================
1123 // name    : onFilterNameChanged()
1124 // Purpose : SLOT. Called when name of filter changed
1125 //           Change filter name in list box
1126 //=======================================================================
1127 void SMESHGUI_FilterLibraryDlg::onFilterNameChanged (const QString& theName)
1128 {
1129   int aCurrItem = myListBox->currentRow();
1130   if (aCurrItem == -1)
1131     return;
1132
1133   myListBox->blockSignals(true);
1134   myListBox->item(aCurrItem)->setText(theName);
1135   myListBox->blockSignals(false);
1136 }
1137
1138 //=======================================================================
1139 // name    : SMESHGUI_FilterLibraryDlg::SetTable
1140 // Purpose : Set table
1141 //=======================================================================
1142 void SMESHGUI_FilterLibraryDlg::SetTable(const SMESHGUI_FilterTable* theTable)
1143 {
1144   myTable->Copy(theTable);
1145   myName->setText(getDefaultFilterName());
1146   addFilterToLib(myName->text());
1147   myTable->Update();
1148 }
1149
1150 //=======================================================================
1151 // name    : SMESHGUI_FilterLibraryDlg::GetTable
1152 // Purpose : Get table
1153 //=======================================================================
1154 const SMESHGUI_FilterTable* SMESHGUI_FilterLibraryDlg::GetTable() const
1155 {
1156   return myTable;
1157 }
1158
1159
1160 //=======================================================================
1161 // name    : SMESHGUI_FilterLibraryDlg::onEntityTypeChanged
1162 // Purpose : SLOT. Called when entiyt type changed
1163 //=======================================================================
1164 void SMESHGUI_FilterLibraryDlg::onEntityTypeChanged(const int theType)
1165 {
1166   if (myLibrary->_is_nil())
1167     return;
1168
1169   myName->clear();
1170   myCurrFilterName = "";
1171   myCurrFilter = -1;
1172   updateList();
1173   if (myListBox->count())
1174     myListBox->setCurrentItem(0);
1175 }
1176
1177 //=======================================================================
1178 // name    : SMESHGUI_FilterLibraryDlg::onNeedValidation
1179 // Purpose :
1180 //=======================================================================
1181 void SMESHGUI_FilterLibraryDlg::onNeedValidation()
1182 {
1183   if (!myCurrFilterName.isEmpty())
1184   {
1185     bool valid = isValid(true);
1186     myTable->SetValidity(valid);
1187
1188     if (valid)
1189     {
1190       SMESH::Filter_var aFilter = createFilter(myTable->GetType());
1191       myLibrary->Replace(myCurrFilterName.toLatin1().data(),
1192                          myName->text().toLatin1().data(),
1193                          aFilter);
1194     }
1195   }
1196 }
1197
1198 //=================================================================================
1199 // function : keyPressEvent()
1200 // purpose  :
1201 //=================================================================================
1202 void SMESHGUI_FilterLibraryDlg::keyPressEvent( QKeyEvent* e )
1203 {
1204   QDialog::keyPressEvent( e );
1205   if ( e->isAccepted() )
1206     return;
1207
1208   if ( e->key() == Qt::Key_F1 ) {
1209     e->accept();
1210     onHelp();
1211   }
1212 }