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