Salome HOME
Porting SMESH module to Qt 4
[modules/smesh.git] / src / SMESHGUI / SMESHGUI_FilterDlg.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_FilterDlg.cxx
23 // Author : Sergey LITONIN, Open CASCADE S.A.S.
24 //
25
26 // SMESH includes
27 #include "SMESHGUI_FilterDlg.h"
28
29 #include "SMESHGUI.h"
30 #include "SMESHGUI_Utils.h"
31 #include "SMESHGUI_VTKUtils.h"
32 #include "SMESHGUI_Filter.h"
33 #include "SMESHGUI_FilterUtils.h"
34 #include "SMESHGUI_FilterLibraryDlg.h"
35
36 #include <SMESH_Actor.h>
37 #include <SMESH_NumberFilter.hxx>
38 #include <SMESH_TypeFilter.hxx>
39
40 // SALOME GEOM includes
41 #include <GEOMBase.h>
42 #include <GEOM_FaceFilter.h>
43 #include <GEOM_TypeFilter.h>
44
45 // SALOME GUI includes
46 #include <SUIT_Desktop.h>
47 #include <SUIT_ResourceMgr.h>
48 #include <SUIT_Session.h>
49 #include <SUIT_MessageBox.h>
50
51 #include <LightApp_Application.h>
52 #include <LightApp_SelectionMgr.h>
53 #include <SalomeApp_Tools.h>
54 #include <SalomeApp_Study.h>
55
56 #include <SALOME_ListIO.hxx>
57 #include <SALOME_ListIteratorOfListIO.hxx>
58 #include <SALOME_DataMapIteratorOfDataMapOfIOMapOfInteger.hxx>
59
60 #include <SVTK_ViewWindow.h>
61
62 // SALOME KERNEL includes
63 #include <SALOMEDSClient_Study.hxx>
64
65 // OCCT includes
66 #include <StdSelect_TypeOfFace.hxx>
67 #include <BRep_Tool.hxx>
68 #include <TopoDS.hxx>
69 #include <TopoDS_Shape.hxx>
70 #include <Geom_Plane.hxx>
71 #include <Geom_CylindricalSurface.hxx>
72 #include <Precision.hxx>
73 #include <TColStd_MapOfInteger.hxx>
74 #include <TColStd_IndexedMapOfInteger.hxx>
75 #include <TColStd_MapIteratorOfMapOfInteger.hxx>
76
77 // Qt includes
78 #include <QFrame>
79 #include <QLineEdit>
80 #include <QPushButton>
81 #include <QGroupBox>
82 #include <QTableWidget>
83 #include <QStringList>
84 #include <QHBoxLayout>
85 #include <QVBoxLayout>
86 #include <QGridLayout>
87 #include <QStackedWidget>
88 #include <QApplication>
89 #include <QComboBox>
90 #include <QFontMetrics>
91 #include <QLabel>
92 #include <QButtonGroup>
93 #include <QRadioButton>
94 #include <QRegExp>
95 #include <QListWidget>
96 #include <QCheckBox>
97 #include <QItemDelegate>
98 #include <QDoubleValidator>
99 #include <QKeyEvent>
100 #include <QHeaderView>
101
102 // IDL includes
103 #include <SALOMEconfig.h>
104 #include CORBA_SERVER_HEADER(SMESH_Group)
105
106 #define SPACING 6
107 #define MARGIN  11
108
109 //---------------------------------------
110 // maxLength
111 //---------------------------------------
112 static int maxLength (const QMap<int, QString> theMap, const QFontMetrics& theMetrics)
113 {
114   int aRes = 0;
115   QMap<int, QString>::const_iterator anIter;
116   for (anIter = theMap.begin(); anIter != theMap.end(); ++anIter)
117     aRes = qMax(aRes, theMetrics.width(anIter.value()));
118   return aRes;
119 }
120
121 //---------------------------------------
122 // getFilterId
123 //---------------------------------------
124 static int getFilterId (SMESH::ElementType theType)
125 {
126   switch (theType)
127   {
128     case SMESH::NODE   : return SMESH::NodeFilter;
129     case SMESH::EDGE   : return SMESH::EdgeFilter;
130     case SMESH::FACE   : return SMESH::FaceFilter;
131     case SMESH::VOLUME : return SMESH::VolumeFilter;
132     case SMESH::ALL    : return SMESH::AllElementsFilter;
133     default            : return SMESH::UnknownFilter;
134   }
135 }
136
137 /*
138   Class       : SMESHGUI_FilterTable::AdditionalWidget
139   Description : Class for storing additional parameters of criterion
140 */
141
142 class SMESHGUI_FilterTable::AdditionalWidget : public QWidget
143 {
144 public:
145   enum { Tolerance };
146
147 public:
148   AdditionalWidget(QWidget* theParent);
149   virtual ~AdditionalWidget();
150
151   virtual QList<int>      GetParameters() const;
152   virtual bool            IsValid(const bool = true) const;
153   virtual double          GetDouble(const int) const;
154   virtual int             GetInteger(const int) const;
155   virtual QString         GetString(const int) const;
156   virtual void            SetDouble(const int, const double);
157   virtual void            SetInteger(const int, const int);
158   virtual void            SetString(const int, const QString&);
159   void                    SetEditable(const int, const bool);
160   void                    SetEditable(const bool);
161
162 private:
163   QMap< int, QLineEdit* > myLineEdits;
164 };
165
166 SMESHGUI_FilterTable::AdditionalWidget::AdditionalWidget (QWidget* theParent)
167   : QWidget(theParent)
168 {
169   QLabel* aLabel = new QLabel(tr("SMESH_TOLERANCE"), this);
170   myLineEdits[ Tolerance ] = new QLineEdit(this);
171   QDoubleValidator* aValidator = new QDoubleValidator(myLineEdits[ Tolerance ]);
172   aValidator->setBottom(0);
173   myLineEdits[ Tolerance ]->setValidator(aValidator);
174
175   QHBoxLayout* aLay = new QHBoxLayout(this);
176   aLay->setSpacing(SPACING);
177   aLay->setMargin(0);
178
179   aLay->addWidget(aLabel);
180   aLay->addWidget(myLineEdits[ Tolerance ]);
181   aLay->addStretch();
182
183   QString aText = QString("%1").arg(Precision::Confusion());
184   myLineEdits[ Tolerance ]->setText(aText);
185 }
186
187 SMESHGUI_FilterTable::AdditionalWidget::~AdditionalWidget()
188 {
189 }
190
191 QList<int> SMESHGUI_FilterTable::AdditionalWidget::GetParameters() const
192 {
193   QList<int> theList;
194   theList.append(Tolerance);
195   return theList;
196 }
197
198 bool SMESHGUI_FilterTable::AdditionalWidget::IsValid (const bool theMsg) const
199 {
200   if (!isEnabled())
201     return true;
202
203   QList<int> aParams = GetParameters();
204   QList<int>::const_iterator anIter;
205   for (anIter = aParams.begin(); anIter != aParams.end(); ++anIter) {
206     const QLineEdit* aWg = myLineEdits[ *anIter ];
207     int p = 0;
208     QString aText = aWg->text();
209     if (aWg->isEnabled() && aWg->validator()->validate(aText, p) != QValidator::Acceptable) {
210       if (theMsg)
211         SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
212                                      tr("SMESHGUI_INVALID_PARAMETERS"));
213       return false;
214     }
215   }
216
217   return true;
218 }
219
220 double SMESHGUI_FilterTable::AdditionalWidget::GetDouble (const int theId) const
221 {
222   return myLineEdits.contains(theId) ? myLineEdits[ theId ]->text().toDouble() : 0;
223 }
224
225 int SMESHGUI_FilterTable::AdditionalWidget::GetInteger (const int theId) const
226 {
227   return myLineEdits.contains(theId) ? myLineEdits[ theId ]->text().toInt() : 0;
228 }
229
230 QString SMESHGUI_FilterTable::AdditionalWidget::GetString (const int theId) const
231 {
232   return myLineEdits.contains(theId) ? myLineEdits[ theId ]->text() : QString("");
233 }
234
235 void SMESHGUI_FilterTable::AdditionalWidget::SetDouble (const int theId, const double theVal)
236 {
237   if (myLineEdits.contains(theId))
238     myLineEdits[ theId ]->setText(QString("%1").arg(theVal));
239 }
240
241 void SMESHGUI_FilterTable::AdditionalWidget::SetInteger (const int theId, const int theVal)
242 {
243   if (myLineEdits.contains(theId))
244     myLineEdits[ theId ]->setText(QString("%1").arg(theVal));
245 }
246
247 void SMESHGUI_FilterTable::AdditionalWidget::SetString (const int theId, const QString& theVal)
248 {
249   if (myLineEdits.contains(theId))
250     myLineEdits[ theId ]->setText(theVal);
251 }
252
253 void SMESHGUI_FilterTable::AdditionalWidget::SetEditable (const int theId, const bool isEditable)
254 {
255   if (myLineEdits.contains(theId))
256     myLineEdits[ theId ]->setReadOnly(!isEditable);
257 }
258
259 void SMESHGUI_FilterTable::AdditionalWidget::SetEditable (const bool isEditable)
260 {
261   QList<int> aParams = GetParameters();
262   QList<int>::const_iterator anIter;
263   for (anIter = aParams.begin(); anIter != aParams.end(); ++anIter)
264     SetEditable( *anIter,  isEditable );
265 }
266
267 /*
268   Class       : SMESHGUI_FilterTable::ComboItem
269   Description : Combo table item. Identificator corresponding to string may be assigned
270 */
271
272 class SMESHGUI_FilterTable::ComboItem : public QTableWidgetItem
273 {
274 public:
275   static int     Type();
276
277   ComboItem( const QMap<int, QString>& );
278
279   void           setItems( const QMap<int, QString>& );
280   void           clear();
281   int            count() const;
282
283   int            value() const;
284   void           setValue( const int );
285
286 private:
287   int            id( int ) const;
288   int            index( int ) const;
289
290 private:
291   QMap<int, int> myIdToIdx;
292 };
293
294 int SMESHGUI_FilterTable::ComboItem::Type()
295 {
296   return QTableWidgetItem::UserType + 1;
297 }
298
299 SMESHGUI_FilterTable::ComboItem::ComboItem( const QMap<int, QString>& theIds )
300  : QTableWidgetItem( Type() )
301 {
302   setItems( theIds );
303 }
304
305 void SMESHGUI_FilterTable::ComboItem::setItems( const QMap<int, QString>& theIds )
306 {
307   myIdToIdx.clear();
308   QMap<int, QString>::const_iterator it;
309   QStringList items;
310   for ( it = theIds.begin(); it != theIds.end(); ++it ) {
311     myIdToIdx[it.key()] = items.count();
312     items.append( it.value() );
313   }
314   setData( Qt::UserRole, items );
315   setValue( id( 0 ) ); 
316 }
317
318 void SMESHGUI_FilterTable::ComboItem::clear()
319 {
320   QMap<int, QString> empty;
321   setItems( empty );
322 }
323
324 int SMESHGUI_FilterTable::ComboItem::count() const
325 {
326   return myIdToIdx.count();
327 }
328
329 int SMESHGUI_FilterTable::ComboItem::value() const
330 {
331   return( id( data( Qt::UserRole ).toStringList().indexOf( text() ) ) ); 
332 }
333
334 void SMESHGUI_FilterTable::ComboItem::setValue( const int theId )
335 {
336   int idx = index( theId );
337   QStringList items = data( Qt::UserRole ).toStringList();
338   setText( idx >= 0 && idx < items.count() ? items[idx] : "" );
339 }
340
341 int SMESHGUI_FilterTable::ComboItem::id( int idx ) const
342 {
343   QMap<int,int>::const_iterator it;
344   for ( it = myIdToIdx.begin(); it != myIdToIdx.end(); ++it )
345     if ( it.value() == idx ) return it.key();
346   return -1;
347 }
348
349 int SMESHGUI_FilterTable::ComboItem::index( int i ) const
350 {
351   return myIdToIdx.contains( i ) ? myIdToIdx[i] : -1;
352 }
353 /*
354   Class       : SMESHGUI_FilterTable::CheckItem
355   Description : Check table item.
356 */
357
358 class SMESHGUI_FilterTable::CheckItem : public QTableWidgetItem
359 {
360 public:
361   static int     Type();
362
363   CheckItem( bool = false );
364   CheckItem( const QString&, bool = false );
365   ~CheckItem();
366
367   void  setChecked( bool );
368   bool  checked() const;
369 };
370
371 int SMESHGUI_FilterTable::CheckItem::Type()
372 {
373   return QTableWidgetItem::UserType + 2;
374 }
375
376 SMESHGUI_FilterTable::CheckItem::CheckItem( bool value )
377  : QTableWidgetItem( Type() )
378 {
379   Qt::ItemFlags f = flags();
380   f = f | Qt::ItemIsUserCheckable;
381   f = f & ~Qt::ItemIsTristate;
382   setFlags( f );
383   setChecked(value);
384 }
385
386 SMESHGUI_FilterTable::CheckItem::CheckItem( const QString& text, bool value )
387  : QTableWidgetItem( Type() )
388 {
389   Qt::ItemFlags f = flags();
390   f = f | Qt::ItemIsUserCheckable;
391   f = f & ~Qt::ItemIsTristate;
392   setFlags( f );
393   setChecked( value );
394   setText( text );
395 }
396
397 SMESHGUI_FilterTable::CheckItem::~CheckItem()
398 {
399 }
400
401 void SMESHGUI_FilterTable::CheckItem::setChecked( bool value )
402 {
403   setCheckState( value ? Qt::Checked : Qt::Unchecked );
404 }
405
406 bool SMESHGUI_FilterTable::CheckItem::checked() const
407 {
408   return checkState() == Qt::Checked;
409 }
410
411 /*
412   Class       : SMESHGUI_FilterTable::ComboDelegate
413   Description : Table used by this widget
414 */
415
416 class SMESHGUI_FilterTable::ComboDelegate : public QItemDelegate
417 {
418 public:
419   ComboDelegate( QObject* = 0 );
420   ~ComboDelegate();
421   
422   QWidget*      createEditor( QWidget*, const QStyleOptionViewItem&,
423                               const QModelIndex& ) const;
424   
425   void          setEditorData( QWidget*, const QModelIndex& ) const;
426   void          setModelData( QWidget*, QAbstractItemModel*, const QModelIndex& ) const;
427   
428   void          updateEditorGeometry( QWidget*, const QStyleOptionViewItem&, 
429                                       const QModelIndex& ) const;
430 private:
431   QTableWidget* myTable;
432 };
433
434 SMESHGUI_FilterTable::ComboDelegate::ComboDelegate( QObject* parent )
435   : QItemDelegate( parent ), 
436     myTable( qobject_cast<QTableWidget*>( parent ) )
437 {
438 }
439   
440 SMESHGUI_FilterTable::ComboDelegate::~ComboDelegate()
441 {
442 }
443
444 QWidget* SMESHGUI_FilterTable::ComboDelegate::createEditor( QWidget* parent,
445                                                             const QStyleOptionViewItem& option,
446                                                             const QModelIndex& index ) const
447 {
448   QStringList l = index.data( Qt::UserRole ).toStringList();
449   if ( !l.isEmpty() ) {
450     QComboBox* cb = new QComboBox( parent );
451     cb->setFrame( false );
452     cb->addItems( l );
453     return cb;
454   }
455   return QItemDelegate::createEditor( parent, option, index );
456 }
457
458 void SMESHGUI_FilterTable::ComboDelegate::setEditorData( QWidget* editor, 
459                                                          const QModelIndex& index ) const
460 {
461   QString value = index.model()->data( index, Qt::DisplayRole ).toString();
462   QComboBox* cb = static_cast<QComboBox*>( editor );
463   bool bOk = false;
464   if ( cb ) {
465     int i = cb->findText( value );
466     if ( i >= 0 ) {
467       cb->setCurrentIndex( i );
468       bOk = true;
469     }
470   }
471   if ( !bOk ) QItemDelegate::setEditorData( editor, index );
472 }
473
474 void SMESHGUI_FilterTable::ComboDelegate::setModelData( QWidget* editor,
475                                                         QAbstractItemModel* model,
476                                                         const QModelIndex& index) const
477 {
478   QComboBox* cb = static_cast<QComboBox*>( editor );
479   if ( cb ) model->setData( index, cb->currentText(), Qt::DisplayRole );
480   else QItemDelegate::setModelData( editor, model, index );
481 }
482
483 void SMESHGUI_FilterTable::ComboDelegate::updateEditorGeometry( QWidget* editor,
484                                                                 const QStyleOptionViewItem& option, 
485                                                                 const QModelIndex& index ) const
486 {
487   editor->setGeometry( option.rect );
488 }
489
490 /*
491   Class       : SMESHGUI_FilterTable::Table
492   Description : Table used by this widget
493 */
494
495 class SMESHGUI_FilterTable::Table : public QTableWidget
496 {
497 public:
498   Table( QWidget* = 0 );
499   Table( int, int, QWidget* = 0 );
500   virtual ~Table();
501
502   void                    setEditable( bool, int, int );
503   bool                    isEditable( int, int ) const;
504
505   void                    setReadOnly( bool );
506   bool                    isReadOnly() const;
507
508   void                    insertRows( int, int = 1 );
509   QString                 text( int, int );
510
511   QList<int>              selectedRows();
512 };
513
514 //=======================================================================
515 // name    : SMESHGUI_FilterTable::Table::Table
516 // Purpose : Constructor
517 //=======================================================================
518 SMESHGUI_FilterTable::Table::Table (QWidget* parent)
519 : QTableWidget(parent)
520 {
521   // set custom item delegate
522   setItemDelegate( new ComboDelegate(this) );
523   // set edit triggers by default
524   setReadOnly( false );
525 }
526
527 SMESHGUI_FilterTable::Table::Table (int numRows, int numCols, QWidget* parent)
528 : QTableWidget(numRows, numCols, parent)
529 {
530   // set custom item delegate
531   setItemDelegate( new ComboDelegate(this) );
532   // set edit triggers by default
533   setReadOnly( false );
534 }
535
536 SMESHGUI_FilterTable::Table::~Table()
537 {
538 }
539
540 //=======================================================================
541 // name    : SMESHGUI_FilterTable::Table::setEditable
542 // Purpose : Set editable of specified cell
543 //=======================================================================
544 void SMESHGUI_FilterTable::Table::setEditable (bool isEditable,
545                                                int row, int col)
546 {
547   QTableWidgetItem* anItem = item( row, col );
548   if ( anItem ) {
549     Qt::ItemFlags f = anItem->flags();
550     if ( !isEditable ) f = f & ~Qt::ItemIsEditable;
551     else f = f | Qt::ItemIsEditable;
552     anItem->setFlags( f );
553   }
554 }
555
556 //=======================================================================
557 // name    : SMESHGUI_FilterTable::Table::isEditable
558 // Purpose : Verify wheter cell is editable
559 //=======================================================================
560 bool SMESHGUI_FilterTable::Table::isEditable (int row, int col) const
561 {
562   QTableWidgetItem* anItem = item( row, col );
563   return anItem == 0 || anItem->flags() & Qt::ItemIsEditable;
564 }
565
566 void SMESHGUI_FilterTable::Table::setReadOnly( bool on )
567 {
568   setEditTriggers( on ? 
569                    QAbstractItemView::DoubleClicked   |
570                    QAbstractItemView::SelectedClicked |
571                    QAbstractItemView::EditKeyPressed  |
572                    QAbstractItemView::AnyKeyPressed   :
573                    QAbstractItemView::NoEditTriggers );
574 }
575
576 bool SMESHGUI_FilterTable::Table::isReadOnly() const
577 {
578   return editTriggers() != QAbstractItemView::NoEditTriggers;
579 }
580
581 //=======================================================================
582 // name    : SMESHGUI_FilterTable::Table::insertRows
583 // Purpose : Insert rows (virtual redefined)
584 //=======================================================================
585 void SMESHGUI_FilterTable::Table::insertRows (int row, int count)
586 {
587   closePersistentEditor( currentItem() );
588   while ( count-- ) insertRow( row );
589 }
590
591 //=======================================================================
592 // name    : SMESHGUI_FilterTable::Table::text
593 // Purpose : Get text from cell (virtual redefined)
594 //=======================================================================
595 QString SMESHGUI_FilterTable::Table::text (int row, int col)
596 {
597   closePersistentEditor( currentItem() );
598   QTableWidgetItem* anItem = item( row, col );
599   return anItem ? anItem->text() : QString();
600 }
601
602 QList<int> SMESHGUI_FilterTable::Table::selectedRows()
603 {
604   QList<QTableWidgetItem*> selItems = selectedItems();
605   QTableWidgetItem* anItem;
606   QList<int> rows;
607
608   foreach( anItem, selItems ) {
609     int r = row( anItem );
610     if ( !rows.contains( r ) ) rows.append( r );
611   }
612
613   qSort( rows );
614   return rows;
615 }
616
617 /*
618   Class       : SMESHGUI_FilterTable
619   Description : Frame containig
620                   - Button group for switching entity type
621                   - Table for displaying filter criterions
622                   - Buttons for editing table and filter libraries
623 */
624
625 //=======================================================================
626 // name    : SMESHGUI_FilterTable::SMESHGUI_FilterTable
627 // Purpose : Constructor
628 //=======================================================================
629 SMESHGUI_FilterTable::SMESHGUI_FilterTable( SMESHGUI* theModule,
630                                             QWidget* parent,
631                                             const int type )
632 : QWidget( parent ),
633   myIsLocked( false ),
634   mySMESHGUI( theModule )
635 {
636   myEntityType = -1;
637
638   QList<int> aTypes;
639   aTypes.append(type);
640   Init(aTypes);
641 }
642
643 //=======================================================================
644 // name    : SMESHGUI_FilterTable::SMESHGUI_FilterTable
645 // Purpose : Constructor
646 //=======================================================================
647 SMESHGUI_FilterTable::SMESHGUI_FilterTable( SMESHGUI* theModule,
648                                             QWidget* parent,
649                                             const QList<int>& types )
650 : QWidget( parent ),
651   myIsLocked( false ),
652   mySMESHGUI( theModule )
653 {
654   myEntityType = -1;
655   Init(types);
656 }
657
658 SMESHGUI_FilterTable::~SMESHGUI_FilterTable()
659 {
660 }
661
662 //=======================================================================
663 // name    : SMESHGUI_FilterTable::Init
664 // Purpose : Create table corresponding to the specified type
665 //=======================================================================
666 void SMESHGUI_FilterTable::Init (const QList<int>& theTypes)
667 {
668   if (theTypes.isEmpty())
669     return;
670
671   // Create buttons if necessary
672
673   if (myTables.isEmpty())
674   {
675     int aType = theTypes.first();
676
677     // create main layout
678     QVBoxLayout* aMainLay = new QVBoxLayout(this);
679     aMainLay->setMargin( 0 );
680     aMainLay->setSpacing( SPACING );
681
682     // create switch of entity types
683     myEntityTypeBox = new QGroupBox(tr("ENTITY_TYPE"), this);
684     QHBoxLayout* myEntityTypeBoxLayout = new QHBoxLayout(myEntityTypeBox);
685     myEntityTypeBoxLayout->setMargin( MARGIN );
686     myEntityTypeBoxLayout->setSpacing( SPACING );
687     myEntityTypeGrp = new QButtonGroup(this);
688
689     const QMap<int, QString>& aSupportedTypes = getSupportedTypes();
690     QMap<int, QString>::const_iterator anIter;
691     for (anIter = aSupportedTypes.begin(); anIter != aSupportedTypes.end(); ++anIter)
692     {
693       QRadioButton* aBtn = new QRadioButton(anIter.value(), myEntityTypeBox);
694       myEntityTypeGrp->addButton(aBtn, anIter.key());
695       myEntityTypeBoxLayout->addWidget(aBtn);
696     }
697
698     myTableGrp = new QGroupBox(tr("FILTER"), this );
699
700     // create table
701     mySwitchTableGrp = new QWidget(myTableGrp);
702     QVBoxLayout* mySwitchTableGrpLayout = new QVBoxLayout(mySwitchTableGrp);
703     mySwitchTableGrpLayout->setMargin(0);
704     mySwitchTableGrpLayout->setSpacing(0);
705
706     myTables[ aType ] = createTable(mySwitchTableGrp, aType);
707     mySwitchTableGrpLayout->addWidget(myTables[ aType ]);
708
709     // create buttons
710     myAddBtn      = new QPushButton(tr("ADD"),       myTableGrp);
711     myRemoveBtn   = new QPushButton(tr("REMOVE"),    myTableGrp);
712     myClearBtn    = new QPushButton(tr("CLEAR"),     myTableGrp);
713     myInsertBtn   = new QPushButton(tr("INSERT"),    myTableGrp);
714     myCopyFromBtn = new QPushButton(tr("COPY_FROM"), myTableGrp);
715     myAddToBtn    = new QPushButton(tr("ADD_TO"),    myTableGrp);
716
717     myAddBtn->setAutoDefault(false);
718     myRemoveBtn->setAutoDefault(false);
719     myClearBtn->setAutoDefault(false);
720     myInsertBtn->setAutoDefault(false);
721     myCopyFromBtn->setAutoDefault(false);
722     myAddToBtn->setAutoDefault(false);
723
724     myCopyFromBtn->hide();
725     myAddToBtn->hide();
726
727     // layout widgets
728     QGridLayout* aLay = new QGridLayout(myTableGrp);
729     aLay->setMargin(0);
730     aLay->setSpacing(SPACING);
731
732     aLay->addWidget(mySwitchTableGrp, 0, 0, 7, 1);
733     aLay->addWidget(myAddBtn,         0, 1);
734     aLay->addWidget(myInsertBtn,      1, 1);
735     aLay->addWidget(myRemoveBtn,      2, 1);
736     aLay->addWidget(myClearBtn,       3, 1);
737     aLay->addWidget(myCopyFromBtn,    5, 1);
738     aLay->addWidget(myAddToBtn,       6, 1);
739     aLay->addWidget(createAdditionalFrame(myTableGrp), 7, 0, 1, 2 );
740
741     aLay->setRowMinimumHeight(4, 10);
742     aLay->setRowStretch(4, 1);
743     aLay->setColumnStretch(0, 1);
744     aLay->setColumnStretch(1, 0);
745
746     // layout 
747     aMainLay->addWidget(myEntityTypeBox);
748     aMainLay->addWidget(myTableGrp);
749     
750     // signals and slots
751     connect(myAddBtn,    SIGNAL(clicked()), this, SLOT(onAddBtn()));
752     connect(myInsertBtn, SIGNAL(clicked()), this, SLOT(onInsertBtn()));
753     connect(myRemoveBtn, SIGNAL(clicked()), this, SLOT(onRemoveBtn()));
754     connect(myClearBtn,  SIGNAL(clicked()), this, SLOT(onClearBtn()));
755
756     connect(myCopyFromBtn, SIGNAL(clicked()), this, SLOT(onCopyFromBtn()));
757     connect(myAddToBtn,    SIGNAL(clicked()), this, SLOT(onAddToBtn()));
758
759     connect(myEntityTypeGrp, SIGNAL(buttonClicked(int)), this, SLOT(onEntityType(int)));
760
761     myLibDlg = 0;
762   }
763
764   // Hide buttons of entity types if necessary
765   const QMap<int, QString>& aSupportedTypes = getSupportedTypes();
766   QMap<int, QString>::const_iterator anIt;
767   for (anIt = aSupportedTypes.begin(); anIt != aSupportedTypes.end(); ++anIt)
768   {
769     QAbstractButton* aBtn = myEntityTypeGrp->button(anIt.key());
770     if ( aBtn ) aBtn->setVisible( theTypes.contains(anIt.key()) );
771   }
772
773   // select first button if there is no selected buttons or it is hidden
774   int aBtnId = myEntityTypeGrp->checkedId();
775   if ( aBtnId == -1 || !theTypes.contains(aBtnId) ) {
776     QAbstractButton* aBtn = myEntityTypeGrp->button(theTypes.first());
777     if ( aBtn ) aBtn->setChecked(true);
778   }
779
780   myEntityTypeBox->setVisible(theTypes.count() > 1);
781
782   myTableGrp->updateGeometry();
783   int cType = myEntityTypeGrp->checkedId();
784   onEntityType(cType);
785 }
786
787 //=======================================================================
788 // name    : SMESHGUI_FilterTable::createAdditionalFrame
789 // Purpose : Get group box containing table. May be used for adding new widgets in it
790 //=======================================================================
791 QWidget* SMESHGUI_FilterTable::createAdditionalFrame (QWidget* theParent)
792 {
793   QWidget* aFrame = new QWidget(theParent);
794
795   QFrame* aLine1 = new QFrame(aFrame);
796   QFrame* aLine2 = new QFrame(aFrame);
797   aLine1->setFrameStyle(QFrame::HLine | QFrame::Sunken);
798   aLine2->setFrameStyle(QFrame::HLine | QFrame::Sunken);
799   aLine1->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
800   aLine2->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
801
802   QLabel* aLabel = new QLabel(tr("ADDITIONAL_PARAMETERS"), aFrame);
803
804   myWgStack = new QStackedWidget(aFrame);
805
806   QGridLayout* aLay = new QGridLayout(aFrame);
807   aLay->setMargin(0);
808   aLay->setSpacing(SPACING);
809   aLay->addWidget(aLine1,    0, 0);
810   aLay->addWidget(aLabel,    0, 1);
811   aLay->addWidget(aLine2,    0, 2);
812   aLay->addWidget(myWgStack, 1, 0, 1, 3);
813
814   return aFrame;
815 }
816
817 //=======================================================================
818 // name    : SMESHGUI_FilterTable::GetTableGrp
819 // Purpose : Get group box containing table. May be used for adding new widgets in it
820 //=======================================================================
821 QGroupBox* SMESHGUI_FilterTable::GetTableGrp()
822 {
823   return myTableGrp;
824 }
825
826 //=======================================================================
827 // name    : SMESHGUI_FilterTable::onEntityType
828 // Purpose : SLOT. Called when entity type changed.
829 //           Display corresponding table
830 //=======================================================================
831 void SMESHGUI_FilterTable::onEntityType (int theType)
832 {
833   if (myEntityType == theType)
834     return;
835
836   myIsValid = true;
837   emit NeedValidation();
838   if (!myIsValid)
839   {
840     myEntityTypeGrp->button(myEntityType)->setChecked(true);
841     return;
842   }
843
844   myEntityType = theType;
845
846   if (!myTables.contains(theType)) {
847     myTables[ theType ] = createTable(mySwitchTableGrp, theType);
848     ((QVBoxLayout*)mySwitchTableGrp->layout())->addWidget(myTables[ theType ]);
849   }
850
851   TableMap::iterator anIter;
852   for (anIter = myTables.begin(); anIter != myTables.end(); ++anIter)
853      anIter.value()->setVisible( myEntityType == anIter.key() );
854
855   updateBtnState();
856   qApp->processEvents();
857   myTables[ myEntityType ]->updateGeometry();
858   adjustSize();
859
860   emit EntityTypeChanged(theType);
861 }
862
863 //=======================================================================
864 // name    : SMESHGUI_FilterTable::IsValid
865 // Purpose : Verify validity of entered data
866 //=======================================================================
867 bool SMESHGUI_FilterTable::IsValid (const bool theMess, const int theEntityType) const
868 {
869   int aType = theEntityType == -1 ? GetType() : theEntityType;
870
871   Table* aTable = myTables[ aType ];
872   for (int i = 0, n = aTable->rowCount(); i < n; i++)
873   {
874     int aCriterion = GetCriterionType(i, aType);
875
876     if (aCriterion == SMESH::FT_RangeOfIds ||
877          aCriterion == SMESH::FT_BelongToGeom ||
878          aCriterion == SMESH::FT_BelongToPlane ||
879          aCriterion == SMESH::FT_BelongToCylinder ||
880          aCriterion == SMESH::FT_BelongToGenSurface ||
881          aCriterion == SMESH::FT_LyingOnGeom) {
882       if (aTable->text(i, 2).isEmpty()) {
883         if (theMess)
884           SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
885                                        tr("ERROR"));
886         return false;
887       }
888     } else {
889       bool aRes = false;
890       aTable->blockSignals(true);
891       double  aThreshold = (int)aTable->text(i, 2).toDouble(&aRes);
892       aTable->blockSignals(false);
893
894       if (!aRes && aTable->isEditable(i, 2)) {
895         if (theMess)
896           SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
897                                        tr("ERROR"));
898         return false;
899       }
900       else if (aType == SMESH::EDGE &&
901                 GetCriterionType(i, aType) == SMESH::FT_MultiConnection &&
902                 aThreshold == 1)
903       {
904         if (theMess)
905           SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
906                                        tr("MULTIEDGES_ERROR"));
907         return false;
908       }
909     }
910
911     QTableWidgetItem* anItem = aTable->item(i, 0);
912     if (myAddWidgets.contains(anItem) && !myAddWidgets[ anItem ]->IsValid())
913       return false;
914   }
915
916   return true;
917 }
918
919 //=======================================================================
920 // name    : SMESHGUI_FilterTable::SetValidity
921 // Purpose : Set validity of the table
922 //=======================================================================
923 void SMESHGUI_FilterTable::SetValidity (const bool isValid)
924 {
925   myIsValid = isValid;
926 }
927
928 //=======================================================================
929 // name    : SMESHGUI_FilterTable::GetType
930 // Purpose : Get current entity type
931 //=======================================================================
932 int SMESHGUI_FilterTable::GetType() const
933 {
934   return myEntityType;
935 }
936
937 //=======================================================================
938 // name    : SMESHGUI_FilterTable::SetType
939 // Purpose : Set current entity type
940 //=======================================================================
941 void SMESHGUI_FilterTable::SetType (const int type)
942 {
943   myEntityTypeGrp->button(type)->setChecked(true);
944   onEntityType(type);
945 }
946
947 //=======================================================================
948 // name    : SMESHGUI_FilterTable::RestorePreviousEntityType
949 // Purpose : Restore previous entity type
950 //=======================================================================
951 void SMESHGUI_FilterTable::RestorePreviousEntityType()
952 {
953   SetType(myEntityType);
954 }
955
956 //=======================================================================
957 // name    : SMESHGUI_FilterTable::GetCriterionType
958 // Purpose : Get type of criterion from specified row (corresponding enums in h-file)
959 //=======================================================================
960 int SMESHGUI_FilterTable::GetCriterionType (const int theRow, const int theType) const
961 {
962   int aType = theType == -1 ? GetType() : theType;
963   Table* aTable = myTables[ aType ];
964   ComboItem* anItem = (ComboItem*)aTable->item(theRow, 0);
965   return anItem != 0 ? anItem->value() : SMESH::FT_Undefined;
966 }
967
968 //=======================================================================
969 // name    : SMESHGUI_FilterTable::GetCriterion
970 // Purpose : Get parameters of criterion from specified row
971 //=======================================================================
972 void SMESHGUI_FilterTable::GetCriterion (const int                 theRow,
973                                          SMESH::Filter::Criterion& theCriterion,
974                                          const int                 theEntityType) const
975 {
976   int aType = theEntityType == -1 ? GetType() : theEntityType;
977   Table* aTable = myTables[ aType ];
978
979   theCriterion.Type = ((ComboItem*)aTable->item(theRow, 0))->value();
980   theCriterion.UnaryOp = ((CheckItem*)aTable->item(theRow, 3))->checked() ? SMESH::FT_LogicalNOT : SMESH::FT_Undefined;
981   theCriterion.BinaryOp = theRow != aTable->rowCount() - 1 ?
982     ((ComboItem*)aTable->item(theRow, 4))->value() : SMESH::FT_Undefined;
983   theCriterion.TypeOfElement = (SMESH::ElementType)aType;
984
985   int aCriterionType = GetCriterionType(theRow, aType);
986
987   if ( aCriterionType != SMESH::FT_RangeOfIds &&
988        aCriterionType != SMESH::FT_BelongToGeom &&
989        aCriterionType != SMESH::FT_BelongToPlane &&
990        aCriterionType != SMESH::FT_BelongToCylinder &&
991        aCriterionType != SMESH::FT_BelongToGenSurface &&
992        aCriterionType != SMESH::FT_LyingOnGeom)
993   {
994     theCriterion.Compare = ((ComboItem*)aTable->item(theRow, 1))->value();
995     theCriterion.Threshold = aTable->item(theRow, 2)->text().toDouble();
996   }
997   else
998   {
999     theCriterion.ThresholdStr = aTable->text(theRow, 2).toLatin1().data();
1000     if ( aCriterionType != SMESH::FT_RangeOfIds )
1001       theCriterion.ThresholdID = aTable->text( theRow, 5 ).toLatin1().data();
1002   }
1003
1004   QTableWidgetItem* anItem = aTable->item(theRow, 0);
1005   if (myAddWidgets.contains(anItem))
1006     theCriterion.Tolerance = myAddWidgets[ anItem ]->GetDouble(AdditionalWidget::Tolerance);
1007 }
1008
1009 //=======================================================================
1010 // name    : SMESHGUI_FilterTable::SetCriterion
1011 // Purpose : Set parameters of criterion of specified row
1012 //=======================================================================
1013 void SMESHGUI_FilterTable::SetCriterion (const int                       theRow,
1014                                          const SMESH::Filter::Criterion& theCriterion,
1015                                          const int                       theEntityType)
1016 {
1017   int aType = theEntityType == -1 ? GetType() : theEntityType;
1018
1019   Table* aTable = myTables[ aType ];
1020
1021   if (theRow > aTable->rowCount() - 1)
1022     return;
1023
1024   ((ComboItem*)aTable->item(theRow, 0))->setValue(theCriterion.Type);
1025   onCriterionChanged(theRow, 0, aType);
1026   ((ComboItem*)aTable->item(theRow, 1))->setValue(theCriterion.Compare);
1027   ((CheckItem*)aTable->item(theRow, 3))->setChecked(theCriterion.UnaryOp == SMESH::FT_LogicalNOT);
1028
1029   if (theCriterion.BinaryOp != SMESH::FT_Undefined)
1030   {
1031     if (!aTable->isEditable(theRow, 4))
1032       aTable->setItem(theRow, 4, getBinaryItem());
1033     ((ComboItem*)aTable->item(theRow, 4))->setValue(theCriterion.BinaryOp);
1034   }
1035   else
1036     aTable->setEditable(false, theRow, 4);
1037
1038   if (theCriterion.Type != SMESH::FT_RangeOfIds &&
1039       theCriterion.Type != SMESH::FT_BelongToGeom &&
1040       theCriterion.Type != SMESH::FT_BelongToPlane &&
1041       theCriterion.Type != SMESH::FT_BelongToCylinder &&
1042       theCriterion.Type != SMESH::FT_BelongToGenSurface &&
1043       theCriterion.Type != SMESH::FT_LyingOnGeom &&
1044       theCriterion.Type != SMESH::FT_FreeBorders &&
1045       theCriterion.Type != SMESH::FT_FreeEdges &&
1046       theCriterion.Type != SMESH::FT_BadOrientedVolume)
1047     aTable->item( theRow, 2 )->setText(QString("%1").arg(theCriterion.Threshold, 0, 'g', 15));
1048   else
1049   {
1050     aTable->item( theRow, 2 )->setText(QString(theCriterion.ThresholdStr));
1051     if ( theCriterion.Type != SMESH::FT_RangeOfIds )
1052       aTable->item( theRow, 5 )->setText( QString( theCriterion.ThresholdID ) );
1053   }
1054
1055   if (theCriterion.Compare == SMESH::FT_EqualTo ||
1056        theCriterion.Type    == SMESH::FT_BelongToPlane ||
1057        theCriterion.Type    == SMESH::FT_BelongToCylinder ||
1058        theCriterion.Type    == SMESH::FT_BelongToGenSurface)
1059   {
1060     QTableWidgetItem* anItem = aTable->item(theRow, 0);
1061     if (!myAddWidgets.contains(anItem))
1062     {
1063       myAddWidgets[ anItem ] = new AdditionalWidget(myWgStack);
1064       myWgStack->addWidget(myAddWidgets[ anItem ]);
1065     }
1066     myAddWidgets[ anItem ]->SetDouble(AdditionalWidget::Tolerance, theCriterion.Tolerance);
1067   }
1068
1069   emit CriterionChanged(theRow, aType);
1070
1071 }
1072
1073 //=======================================================================
1074 // name    : SMESHGUI_FilterTable::Update
1075 // Purpose : Update table
1076 //=======================================================================
1077 void SMESHGUI_FilterTable::Update()
1078 {
1079   Table* aTable = myTables[ GetType() ];
1080   int aCurrRow = aTable->currentRow();
1081   int numRows = aTable->rowCount();
1082   if ((aCurrRow < 0 || aCurrRow >= numRows) && numRows > 0)
1083     aTable->setCurrentCell(0, 0);
1084   updateAdditionalWidget();
1085 }
1086
1087 //=======================================================================
1088 // name    : SMESHGUI_FilterTable::AddCriterion
1089 // Purpose : Add criterion with parameters
1090 //=======================================================================
1091 void SMESHGUI_FilterTable::AddCriterion (const SMESH::Filter::Criterion& theCriterion,
1092                                          const int                       theEntityType)
1093 {
1094   int aType = theEntityType == -1 ? GetType() : theEntityType;
1095   Table* aTable = myTables[ aType ];
1096   addRow(aTable, aType);
1097   SetCriterion(aTable->rowCount() - 1, theCriterion);
1098 }
1099
1100 //=======================================================================
1101 // name    : SMESHGUI_FilterTable::NumRows
1102 // Purpose : Get number of criterions of current type
1103 //=======================================================================
1104 int SMESHGUI_FilterTable::NumRows (const int theEntityType) const
1105 {
1106   return myTables[ theEntityType == -1 ? GetType() : theEntityType ]->rowCount();
1107 }
1108
1109 //=======================================================================
1110 // name    : SMESHGUI_FilterTable::Clear
1111 // Purpose : Clear current table
1112 //=======================================================================
1113 void SMESHGUI_FilterTable::Clear (const int theType)
1114 {
1115   int aType = theType == -1 ? GetType() : theType;
1116   Table* aTable = myTables[ aType ];
1117
1118   if (aTable->rowCount() == 0)
1119     return;
1120
1121   while (aTable->rowCount() > 0)
1122   {
1123     removeAdditionalWidget(aTable, 0);
1124     aTable->removeRow(0);
1125   }
1126
1127   updateBtnState();
1128 }
1129
1130 //=======================================================================
1131 // name    : SMESHGUI_FilterTable::onAddBtn
1132 // Purpose : SLOT. Called then "Add" button pressed.
1133 //           Adds new string to table
1134 //=======================================================================
1135 void SMESHGUI_FilterTable::onAddBtn()
1136 {
1137   int aType = GetType();
1138   addRow(myTables[ aType ], aType);
1139
1140   Update();
1141 }
1142
1143 //=======================================================================
1144 // name    : SMESHGUI_FilterTable::onInsertBtn
1145 // Purpose : SLOT. Called then "Insert" button pressed.
1146 //           Inserts new string before current one
1147 //=======================================================================
1148 void SMESHGUI_FilterTable::onInsertBtn()
1149 {
1150   addRow(myTables[ GetType() ], GetType(), false);
1151 }
1152
1153 //=======================================================================
1154 // name    : SMESHGUI_FilterTable::onRemoveBtn
1155 // Purpose : SLOT. Called then "Remove" button pressed.
1156 //           Removes current string from table
1157 //=======================================================================
1158 void SMESHGUI_FilterTable::onRemoveBtn()
1159 {
1160   Table* aTable = myTables[ GetType() ];
1161
1162   if (aTable->rowCount() == 0)
1163     return;
1164
1165   QList<QTableWidgetItem*> items = aTable->selectedItems();
1166   
1167   QList<int> aRows = aTable->selectedRows(); // already sorted
1168   int i;
1169   foreach( i, aRows )
1170   {
1171     removeAdditionalWidget(aTable, i);
1172     aTable->removeRow(i);
1173   }
1174
1175   // remove control of binary logical operation from last row
1176   if (aTable->rowCount() > 0)
1177     aTable->setEditable(false, aTable->rowCount() - 1, 4);
1178
1179   updateBtnState();
1180 }
1181
1182 //=======================================================================
1183 // name    : SMESHGUI_FilterTable::updateAdditionalWidget
1184 // Purpose : Enable/Disable widget with additonal parameters
1185 //=======================================================================
1186 void SMESHGUI_FilterTable::updateAdditionalWidget()
1187 {
1188   Table* aTable = myTables[ GetType() ];
1189   int aRow = aTable->currentRow();
1190   if (aRow < 0 || aRow >= aTable->rowCount())
1191   {
1192     myWgStack->setEnabled(false);
1193     return;
1194   }
1195
1196   ComboItem* anItem = ((ComboItem*)aTable->item(aRow, 0));
1197   bool toEnable = ((ComboItem*)aTable->item(aRow, 1))->value() == SMESH::FT_EqualTo &&
1198                   GetCriterionType(aRow) != SMESH::FT_BelongToGeom &&
1199                   GetCriterionType(aRow) != SMESH::FT_LyingOnGeom &&
1200                   GetCriterionType(aRow) != SMESH::FT_RangeOfIds &&
1201                   GetCriterionType(aRow) != SMESH::FT_FreeEdges &&
1202                   GetCriterionType(aRow) != SMESH::FT_BadOrientedVolume;
1203   if (!myAddWidgets.contains(anItem))
1204   {
1205     myAddWidgets[ anItem ] = new AdditionalWidget(myWgStack);
1206     myWgStack->addWidget(myAddWidgets[ anItem ]);
1207   }
1208
1209   myWgStack->setCurrentWidget(myAddWidgets[ anItem ]);
1210   myWgStack->setEnabled(toEnable);
1211 }
1212
1213 //=======================================================================
1214 // name    : SMESHGUI_FilterTable::removeAdditionalWidget
1215 // Purpose : Remove widgets containing additional parameters from widget
1216 //           stack and internal map
1217 //=======================================================================
1218 void SMESHGUI_FilterTable::removeAdditionalWidget (QTableWidget* theTable, const int theRow)
1219 {
1220   QTableWidgetItem* anItem = theTable->item(theRow, 0);
1221   if (myAddWidgets.contains(anItem))
1222   {
1223     myWgStack->removeWidget(myAddWidgets[ anItem ]);
1224     myAddWidgets[ anItem ]->setParent(0);
1225     delete myAddWidgets[ anItem ];
1226     myAddWidgets.remove(anItem);
1227   }
1228 }
1229
1230 //=======================================================================
1231 // name    : SMESHGUI_FilterTable::onClearBtn
1232 // Purpose : SLOT. Called then "Clear" button pressed.
1233 //           Removes all strings from table
1234 //=======================================================================
1235 void SMESHGUI_FilterTable::onClearBtn()
1236 {
1237   Table* aTable = myTables[ GetType() ];
1238
1239   if (aTable->rowCount() == 0)
1240     return;
1241
1242   while (aTable->rowCount() > 0)
1243   {
1244     removeAdditionalWidget(aTable, 0);
1245     aTable->removeRow(0);
1246   }
1247
1248   updateBtnState();
1249 }
1250
1251 //=======================================================================
1252 // name    : SMESHGUI_FilterTable::onCurrentChanged()
1253 // Purpose : SLOT. Called when current cell changed
1254 //=======================================================================
1255 void SMESHGUI_FilterTable::onCurrentChanged (int theRow, int theCol)
1256 {
1257   if( !myIsLocked )
1258     updateAdditionalWidget();
1259   emit CurrentChanged(theRow, theCol);
1260 }
1261
1262 //=======================================================================
1263 // name    : SMESHGUI_FilterTable::onCriterionChanged()
1264 // Purpose : Provides reaction on change of criterion
1265 //=======================================================================
1266 void SMESHGUI_FilterTable::onCriterionChanged (const int row, const int col, const int entityType)
1267 {
1268   int aType = entityType == -1 ? GetType() : entityType;
1269   Table* aTable = myTables[ aType ];
1270   ComboItem* aCompareItem = (ComboItem*)aTable->item(row, 1);
1271
1272   int aCriterionType = GetCriterionType(row);
1273
1274   if (aType == SMESH::EDGE && aCriterionType == SMESH::FT_FreeBorders ||
1275        aType == SMESH::FACE && aCriterionType == SMESH::FT_FreeEdges ||
1276        aType == SMESH::VOLUME && aCriterionType == SMESH::FT_BadOrientedVolume)
1277   {
1278     if (aCompareItem->count() > 0)
1279       aCompareItem->clear();
1280     aTable->setEditable(false, row, 2);
1281   }
1282   else if (aCriterionType == SMESH::FT_RangeOfIds ||
1283            aCriterionType == SMESH::FT_BelongToGeom ||
1284            aCriterionType == SMESH::FT_BelongToPlane ||
1285            aCriterionType == SMESH::FT_BelongToCylinder ||
1286            aCriterionType == SMESH::FT_BelongToGenSurface ||
1287            aCriterionType == SMESH::FT_LyingOnGeom)
1288   {
1289     QMap<int, QString> aMap;
1290     aMap[ SMESH::FT_EqualTo ] = tr("EQUAL_TO");
1291     aCompareItem->setItems(aMap);
1292     if (!aTable->isEditable(row, 2))
1293       aTable->setEditable(true, row, 2);
1294   }
1295   else
1296   {
1297     if (aCompareItem->count() != 3)
1298     {
1299       aCompareItem->setItems(getCompare());
1300     }
1301
1302     QString aText = aTable->text(row, 2);
1303     bool isOk = false;
1304     aText.toDouble(&isOk);
1305     aTable->item( row, 2 )->setText(isOk ? aText : QString(""));
1306     if (!aTable->isEditable(row, 2))
1307       aTable->setEditable(true, row, 2);
1308   }
1309
1310   updateAdditionalWidget();
1311
1312   emit CriterionChanged(row, entityType);
1313 }
1314
1315 //=======================================================================
1316 // name    : SMESHGUI_FilterTable::onCriterionChanged()
1317 // Purpose : SLOT. Called then contents of table changed
1318 //           Provides reaction on change of criterion
1319 //=======================================================================
1320 void SMESHGUI_FilterTable::onCriterionChanged (int row, int col)
1321 {
1322   onCriterionChanged(row, col, -1);
1323 }
1324
1325 //=======================================================================
1326 // name    : SMESHGUI_FilterTable::getFirstSelectedRow
1327 // Purpose : Get first selected row
1328 //=======================================================================
1329 int SMESHGUI_FilterTable::getFirstSelectedRow() const
1330 {
1331   Table* aTable = myTables[ GetType() ];
1332
1333   QList<int> selRows = aTable->selectedRows(); // already sorted
1334   int aRow = selRows.count() > 0 ? selRows[0] : aTable->currentRow();
1335
1336   return aRow >= 0 && aRow < aTable->rowCount() ? aRow : -1;
1337 }
1338
1339 //=======================================================================
1340 // name    : SMESHGUI_FilterTable::addRow
1341 // Purpose : Add row at the end of table
1342 //=======================================================================
1343 void SMESHGUI_FilterTable::addRow (Table* theTable, const int theType, const bool toTheEnd)
1344 {
1345   int aCurrRow = 0;
1346   int aSelectedRow = getFirstSelectedRow();
1347   int aCurrCol = theTable->currentColumn();
1348
1349   myIsLocked = true;
1350   if (toTheEnd || aSelectedRow == -1)
1351   {
1352     theTable->insertRows(theTable->rowCount());
1353     aCurrRow = theTable->rowCount() - 1;
1354   }
1355   else
1356   {
1357     theTable->insertRows(aSelectedRow);
1358     aCurrRow = aSelectedRow;
1359   }
1360   myIsLocked = false;
1361
1362   // Criteria
1363   theTable->setItem(aCurrRow, 0, getCriterionItem(theType));
1364
1365   // Compare
1366   theTable->setItem(aCurrRow, 1, getCompareItem());
1367
1368   // Threshold
1369   //theTable->setItem(aCurrRow, 2, new QTableWidgetItem());
1370
1371   //Logical operation NOT
1372   theTable->setItem(aCurrRow, 3, getUnaryItem());
1373
1374   // Logical binary operation for previous value
1375   int anAddBinOpStr = -1;
1376   if (aCurrRow == theTable->rowCount() - 1)
1377     anAddBinOpStr = aCurrRow - 1;
1378   else if (aCurrRow >= 0 )
1379     anAddBinOpStr = aCurrRow;
1380
1381   if (theTable->item(aCurrRow, 4) == 0 ||
1382        theTable->item(aCurrRow, 4)->type() != ComboItem::Type())
1383   {
1384
1385
1386     if (anAddBinOpStr >= 0 &&
1387          (theTable->item(anAddBinOpStr, 4) == 0 ||
1388            theTable->item(anAddBinOpStr, 4)->type() != ComboItem::Type()))
1389       theTable->setItem(anAddBinOpStr, 4, getBinaryItem());
1390   }
1391
1392   theTable->setEditable(false, theTable->rowCount() - 1, 4);
1393
1394   if (aCurrRow >=0 && aCurrRow < theTable->rowCount() &&
1395        aCurrCol >=0 && aCurrCol < theTable->rowCount())
1396   theTable->setCurrentCell(aCurrRow, aCurrCol);
1397
1398   onCriterionChanged(aCurrRow, 0);
1399
1400   updateBtnState();
1401 }
1402
1403 //=======================================================================
1404 // name    : SMESHGUI_FilterTable::getCriterionItem
1405 // Purpose : Get combo table item for criteria of specified type
1406 //=======================================================================
1407 QTableWidgetItem* SMESHGUI_FilterTable::getCriterionItem (const int theType) const
1408 {
1409   return new ComboItem(getCriteria(theType));
1410 }
1411
1412 //=======================================================================
1413 // name    : SMESHGUI_FilterTable::getCompareItem
1414 // Purpose : Get combo table item for operation of comparision
1415 //=======================================================================
1416 QTableWidgetItem* SMESHGUI_FilterTable::getCompareItem () const
1417 {
1418   return new ComboItem(getCompare());
1419 }
1420
1421 //=======================================================================
1422 // name    : SMESHGUI_FilterTable::getBinaryItem
1423 // Purpose :
1424 //=======================================================================
1425 QTableWidgetItem* SMESHGUI_FilterTable::getBinaryItem () const
1426 {
1427   static QMap<int, QString> aMap;
1428   if (aMap.isEmpty())
1429   {
1430     aMap[ SMESH::FT_LogicalAND ] = tr("AND");
1431     aMap[ SMESH::FT_LogicalOR  ] = tr("OR");
1432   }
1433
1434   return new ComboItem(aMap);
1435 }
1436
1437 //=======================================================================
1438 // name    : SMESHGUI_FilterTable::getUnaryItem
1439 // Purpose : Get check table item
1440 //=======================================================================
1441 QTableWidgetItem* SMESHGUI_FilterTable::getUnaryItem () const
1442 {
1443   return new CheckItem(tr("NOT"));
1444 }
1445
1446 //=======================================================================
1447 // name    : SMESHGUI_FilterTable::getSupportedTypes
1448 // Purpose : Get all supported type
1449 //=======================================================================
1450 const QMap<int, QString>& SMESHGUI_FilterTable::getSupportedTypes() const
1451 {
1452   static QMap<int, QString> aTypes;
1453   if (aTypes.isEmpty())
1454   {
1455     aTypes[ SMESH::NODE   ] = tr("NODES");
1456     aTypes[ SMESH::EDGE   ] = tr("EDGES");
1457     aTypes[ SMESH::FACE   ] = tr("FACES");
1458     aTypes[ SMESH::VOLUME ] = tr("VOLUMES");
1459   }
1460
1461   return aTypes;
1462 }
1463
1464 //=======================================================================
1465 // name    : SMESHGUI_FilterTable::getCriteria
1466 // Purpose : Get criteria for specified type
1467 //=======================================================================
1468 const QMap<int, QString>& SMESHGUI_FilterTable::getCriteria (const int theType) const
1469 {
1470   if (theType == SMESH::NODE)
1471   {
1472     static QMap<int, QString> aCriteria;
1473     if (aCriteria.isEmpty())
1474     {
1475       aCriteria[ SMESH::FT_RangeOfIds         ] = tr("RANGE_OF_IDS");
1476       aCriteria[ SMESH::FT_BelongToGeom       ] = tr("BELONG_TO_GEOM");
1477       aCriteria[ SMESH::FT_BelongToPlane      ] = tr("BELONG_TO_PLANE");
1478       aCriteria[ SMESH::FT_BelongToCylinder   ] = tr("BELONG_TO_CYLINDER");
1479       aCriteria[ SMESH::FT_BelongToGenSurface ] = tr("BELONG_TO_GENSURFACE");
1480       aCriteria[ SMESH::FT_LyingOnGeom        ] = tr("LYING_ON_GEOM");
1481     }
1482     return aCriteria;
1483   }
1484   else if (theType == SMESH::EDGE)
1485   {
1486     static QMap<int, QString> aCriteria;
1487     if (aCriteria.isEmpty())
1488     {
1489       aCriteria[ SMESH::FT_FreeBorders        ] = tr("FREE_BORDERS");
1490       aCriteria[ SMESH::FT_MultiConnection    ] = tr("MULTI_BORDERS");
1491       aCriteria[ SMESH::FT_Length             ] = tr("LENGTH");
1492       aCriteria[ SMESH::FT_RangeOfIds         ] = tr("RANGE_OF_IDS");
1493       aCriteria[ SMESH::FT_BelongToGeom       ] = tr("BELONG_TO_GEOM");
1494       aCriteria[ SMESH::FT_BelongToPlane      ] = tr("BELONG_TO_PLANE");
1495       aCriteria[ SMESH::FT_BelongToCylinder   ] = tr("BELONG_TO_CYLINDER");
1496       aCriteria[ SMESH::FT_BelongToGenSurface ] = tr("BELONG_TO_GENSURFACE");
1497       aCriteria[ SMESH::FT_LyingOnGeom        ] = tr("LYING_ON_GEOM");
1498     }
1499     return aCriteria;
1500   }
1501   else if (theType == SMESH::FACE)
1502   {
1503     static QMap<int, QString> aCriteria;
1504     if (aCriteria.isEmpty())
1505     {
1506       aCriteria[ SMESH::FT_AspectRatio        ] = tr("ASPECT_RATIO");
1507       aCriteria[ SMESH::FT_Warping            ] = tr("WARPING");
1508       aCriteria[ SMESH::FT_MinimumAngle       ] = tr("MINIMUM_ANGLE");
1509       aCriteria[ SMESH::FT_Taper              ] = tr("TAPER");
1510       aCriteria[ SMESH::FT_Skew               ] = tr("SKEW");
1511       aCriteria[ SMESH::FT_Area               ] = tr("AREA");
1512       aCriteria[ SMESH::FT_FreeEdges          ] = tr("FREE_EDGES");
1513       aCriteria[ SMESH::FT_RangeOfIds         ] = tr("RANGE_OF_IDS");
1514       aCriteria[ SMESH::FT_BelongToGeom       ] = tr("BELONG_TO_GEOM");
1515       aCriteria[ SMESH::FT_BelongToPlane      ] = tr("BELONG_TO_PLANE");
1516       aCriteria[ SMESH::FT_BelongToCylinder   ] = tr("BELONG_TO_CYLINDER");
1517       aCriteria[ SMESH::FT_BelongToGenSurface ] = tr("BELONG_TO_GENSURFACE");
1518       aCriteria[ SMESH::FT_LyingOnGeom        ] = tr("LYING_ON_GEOM");
1519       aCriteria[ SMESH::FT_Length2D           ] = tr("LENGTH2D");
1520       aCriteria[ SMESH::FT_MultiConnection2D  ] = tr("MULTI2D_BORDERS");
1521     }
1522     return aCriteria;
1523   }
1524   else if (theType == SMESH::VOLUME)
1525   {
1526     static QMap<int, QString> aCriteria;
1527     if (aCriteria.isEmpty())
1528     {
1529       aCriteria[ SMESH::FT_AspectRatio3D     ] = tr("ASPECT_RATIO_3D");
1530       aCriteria[ SMESH::FT_RangeOfIds        ] = tr("RANGE_OF_IDS");
1531       aCriteria[ SMESH::FT_BelongToGeom      ] = tr("BELONG_TO_GEOM");
1532       aCriteria[ SMESH::FT_LyingOnGeom       ] = tr("LYING_ON_GEOM");
1533       aCriteria[ SMESH::FT_BadOrientedVolume ] = tr("BAD_ORIENTED_VOLUME");
1534       aCriteria[ SMESH::FT_Volume3D          ] = tr("VOLUME_3D");
1535     }
1536     return aCriteria;
1537   }
1538   else
1539   {
1540     static QMap<int, QString> aCriteria;
1541     return aCriteria;
1542   }
1543 }
1544
1545
1546 //=======================================================================
1547 // name    : SMESHGUI_FilterTable::getCompare
1548 // Purpose : Get operation of comparison
1549 //=======================================================================
1550 const QMap<int, QString>& SMESHGUI_FilterTable::getCompare() const
1551 {
1552   static QMap<int, QString> aMap;
1553
1554   if (aMap.isEmpty())
1555   {
1556     aMap[ SMESH::FT_LessThan ] = tr("LESS_THAN");
1557     aMap[ SMESH::FT_MoreThan ] = tr("MORE_THAN");
1558     aMap[ SMESH::FT_EqualTo  ] = tr("EQUAL_TO" );
1559   }
1560
1561   return aMap;
1562 }
1563
1564 //=======================================================================
1565 // name    : SMESHGUI_FilterTable::createTable
1566 // Purpose : Create table
1567 //=======================================================================
1568 SMESHGUI_FilterTable::Table* SMESHGUI_FilterTable::createTable (QWidget*  theParent,
1569                                                                 const int theType)
1570 {
1571   // create table
1572   Table* aTable= new Table(0, 6, theParent);
1573
1574   QHeaderView* aHeaders = aTable->horizontalHeader();
1575
1576   QFontMetrics aMetrics(aHeaders->font());
1577
1578   // append spaces to the header of criteria in order to
1579   // provide visibility of criterion inside comboboxes
1580   static int aMaxLenCr = 0;
1581
1582   if (aMaxLenCr == 0)
1583   {
1584     const QMap<int, QString>& aSupportedTypes = getSupportedTypes();
1585     QMap<int, QString>::const_iterator anIter;
1586     for (anIter = aSupportedTypes.begin(); anIter != aSupportedTypes.end(); ++anIter)
1587       aMaxLenCr = qMax(maxLength(getCriteria(anIter.key()), aMetrics), aMaxLenCr);
1588   }
1589
1590   static int aLenCr = qAbs( aMaxLenCr -
1591                             aMetrics.width(tr("CRITERION"))) / aMetrics.width(' ') + 5;
1592
1593   QString aCrStr;
1594   aCrStr.fill(' ', aLenCr);
1595   QString aCoStr;
1596   aCoStr.fill(' ', 10);
1597
1598   aTable->horizontalHeaderItem(0)->setText(tr("CRITERION") + aCrStr);
1599   aTable->horizontalHeaderItem(1)->setText(tr("COMPARE")   + aCoStr);
1600   aTable->horizontalHeaderItem(2)->setText(tr("THRESHOLD_VALUE"));
1601   aTable->horizontalHeaderItem(3)->setText(tr("UNARY"));
1602   aTable->horizontalHeaderItem(4)->setText(tr("BINARY") + "  ");
1603   aTable->horizontalHeaderItem(5)->setText(tr("ID"));
1604
1605   // set geometry of the table
1606   for (int i = 0; i <= 4; i++)
1607     aTable->resizeColumnToContents(i);
1608
1609   // set the ID column invisible
1610   aTable->hideColumn( 5 );
1611
1612   aTable->updateGeometry();
1613   QSize aSize = aTable->sizeHint();
1614   int aWidth = aSize.width();
1615   aTable->setMinimumSize(QSize(aWidth, aWidth / 2));
1616   aTable->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));
1617
1618   connect(aTable, SIGNAL(cellChanged(int, int)),
1619           this,   SLOT(onCriterionChanged(int, int)));
1620
1621   connect(aTable, SIGNAL(currentCellChanged(int, int, int, int)),
1622           this,   SLOT(onCurrentChanged(int, int)));
1623   
1624   return aTable;
1625 }
1626
1627 //=======================================================================
1628 // name    : SMESHGUI_FilterTable::updateBtnState
1629 // Purpose : Update button state
1630 //=======================================================================
1631 void SMESHGUI_FilterTable::updateBtnState()
1632 {
1633   myRemoveBtn->setEnabled(myTables[ GetType() ]->rowCount() > 0);
1634   myClearBtn->setEnabled(myTables[ GetType() ]->rowCount() > 0);
1635 }
1636
1637 //=======================================================================
1638 // name    : SMESHGUI_FilterTable::SetEditable
1639 // Purpose : Set read only flag for tables. Show/hide buttons for work with rows
1640 //=======================================================================
1641 void SMESHGUI_FilterTable::SetEditable (const bool isEditable)
1642 {
1643   TableMap::iterator anIter;
1644   for (anIter = myTables.begin(); anIter != myTables.end(); ++anIter)
1645   {
1646     anIter.value()->setReadOnly(!isEditable);
1647
1648     if (isEditable)
1649     {
1650       myAddBtn->show();
1651       myInsertBtn->show();
1652       myRemoveBtn->show();
1653       myClearBtn->show();
1654     }
1655     else
1656     {
1657       myAddBtn->hide();
1658       myInsertBtn->hide();
1659       myRemoveBtn->hide();
1660       myClearBtn->hide();
1661     }
1662   }
1663
1664   QMap<QTableWidgetItem*, AdditionalWidget*>::iterator anIter2;
1665   for (anIter2 = myAddWidgets.begin(); anIter2 != myAddWidgets.end(); ++anIter2)
1666     anIter2.value()->SetEditable(isEditable);
1667 }
1668
1669 //=======================================================================
1670 // name    : SMESHGUI_FilterTable::SetEnabled
1671 // Purpose : Enable/Disable table. Switching type of elements already enabled
1672 //=======================================================================
1673 void SMESHGUI_FilterTable::SetEnabled (const bool isEnabled)
1674 {
1675   myAddBtn->setEnabled(isEnabled);
1676   myInsertBtn->setEnabled(isEnabled);
1677   myRemoveBtn->setEnabled(isEnabled);
1678   myClearBtn->setEnabled(isEnabled);
1679
1680   if (isEnabled)
1681     updateBtnState();
1682
1683   QMap<QTableWidgetItem*, AdditionalWidget*>::iterator anIter2;
1684   for (anIter2 = myAddWidgets.begin(); anIter2 != myAddWidgets.end(); ++anIter2)
1685     anIter2.value()->setEnabled(isEnabled);
1686 }
1687
1688 //=======================================================================
1689 // name    : SMESHGUI_FilterTable::IsEditable
1690 // Purpose : Verify whether table is editable
1691 //=======================================================================
1692 bool SMESHGUI_FilterTable::IsEditable() const
1693 {
1694   return !myTables[ GetType() ]->isReadOnly();
1695 }
1696
1697 //=======================================================================
1698 // name    : SMESHGUI_FilterTable::SetLibsEnabled
1699 // Purpose : Show/hide buttons for work with libraries
1700 //=======================================================================
1701 void SMESHGUI_FilterTable::SetLibsEnabled (const bool isEnabled)
1702 {
1703   if (isEnabled)
1704   {
1705     myCopyFromBtn->show();
1706     myAddToBtn->show();
1707   }
1708   else
1709   {
1710     myCopyFromBtn->hide();
1711     myAddToBtn->hide();
1712   }
1713 }
1714
1715 //=======================================================================
1716 // name    : SMESHGUI_FilterTable::onCopyFromBtn
1717 // Purpose : SLOT. Called the "Copy from ..." button clicked
1718 //           Display filter library dialog
1719 //=======================================================================
1720 void SMESHGUI_FilterTable::onCopyFromBtn()
1721 {
1722   if (myLibDlg == 0)
1723     myLibDlg = new SMESHGUI_FilterLibraryDlg(
1724       mySMESHGUI, this, GetType(), SMESHGUI_FilterLibraryDlg::COPY_FROM);
1725   else
1726     myLibDlg->Init(GetType(), SMESHGUI_FilterLibraryDlg::COPY_FROM);
1727
1728   if (myLibDlg->exec() == QDialog::Accepted)
1729   {
1730     Copy(myLibDlg->GetTable());
1731     Update();
1732   }
1733 }
1734
1735 //=======================================================================
1736 // name    : SMESHGUI_FilterTable::onAddToBtn
1737 // Purpose : SLOT. Called the "Add to ..." button clicked
1738 //           Display filter library dialog
1739 //=======================================================================
1740 void SMESHGUI_FilterTable::onAddToBtn()
1741 {
1742   if (!IsValid(true))
1743     return;
1744   if (myLibDlg == 0)
1745     myLibDlg = new SMESHGUI_FilterLibraryDlg(
1746       mySMESHGUI, this, GetType(), SMESHGUI_FilterLibraryDlg::ADD_TO);
1747   else
1748     myLibDlg->Init(GetType(), SMESHGUI_FilterLibraryDlg::ADD_TO);
1749
1750   myLibDlg->SetTable(this);
1751
1752   myLibDlg->exec();
1753 }
1754
1755 //=======================================================================
1756 // name    : SMESHGUI_FilterTable::Copy
1757 // Purpose : Initialise table with values of other table
1758 //=======================================================================
1759 void SMESHGUI_FilterTable::Copy (const SMESHGUI_FilterTable* theTable)
1760 {
1761   Clear();
1762
1763   for (int i = 0, n = theTable->NumRows(); i < n; i++)
1764   {
1765     SMESH::Filter::Criterion aCriterion = SMESHGUI_FilterDlg::createCriterion();
1766     theTable->GetCriterion(i, aCriterion);
1767     AddCriterion(aCriterion);
1768   }
1769 }
1770
1771 //=======================================================================
1772 // name    : SMESHGUI_FilterTable::CurrentCell
1773 // Purpose : Returns current cell
1774 //=======================================================================
1775 bool SMESHGUI_FilterTable::CurrentCell (int& theRow, int& theCol) const
1776 {
1777   theRow = myTables[ GetType() ]->currentRow();
1778   theCol = myTables[ GetType() ]->currentColumn();
1779   return theRow >= 0 && theCol >= 0;
1780 }
1781
1782 //=======================================================================
1783 // name    : SMESHGUI_FilterTable::SetText
1784 // Purpose : Set text and internal value in cell of threshold value
1785 //=======================================================================
1786 void SMESHGUI_FilterTable::SetThreshold (const int      theRow,
1787                                          const QString& theText,
1788                                          const int      theEntityType)
1789 {
1790   Table* aTable = myTables[ theEntityType == -1 ? GetType() : theEntityType ];
1791   aTable->item( theRow, 2 )->setText(theText);
1792 }
1793
1794 //=======================================================================
1795 // name    : SMESHGUI_FilterTable::SetText
1796 // Purpose : Get text and internal value from cell of threshold value
1797 //=======================================================================
1798 bool SMESHGUI_FilterTable::GetThreshold (const int      theRow,
1799                                          QString&       theText,
1800                                          const int      theEntityType)
1801 {
1802   Table* aTable = myTables[ theEntityType == -1 ? GetType() : theEntityType ];
1803   QTableWidgetItem* anItem = aTable->item(theRow, 2);
1804   if (anItem != 0)
1805   {
1806     theText = anItem->text();
1807     return true;
1808   }
1809   else
1810    return false;
1811 }
1812
1813 //=======================================================================
1814 // name    : SMESHGUI_FilterTable::SetID
1815 // Purpose : Set text and internal value in cell of ID value 
1816 //=======================================================================
1817 void SMESHGUI_FilterTable::SetID( const int      theRow,
1818                                          const QString& theText,
1819                                          const int      theEntityType )
1820 {
1821   Table* aTable = myTables[ theEntityType == -1 ? GetType() : theEntityType ];
1822   aTable->item( theRow, 5 )->setText( theText );
1823 }
1824
1825 //=======================================================================
1826 // name    : SMESHGUI_FilterTable::GetID
1827 // Purpose : Get text and internal value from cell of ID value
1828 //=======================================================================
1829 bool SMESHGUI_FilterTable::GetID( const int      theRow,
1830                                   QString&       theText,
1831                                   const int      theEntityType )
1832 {
1833   Table* aTable = myTables[ theEntityType == -1 ? GetType() : theEntityType ];
1834   QTableWidgetItem* anItem = aTable->item( theRow, 5 );
1835   if ( anItem != 0 )
1836     {
1837       theText = anItem->text();
1838       return true;    
1839     }
1840   else
1841     return false;
1842
1843
1844 /*
1845   Class       : SMESHGUI_FilterDlg
1846   Description : Dialog to specify filters for VTK viewer
1847 */
1848
1849
1850 //=======================================================================
1851 // name    : SMESHGUI_FilterDlg::SMESHGUI_FilterDlg
1852 // Purpose : Constructor
1853 //=======================================================================
1854 SMESHGUI_FilterDlg::SMESHGUI_FilterDlg( SMESHGUI*         theModule,
1855                                         const QList<int>& theTypes )
1856 : QDialog( SMESH::GetDesktop( theModule ) ),
1857   mySMESHGUI( theModule ),
1858   mySelectionMgr( SMESH::GetSelectionMgr( theModule ) )
1859 {
1860   if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
1861     mySelector = aViewWindow->GetSelector();
1862
1863   construct(theTypes);
1864 }
1865
1866 //=======================================================================
1867 // name    : SMESHGUI_FilterDlg::SMESHGUI_FilterDlg
1868 // Purpose : Constructor
1869 //=======================================================================
1870 SMESHGUI_FilterDlg::SMESHGUI_FilterDlg( SMESHGUI*   theModule,
1871                                         const int   theType )
1872 : QDialog( SMESH::GetDesktop( theModule ) ),
1873   mySMESHGUI( theModule ),
1874   mySelectionMgr( SMESH::GetSelectionMgr( theModule ) )
1875 {
1876   if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
1877     mySelector = aViewWindow->GetSelector();
1878   QList<int> aTypes;
1879   aTypes.append(theType);
1880   construct(aTypes);
1881 }
1882
1883 //=======================================================================
1884 // name    : SMESHGUI_FilterDlg::construct
1885 // Purpose : Construct dialog (called by constructor)
1886 //=======================================================================
1887 void SMESHGUI_FilterDlg::construct (const QList<int>& theTypes)
1888 {
1889   myTypes = theTypes;
1890
1891   setModal(false);
1892   //setAttribute(Qt::WA_DeleteOnClose, true); // VSR ??? is it required?
1893   setWindowTitle(tr("CAPTION"));
1894
1895   QVBoxLayout* aDlgLay = new QVBoxLayout (this);
1896   aDlgLay->setMargin(MARGIN);
1897   aDlgLay->setSpacing(SPACING);
1898
1899   myMainFrame         = createMainFrame  (this);
1900   QWidget* aBtnFrame  = createButtonFrame(this);
1901
1902   aDlgLay->addWidget(myMainFrame);
1903   aDlgLay->addWidget(aBtnFrame);
1904
1905   aDlgLay->setStretchFactor(myMainFrame, 1);
1906
1907   myHelpFileName = "selection_filter_library_page.html";
1908
1909   Init(myTypes);
1910 }
1911
1912 //=======================================================================
1913 // name    : SMESHGUI_FilterDlg::createMainFrame
1914 // Purpose : Create frame containing dialog's input fields
1915 //=======================================================================
1916 QWidget* SMESHGUI_FilterDlg::createMainFrame (QWidget* theParent)
1917 {
1918   QWidget* aMainFrame = new QWidget(theParent);
1919   QVBoxLayout* aMainLay = new QVBoxLayout(aMainFrame);
1920   aMainLay->setMargin(0);
1921   aMainLay->setSpacing(SPACING);
1922
1923   // filter frame
1924
1925   myTable = new SMESHGUI_FilterTable( mySMESHGUI, aMainFrame, myTypes );
1926   myTable->SetLibsEnabled(true);
1927
1928   QGroupBox* aGrp = myTable->GetTableGrp();
1929   QGridLayout* aLay = qobject_cast<QGridLayout*>( aGrp->layout() );
1930   int rows = aLay->rowCount();
1931   int cols = aLay->columnCount();
1932
1933   QFrame* aLine = new QFrame(aGrp);
1934   aLine->setFrameStyle(QFrame::HLine | QFrame::Sunken);
1935   aLay->addWidget(aLine, rows++, 0, 1, cols);
1936
1937   mySetInViewer = new QCheckBox(tr("SET_IN_VIEWER"), aGrp);
1938   mySetInViewer->setChecked(true);
1939   aLay->addWidget(mySetInViewer, rows++, 0, 1, cols);
1940
1941   // other controls
1942   QWidget* aSourceGrp = createSourceGroup(aMainFrame);
1943
1944   connect(myTable, SIGNAL(CriterionChanged(const int, const int)),
1945                     SLOT(onCriterionChanged(const int, const int)));
1946
1947   connect(myTable, SIGNAL(CurrentChanged(int, int)),
1948                     SLOT(onCurrentChanged(int, int)));
1949
1950   aMainLay->addWidget(myTable);
1951   aMainLay->addWidget(aSourceGrp);
1952   
1953   return aMainFrame;
1954 }
1955
1956 //=======================================================================
1957 // name    : SMESHGUI_FilterDlg::createSourceFrame
1958 // Purpose : Create frame containing source radio button
1959 //=======================================================================
1960 QWidget* SMESHGUI_FilterDlg::createSourceGroup (QWidget* theParent)
1961 {
1962   QGroupBox* aBox = new QGroupBox(tr("SOURCE"), theParent);
1963   QHBoxLayout* aLay = new QHBoxLayout(aBox);
1964   aLay->setMargin(MARGIN);
1965   aLay->setSpacing(SPACING);
1966
1967   mySourceGrp = new QButtonGroup(theParent);
1968
1969   QRadioButton* aMeshBtn = new QRadioButton(tr("MESH"),          aBox);
1970   QRadioButton* aSelBtn  = new QRadioButton(tr("SELECTION"),     aBox);
1971   QRadioButton* aGrpBtn  = new QRadioButton(tr("CURRENT_GROUP"), aBox);
1972
1973   aLay->addWidget(aMeshBtn);
1974   aLay->addWidget(aSelBtn);
1975   aLay->addWidget(aGrpBtn);
1976
1977   mySourceGrp->addButton(aMeshBtn, Mesh);
1978   mySourceGrp->addButton(aSelBtn,  Selection);
1979   mySourceGrp->addButton(aGrpBtn,  Dialog);
1980
1981   aSelBtn->setChecked(true);
1982
1983   return aBox;
1984 }
1985
1986 //=======================================================================
1987 // name    : SMESHGUI_FilterDlg::updateMainButtons
1988 // Purpose : Update visibility of main buttons (OK, Cancel, Close ...)
1989 //=======================================================================
1990 void SMESHGUI_FilterDlg::updateMainButtons()
1991 {
1992   if (myTypes.count() == 1)
1993   {
1994     myButtons[ BTN_Cancel ]->show();
1995     myButtons[ BTN_Apply  ]->hide();
1996     myButtons[ BTN_Close  ]->hide();
1997   }
1998   else
1999   {
2000     myButtons[ BTN_Cancel ]->hide();
2001     myButtons[ BTN_Apply  ]->show();
2002     myButtons[ BTN_Close  ]->show();
2003   }
2004
2005 //  updateGeometry();
2006 }
2007
2008 //=======================================================================
2009 // name    : SMESHGUI_FilterDlg::createButtonFrame
2010 // Purpose : Create frame containing buttons
2011 //=======================================================================
2012 QWidget* SMESHGUI_FilterDlg::createButtonFrame (QWidget* theParent)
2013 {
2014   QGroupBox* aGrp = new QGroupBox(theParent);
2015   QHBoxLayout* aLay = new QHBoxLayout(aGrp);
2016   aLay->setMargin(MARGIN);
2017   aLay->setSpacing(SPACING);
2018
2019   myButtons[ BTN_OK     ] = new QPushButton(tr("SMESH_BUT_OK"   ),  aGrp);
2020   myButtons[ BTN_Apply  ] = new QPushButton(tr("SMESH_BUT_APPLY"),  aGrp);
2021   myButtons[ BTN_Cancel ] = new QPushButton(tr("SMESH_BUT_CANCEL"), aGrp);
2022   myButtons[ BTN_Close  ] = new QPushButton(tr("SMESH_BUT_CLOSE"),  aGrp);
2023   myButtons[ BTN_Help   ] = new QPushButton(tr("SMESH_BUT_HELP"),   aGrp);
2024
2025   aLay->addWidget(myButtons[ BTN_OK     ]);
2026   aLay->addSpacing(10);
2027   aLay->addWidget(myButtons[ BTN_Apply  ]);
2028   aLay->addSpacing(10);
2029   aLay->addStretch();
2030   aLay->addWidget(myButtons[ BTN_Cancel ]);
2031   aLay->addWidget(myButtons[ BTN_Close  ]);
2032   aLay->addWidget(myButtons[ BTN_Help   ]);
2033
2034   connect(myButtons[ BTN_OK     ], SIGNAL(clicked()), SLOT(onOk()));
2035   connect(myButtons[ BTN_Cancel ], SIGNAL(clicked()), SLOT(onClose()));
2036   connect(myButtons[ BTN_Close  ], SIGNAL(clicked()), SLOT(onClose()));
2037   connect(myButtons[ BTN_Apply  ], SIGNAL(clicked()), SLOT(onApply()));
2038   connect(myButtons[ BTN_Help   ], SIGNAL(clicked()), SLOT(onHelp()));
2039
2040   updateMainButtons();
2041
2042   return aGrp;
2043 }
2044
2045 //=======================================================================
2046 // name    : SMESHGUI_FilterDlg::~SMESHGUI_FilterDlg
2047 // Purpose : Destructor
2048 //=======================================================================
2049 SMESHGUI_FilterDlg::~SMESHGUI_FilterDlg()
2050 {
2051 }
2052
2053 //=======================================================================
2054 // name    : SMESHGUI_FilterDlg::Init
2055 // Purpose : Init dialog fields, connect signals and slots, show dialog
2056 //=======================================================================
2057 void SMESHGUI_FilterDlg::Init (const int type)
2058 {
2059   QList<int> aTypes;
2060   aTypes.append(type);
2061   Init(aTypes);
2062 }
2063
2064 //=======================================================================
2065 // name    : SMESHGUI_FilterDlg::Init
2066 // Purpose : Init dialog fields, connect signals and slots, show dialog
2067 //=======================================================================
2068 void SMESHGUI_FilterDlg::Init (const QList<int>& theTypes)
2069 {
2070   mySourceWg  = 0;
2071   myTypes     = theTypes;
2072   myMesh      = SMESH::SMESH_Mesh::_nil();
2073   myIObjects.Clear();
2074   myIsSelectionChanged = false;
2075
2076   myTable->Init(theTypes);
2077
2078   // set caption
2079   if (theTypes.count() == 1)
2080   {
2081     int aType = theTypes.first();
2082     if      (aType == SMESH::NODE  ) setWindowTitle(tr("NODES_TLT"));
2083     else if (aType == SMESH::EDGE  ) setWindowTitle(tr("EDGES_TLT"));
2084     else if (aType == SMESH::FACE  ) setWindowTitle(tr("FACES_TLT"));
2085     else if (aType == SMESH::VOLUME) setWindowTitle(tr("VOLUMES_TLT"));
2086   }
2087   else
2088     setWindowTitle(tr("TLT"));
2089
2090   qApp->processEvents();
2091   updateGeometry();
2092   adjustSize();
2093   setEnabled(true);
2094
2095   mySMESHGUI->SetActiveDialogBox((QDialog*)this);
2096
2097   connect(mySMESHGUI, SIGNAL(SignalDeactivateActiveDialog()), SLOT(onDeactivate()));
2098   connect(mySMESHGUI, SIGNAL(SignalCloseAllDialogs()), SLOT(onClose()));
2099   
2100   updateMainButtons();
2101   updateSelection();
2102
2103   // Initialise filter table with values of previous filter
2104   QList<int>::const_iterator anIter;
2105   for (anIter = theTypes.begin(); anIter != theTypes.end(); ++anIter)
2106   {
2107     myTable->Clear(*anIter);
2108     if (!myFilter[ *anIter ]->_is_nil())
2109     {
2110       SMESH::Filter::Criteria_var aCriteria = new SMESH::Filter::Criteria;
2111       if (myFilter[ *anIter ]->GetCriteria(aCriteria))
2112       {
2113         for (int i = 0, n = aCriteria->length(); i < n; i++)
2114           myTable->AddCriterion(aCriteria[ i ], *anIter);
2115       }
2116     }
2117   }
2118
2119   if (myInsertState.contains(theTypes.first()))
2120     mySetInViewer->setChecked(myInsertState[ theTypes.first() ]);
2121   else
2122     mySetInViewer->setChecked(true);
2123
2124   mySourceGrp->button(myApplyToState.contains(theTypes.first()) ? 
2125                       myApplyToState[ theTypes.first() ] :
2126                       Selection)->setChecked(true);
2127 }
2128
2129 //=======================================================================
2130 // name    : SMESHGUI_FilterDlg::onOk
2131 // Purpose : SLOT called when "Ok" button pressed.
2132 //           Assign filters VTK viewer and close dialog
2133 //=======================================================================
2134 void SMESHGUI_FilterDlg::onOk()
2135 {
2136   if (onApply())
2137   {
2138     mySelectionMgr->clearFilters();
2139     disconnect(mySMESHGUI, 0, this, 0);
2140     disconnect(mySelectionMgr, 0, this, 0);
2141     mySMESHGUI->ResetState();
2142     accept();
2143     emit Accepted();
2144   }
2145 }
2146
2147 //=======================================================================
2148 // name    : SMESHGUI_FilterDlg::onClose
2149 // Purpose : SLOT called when "Close" button pressed. Close dialog
2150 //=======================================================================
2151 void SMESHGUI_FilterDlg::onClose()
2152 {
2153   // Restore previously selected object
2154   if (mySelectionMgr)
2155   {
2156     SALOME_ListIO aList;
2157     mySelectionMgr->clearFilters();
2158     mySelectionMgr->clearSelected();
2159     SALOME_DataMapIteratorOfDataMapOfIOMapOfInteger anIter (myIObjects);
2160     for ( ; anIter.More(); anIter.Next())
2161     {
2162       aList.Append(anIter.Key());
2163
2164       TColStd_MapOfInteger aResMap;
2165       const TColStd_IndexedMapOfInteger& anIndMap = anIter.Value();
2166       for (int i = 1, n = anIndMap.Extent(); i <= n; i++)
2167         aResMap.Add(anIndMap(i));
2168
2169       mySelector->AddOrRemoveIndex( anIter.Key(), aResMap, false);
2170       if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
2171         aViewWindow->highlight( anIter.Key(), true, true );
2172     }
2173     mySelectionMgr->setSelectedObjects(aList, false);
2174   }
2175
2176   disconnect(mySMESHGUI, 0, this, 0);
2177   disconnect(mySelectionMgr, 0, this, 0);
2178   mySMESHGUI->ResetState();
2179   reject();
2180   return;
2181 }
2182
2183 //=================================================================================
2184 // function : onHelp()
2185 // purpose  :
2186 //=================================================================================
2187 void SMESHGUI_FilterDlg::onHelp()
2188 {
2189   LightApp_Application* app = (LightApp_Application*)(SUIT_Session::session()->activeApplication());
2190   if (app) 
2191     app->onHelpContextModule(mySMESHGUI ? app->moduleName(mySMESHGUI->moduleName()) : QString(""), myHelpFileName);
2192   else {
2193     QString platform;
2194 #ifdef WIN32
2195     platform = "winapplication";
2196 #else
2197     platform = "application";
2198 #endif
2199     SUIT_MessageBox::warning(this, tr("WRN_WARNING"),
2200                              tr("EXTERNAL_BROWSER_CANNOT_SHOW_PAGE").
2201                              arg(app->resourceMgr()->stringValue("ExternalBrowser", 
2202                                                                  platform)).
2203                              arg(myHelpFileName));
2204   }
2205 }
2206
2207 //=======================================================================
2208 // name    : SMESHGUI_FilterDlg::onDeactivate
2209 // Purpose : SLOT called when dialog must be deativated
2210 //=======================================================================
2211 void SMESHGUI_FilterDlg::onDeactivate()
2212 {
2213   setEnabled(false);
2214 }
2215
2216 //=======================================================================
2217 // name    : SMESHGUI_FilterDlg::enterEvent
2218 // Purpose : Event filter
2219 //=======================================================================
2220 void SMESHGUI_FilterDlg::enterEvent (QEvent*)
2221 {
2222 //  mySMESHGUI->EmitSignalDeactivateDialog();
2223   mySMESHGUI->SetActiveDialogBox((QDialog*)this);
2224   mySMESHGUI->ResetState();
2225   setEnabled(true);
2226 }
2227
2228 //=======================================================================
2229 // name    : closeEvent()
2230 // Purpose :
2231 //=======================================================================
2232 void SMESHGUI_FilterDlg::closeEvent (QCloseEvent*)
2233 {
2234   onClose();
2235 }
2236
2237 //=======================================================================
2238 // name    : SMESHGUI_FilterDlg::getIdsFromWg
2239 // Purpose : Retrieve list of ids from given widget
2240 //=======================================================================
2241 void SMESHGUI_FilterDlg::getIdsFromWg (const QWidget* theWg, QList<int>& theRes) const
2242 {
2243   theRes.clear();
2244   if (theWg == 0)
2245     return;
2246
2247   if (theWg->inherits("QListWidget"))
2248   {
2249     const QListWidget* aListBox = qobject_cast<const QListWidget*>( theWg );
2250     bool b;
2251     for (int i = 0, n = aListBox->count(); i < n; i++)
2252     {
2253       int anId = aListBox->item(i)->text().toInt(&b);
2254       if (b)
2255         theRes.append(anId);
2256     }
2257   }
2258   else if (theWg->inherits("QLineEdit"))
2259   {
2260     const QLineEdit* aLineEdit = qobject_cast<const QLineEdit*>( theWg );
2261     QString aStr = aLineEdit->text();
2262     QRegExp aRegExp("(\\d+)");
2263     bool b;
2264     int aPos = 0;
2265     while (aPos >= 0)
2266     {
2267       aPos = aRegExp.indexIn(aStr, aPos);
2268       if (aPos > -1)
2269       {
2270         int anId = aRegExp.cap(1).toInt(&b);
2271         if (b)
2272           theRes.append(anId);
2273         aPos += aRegExp.matchedLength();
2274       }
2275     }
2276   }
2277 }
2278
2279 //=======================================================================
2280 // name    : SMESHGUI_FilterDlg::getSelMode
2281 // Purpose : Get selection mode of specified type
2282 //=======================================================================
2283 Selection_Mode SMESHGUI_FilterDlg::getSelMode (const int theType) const
2284 {
2285   switch (theType)
2286   {
2287     case SMESH::NODE   : return NodeSelection;
2288     case SMESH::EDGE   : return EdgeSelection;
2289     case SMESH::FACE   : return FaceSelection;
2290     case SMESH::VOLUME : return VolumeSelection;
2291     default            : return ActorSelection;
2292   }
2293
2294 }
2295
2296 //=======================================================================
2297 // name    : SMESHGUI_FilterDlg::setIdsToWg
2298 // Purpose : Insert identifiers in specified widgets
2299 //=======================================================================
2300 void SMESHGUI_FilterDlg::setIdsToWg (QWidget* theWg, const QList<int>& theIds)
2301 {
2302   if (theWg == 0)
2303     return;
2304
2305   if (theWg->inherits("QListWidget"))
2306   {
2307     QListWidget* aListBox = qobject_cast<QListWidget*>( theWg );
2308     aListBox->clear();
2309
2310     QStringList aStrList;
2311     QList<int>::const_iterator anIter;
2312     for (anIter = theIds.begin(); anIter != theIds.end(); ++anIter)
2313       aStrList.append(QString("%1").arg(*anIter));
2314
2315     aListBox->addItems(aStrList);
2316   }
2317   else if (theWg->inherits("QLineEdit"))
2318   {
2319     QLineEdit* aLineEdit = qobject_cast<QLineEdit*>( theWg );
2320     QString aStr;
2321     QList<int>::const_iterator anIter;
2322
2323     for (anIter = theIds.begin(); anIter != theIds.end(); ++ anIter)
2324       aStr += QString("%1 ").arg(*anIter);
2325
2326     if (!aStr.isEmpty())
2327       aStr.remove(aStr.length() - 1, 1);
2328
2329     aLineEdit->setText(aStr);
2330   }
2331 }
2332
2333 //=======================================================================
2334 // name    : SMESHGUI_FilterDlg::isValid
2335 // Purpose : Verify validity of input data
2336 //=======================================================================
2337 bool SMESHGUI_FilterDlg::isValid() const
2338 {
2339   if (!myTable->IsValid())
2340     return false;
2341
2342   for (int i = 0, n = myTable->NumRows(); i < n; i++)
2343   {
2344     int aType = myTable->GetCriterionType(i);
2345     if (aType == SMESH::FT_BelongToGeom ||
2346         aType == SMESH::FT_BelongToPlane ||
2347         aType == SMESH::FT_BelongToCylinder ||
2348         aType == SMESH::FT_BelongToGenSurface ||
2349         aType == SMESH::FT_LyingOnGeom) {
2350       QString aName;
2351       myTable->GetThreshold(i, aName);
2352
2353       std::vector<_PTR(SObject)> aList =
2354         SMESH::GetActiveStudyDocument()->FindObjectByName(aName.toLatin1().data(), "GEOM");
2355       if (aList.size() == 0) {
2356         SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
2357                                      tr("BAD_SHAPE_NAME").arg(aName));
2358         return false;
2359       }
2360
2361       if (aType == SMESH::FT_BelongToCylinder ||
2362           aType == SMESH::FT_BelongToPlane    ||
2363           aType == SMESH::FT_BelongToGenSurface ) {
2364         CORBA::Object_var anObject = SMESH::SObjectToObject(aList[ 0 ]);
2365         //GEOM::GEOM_Object_var aGeomObj = GEOM::GEOM_Object::_narrow(aList[ 0 ]->GetObject());
2366         GEOM::GEOM_Object_var aGeomObj = GEOM::GEOM_Object::_narrow(anObject);
2367         if (!aGeomObj->_is_nil()) {
2368           TopoDS_Shape aFace;
2369           if (!GEOMBase::GetShape(aGeomObj, aFace) ||
2370                aFace.IsNull() ||
2371                aFace.ShapeType() != TopAbs_FACE) {
2372             SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
2373                                          tr("SHAPE_IS_NOT_A_FACE").arg(aName));
2374             return false;
2375           }
2376
2377           Handle(Geom_Surface) aSurf = BRep_Tool::Surface(TopoDS::Face(aFace));
2378           if (aSurf.IsNull()) {
2379             SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
2380                                          tr("SHAPE_IS_NOT_A_FACE").arg(aName));
2381             return false;
2382           }
2383
2384           if (aType == SMESH::FT_BelongToPlane && !aSurf->IsKind(STANDARD_TYPE(Geom_Plane))) {
2385             SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
2386                                          tr("SHAPE_IS_NOT_A_PLANE").arg(aName));
2387             return false;
2388           }
2389
2390           if (aType == SMESH::FT_BelongToCylinder && !aSurf->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
2391             SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
2392                                          tr("SHAPE_IS_NOT_A_CYLINDER").arg(aName));
2393             return false;
2394           }
2395         }
2396       }
2397     }
2398   }
2399
2400   return true;
2401 }
2402
2403 //=======================================================================
2404 // name    : SMESHGUI_FilterDlg::SetSourceWg
2405 // Purpose : Set widget of parent dialog containing idsto be filtered if
2406 //           user select corresponding source radio button
2407 //=======================================================================
2408 void SMESHGUI_FilterDlg::SetSourceWg (QWidget* theWg)
2409 {
2410   mySourceWg = theWg;
2411 }
2412
2413 //=======================================================================
2414 // name    : SMESHGUI_FilterDlg::SetGroupIds
2415 // Purpose : Set mesh
2416 //=======================================================================
2417 void SMESHGUI_FilterDlg::SetMesh (SMESH::SMESH_Mesh_ptr theMesh)
2418 {
2419   myMesh = theMesh;
2420 }
2421
2422 //=======================================================================
2423 // name    : SMESHGUI_FilterDlg::SetSelection
2424 // Purpose : Get filtered ids
2425 //=======================================================================
2426 void SMESHGUI_FilterDlg::SetSelection()
2427 {
2428   if (mySelectionMgr)
2429     disconnect(mySelectionMgr, SIGNAL(currentSelectionChanged()), this, SLOT(onSelectionDone()));
2430
2431   if (mySelectionMgr) {
2432     myIObjects.Clear();
2433     const SALOME_ListIO& anObjs = mySelector->StoredIObjects();
2434     SALOME_ListIteratorOfListIO anIter (anObjs);
2435     for ( ; anIter.More(); anIter.Next()) {
2436       TColStd_IndexedMapOfInteger aMap;
2437       mySelector->GetIndex(anIter.Value(), aMap);
2438       myIObjects.Bind(anIter.Value(), aMap);
2439     }
2440
2441     connect(mySelectionMgr, SIGNAL(currentSelectionChanged()), SLOT(onSelectionDone()));
2442
2443     updateSelection();
2444   }
2445   else
2446     myIObjects.Clear();
2447 }
2448
2449 //=======================================================================
2450 // name    : SMESHGUI_FilterDlg::onApply
2451 // Purpose : SLOT called when "Apply" button pressed.
2452 //           Assign filters to VTK viewer
2453 //=======================================================================
2454 bool SMESHGUI_FilterDlg::onApply()
2455 {
2456   if (!isValid())
2457     return false;
2458
2459   try {
2460     int aCurrType = myTable->GetType();
2461
2462     if (!createFilter(aCurrType))
2463       return false;
2464
2465     insertFilterInViewer();
2466
2467     if (!myFilter[ aCurrType ]->GetPredicate()->_is_nil()) {
2468       QList<int> aResultIds;
2469       filterSource(aCurrType, aResultIds);
2470       selectInViewer(aCurrType, aResultIds);
2471     }
2472
2473     myInsertState[ aCurrType ] = mySetInViewer->isChecked();
2474     myApplyToState[ aCurrType ] = mySourceGrp->checkedId();
2475   }
2476   catch(const SALOME::SALOME_Exception& S_ex)
2477   {
2478     SalomeApp_Tools::QtCatchCorbaException(S_ex);
2479   }
2480   catch(...)
2481   {
2482   }
2483
2484   return true;
2485 }
2486
2487 //=======================================================================
2488 // name    : SMESHGUI_FilterDlg::createFilter
2489 // Purpose : Create predicate for given type
2490 //=======================================================================
2491 bool SMESHGUI_FilterDlg::createFilter (const int theType)
2492 {
2493   SMESH::FilterManager_var aFilterMgr = SMESH::GetFilterManager();
2494   if (aFilterMgr->_is_nil())
2495     return false;
2496
2497   int n = myTable->NumRows();
2498
2499   SMESH::Filter::Criteria_var aCriteria = new SMESH::Filter::Criteria;
2500   aCriteria->length(n);
2501
2502   long aPrecision = -1;
2503   SUIT_ResourceMgr* mgr = SMESH::GetResourceMgr( mySMESHGUI );
2504
2505   if ( mgr && mgr->booleanValue( "SMESH", "use_precision", false ) )
2506     aPrecision = mgr->integerValue( "SMESH", "controls_precision", aPrecision );
2507
2508   for (CORBA::ULong i = 0; i < n; i++) {
2509     SMESH::Filter::Criterion aCriterion = createCriterion();
2510     myTable->GetCriterion(i, aCriterion);
2511     aCriterion.Precision = aPrecision;
2512     aCriteria[ i ] = aCriterion;
2513   }
2514
2515   myFilter[ theType ] = aFilterMgr->CreateFilter();
2516   myFilter[ theType ]->SetCriteria(aCriteria.inout());
2517
2518   return true;
2519 }
2520
2521 //=======================================================================
2522 // name    : SMESHGUI_FilterDlg::insertFilterInViewer
2523 // Purpose : Insert filter in viewer
2524 //=======================================================================
2525 void SMESHGUI_FilterDlg::insertFilterInViewer()
2526 {
2527   if (SVTK_Selector* aSelector = SMESH::GetSelector()) {
2528     SMESH::ElementType anEntType = (SMESH::ElementType)myTable->GetType();
2529
2530     if (myFilter[ myTable->GetType() ]->_is_nil() ||
2531          myFilter[ myTable->GetType() ]->GetPredicate()->_is_nil() ||
2532          !mySetInViewer->isChecked()) {
2533       SMESH::RemoveFilter(getFilterId(anEntType), aSelector);
2534     }
2535     else {
2536       Handle(SMESHGUI_PredicateFilter) aFilter = new SMESHGUI_PredicateFilter();
2537       aFilter->SetPredicate(myFilter[ myTable->GetType() ]->GetPredicate());
2538       SMESH::RemoveFilter(getFilterId(anEntType), aSelector); //skl for IPAL12631
2539       SMESH::SetFilter(aFilter, aSelector);
2540     }
2541   }
2542 }
2543
2544 //=======================================================================
2545 // name    : SMESHGUI_FilterDlg::filterSource
2546 // Purpose : Filter source ids
2547 //=======================================================================
2548 void SMESHGUI_FilterDlg::filterSource (const int theType,
2549                                        QList<int>& theResIds)
2550 {
2551   theResIds.clear();
2552   if (myFilter[ theType ]->_is_nil())
2553     return;
2554
2555   int aSourceId = mySourceGrp->checkedId();
2556
2557   if (aSourceId == Mesh)
2558   {
2559     if (myMesh->_is_nil())
2560       return;
2561     SMESH::long_array_var anIds = myFilter[ theType ]->GetElementsId(myMesh);
2562     for (int i = 0, n = anIds->length(); i < n; i++)
2563       theResIds.append(anIds[ i ]);
2564   }
2565   else if (aSourceId == Selection)
2566   {
2567     filterSelectionSource(theType, theResIds);
2568   }
2569   else if (aSourceId == Dialog)
2570   {
2571     // retrieve ids from dialog
2572     QList<int> aDialogIds;
2573     getIdsFromWg(mySourceWg, aDialogIds);
2574
2575     if (myMesh->_is_nil())
2576     {
2577       theResIds = aDialogIds;
2578       return;
2579     }
2580
2581     // filter ids
2582     SMESH::Predicate_ptr aPred = myFilter[ theType ]->GetPredicate();
2583     aPred->SetMesh(myMesh);
2584     QList<int>::const_iterator anIter;
2585     for (anIter = aDialogIds.begin(); anIter != aDialogIds.end(); ++ anIter)
2586       if (aPred->IsSatisfy(*anIter))
2587         theResIds.append(*anIter);
2588
2589     // set ids to the dialog
2590     setIdsToWg(mySourceWg, theResIds);
2591   }
2592 }
2593
2594 //=======================================================================
2595 // name    : SMESHGUI_FilterDlg::filterSelectionSource
2596 // Purpose : Filter source selection
2597 //=======================================================================
2598 void SMESHGUI_FilterDlg::filterSelectionSource (const int theType,
2599                                                 QList<int>& theResIds)
2600 {
2601   theResIds.clear();
2602   if (myMesh->_is_nil() || mySelectionMgr == 0)
2603     return;
2604
2605   // Create map of entities to be filtered
2606   TColStd_MapOfInteger aToBeFiltered;
2607   SALOME_DataMapIteratorOfDataMapOfIOMapOfInteger anIter(myIObjects);
2608
2609   for ( ; anIter.More(); anIter.Next())
2610   {
2611     // process sub mesh
2612     SMESH::SMESH_subMesh_var aSubMesh = SMESH::IObjectToInterface<SMESH::SMESH_subMesh>(anIter.Key());
2613     if (!aSubMesh->_is_nil())
2614     {
2615       if (aSubMesh->GetFather()->GetId() == myMesh->GetId())
2616       {
2617         SMESH::long_array_var anIds =
2618           theType == SMESH::NODE ? aSubMesh->GetNodesId() : aSubMesh->GetElementsId();
2619         for (int i = 0, n = anIds->length(); i < n; i++)
2620           aToBeFiltered.Add(anIds[ i ]);
2621       }
2622     }
2623
2624     // process group
2625     SMESH::SMESH_GroupBase_var aGroup =
2626       SMESH::IObjectToInterface<SMESH::SMESH_GroupBase>(anIter.Key());
2627     if (!aGroup->_is_nil())
2628     {
2629       if (aGroup->GetType() == theType && aGroup->GetMesh()->GetId() == myMesh->GetId())
2630       {
2631         SMESH::long_array_var anIds = aGroup->GetListOfID();
2632         for (int i = 0, n = anIds->length(); i < n; i++)
2633           aToBeFiltered.Add(anIds[ i ]);
2634       }
2635     }
2636
2637     // process mesh
2638     SMESH::SMESH_Mesh_var aMeshPtr = SMESH::IObjectToInterface<SMESH::SMESH_Mesh>(anIter.Key());
2639     if (!aMeshPtr->_is_nil() && aMeshPtr->GetId() == myMesh->GetId())
2640     {
2641       const TColStd_IndexedMapOfInteger& aSelMap = anIter.Value();
2642
2643       if (aSelMap.Extent() > 0)
2644       {
2645         if(SMESH::FindActorByEntry(anIter.Key()->getEntry()))
2646         {
2647           for (int i = 1; i <= aSelMap.Extent(); i++)
2648             aToBeFiltered.Add(aSelMap(i));
2649         }
2650       }
2651     }
2652   }
2653
2654   // Filter entities
2655   SMESH::Predicate_ptr aPred = myFilter[ theType ]->GetPredicate();
2656   aPred->SetMesh(myMesh);
2657   TColStd_MapIteratorOfMapOfInteger aResIter(aToBeFiltered);
2658   for ( ; aResIter.More(); aResIter.Next())
2659     if (aPred->IsSatisfy(aResIter.Key()))
2660       theResIds.append(aResIter.Key());
2661 }
2662
2663 //=======================================================================
2664 // name    : SMESHGUI_FilterDlg::selectInViewer
2665 // Purpose : Select given entities in viewer
2666 //=======================================================================
2667 void SMESHGUI_FilterDlg::selectInViewer (const int theType, const QList<int>& theIds)
2668 {
2669   if (mySelectionMgr == 0 || myMesh->_is_nil())
2670     return;
2671
2672   mySelectionMgr->clearFilters();
2673
2674   // Set new selection mode if necessary
2675   Selection_Mode aSelMode = getSelMode(theType);
2676   SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI );
2677   if ( aViewWindow && aViewWindow->SelectionMode()!=aSelMode) {
2678     mySelectionMgr->clearSelected();
2679     mySelectionMgr->clearFilters();
2680     if (aSelMode == NodeSelection)
2681       SMESH::SetPointRepresentation(true);
2682     aViewWindow->SetSelectionMode(aSelMode);
2683   }
2684
2685   // Clear selection
2686   SMESH_Actor* anActor = SMESH::FindActorByObject(myMesh);
2687   if (!anActor || !anActor->hasIO())
2688     return;
2689
2690   Handle(SALOME_InteractiveObject) anIO = anActor->getIO();
2691   //mySelectionMgr->clearSelected();
2692   //mySelectionMgr->AddIObject(anIO, false);
2693   SALOME_ListIO aList;
2694   aList.Append(anIO);
2695   mySelectionMgr->setSelectedObjects(aList, false);
2696
2697   // Remove filter corresponding to the current type from viewer
2698   int aType = myTable->GetType();
2699   int aFilterId = SMESH::UnknownFilter;
2700   if      (aType == SMESH::EDGE  ) aFilterId = SMESH::EdgeFilter;
2701   else if (aType == SMESH::FACE  ) aFilterId = SMESH::FaceFilter;
2702   else if (aType == SMESH::VOLUME) aFilterId = SMESH::VolumeFilter;
2703   Handle(VTKViewer_Filter) aFilter = SMESH::GetFilter(aFilterId);
2704   SMESH::RemoveFilter(aFilterId);
2705
2706   // get vtk ids
2707   TColStd_MapOfInteger aMap;
2708   QList<int>::const_iterator anIter;
2709   for (anIter = theIds.begin(); anIter != theIds.end(); ++anIter) {
2710     aMap.Add(*anIter);
2711   }
2712
2713   // Set new selection
2714   mySelector->AddOrRemoveIndex(anIO, aMap, false);
2715   if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
2716     aViewWindow->highlight( anIO, true, true );
2717
2718   // insert previously stored filter in viewer if necessary
2719   if (!aFilter.IsNull())
2720     SMESH::SetFilter(aFilter);
2721 }
2722
2723 //=======================================================================
2724 // name    : SMESHGUI_FilterDlg::createCriterion
2725 // Purpose : Create criterion structure with default values
2726 //=======================================================================
2727 SMESH::Filter::Criterion SMESHGUI_FilterDlg::createCriterion()
2728 {
2729    SMESH::Filter::Criterion aCriterion;
2730
2731   aCriterion.Type          = SMESH::FT_Undefined;
2732   aCriterion.Compare       = SMESH::FT_Undefined;
2733   aCriterion.Threshold     = 0;
2734   aCriterion.UnaryOp       = SMESH::FT_Undefined;
2735   aCriterion.BinaryOp      = SMESH::FT_Undefined;
2736   aCriterion.ThresholdStr  = "";
2737   aCriterion.ThresholdID   = "";
2738   aCriterion.TypeOfElement = SMESH::ALL;
2739
2740   return aCriterion;
2741 }
2742
2743 //=======================================================================
2744 // name    : SMESHGUI_FilterDlg::onSelectionDone
2745 // Purpose : SLOT called when selection changed.
2746 //           If current cell corresponds to the threshold value of
2747 //           BelongToGeom criterion name of selected object is set in this cell
2748 //=======================================================================
2749 void SMESHGUI_FilterDlg::onSelectionDone()
2750 {
2751   int aRow, aCol;
2752   const SALOME_ListIO& aList = mySelector->StoredIObjects();
2753
2754   if (aList.Extent() != 1 ||
2755       !myTable->CurrentCell(aRow, aCol) ||
2756       myTable->GetCriterionType(aRow) != SMESH::FT_BelongToGeom &&
2757       myTable->GetCriterionType(aRow) != SMESH::FT_BelongToPlane &&
2758       myTable->GetCriterionType(aRow) != SMESH::FT_BelongToCylinder &&
2759       myTable->GetCriterionType(aRow) != SMESH::FT_BelongToGenSurface &&
2760       myTable->GetCriterionType(aRow) != SMESH::FT_LyingOnGeom)
2761     return;
2762
2763   Handle(SALOME_InteractiveObject) anIO = aList.First();
2764   GEOM::GEOM_Object_var anObj = SMESH::IObjectToInterface<GEOM::GEOM_Object>(anIO);
2765   if (!anObj->_is_nil())
2766     {
2767       myTable->SetThreshold(aRow, GEOMBase::GetName(anObj));
2768       //myTable->SetID( aRow, GEOMBase::GetIORFromObject(anObj));
2769       myTable->SetID(aRow, anIO->getEntry());
2770     }
2771 }
2772
2773 //=======================================================================
2774 // name    : SMESHGUI_FilterDlg::onCriterionChanged
2775 // Purpose : SLOT called when cretarion of current row changed. Update selection
2776 //=======================================================================
2777 void SMESHGUI_FilterDlg::onCriterionChanged (const int, const int)
2778 {
2779   updateSelection();
2780 }
2781
2782 //=======================================================================
2783 // name    : SMESHGUI_FilterDlg::onCurrentChanged
2784 // Purpose : SLOT called when current row changed. Update selection
2785 //=======================================================================
2786 void SMESHGUI_FilterDlg::onCurrentChanged (int, int)
2787 {
2788   updateSelection();
2789 }
2790
2791 //=======================================================================
2792 // name    : SMESHGUI_FilterDlg::updateSelection
2793 // Purpose : UpdateSelection in accordance with current row
2794 //=======================================================================
2795 void SMESHGUI_FilterDlg::updateSelection()
2796 {
2797   if (mySelectionMgr == 0)
2798     return;
2799
2800   TColStd_MapOfInteger allTypes;
2801   for( int i=0; i<10; i++ )
2802     allTypes.Add( i );
2803   SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>( mySMESHGUI->application()->activeStudy() );
2804   if( !aStudy )
2805     return;
2806
2807
2808   mySelectionMgr->clearFilters();
2809
2810   int aRow, aCol;
2811
2812   if (myTable->CurrentCell(aRow, aCol) &&
2813       (myTable->GetCriterionType(aRow) == SMESH::FT_BelongToGeom ||
2814        myTable->GetCriterionType(aRow) == SMESH::FT_BelongToPlane ||
2815        myTable->GetCriterionType(aRow) == SMESH::FT_BelongToCylinder ||
2816        myTable->GetCriterionType(aRow) == SMESH::FT_BelongToGenSurface ||
2817        myTable->GetCriterionType(aRow) == SMESH::FT_LyingOnGeom)) {
2818
2819     if (myTable->GetCriterionType(aRow) == SMESH::FT_BelongToGeom ||
2820         myTable->GetCriterionType(aRow) == SMESH::FT_BelongToGenSurface ||
2821         myTable->GetCriterionType(aRow) == SMESH::FT_LyingOnGeom) {
2822
2823       mySelectionMgr->installFilter(new GEOM_SelectionFilter( aStudy, true ));
2824
2825     } else if (myTable->GetCriterionType(aRow) == SMESH::FT_BelongToPlane) {
2826       mySelectionMgr->installFilter(new GEOM_FaceFilter( aStudy, StdSelect_Plane ) );
2827
2828     } else if (myTable->GetCriterionType(aRow) == SMESH::FT_BelongToCylinder) {
2829       mySelectionMgr->installFilter(new GEOM_FaceFilter( aStudy, StdSelect_Cylinder ) );
2830     }
2831     myIsSelectionChanged = true;
2832
2833   } else {
2834     if (myIsSelectionChanged) {
2835       mySelectionMgr->installFilter( new GEOM_TypeFilter( aStudy, -1 ) ); // This filter deactivates selection
2836     }
2837   }
2838 }
2839
2840 //=================================================================================
2841 // function : keyPressEvent()
2842 // purpose  :
2843 //=================================================================================
2844 void SMESHGUI_FilterDlg::keyPressEvent( QKeyEvent* e )
2845 {
2846   QDialog::keyPressEvent( e );
2847   if ( e->isAccepted() )
2848     return;
2849
2850   if ( e->key() == Qt::Key_F1 ) {
2851     e->accept();
2852     onHelp();
2853   }
2854 }