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