Salome HOME
Merge branch 'master' into pre/penta18
[modules/smesh.git] / src / SMESHGUI / SMESHGUI_FilterDlg.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // SMESH SMESHGUI : GUI for SMESH component
24 // File   : SMESHGUI_FilterDlg.cxx
25 // Author : Sergey LITONIN, Open CASCADE S.A.S.
26 //
27
28 // SMESH includes
29 #include "SMESHGUI_FilterDlg.h"
30
31 #include "SMESHGUI.h"
32 #include "SMESHGUI_Utils.h"
33 #include "SMESHGUI_VTKUtils.h"
34 #include "SMESHGUI_Filter.h"
35 #include "SMESHGUI_FilterUtils.h"
36 #include "SMESHGUI_FilterLibraryDlg.h"
37 #include "SMESHGUI_SpinBox.h"
38
39 #include "SMESH_Actor.h"
40 #include "SMESH_NumberFilter.hxx"
41 #include "SMESH_TypeFilter.hxx"
42 #include "SMESH_LogicalFilter.hxx"
43
44 // SALOME GEOM includes
45 #include <GEOMBase.h>
46 #include <GEOM_FaceFilter.h>
47 #include <GEOM_TypeFilter.h>
48
49 // SALOME GUI includes
50 #include <SUIT_Desktop.h>
51 #include <SUIT_ResourceMgr.h>
52 #include <SUIT_Session.h>
53 #include <SUIT_MessageBox.h>
54 #include <SUIT_OverrideCursor.h>
55 #include <QtxColorButton.h>
56
57 #include <LightApp_Application.h>
58 #include <LightApp_SelectionMgr.h>
59 #include <SalomeApp_Application.h>
60 #include <SalomeApp_DoubleSpinBox.h>
61 #include <SalomeApp_IntSpinBox.h>
62 #include <SalomeApp_Study.h>
63 #include <SalomeApp_Tools.h>
64
65 #include <SALOME_ListIO.hxx>
66
67 #include <SVTK_ViewWindow.h>
68
69 // SALOME KERNEL includes
70 #include <SALOMEDSClient_Study.hxx>
71 #include <Basics_Utils.hxx>
72
73 // OCCT includes
74 #include <StdSelect_TypeOfFace.hxx>
75 #include <BRep_Tool.hxx>
76 #include <TopoDS.hxx>
77 #include <TopoDS_Shape.hxx>
78 #include <Geom_Plane.hxx>
79 #include <Geom_CylindricalSurface.hxx>
80 #include <Precision.hxx>
81 #include <TColStd_MapOfInteger.hxx>
82 #include <TColStd_IndexedMapOfInteger.hxx>
83 #include <TColStd_MapIteratorOfMapOfInteger.hxx>
84
85 // Qt includes
86 #include <QFrame>
87 #include <QLineEdit>
88 #include <QPushButton>
89 #include <QGroupBox>
90 #include <QTableWidget>
91 #include <QStringList>
92 #include <QHBoxLayout>
93 #include <QVBoxLayout>
94 #include <QGridLayout>
95 #include <QStackedWidget>
96 #include <QApplication>
97 #include <QComboBox>
98 #include <QFontMetrics>
99 #include <QLabel>
100 #include <QButtonGroup>
101 #include <QRadioButton>
102 #include <QRegExp>
103 #include <QListWidget>
104 #include <QCheckBox>
105 #include <QItemDelegate>
106 #include <QDoubleValidator>
107 #include <QKeyEvent>
108 #include <QHeaderView>
109
110 // IDL includes
111 #include <SALOMEconfig.h>
112 #include CORBA_SERVER_HEADER(SMESH_Group)
113
114 #define SPACING 6
115 #define MARGIN  11
116
117 //---------------------------------------
118 // maxLength
119 //---------------------------------------
120 static int maxLength (const QMap<int, QString> theMap, const QFontMetrics& theMetrics)
121 {
122   int aRes = 0;
123   QMap<int, QString>::const_iterator anIter;
124   for (anIter = theMap.begin(); anIter != theMap.end(); ++anIter)
125     aRes = qMax(aRes, theMetrics.width(anIter.value()));
126   return aRes;
127 }
128
129 //---------------------------------------
130 // getFilterId
131 //---------------------------------------
132 static int getFilterId (SMESH::ElementType theType)
133 {
134   switch (theType)
135   {
136     case SMESH::NODE   : return SMESH::NodeFilter;
137     case SMESH::EDGE   : return SMESH::EdgeFilter;
138     case SMESH::FACE   : return SMESH::FaceFilter;
139     case SMESH::VOLUME : return SMESH::VolumeFilter;
140     case SMESH::ALL    : return SMESH::AllElementsFilter;
141     default            : return SMESH::UnknownFilter;
142   }
143 }
144
145 /*
146   Class       : SMESHGUI_FilterTable::AdditionalWidget
147   Description : Class for storing additional parameters of criterion
148 */
149
150 class SMESHGUI_FilterTable::AdditionalWidget : public QWidget
151 {
152 public:
153   enum { Tolerance };
154
155 public:
156   AdditionalWidget(QWidget* theParent);
157   virtual ~AdditionalWidget();
158
159   virtual QList<int>      GetParameters() const;
160   virtual bool            IsValid(const bool = true) const;
161   virtual double          GetDouble(const int) const;
162   virtual int             GetInteger(const int) const;
163   virtual QString         GetString(const int) const;
164   virtual void            SetDouble(const int, const double);
165   virtual void            SetInteger(const int, const int);
166   virtual void            SetString(const int, const QString&);
167   void                    SetEditable(const int, const bool);
168   void                    SetEditable(const bool);
169   void                    SetPrecision(const int, const char* = 0);
170
171 private:
172   QMap< int, QWidget* > myWidgets;
173 };
174
175 SMESHGUI_FilterTable::AdditionalWidget::AdditionalWidget (QWidget* theParent)
176   : QWidget(theParent)
177 {
178   QLabel* aLabel = new QLabel(tr("SMESH_TOLERANCE"), this);
179
180   SMESHGUI_SpinBox* sb = new SMESHGUI_SpinBox(this);
181   sb->setAcceptNames( false ); // No Notebook variables allowed
182   sb->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ) );
183   sb->RangeStepAndValidator( 0., 1.e20, 0.1, "len_tol_precision" );
184   myWidgets[ Tolerance ] = sb;
185
186   QHBoxLayout* aLay = new QHBoxLayout(this);
187   aLay->setSpacing(SPACING);
188   aLay->setMargin(0);
189
190   aLay->addWidget(aLabel);
191   aLay->addWidget(myWidgets[ Tolerance ]);
192   aLay->addStretch();
193
194   SetDouble( Tolerance, Precision::Confusion() );
195 }
196
197 SMESHGUI_FilterTable::AdditionalWidget::~AdditionalWidget()
198 {
199 }
200
201 QList<int> SMESHGUI_FilterTable::AdditionalWidget::GetParameters() const
202 {
203   QList<int> theList;
204   theList.append(Tolerance);
205   return theList;
206 }
207
208 bool SMESHGUI_FilterTable::AdditionalWidget::IsValid (const bool theMsg) const
209 {
210   if (!isEnabled())
211     return true;
212
213   QList<int> aParams = GetParameters();
214   QList<int>::const_iterator anIter;
215   for (anIter = aParams.begin(); anIter != aParams.end(); ++anIter) {
216     if ( !myWidgets.contains( *anIter ) ) continue;
217     bool valid = true;
218     if ( qobject_cast<QLineEdit*>( myWidgets[ *anIter ] ) ) {
219       valid = qobject_cast<QLineEdit*>( myWidgets[ *anIter ] )->hasAcceptableInput();
220     }
221     else if ( qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ *anIter ] ) ) {
222       QString foo;
223       valid = qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ *anIter ] )->isValid( foo, false );
224     }
225     if (!valid && theMsg) {
226       SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
227                                    tr("SMESHGUI_INVALID_PARAMETERS"));
228       return false;
229     }
230   }
231
232   return true;
233 }
234
235 double SMESHGUI_FilterTable::AdditionalWidget::GetDouble (const int theId) const
236 {
237   double retval = 0;
238   if ( myWidgets.contains( theId ) ) {
239     if ( qobject_cast<QLineEdit*>( myWidgets[ theId ] ) )
240       retval = qobject_cast<QLineEdit*>( myWidgets[ theId ] )->text().toDouble();
241     if ( qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] ) )
242       retval = qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] )->GetValue();
243   }
244   return retval;
245 }
246
247 int SMESHGUI_FilterTable::AdditionalWidget::GetInteger (const int theId) const
248 {
249   int retval = 0;
250   if ( myWidgets.contains( theId ) ) {
251     if ( qobject_cast<QLineEdit*>( myWidgets[ theId ] ) )
252       retval = qobject_cast<QLineEdit*>( myWidgets[ theId ] )->text().toInt();
253     if ( qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] ) )
254       retval = (int)( qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] )->GetValue() );
255   }
256   return retval;
257 }
258
259 QString SMESHGUI_FilterTable::AdditionalWidget::GetString (const int theId) const
260 {
261   QString retval = "";
262   if ( myWidgets.contains( theId ) ) {
263     if ( qobject_cast<QLineEdit*>( myWidgets[ theId ] ) )
264       retval = qobject_cast<QLineEdit*>( myWidgets[ theId ] )->text();
265     if ( qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] ) )
266       retval = QString::number( qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] )->GetValue() );
267   }
268   return retval;
269 }
270
271 void SMESHGUI_FilterTable::AdditionalWidget::SetDouble (const int theId, const double theVal)
272 {
273   if ( myWidgets.contains( theId ) ) {
274     if ( qobject_cast<QLineEdit*>( myWidgets[ theId ] ) )
275       qobject_cast<QLineEdit*>( myWidgets[ theId ] )->setText( QString::number( theVal ) );
276     if ( qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] ) )
277       qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] )->SetValue( theVal );
278   }
279 }
280
281 void SMESHGUI_FilterTable::AdditionalWidget::SetInteger (const int theId, const int theVal)
282 {
283   if ( myWidgets.contains( theId ) ) {
284     if ( qobject_cast<QLineEdit*>( myWidgets[ theId ] ) )
285       qobject_cast<QLineEdit*>( myWidgets[ theId ] )->setText( QString::number( theVal ) );
286     if ( qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] ) )
287       qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] )->SetValue( (double)theVal );
288   }
289 }
290
291 void SMESHGUI_FilterTable::AdditionalWidget::SetString (const int theId, const QString& theVal)
292 {
293   if ( myWidgets.contains( theId ) ) {
294     if ( qobject_cast<QLineEdit*>( myWidgets[ theId ] ) )
295       qobject_cast<QLineEdit*>( myWidgets[ theId ] )->setText( theVal );
296     if ( qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] ) )
297       qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] )->SetValue( theVal.toDouble() );
298   }
299 }
300
301 void SMESHGUI_FilterTable::AdditionalWidget::SetEditable (const int theId, const bool isEditable)
302 {
303   if ( myWidgets.contains( theId ) ) {
304     if ( qobject_cast<QLineEdit*>( myWidgets[ theId ] ) )
305       qobject_cast<QLineEdit*>( myWidgets[ theId ] )->setReadOnly( !isEditable );
306     if ( qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] ) )
307       qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] )->setReadOnly( !isEditable );
308   }
309 }
310
311 void SMESHGUI_FilterTable::AdditionalWidget::SetEditable (const bool isEditable)
312 {
313   QList<int> aParams = GetParameters();
314   QList<int>::const_iterator anIter;
315   for (anIter = aParams.begin(); anIter != aParams.end(); ++anIter)
316     SetEditable( *anIter,  isEditable );
317 }
318
319 void SMESHGUI_FilterTable::AdditionalWidget::SetPrecision(const int theId, const char* precision)
320 {
321   if ( myWidgets.contains( theId ) ) {
322     if ( qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] ) ) {
323       SMESHGUI_SpinBox* sb = qobject_cast<SMESHGUI_SpinBox*>( myWidgets[ theId ] );
324       double val = sb->GetValue();
325       double min = pow(10.0, -(sb->decimals()));
326       sb->RangeStepAndValidator( 0., 1.e20, 0.1, precision ? precision : "len_tol_precision" );
327       sb->SetValue( qMax( val, min ) );
328     }
329   }
330 }
331
332 /*
333   Class       : SMESHGUI_FilterTable::ComboItem
334   Description : Combo table item. Identificator corresponding to string may be assigned
335 */
336
337 class SMESHGUI_FilterTable::ComboItem : public QTableWidgetItem
338 {
339 public:
340   static int     Type();
341
342   ComboItem( const QMap<int, QString>& );
343
344   void           setItems( const QMap<int, QString>& );
345   void           clear();
346   int            count() const;
347
348   int            value() const;
349   void           setValue( const int );
350
351 private:
352   int            id( int ) const;
353   int            index( int ) const;
354
355 private:
356   QMap<int, int> myIdToIdx;
357 };
358
359 int SMESHGUI_FilterTable::ComboItem::Type()
360 {
361   return QTableWidgetItem::UserType + 1;
362 }
363
364 SMESHGUI_FilterTable::ComboItem::ComboItem( const QMap<int, QString>& theIds )
365  : QTableWidgetItem( Type() )
366 {
367   setItems( theIds );
368 }
369
370 void SMESHGUI_FilterTable::ComboItem::setItems( const QMap<int, QString>& theIds )
371 {
372   myIdToIdx.clear();
373   QMap<int, QString>::const_iterator it;
374   QStringList items;
375   for ( it = theIds.begin(); it != theIds.end(); ++it ) {
376     myIdToIdx[it.key()] = items.count();
377     items.append( it.value() );
378   }
379   setData( Qt::UserRole, items );
380   setValue( id( 0 ) ); 
381 }
382
383 void SMESHGUI_FilterTable::ComboItem::clear()
384 {
385   QMap<int, QString> empty;
386   setItems( empty );
387 }
388
389 int SMESHGUI_FilterTable::ComboItem::count() const
390 {
391   return myIdToIdx.count();
392 }
393
394 int SMESHGUI_FilterTable::ComboItem::value() const
395 {
396   return( id( data( Qt::UserRole ).toStringList().indexOf( text() ) ) ); 
397 }
398
399 void SMESHGUI_FilterTable::ComboItem::setValue( const int theId )
400 {
401   int idx = index( theId );
402   QStringList items = data( Qt::UserRole ).toStringList();
403   setText( idx >= 0 && idx < items.count() ? items[idx] : "" );
404 }
405
406 int SMESHGUI_FilterTable::ComboItem::id( int idx ) const
407 {
408   QMap<int,int>::const_iterator it;
409   for ( it = myIdToIdx.begin(); it != myIdToIdx.end(); ++it )
410     if ( it.value() == idx ) return it.key();
411   return -1;
412 }
413
414 int SMESHGUI_FilterTable::ComboItem::index( int i ) const
415 {
416   return myIdToIdx.contains( i ) ? myIdToIdx[i] : -1;
417 }
418 /*
419   Class       : SMESHGUI_FilterTable::CheckItem
420   Description : Check table item.
421 */
422
423 class SMESHGUI_FilterTable::CheckItem : public QTableWidgetItem
424 {
425 public:
426   static int     Type();
427
428   CheckItem( bool = false );
429   CheckItem( const QString&, bool = false );
430   ~CheckItem();
431
432   void  setChecked( bool );
433   bool  checked() const;
434 };
435
436 int SMESHGUI_FilterTable::CheckItem::Type()
437 {
438   return QTableWidgetItem::UserType + 2;
439 }
440
441 SMESHGUI_FilterTable::CheckItem::CheckItem( bool value )
442  : QTableWidgetItem( Type() )
443 {
444   Qt::ItemFlags f = flags();
445   f = f | Qt::ItemIsUserCheckable;
446   f = f & ~Qt::ItemIsTristate;
447   f = f & ~Qt::ItemIsEditable;
448   setFlags( f );
449   setChecked(value);
450 }
451
452 SMESHGUI_FilterTable::CheckItem::CheckItem( const QString& text, bool value )
453  : QTableWidgetItem( Type() )
454 {
455   Qt::ItemFlags f = flags();
456   f = f | Qt::ItemIsUserCheckable;
457   f = f & ~Qt::ItemIsTristate;
458   f = f & ~Qt::ItemIsEditable;
459   setFlags( f );
460   setChecked( value );
461   setText( text );
462 }
463
464 SMESHGUI_FilterTable::CheckItem::~CheckItem()
465 {
466 }
467
468 void SMESHGUI_FilterTable::CheckItem::setChecked( bool value )
469 {
470   setCheckState( value ? Qt::Checked : Qt::Unchecked );
471 }
472
473 bool SMESHGUI_FilterTable::CheckItem::checked() const
474 {
475   return checkState() == Qt::Checked;
476 }
477
478 /*
479   Class       : SMESHGUI_FilterTable::IntSpinItem
480   Description : Integer spin table item.
481 */
482
483 class SMESHGUI_FilterTable::IntSpinItem : public QTableWidgetItem
484 {
485 public:
486   static int     Type();
487
488   IntSpinItem( const int theValue );
489
490   int            value() const;
491   void           setValue( const int theValue );
492
493   void           clear();
494 };
495
496 int SMESHGUI_FilterTable::IntSpinItem::Type()
497 {
498   return QTableWidgetItem::UserType + 3;
499 }
500
501 SMESHGUI_FilterTable::IntSpinItem::IntSpinItem( const int theValue )
502  : QTableWidgetItem( Type() )
503 {
504   setValue( theValue );
505 }
506
507 int SMESHGUI_FilterTable::IntSpinItem::value() const
508 {
509   bool ok = false;
510   int value = data( Qt::UserRole ).toInt( &ok );
511   return ok ? value : 0; 
512 }
513
514 void SMESHGUI_FilterTable::IntSpinItem::setValue( const int theValue )
515 {
516   setData( Qt::UserRole, theValue );
517   setText( QString::number( theValue ) ); 
518 }
519
520 void SMESHGUI_FilterTable::IntSpinItem::clear()
521 {
522   setText( "" );
523 }
524
525 /*
526   Class       : SMESHGUI_FilterTable::DoubleSpinItem
527   Description : Double spin table item.
528 */
529
530 class SMESHGUI_FilterTable::DoubleSpinItem : public QTableWidgetItem
531 {
532 public:
533   static int     Type();
534
535   DoubleSpinItem( const double theValue );
536
537   double         value() const;
538   void           setValue( const double theValue );
539
540   int            precision() const;
541   void           setPrecision( const int thePrecision );
542
543   void           clear();
544 };
545
546 int SMESHGUI_FilterTable::DoubleSpinItem::Type()
547 {
548   return QTableWidgetItem::UserType + 4;
549 }
550
551 SMESHGUI_FilterTable::DoubleSpinItem::DoubleSpinItem( const double theValue )
552  : QTableWidgetItem( Type() )
553 {
554   setValue( theValue );
555 }
556
557 double SMESHGUI_FilterTable::DoubleSpinItem::value() const
558 {
559   bool ok = false;
560   double value = data( Qt::UserRole ).toDouble( &ok );
561   return ok ? value : 0; 
562 }
563
564 void SMESHGUI_FilterTable::DoubleSpinItem::setValue( const double theValue )
565 {
566   setData( Qt::UserRole, theValue );
567   setText( QString::number( theValue ) ); 
568 }
569
570 int SMESHGUI_FilterTable::DoubleSpinItem::precision() const
571 {
572   bool ok = false;
573   int precision = data( Qt::UserRole + 1 ).toInt( &ok );
574   return ok ? precision : 0; 
575 }
576
577 void SMESHGUI_FilterTable::DoubleSpinItem::setPrecision( const int thePrecision )
578 {
579   setData( Qt::UserRole + 1, thePrecision );
580 }
581
582 void SMESHGUI_FilterTable::DoubleSpinItem::clear()
583 {
584   setText( "" );
585 }
586
587 /*
588   Class       : SMESHGUI_FilterTable::ComboDelegate
589   Description : Table used by this widget
590 */
591
592 class SMESHGUI_FilterTable::ComboDelegate : public QItemDelegate
593 {
594 public:
595   ComboDelegate( QObject* = 0 );
596   ~ComboDelegate();
597   
598   QWidget*      createEditor( QWidget*, const QStyleOptionViewItem&,
599                               const QModelIndex& ) const;
600   
601   void          setEditorData( QWidget*, const QModelIndex& ) const;
602   void          setModelData( QWidget*, QAbstractItemModel*, const QModelIndex& ) const;
603   
604   void          updateEditorGeometry( QWidget*, const QStyleOptionViewItem&, 
605                                       const QModelIndex& ) const;
606 private:
607   QTableWidget* myTable;
608 };
609
610 SMESHGUI_FilterTable::ComboDelegate::ComboDelegate( QObject* parent )
611   : QItemDelegate( parent ), 
612     myTable( qobject_cast<QTableWidget*>( parent ) )
613 {
614 }
615   
616 SMESHGUI_FilterTable::ComboDelegate::~ComboDelegate()
617 {
618 }
619
620 QWidget* SMESHGUI_FilterTable::ComboDelegate::createEditor( QWidget* parent,
621                                                             const QStyleOptionViewItem& option,
622                                                             const QModelIndex& index ) const
623 {
624   QVariant aData = index.data( Qt::UserRole );
625   QVariant::Type aDataType = aData.type();
626   if( aDataType == QVariant::StringList ) {
627     QStringList l = aData.toStringList();
628     if ( !l.isEmpty() ) {
629       QComboBox* cb = new QComboBox( parent );
630       cb->setFrame( false );
631       cb->addItems( l );
632       return cb;
633     }
634   }
635   else if( aDataType == QVariant::Int ) {
636     bool ok = false;
637     int aValue = aData.toInt( &ok );
638     if ( ok ) {
639       SalomeApp_IntSpinBox* intSpin = new SalomeApp_IntSpinBox( 0, 1000, 1, parent, false, true );
640       intSpin->setFrame( false );
641       intSpin->setValue( aValue );
642       return intSpin;
643     }
644   }
645   else if( aDataType == QVariant::Double ) {
646     bool ok = false;
647     double aValue = aData.toDouble( &ok );
648     if ( ok ) {
649       int aPrecision = index.data( Qt::UserRole + 1 ).toInt( &ok );
650       if ( !ok )
651         aPrecision = 0;
652
653       SalomeApp_DoubleSpinBox* dblSpin = new SalomeApp_DoubleSpinBox( -1.e20, 1.e20, 1, aPrecision, 20, parent, false, true );
654       dblSpin->setFrame( false );
655       dblSpin->setValue( aValue );
656       return dblSpin;
657     }
658   }
659   return QItemDelegate::createEditor( parent, option, index );
660 }
661
662 void SMESHGUI_FilterTable::ComboDelegate::setEditorData( QWidget* editor, 
663                                                          const QModelIndex& index ) const
664 {
665   QVariant data = index.model()->data( index, Qt::DisplayRole );
666   QString value = data.toString();
667   bool bOk = false;
668   if ( QComboBox* cb = dynamic_cast<QComboBox*>( editor ) ) {
669     int i = cb->findText( value );
670     if ( i >= 0 ) {
671       cb->setCurrentIndex( i );
672       bOk = true;
673     }
674   }
675   else if ( SalomeApp_DoubleSpinBox* dblSpin = dynamic_cast<SalomeApp_DoubleSpinBox*>( editor ) ) {
676     if( data.type() == QVariant::Double ) {
677       double valueDouble = data.toDouble( &bOk );
678       if( bOk )
679         dblSpin->setValue( valueDouble );
680     }
681   }
682   if ( !bOk ) QItemDelegate::setEditorData( editor, index );
683 }
684
685 void SMESHGUI_FilterTable::ComboDelegate::setModelData( QWidget* editor,
686                                                         QAbstractItemModel* model,
687                                                         const QModelIndex& index) const
688 {
689   if( QComboBox* cb = dynamic_cast<QComboBox*>( editor ) )
690     model->setData( index, cb->currentText(), Qt::DisplayRole );
691   else if( SalomeApp_IntSpinBox* intSpin = dynamic_cast<SalomeApp_IntSpinBox*>( editor ) )
692     model->setData( index, intSpin->value(), Qt::DisplayRole );
693   else if( SalomeApp_DoubleSpinBox* dblSpin = dynamic_cast<SalomeApp_DoubleSpinBox*>( editor ) )
694     model->setData( index, dblSpin->value(), Qt::DisplayRole );
695   else QItemDelegate::setModelData( editor, model, index );
696 }
697
698 void SMESHGUI_FilterTable::ComboDelegate::updateEditorGeometry( QWidget* editor,
699                                                                 const QStyleOptionViewItem& option, 
700                                                                 const QModelIndex& index ) const
701 {
702   editor->setGeometry( option.rect );
703 }
704
705 /*
706   Class       : SMESHGUI_FilterTable::Table
707   Description : Table used by this widget
708 */
709
710 class SMESHGUI_FilterTable::Table : public QTableWidget
711 {
712 public:
713   Table( QWidget* = 0 );
714   Table( int, int, QWidget* = 0 );
715   virtual ~Table();
716
717   QSize                   minimumSizeHint() const;
718
719   void                    setEditable( bool, int, int );
720   bool                    isEditable( int, int ) const;
721
722   void                    setReadOnly( bool );
723   bool                    isReadOnly() const;
724
725   void                    insertRows( int, int = 1 );
726   QString                 text( int, int );
727
728   QList<int>              selectedRows();
729 };
730
731 //=======================================================================
732 // name    : SMESHGUI_FilterTable::Table::Table
733 // Purpose : Constructor
734 //=======================================================================
735 SMESHGUI_FilterTable::Table::Table (QWidget* parent)
736 : QTableWidget(parent)
737 {
738   // set custom item delegate
739   setItemDelegate( new ComboDelegate(this) );
740   // set edit triggers by default
741   setReadOnly( false );
742 }
743
744 //=======================================================================
745 // name    : SMESHGUI_FilterTable::Table::Table
746 // Purpose : Constructor
747 //=======================================================================
748 SMESHGUI_FilterTable::Table::Table (int numRows, int numCols, QWidget* parent)
749 : QTableWidget(numRows, numCols, parent)
750 {
751   // set custom item delegate
752   setItemDelegate( new ComboDelegate(this) );
753   // set edit triggers by default
754   setReadOnly( false );
755 }
756
757 //=======================================================================
758 // name    : SMESHGUI_FilterTable::Table::~Table
759 // Purpose : Destructor
760 //=======================================================================
761 SMESHGUI_FilterTable::Table::~Table()
762 {
763 }
764
765 //=======================================================================
766 // name    : SMESHGUI_FilterTable::Table::minimumSizeHint
767 // Purpose : Get minimum size for the table
768 //=======================================================================
769 QSize SMESHGUI_FilterTable::Table::minimumSizeHint() const
770 {
771   QSize s = QTableWidget::minimumSizeHint();
772   QHeaderView* hv = horizontalHeader();
773   if ( hv )
774     s.setWidth( qMax( s.width(), hv->length() ) );
775   return s;
776 }
777
778 //=======================================================================
779 // name    : SMESHGUI_FilterTable::Table::setEditable
780 // Purpose : Set editable of specified cell
781 //=======================================================================
782 void SMESHGUI_FilterTable::Table::setEditable (bool isEditable,
783                                                int row, int col)
784 {
785   QTableWidgetItem* anItem = item( row, col );
786   if ( anItem ) {
787     bool isSignalsBlocked = signalsBlocked();
788     blockSignals( true );
789
790     Qt::ItemFlags f = anItem->flags();
791     if ( !isEditable ) f = f & ~Qt::ItemIsEditable;
792     else f = f | Qt::ItemIsEditable;
793     anItem->setFlags( f );
794     
795     blockSignals( isSignalsBlocked );
796   }
797 }
798
799 //=======================================================================
800 // name    : SMESHGUI_FilterTable::Table::isEditable
801 // Purpose : Verify wheter cell is editable
802 //=======================================================================
803 bool SMESHGUI_FilterTable::Table::isEditable (int row, int col) const
804 {
805   QTableWidgetItem* anItem = item( row, col );
806   return anItem == 0 || anItem->flags() & Qt::ItemIsEditable;
807 }
808
809 void SMESHGUI_FilterTable::Table::setReadOnly( bool on )
810 {
811   setEditTriggers( on ? 
812                    QAbstractItemView::NoEditTriggers  :
813                    QAbstractItemView::AllEditTriggers );
814 }
815
816 bool SMESHGUI_FilterTable::Table::isReadOnly() const
817 {
818   return editTriggers() == QAbstractItemView::NoEditTriggers;
819 }
820
821 //=======================================================================
822 // name    : SMESHGUI_FilterTable::Table::insertRows
823 // Purpose : Insert rows (virtual redefined)
824 //=======================================================================
825 void SMESHGUI_FilterTable::Table::insertRows (int row, int count)
826 {
827   closePersistentEditor( currentItem() );
828   while ( count-- ) insertRow( row );
829 }
830
831 //=======================================================================
832 // name    : SMESHGUI_FilterTable::Table::text
833 // Purpose : Get text from cell (virtual redefined)
834 //=======================================================================
835 QString SMESHGUI_FilterTable::Table::text (int row, int col)
836 {
837   closePersistentEditor( currentItem() );
838   QTableWidgetItem* anItem = item( row, col );
839   return anItem ? anItem->text() : QString();
840 }
841
842 QList<int> SMESHGUI_FilterTable::Table::selectedRows()
843 {
844   QList<QTableWidgetItem*> selItems = selectedItems();
845   QTableWidgetItem* anItem;
846   QList<int> rows;
847
848   foreach( anItem, selItems ) {
849     int r = row( anItem );
850     if ( !rows.contains( r ) ) rows.append( r );
851   }
852
853   qSort( rows );
854   return rows;
855 }
856
857 /*
858   Class       : SMESHGUI_FilterTable
859   Description : Frame containig
860                   - Button group for switching entity type
861                   - Table for displaying filter criterions
862                   - Buttons for editing table and filter libraries
863 */
864
865 //=======================================================================
866 // name    : SMESHGUI_FilterTable::SMESHGUI_FilterTable
867 // Purpose : Constructor
868 //=======================================================================
869 SMESHGUI_FilterTable::SMESHGUI_FilterTable( SMESHGUI* theModule,
870                                             QWidget* parent,
871                                             const int type )
872 : QWidget( parent ),
873   mySMESHGUI( theModule ),
874   myIsLocked( false )
875 {
876   myEntityType = -1;
877
878   QList<int> aTypes;
879   aTypes.append(type);
880   Init(aTypes);
881 }
882
883 //=======================================================================
884 // name    : SMESHGUI_FilterTable::SMESHGUI_FilterTable
885 // Purpose : Constructor
886 //=======================================================================
887 SMESHGUI_FilterTable::SMESHGUI_FilterTable( SMESHGUI* theModule,
888                                             QWidget* parent,
889                                             const QList<int>& types )
890 : QWidget( parent ),
891   mySMESHGUI( theModule ),
892   myIsLocked( false )
893 {
894   myEntityType = -1;
895   Init(types);
896 }
897
898 SMESHGUI_FilterTable::~SMESHGUI_FilterTable()
899 {
900 }
901
902 //=======================================================================
903 // name    : SMESHGUI_FilterTable::Init
904 // Purpose : Create table corresponding to the specified type
905 //=======================================================================
906 void SMESHGUI_FilterTable::Init (const QList<int>& theTypes)
907 {
908   if (theTypes.isEmpty())
909     return;
910
911   // Create buttons if necessary
912
913   if (myTables.isEmpty())
914   {
915     // create main layout
916     QVBoxLayout* aMainLay = new QVBoxLayout(this);
917     aMainLay->setMargin( 0 );
918     aMainLay->setSpacing( SPACING );
919
920     // create switch of entity types
921     myEntityTypeBox = new QGroupBox(tr("ENTITY_TYPE"), this);
922     QHBoxLayout* myEntityTypeBoxLayout = new QHBoxLayout(myEntityTypeBox);
923     myEntityTypeBoxLayout->setMargin( MARGIN );
924     myEntityTypeBoxLayout->setSpacing( SPACING );
925     myEntityTypeGrp = new QButtonGroup(this);
926
927     const QMap<int, QString>& aSupportedTypes = getSupportedTypes();
928     QMap<int, QString>::const_iterator anIter;
929     for (anIter = aSupportedTypes.begin(); anIter != aSupportedTypes.end(); ++anIter)
930     {
931       QRadioButton* aBtn = new QRadioButton(anIter.value(), myEntityTypeBox);
932       myEntityTypeGrp->addButton(aBtn, anIter.key());
933       myEntityTypeBoxLayout->addWidget(aBtn);
934     }
935
936     myTableGrp = new QGroupBox(tr("FILTER"), this );
937
938     // create table
939     mySwitchTableGrp = new QWidget(myTableGrp);
940     QVBoxLayout* mySwitchTableGrpLayout = new QVBoxLayout(mySwitchTableGrp);
941     mySwitchTableGrpLayout->setMargin(0);
942     mySwitchTableGrpLayout->setSpacing(0);
943
944     QList<int>::const_iterator typeIt = theTypes.begin();
945     for ( ; typeIt != theTypes.end(); ++typeIt ) {
946       Table* aTable = createTable(mySwitchTableGrp, *typeIt);
947       myTables[ *typeIt ] = aTable;
948       mySwitchTableGrpLayout->addWidget(aTable);
949       if ( typeIt != theTypes.begin() )
950         aTable->hide();
951     }
952
953     // create buttons
954     myAddBtn      = new QPushButton(tr("ADD"),       myTableGrp);
955     myRemoveBtn   = new QPushButton(tr("REMOVE"),    myTableGrp);
956     myClearBtn    = new QPushButton(tr("CLEAR"),     myTableGrp);
957     myInsertBtn   = new QPushButton(tr("INSERT"),    myTableGrp);
958     myCopyFromBtn = new QPushButton(tr("COPY_FROM"), myTableGrp);
959     myAddToBtn    = new QPushButton(tr("ADD_TO"),    myTableGrp);
960
961     myAddBtn->setAutoDefault(false);
962     myRemoveBtn->setAutoDefault(false);
963     myClearBtn->setAutoDefault(false);
964     myInsertBtn->setAutoDefault(false);
965     myCopyFromBtn->setAutoDefault(false);
966     myAddToBtn->setAutoDefault(false);
967
968     myCopyFromBtn->hide();
969     myAddToBtn->hide();
970
971     // layout widgets
972     QGridLayout* aLay = new QGridLayout(myTableGrp);
973     aLay->setMargin(MARGIN);
974     aLay->setSpacing(SPACING);
975
976     aLay->addWidget(mySwitchTableGrp, 0, 0, 7, 1);
977     aLay->addWidget(myAddBtn,         0, 1);
978     aLay->addWidget(myInsertBtn,      1, 1);
979     aLay->addWidget(myRemoveBtn,      2, 1);
980     aLay->addWidget(myClearBtn,       3, 1);
981     aLay->addWidget(myCopyFromBtn,    5, 1);
982     aLay->addWidget(myAddToBtn,       6, 1);
983     aLay->addWidget(createAdditionalFrame(myTableGrp), 7, 0, 1, 2 );
984
985     aLay->setRowMinimumHeight(4, 10);
986     aLay->setRowStretch(4, 1);
987     aLay->setColumnStretch(0, 1);
988     aLay->setColumnStretch(1, 0);
989
990     // layout 
991     aMainLay->addWidget(myEntityTypeBox);
992     aMainLay->addWidget(myTableGrp);
993     
994     // signals and slots
995     connect(myAddBtn,    SIGNAL(clicked()), this, SLOT(onAddBtn()));
996     connect(myInsertBtn, SIGNAL(clicked()), this, SLOT(onInsertBtn()));
997     connect(myRemoveBtn, SIGNAL(clicked()), this, SLOT(onRemoveBtn()));
998     connect(myClearBtn,  SIGNAL(clicked()), this, SLOT(onClearBtn()));
999
1000     connect(myCopyFromBtn, SIGNAL(clicked()), this, SLOT(onCopyFromBtn()));
1001     connect(myAddToBtn,    SIGNAL(clicked()), this, SLOT(onAddToBtn()));
1002
1003     connect(myEntityTypeGrp, SIGNAL(buttonClicked(int)), this, SLOT(onEntityType(int)));
1004
1005     myLibDlg = 0;
1006   }
1007   else
1008   {
1009     QList<int>::const_iterator typeIt = theTypes.begin();
1010     for ( ; typeIt != theTypes.end(); ++typeIt ) {
1011       if ( !myTables[ *typeIt ] ) {
1012         Table* aTable = createTable(mySwitchTableGrp, *typeIt);
1013         myTables[ *typeIt ] = aTable;
1014         ((QVBoxLayout*)mySwitchTableGrp->layout())->addWidget(myTables[ *typeIt ]);
1015         myEntityType = -1;
1016       }
1017     }
1018   }
1019
1020   // Hide buttons of entity types if necessary
1021   const QMap<int, QString>& aSupportedTypes = getSupportedTypes();
1022   QMap<int, QString>::const_iterator anIt;
1023   for (anIt = aSupportedTypes.begin(); anIt != aSupportedTypes.end(); ++anIt)
1024   {
1025     QAbstractButton* aBtn = myEntityTypeGrp->button(anIt.key());
1026     if ( aBtn ) aBtn->setVisible( theTypes.contains(anIt.key()) );
1027   }
1028
1029   // select first button if there is no selected buttons or it is hidden
1030   int aBtnId = myEntityTypeGrp->checkedId();
1031   if ( aBtnId == -1 || !theTypes.contains(aBtnId) ) {
1032     QAbstractButton* aBtn = myEntityTypeGrp->button(theTypes.first());
1033     if ( aBtn ) aBtn->setChecked(true);
1034   }
1035
1036   myEntityTypeBox->setVisible(theTypes.count() > 1);
1037
1038   myTableGrp->updateGeometry();
1039   int cType = myEntityTypeGrp->checkedId();
1040   onEntityType(cType);
1041 }
1042
1043 //=======================================================================
1044 // name    : SMESHGUI_FilterTable::createAdditionalFrame
1045 // Purpose : Get group box containing table. May be used for adding new widgets in it
1046 //=======================================================================
1047 QWidget* SMESHGUI_FilterTable::createAdditionalFrame (QWidget* theParent)
1048 {
1049   QWidget* aFrame = new QWidget(theParent);
1050
1051   QFrame* aLine1 = new QFrame(aFrame);
1052   QFrame* aLine2 = new QFrame(aFrame);
1053   aLine1->setFrameStyle(QFrame::HLine | QFrame::Sunken);
1054   aLine2->setFrameStyle(QFrame::HLine | QFrame::Sunken);
1055   aLine1->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
1056   aLine2->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
1057
1058   QLabel* aLabel = new QLabel(tr("ADDITIONAL_PARAMETERS"), aFrame);
1059
1060   myWgStack = new QStackedWidget(aFrame);
1061
1062   QGridLayout* aLay = new QGridLayout(aFrame);
1063   aLay->setMargin(0);
1064   aLay->setSpacing(SPACING);
1065   aLay->addWidget(aLine1,    0, 0);
1066   aLay->addWidget(aLabel,    0, 1);
1067   aLay->addWidget(aLine2,    0, 2);
1068   aLay->addWidget(myWgStack, 1, 0, 1, 3);
1069
1070   return aFrame;
1071 }
1072
1073 //=======================================================================
1074 // name    : SMESHGUI_FilterTable::GetTableGrp
1075 // Purpose : Get group box containing table. May be used for adding new widgets in it
1076 //=======================================================================
1077 QGroupBox* SMESHGUI_FilterTable::GetTableGrp()
1078 {
1079   return myTableGrp;
1080 }
1081
1082 //=======================================================================
1083 // name    : SMESHGUI_FilterTable::onEntityType
1084 // Purpose : SLOT. Called when entity type changed.
1085 //           Display corresponding table
1086 //=======================================================================
1087 void SMESHGUI_FilterTable::onEntityType (int theType)
1088 {
1089   if (myEntityType == theType)
1090     return;
1091
1092   myIsValid = true;
1093   emit NeedValidation();
1094   if (!myIsValid)
1095   {
1096     myEntityTypeGrp->button(myEntityType)->setChecked(true);
1097     return;
1098   }
1099
1100   myEntityType = theType;
1101
1102   if (!myTables.contains(theType)) {
1103     myTables[ theType ] = createTable(mySwitchTableGrp, theType);
1104     ((QVBoxLayout*)mySwitchTableGrp->layout())->addWidget(myTables[ theType ]);
1105   }
1106
1107   TableMap::iterator anIter;
1108   for (anIter = myTables.begin(); anIter != myTables.end(); ++anIter)
1109      anIter.value()->setVisible( myEntityType == anIter.key() );
1110
1111   updateBtnState();
1112   qApp->processEvents();
1113   myTables[ myEntityType ]->updateGeometry();
1114   adjustSize();
1115
1116   emit EntityTypeChanged(theType);
1117 }
1118
1119 //=======================================================================
1120 // name    : SMESHGUI_FilterTable::IsValid
1121 // Purpose : Verify validity of entered data
1122 //=======================================================================
1123 bool SMESHGUI_FilterTable::IsValid (const bool theMess, const int theEntityType) const
1124 {
1125   int aType = theEntityType == -1 ? GetType() : theEntityType;
1126
1127   Table* aTable = myTables[ aType ];
1128   for (int i = 0, n = aTable->rowCount(); i < n; i++)
1129   {
1130     int aCriterion = GetCriterionType(i, aType);
1131     QString errMsg;
1132     if (aCriterion == SMESH::FT_GroupColor )
1133     {
1134       QtxColorButton* clrBtn = qobject_cast<QtxColorButton*>(aTable->cellWidget(i, 2));
1135       if (clrBtn && !clrBtn->color().isValid())
1136         errMsg = tr( "GROUPCOLOR_ERROR" );
1137     }
1138     else if (aCriterion == SMESH::FT_RangeOfIds ||
1139              aCriterion == SMESH::FT_BelongToMeshGroup ||
1140              aCriterion == SMESH::FT_BelongToGeom ||
1141              aCriterion == SMESH::FT_BelongToPlane ||
1142              aCriterion == SMESH::FT_BelongToCylinder ||
1143              aCriterion == SMESH::FT_BelongToGenSurface ||
1144              aCriterion == SMESH::FT_ElemGeomType ||
1145              aCriterion == SMESH::FT_EntityType ||
1146              aCriterion == SMESH::FT_CoplanarFaces ||
1147              aCriterion == SMESH::FT_LyingOnGeom ||
1148              aCriterion == SMESH::FT_ConnectedElements )
1149     {
1150       if (aTable->text(i, 2).isEmpty())
1151         errMsg = tr( "ERROR" );
1152     }
1153     else // check correctness of a numeric value
1154     {
1155       bool aRes = false;
1156       bool isSignalsBlocked = aTable->signalsBlocked();
1157       aTable->blockSignals(true);
1158       /*double  aThreshold =*/ aTable->text(i, 2).toDouble( &aRes );
1159       aTable->blockSignals(isSignalsBlocked);
1160
1161       if (!aRes && aTable->isEditable(i, 2))
1162         errMsg = tr( "ERROR" );
1163     }
1164
1165     if (!errMsg.isEmpty()) {
1166       if (theMess)
1167         SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"), errMsg );
1168       return false;
1169     }
1170
1171     QTableWidgetItem* anItem = aTable->item(i, 0);
1172     if (myAddWidgets.contains(anItem) && !myAddWidgets[ anItem ]->IsValid())
1173       return false;
1174   }
1175
1176   return true;
1177 }
1178
1179 //=======================================================================
1180 // name    : SMESHGUI_FilterTable::SetValidity
1181 // Purpose : Set validity of the table
1182 //=======================================================================
1183 void SMESHGUI_FilterTable::SetValidity (const bool isValid)
1184 {
1185   myIsValid = isValid;
1186 }
1187
1188 //=======================================================================
1189 // name    : SMESHGUI_FilterTable::GetType
1190 // Purpose : Get current entity type
1191 //=======================================================================
1192 int SMESHGUI_FilterTable::GetType() const
1193 {
1194   return myEntityType;
1195 }
1196
1197 //=======================================================================
1198 // name    : SMESHGUI_FilterTable::SetType
1199 // Purpose : Set current entity type
1200 //=======================================================================
1201 void SMESHGUI_FilterTable::SetType (const int type)
1202 {
1203   myEntityTypeGrp->button(type)->setChecked(true);
1204   onEntityType(type);
1205 }
1206
1207 //=======================================================================
1208 // name    : SMESHGUI_FilterTable::RestorePreviousEntityType
1209 // Purpose : Restore previous entity type
1210 //=======================================================================
1211 void SMESHGUI_FilterTable::RestorePreviousEntityType()
1212 {
1213   SetType(myEntityType);
1214 }
1215
1216 //=======================================================================
1217 // name    : SMESHGUI_FilterTable::GetCriterionType
1218 // Purpose : Get type of criterion from specified row (corresponding enums in h-file)
1219 //=======================================================================
1220 int SMESHGUI_FilterTable::GetCriterionType (const int theRow, const int theType) const
1221 {
1222   int aType = theType == -1 ? GetType() : theType;
1223   Table* aTable = myTables[ aType ];
1224   ComboItem* anItem = (ComboItem*)aTable->item(theRow, 0);
1225   return anItem != 0 ? anItem->value() : SMESH::FT_Undefined;
1226 }
1227
1228 //=======================================================================
1229 // name    : SMESHGUI_FilterTable::GetCriterion
1230 // Purpose : Get parameters of criterion from specified row
1231 //=======================================================================
1232 void SMESHGUI_FilterTable::GetCriterion (const int                 theRow,
1233                                          SMESH::Filter::Criterion& theCriterion,
1234                                          const int                 theEntityType) const
1235 {
1236   int aType = theEntityType == -1 ? GetType() : theEntityType;
1237   Table* aTable = myTables[ aType ];
1238
1239   theCriterion.Type = ((ComboItem*)aTable->item(theRow, 0))->value();
1240   theCriterion.UnaryOp = ((CheckItem*)aTable->item(theRow, 3))->checked() ? SMESH::FT_LogicalNOT : SMESH::FT_Undefined;
1241   theCriterion.BinaryOp = theRow != aTable->rowCount() - 1 ?
1242     ((ComboItem*)aTable->item(theRow, 4))->value() : SMESH::FT_Undefined;
1243   theCriterion.TypeOfElement = (SMESH::ElementType)aType;
1244
1245   int aCriterionType = GetCriterionType(theRow, aType);
1246
1247   if ( aCriterionType == SMESH::FT_GroupColor )
1248   {
1249     QtxColorButton* clrBtn = qobject_cast<QtxColorButton*>(aTable->cellWidget(theRow, 2));
1250     if ( clrBtn )
1251     {
1252       Kernel_Utils::Localizer loc;
1253       const QColor qClr = clrBtn->color();
1254       QString clrStr = QString( "%1;%2;%3" ).
1255         arg( qClr.red()/256. ).arg( qClr.green()/256. ).arg( qClr.blue()/256. );
1256       theCriterion.ThresholdStr = clrStr.toLatin1().constData();
1257     }
1258   }
1259   else if ( aCriterionType == SMESH::FT_ElemGeomType ||
1260             aCriterionType == SMESH::FT_EntityType )
1261   {
1262     theCriterion.Threshold = (double)((ComboItem*)aTable->item(theRow, 2))->value();
1263   }
1264   else if ( aCriterionType == SMESH::FT_CoplanarFaces )
1265   {
1266     theCriterion.ThresholdID = aTable->text(theRow, 2).toLatin1().constData();
1267   }
1268   else if ( aCriterionType == SMESH::FT_ConnectedElements )
1269   {
1270     QString id = aTable->text(theRow, 5);
1271     if ( !id.isEmpty() ) // shape ID
1272     {
1273       theCriterion.ThresholdID = id.toLatin1().constData();
1274     }
1275     else
1276     {
1277       QString text = aTable->text(theRow, 2).trimmed();
1278       QString workText = text;
1279       for ( char c = '0'; c <= '9'; ++c )
1280         workText.remove( c );
1281
1282       if ( workText.isEmpty() ) // node ID
1283         theCriterion.Threshold = text.toDouble();
1284       else // point coordinates
1285         theCriterion.ThresholdStr = text.toLatin1().constData();
1286     }
1287   }
1288   else if ( aCriterionType != SMESH::FT_RangeOfIds &&
1289             aCriterionType != SMESH::FT_BelongToMeshGroup &&
1290             aCriterionType != SMESH::FT_BelongToGeom &&
1291             aCriterionType != SMESH::FT_BelongToPlane &&
1292             aCriterionType != SMESH::FT_BelongToCylinder &&
1293             aCriterionType != SMESH::FT_BelongToGenSurface &&
1294             aCriterionType != SMESH::FT_LyingOnGeom )
1295   {
1296     theCriterion.Compare = ((ComboItem*)aTable->item(theRow, 1))->value();
1297     theCriterion.Threshold = aTable->item(theRow, 2)->text().toDouble();
1298   }
1299   else
1300   {
1301     theCriterion.ThresholdStr = aTable->text(theRow, 2).toLatin1().constData();
1302     if ( aCriterionType != SMESH::FT_RangeOfIds )
1303       theCriterion.ThresholdID = aTable->text( theRow, 5 ).toLatin1().constData();
1304   }
1305
1306   QTableWidgetItem* anItem = aTable->item(theRow, 0);
1307   if (myAddWidgets.contains(anItem))
1308     theCriterion.Tolerance = myAddWidgets[ anItem ]->GetDouble(AdditionalWidget::Tolerance);
1309 }
1310
1311 //=======================================================================
1312 // name    : SMESHGUI_FilterTable::SetCriterion
1313 // Purpose : Set parameters of criterion of specified row
1314 //=======================================================================
1315 void SMESHGUI_FilterTable::SetCriterion (const int                       theRow,
1316                                          const SMESH::Filter::Criterion& theCriterion,
1317                                          const int                       theEntityType)
1318 {
1319   int aType = theEntityType == -1 ? GetType() : theEntityType;
1320
1321   Table* aTable = myTables[ aType ];
1322
1323   if (theRow > aTable->rowCount() - 1)
1324     return;
1325
1326   ((ComboItem*)aTable->item(theRow, 0))->setValue(theCriterion.Type);
1327   onCriterionChanged(theRow, 0, aType);
1328   if ( theCriterion.Compare == SMESH::FT_Undefined )
1329     ((ComboItem*)aTable->item(theRow, 1))->setValue( SMESH::FT_EqualTo );
1330   else
1331     ((ComboItem*)aTable->item(theRow, 1))->setValue(theCriterion.Compare);
1332   ((CheckItem*)aTable->item(theRow, 3))->setChecked(theCriterion.UnaryOp == SMESH::FT_LogicalNOT);
1333
1334   if (theCriterion.BinaryOp != SMESH::FT_Undefined)
1335   {
1336     if (!aTable->isEditable(theRow, 4))
1337       aTable->setItem(theRow, 4, getBinaryItem());
1338     ((ComboItem*)aTable->item(theRow, 4))->setValue(theCriterion.BinaryOp);
1339   }
1340   else
1341     aTable->setEditable(false, theRow, 4);
1342
1343   if (theCriterion.Type == SMESH::FT_GroupColor )
1344   {
1345     QtxColorButton* clrBtn = qobject_cast<QtxColorButton*>(aTable->cellWidget(theRow, 2));
1346     if ( clrBtn )
1347     {
1348       QColor qClr;
1349       QString clrStr( theCriterion.ThresholdStr );
1350       QStringList clrVals = clrStr.split( ";" );
1351       if ( clrVals.count() > 2 )
1352         qClr.setRgb( (int)256*clrVals[0].toDouble(),
1353                      (int)256*clrVals[1].toDouble(),
1354                      (int)256*clrVals[2].toDouble() );
1355       clrBtn->setColor( qClr );
1356     }
1357   }
1358   else if (theCriterion.Type == SMESH::FT_ElemGeomType || 
1359            theCriterion.Type == SMESH::FT_EntityType )
1360   {
1361     ComboItem* typeBox = (ComboItem*)aTable->item(theRow, 2);
1362     typeBox->setValue( (int)(theCriterion.Threshold + 0.5) );
1363   }
1364   else if (theCriterion.Type == SMESH::FT_CoplanarFaces )
1365   {
1366     aTable->item( theRow, 2 )->setText( QString( theCriterion.ThresholdID ) );
1367   }
1368   else if (theCriterion.Type == SMESH::FT_ConnectedElements )
1369   {
1370     if ( strlen( theCriterion.ThresholdID ) > 0 ) // shape ID -> name
1371     {
1372       _PTR(SObject) sobj =
1373         SMESH::GetActiveStudyDocument()->FindObjectID( theCriterion.ThresholdID.in() );
1374       if ( !sobj )
1375         aTable->item( theRow, 2 )->setText( QString( theCriterion.ThresholdID ) );
1376       else
1377         aTable->item( theRow, 2 )->setText( QString( sobj->GetName().c_str() ));
1378     }
1379     else if ( strlen( theCriterion.ThresholdStr ) > 0 ) // point coords
1380     {
1381       aTable->item( theRow, 2 )->setText( QString( theCriterion.ThresholdStr ));
1382     }
1383     else // node ID
1384     {
1385       aTable->item( theRow, 2 )->setText( QString("%1").arg((int) theCriterion.Threshold ));
1386     }
1387   }
1388   else if (theCriterion.Type != SMESH::FT_RangeOfIds &&
1389            theCriterion.Type != SMESH::FT_BelongToMeshGroup &&
1390            theCriterion.Type != SMESH::FT_BelongToGeom &&
1391            theCriterion.Type != SMESH::FT_BelongToPlane &&
1392            theCriterion.Type != SMESH::FT_BelongToCylinder &&
1393            theCriterion.Type != SMESH::FT_BelongToGenSurface &&
1394            theCriterion.Type != SMESH::FT_LyingOnGeom &&
1395            theCriterion.Type != SMESH::FT_FreeBorders &&
1396            theCriterion.Type != SMESH::FT_FreeEdges &&
1397            theCriterion.Type != SMESH::FT_FreeNodes &&
1398            theCriterion.Type != SMESH::FT_FreeFaces &&
1399            theCriterion.Type != SMESH::FT_BadOrientedVolume &&
1400            theCriterion.Type != SMESH::FT_BareBorderFace &&
1401            theCriterion.Type != SMESH::FT_BareBorderVolume &&
1402            theCriterion.Type != SMESH::FT_OverConstrainedFace &&
1403            theCriterion.Type != SMESH::FT_OverConstrainedVolume &&
1404            theCriterion.Type != SMESH::FT_LinearOrQuadratic)
1405   {
1406     // Numberic criterion
1407     aTable->item( theRow, 2 )->setText(QString("%1").arg(theCriterion.Threshold, 0, 'g', 15));
1408   }
1409   else
1410   {
1411     aTable->item( theRow, 2 )->setText(QString(theCriterion.ThresholdStr));
1412     if ( theCriterion.Type != SMESH::FT_RangeOfIds )
1413       aTable->item( theRow, 5 )->setText( QString( theCriterion.ThresholdID ) );
1414   }
1415
1416   if (theCriterion.Compare == SMESH::FT_EqualTo ||
1417       theCriterion.Type    == SMESH::FT_BelongToPlane ||
1418       theCriterion.Type    == SMESH::FT_BelongToCylinder ||
1419       theCriterion.Type    == SMESH::FT_BelongToGenSurface ||
1420       theCriterion.Type    == SMESH::FT_BelongToGeom ||
1421       theCriterion.Type    == SMESH::FT_LyingOnGeom ||
1422       theCriterion.Type    == SMESH::FT_CoplanarFaces ||
1423       theCriterion.Type    == SMESH::FT_EqualNodes)
1424   {
1425     QTableWidgetItem* anItem = aTable->item(theRow, 0);
1426     if (!myAddWidgets.contains(anItem))
1427     {
1428       myAddWidgets[ anItem ] = new AdditionalWidget(myWgStack);
1429       myAddWidgets[ anItem ]->SetPrecision( AdditionalWidget::Tolerance, getPrecision( theCriterion.Type ) );
1430       myWgStack->addWidget(myAddWidgets[ anItem ]);
1431     }
1432     myAddWidgets[ anItem ]->SetDouble(AdditionalWidget::Tolerance, theCriterion.Tolerance);
1433   }
1434
1435   emit CriterionChanged(theRow, aType);
1436 }
1437
1438 //=======================================================================
1439 // name    : SMESHGUI_FilterTable::Update
1440 // Purpose : Update table
1441 //=======================================================================
1442 void SMESHGUI_FilterTable::Update()
1443 {
1444   Table* aTable = myTables[ GetType() ];
1445   int aCurrRow = aTable->currentRow();
1446   int numRows = aTable->rowCount();
1447   if ((aCurrRow < 0 || aCurrRow >= numRows) && numRows > 0)
1448     aTable->setCurrentCell(0, 0);
1449   updateAdditionalWidget();
1450 }
1451
1452 //=======================================================================
1453 // name    : SMESHGUI_FilterTable::AddCriterion
1454 // Purpose : Add criterion with parameters
1455 //=======================================================================
1456 void SMESHGUI_FilterTable::AddCriterion (const SMESH::Filter::Criterion& theCriterion,
1457                                          const int                       theEntityType)
1458 {
1459   int aType = theEntityType == -1 ? GetType() : theEntityType;
1460   Table* aTable = myTables[ aType ];
1461   addRow(aTable, aType);
1462   SetCriterion(aTable->rowCount() - 1, theCriterion);
1463 }
1464
1465 //=======================================================================
1466 // name    : SMESHGUI_FilterTable::NumRows
1467 // Purpose : Get number of criterions of current type
1468 //=======================================================================
1469 int SMESHGUI_FilterTable::NumRows (const int theEntityType) const
1470 {
1471   return myTables[ theEntityType == -1 ? GetType() : theEntityType ]->rowCount();
1472 }
1473
1474 //=======================================================================
1475 // name    : SMESHGUI_FilterTable::Clear
1476 // Purpose : Clear current table
1477 //=======================================================================
1478 void SMESHGUI_FilterTable::Clear (const int theType)
1479 {
1480   int aType = theType == -1 ? GetType() : theType;
1481   Table* aTable = myTables[ aType ];
1482
1483   if (aTable->rowCount() == 0)
1484     return;
1485
1486   while (aTable->rowCount() > 0)
1487   {
1488     removeAdditionalWidget(aTable, 0);
1489     aTable->removeRow(0);
1490   }
1491
1492   updateBtnState();
1493 }
1494
1495 //=======================================================================
1496 // name    : SMESHGUI_FilterTable::onAddBtn
1497 // Purpose : SLOT. Called then "Add" button pressed.
1498 //           Adds new string to table
1499 //=======================================================================
1500 void SMESHGUI_FilterTable::onAddBtn()
1501 {
1502   int aType = GetType();
1503   addRow(myTables[ aType ], aType);
1504
1505   Update();
1506 }
1507
1508 //=======================================================================
1509 // name    : SMESHGUI_FilterTable::onInsertBtn
1510 // Purpose : SLOT. Called then "Insert" button pressed.
1511 //           Inserts new string before current one
1512 //=======================================================================
1513 void SMESHGUI_FilterTable::onInsertBtn()
1514 {
1515   addRow(myTables[ GetType() ], GetType(), false);
1516 }
1517
1518 //=======================================================================
1519 // name    : SMESHGUI_FilterTable::onRemoveBtn
1520 // Purpose : SLOT. Called then "Remove" button pressed.
1521 //           Removes current string from table
1522 //=======================================================================
1523 void SMESHGUI_FilterTable::onRemoveBtn()
1524 {
1525   Table* aTable = myTables[ GetType() ];
1526
1527   if (aTable->rowCount() == 0)
1528     return;
1529
1530   QList<QTableWidgetItem*> items = aTable->selectedItems();
1531   
1532   QList<int> aRows = aTable->selectedRows(); // already sorted
1533   int i;
1534   foreach( i, aRows )
1535   {
1536     removeAdditionalWidget(aTable, i);
1537     aTable->removeRow(i);
1538   }
1539
1540   // remove control of binary logical operation from last row
1541   if (aTable->rowCount() > 0)
1542     aTable->setEditable(false, aTable->rowCount() - 1, 4);
1543
1544   updateBtnState();
1545 }
1546
1547 //=======================================================================
1548 // name    : SMESHGUI_FilterTable::updateAdditionalWidget
1549 // Purpose : Enable/Disable widget with additional parameters
1550 //=======================================================================
1551 void SMESHGUI_FilterTable::updateAdditionalWidget()
1552 {
1553   Table* aTable = myTables[ GetType() ];
1554   int aRow = aTable->currentRow();
1555   if (aRow < 0 || aRow >= aTable->rowCount())
1556   {
1557     myWgStack->setEnabled(false);
1558     return;
1559   }
1560
1561   ComboItem* anItem = ((ComboItem*)aTable->item(aRow, 0));
1562   int aCriterion = GetCriterionType(aRow);
1563   bool isDbl = ( aCriterion == SMESH::FT_AspectRatio        ||
1564                  aCriterion == SMESH::FT_AspectRatio3D      ||
1565                  aCriterion == SMESH::FT_Warping            ||
1566                  aCriterion == SMESH::FT_MinimumAngle       ||
1567                  aCriterion == SMESH::FT_Taper              ||
1568                  aCriterion == SMESH::FT_Skew               ||
1569                  aCriterion == SMESH::FT_Area               ||
1570                  aCriterion == SMESH::FT_Volume3D           ||
1571                  aCriterion == SMESH::FT_MaxElementLength2D ||
1572                  aCriterion == SMESH::FT_MaxElementLength3D ||
1573                  aCriterion == SMESH::FT_Length             ||
1574                  aCriterion == SMESH::FT_Length2D           ||
1575                  aCriterion == SMESH::FT_BallDiameter );
1576
1577   bool toEnable = (( isDbl && ((ComboItem*)aTable->item(aRow, 1))->value() == SMESH::FT_EqualTo) ||
1578                    aCriterion == SMESH::FT_BelongToPlane                                         ||
1579                    aCriterion == SMESH::FT_BelongToCylinder                                      ||
1580                    aCriterion == SMESH::FT_BelongToGenSurface                                    ||
1581                    aCriterion == SMESH::FT_BelongToGeom                                          ||
1582                    aCriterion == SMESH::FT_LyingOnGeom                                           ||
1583                    aCriterion == SMESH::FT_CoplanarFaces                                         ||
1584                    aCriterion == SMESH::FT_EqualNodes);
1585
1586   if (!myAddWidgets.contains(anItem))
1587   {
1588     myAddWidgets[ anItem ] = new AdditionalWidget(myWgStack);
1589     myWgStack->addWidget(myAddWidgets[ anItem ]);
1590   }
1591
1592   myWgStack->setCurrentWidget(myAddWidgets[ anItem ]);
1593   myAddWidgets[ anItem ]->SetPrecision( AdditionalWidget::Tolerance, getPrecision( aCriterion ) );
1594   myWgStack->setEnabled(toEnable);
1595 }
1596
1597 const char* SMESHGUI_FilterTable::getPrecision( const int aType )
1598 {
1599   const char* retval = 0;
1600   switch ( aType ) {
1601   case SMESH::FT_AspectRatio:
1602   case SMESH::FT_AspectRatio3D:
1603   case SMESH::FT_Taper:
1604     retval = "parametric_precision"; break;
1605   case SMESH::FT_Warping:
1606   case SMESH::FT_MinimumAngle:
1607   case SMESH::FT_Skew:
1608   case SMESH::FT_CoplanarFaces:
1609     retval = "angle_precision"; break;
1610   case SMESH::FT_Area:
1611     retval = "area_precision"; break;
1612   case SMESH::FT_BelongToGeom:
1613   case SMESH::FT_BelongToPlane:
1614   case SMESH::FT_BelongToCylinder:
1615   case SMESH::FT_BelongToGenSurface:
1616   case SMESH::FT_LyingOnGeom:
1617   case SMESH::FT_EqualNodes:
1618     retval = "len_tol_precision"; break;
1619   case SMESH::FT_Length:
1620   case SMESH::FT_Length2D:
1621   case SMESH::FT_MaxElementLength2D:
1622   case SMESH::FT_MaxElementLength3D:
1623   case SMESH::FT_BallDiameter:
1624     retval = "length_precision"; break;
1625   case SMESH::FT_Volume3D:
1626     retval = "vol_precision"; break;
1627   default:
1628     break;
1629   }
1630   return retval;
1631 }
1632
1633 //=======================================================================
1634 // name    : SMESHGUI_FilterTable::removeAdditionalWidget
1635 // Purpose : Remove widgets containing additional parameters from widget
1636 //           stack and internal map
1637 //=======================================================================
1638 void SMESHGUI_FilterTable::removeAdditionalWidget (QTableWidget* theTable, const int theRow)
1639 {
1640   QTableWidgetItem* anItem = theTable->item(theRow, 0);
1641   if (myAddWidgets.contains(anItem))
1642   {
1643     myWgStack->removeWidget(myAddWidgets[ anItem ]);
1644     myAddWidgets[ anItem ]->setParent(0);
1645     delete myAddWidgets[ anItem ];
1646     myAddWidgets.remove(anItem);
1647   }
1648 }
1649
1650 //=======================================================================
1651 // name    : SMESHGUI_FilterTable::onClearBtn
1652 // Purpose : SLOT. Called then "Clear" button pressed.
1653 //           Removes all strings from table
1654 //=======================================================================
1655 void SMESHGUI_FilterTable::onClearBtn()
1656 {
1657   Table* aTable = myTables[ GetType() ];
1658
1659   if (aTable->rowCount() == 0)
1660     return;
1661
1662   while (aTable->rowCount() > 0)
1663   {
1664     removeAdditionalWidget(aTable, 0);
1665     aTable->removeRow(0);
1666   }
1667
1668   updateBtnState();
1669 }
1670
1671 //=======================================================================
1672 // name    : SMESHGUI_FilterTable::onCurrentChanged()
1673 // Purpose : SLOT. Called when current cell changed
1674 //=======================================================================
1675 void SMESHGUI_FilterTable::onCurrentChanged (int theRow, int theCol)
1676 {
1677   if( !myIsLocked )
1678     updateAdditionalWidget();
1679   emit CurrentChanged(theRow, theCol);
1680 }
1681
1682 //=======================================================================
1683 // name    : geomTypes
1684 // Purpose : returns available geometry types of elements
1685 //=======================================================================
1686 static QList<int> geomTypes( const int theType )
1687 {
1688   QList<int> typeIds;
1689   if ( theType == SMESH::NODE )
1690     typeIds.append( SMESH::Geom_POINT );
1691   if ( theType == SMESH::ALL || theType == SMESH::EDGE )
1692     typeIds.append( SMESH::Geom_EDGE );
1693   if ( theType == SMESH::ALL || theType == SMESH::FACE )
1694   {
1695     typeIds.append( SMESH::Geom_TRIANGLE );
1696     typeIds.append( SMESH::Geom_QUADRANGLE );
1697     typeIds.append( SMESH::Geom_POLYGON );
1698   }
1699   if ( theType == SMESH::ALL || theType == SMESH::VOLUME )
1700   {
1701     typeIds.append( SMESH::Geom_TETRA );
1702     typeIds.append( SMESH::Geom_PYRAMID );
1703     typeIds.append( SMESH::Geom_HEXA );
1704     typeIds.append( SMESH::Geom_PENTA );
1705     typeIds.append( SMESH::Geom_HEXAGONAL_PRISM );
1706     typeIds.append( SMESH::Geom_POLYHEDRA );
1707   }
1708   if ( theType == SMESH::ALL || theType == SMESH::ELEM0D )
1709   {
1710     typeIds.append( SMESH::Geom_POINT );
1711   }
1712   if ( theType == SMESH::ALL || theType == SMESH::BALL )
1713   {
1714     typeIds.append( SMESH::Geom_BALL );
1715   }
1716   return typeIds;
1717 }
1718
1719 //=======================================================================
1720 // name    : entityTypes
1721 // Purpose : returns available entity types of elements
1722 //=======================================================================
1723
1724 static QList<int> entityTypes( const int theType )
1725 {
1726   QList<int> typeIds;
1727
1728   switch ( theType )
1729   {
1730   case SMESH::NODE:
1731     typeIds.append( SMDSEntity_Node );
1732   case SMESH::EDGE:
1733     typeIds.append( SMDSEntity_Edge );
1734     typeIds.append( SMDSEntity_Quad_Edge );
1735     break;
1736   case SMESH::FACE:
1737     typeIds.append( SMDSEntity_Triangle );
1738     typeIds.append( SMDSEntity_Quad_Triangle );
1739     typeIds.append( SMDSEntity_BiQuad_Triangle );
1740     typeIds.append( SMDSEntity_Quadrangle );
1741     typeIds.append( SMDSEntity_Quad_Quadrangle );
1742     typeIds.append( SMDSEntity_BiQuad_Quadrangle );
1743     typeIds.append( SMDSEntity_Polygon );
1744     typeIds.append( SMDSEntity_Quad_Polygon );
1745     break;
1746   case SMESH::VOLUME:
1747     typeIds.append( SMDSEntity_Tetra );
1748     typeIds.append( SMDSEntity_Quad_Tetra );
1749     typeIds.append( SMDSEntity_Pyramid );
1750     typeIds.append( SMDSEntity_Quad_Pyramid );
1751     typeIds.append( SMDSEntity_Hexa );
1752     typeIds.append( SMDSEntity_Quad_Hexa );
1753     typeIds.append( SMDSEntity_TriQuad_Hexa );
1754     typeIds.append( SMDSEntity_Penta );
1755     typeIds.append( SMDSEntity_Quad_Penta );
1756     typeIds.append( SMDSEntity_BiQuad_Penta );
1757     typeIds.append( SMDSEntity_Hexagonal_Prism );
1758     typeIds.append( SMDSEntity_Polyhedra );
1759     //typeIds.append( SMDSEntity_Quad_Polyhedra );
1760     break;
1761   case SMESH::ELEM0D:
1762     typeIds.append( SMDSEntity_0D );
1763     break;
1764   case SMESH::BALL:
1765     typeIds.append( SMDSEntity_Ball );
1766     break;
1767   }
1768   return typeIds;
1769 }
1770
1771 //=======================================================================
1772 // name    : SMESHGUI_FilterTable::onCriterionChanged()
1773 // Purpose : Provides reaction on change of criterion
1774 //=======================================================================
1775
1776 void SMESHGUI_FilterTable::onCriterionChanged (const int row, const int col, const int entityType)
1777 {
1778   int aType = entityType == -1 ? GetType() : entityType;
1779   Table* aTable = myTables[ aType ];
1780   ComboItem* aCompareItem = (ComboItem*)aTable->item(row, 1);
1781
1782   // find out type of a existing threshould table item
1783   QtxColorButton* clrBtn = qobject_cast<QtxColorButton*>(aTable->cellWidget(row, 2));
1784   bool isComboItem       = false;
1785   bool isIntSpinItem     = false;
1786   bool isDoubleSpinItem  = false;
1787   if ( QTableWidgetItem* aTableItem = aTable->item(row, 2) )
1788   {
1789     int aTableType   = aTableItem->type();
1790     isComboItem      = ( aTableType == ComboItem::Type() );
1791     isIntSpinItem    = ( aTableType == IntSpinItem::Type() );
1792     isDoubleSpinItem = ( aTableType == DoubleSpinItem::Type() );
1793   }
1794
1795   // find out a type of item required by a new criterion and other table features
1796   int aCriterionType       = GetCriterionType(row);
1797   bool anIsDoubleCriterion = false;
1798   bool anIsIntCriterion    = false;
1799   bool anIsComboCriterion  = false;
1800   // other features:
1801   QList<int> comboIDs; // values to show in a combo item
1802   int nbCompareSigns = 0; // possible values are 0,1,3
1803   bool isThresholdEditable = false; // actual for "simple" item types
1804   switch ( aCriterionType )
1805   {
1806   case SMESH::FT_AspectRatio:
1807   case SMESH::FT_AspectRatio3D:
1808   case SMESH::FT_Warping:
1809   case SMESH::FT_MinimumAngle:
1810   case SMESH::FT_Taper:
1811   case SMESH::FT_Skew:
1812   case SMESH::FT_Area:
1813   case SMESH::FT_Volume3D:
1814   case SMESH::FT_MaxElementLength2D:
1815   case SMESH::FT_MaxElementLength3D:
1816     anIsDoubleCriterion = true; break;
1817
1818   case SMESH::FT_FreeBorders:
1819   case SMESH::FT_FreeEdges:
1820   case SMESH::FT_FreeNodes:
1821   case SMESH::FT_FreeFaces:
1822   case SMESH::FT_EqualNodes:
1823   case SMESH::FT_EqualEdges:
1824   case SMESH::FT_EqualFaces:
1825   case SMESH::FT_EqualVolumes: break;
1826
1827   case SMESH::FT_NodeConnectivityNumber:
1828   case SMESH::FT_MultiConnection:
1829   case SMESH::FT_MultiConnection2D: anIsIntCriterion = true; nbCompareSigns = 3; break;
1830
1831   case SMESH::FT_Length:
1832   case SMESH::FT_Length2D: anIsDoubleCriterion = true; break;
1833
1834   case SMESH::FT_BelongToMeshGroup: break;
1835
1836   case SMESH::FT_BelongToGeom:
1837   case SMESH::FT_BelongToPlane:
1838   case SMESH::FT_BelongToCylinder:
1839   case SMESH::FT_BelongToGenSurface:
1840   case SMESH::FT_LyingOnGeom: nbCompareSigns = 0; isThresholdEditable = true; break;
1841
1842   case SMESH::FT_RangeOfIds: nbCompareSigns = 0; isThresholdEditable = true; break;
1843
1844   case SMESH::FT_BadOrientedVolume:
1845   case SMESH::FT_BareBorderVolume:
1846   case SMESH::FT_BareBorderFace:
1847   case SMESH::FT_OverConstrainedVolume:
1848   case SMESH::FT_OverConstrainedFace:
1849   case SMESH::FT_LinearOrQuadratic: break;
1850
1851   case SMESH::FT_GroupColor: nbCompareSigns = 1; isThresholdEditable = true; break;
1852
1853   case SMESH::FT_ElemGeomType:
1854     comboIDs = geomTypes( aType ); anIsComboCriterion = true; nbCompareSigns = 1; break;
1855
1856   case SMESH::FT_EntityType:
1857     comboIDs = entityTypes( aType ); anIsComboCriterion = true; nbCompareSigns = 1; break;
1858
1859   case SMESH::FT_CoplanarFaces: isThresholdEditable = true; break;
1860
1861   case SMESH::FT_BallDiameter: anIsDoubleCriterion = true; break;
1862
1863   case SMESH::FT_ConnectedElements: isThresholdEditable = true; break;
1864
1865   case SMESH::FT_LessThan:
1866   case SMESH::FT_MoreThan:
1867   case SMESH::FT_EqualTo:
1868   case SMESH::FT_LogicalNOT:
1869   case SMESH::FT_LogicalAND:
1870   case SMESH::FT_LogicalOR:
1871   case SMESH::FT_Undefined:
1872   default: return;
1873   }
1874
1875   // get a precision of a double criterion
1876   int aPrecision = 0;
1877   if ( anIsDoubleCriterion ) {
1878     const char*     aPrecisionType = getPrecision( aCriterionType );
1879     SUIT_ResourceMgr* aResourceMgr = SMESH::GetResourceMgr( mySMESHGUI );
1880     if( aPrecisionType && aResourceMgr )
1881       aPrecision = aResourceMgr->integerValue( "SMESH", aPrecisionType, aPrecision );
1882   }
1883
1884   // check if the current item type satisfies the criterion
1885   bool itemTypeKO =
1886     ( aCriterionType == SMESH::FT_GroupColor && !clrBtn) ||
1887     ( anIsComboCriterion                     && !isComboItem ) ||
1888     ( anIsIntCriterion                       && !isIntSpinItem ) ||
1889     ( anIsDoubleCriterion                    && !isDoubleSpinItem );
1890
1891   if ( !itemTypeKO )
1892   {
1893     if ( anIsDoubleCriterion )
1894     {
1895       // if the precision is to be changed we should remove the existing
1896       // spin item and create another one with new precision
1897       if ( DoubleSpinItem* aDoubleSpinItem = dynamic_cast<DoubleSpinItem*>( aTable->item( row, 2 )))
1898         itemTypeKO = ( aDoubleSpinItem->precision() != aPrecision );
1899       else
1900         itemTypeKO = true;
1901     }
1902     else if ( anIsComboCriterion )
1903     {
1904       if ( ComboItem* aComboItem = dynamic_cast<ComboItem*>( aTable->item( row, 2 )))
1905         itemTypeKO = ( aComboItem->count() != comboIDs.count() );
1906       else
1907         itemTypeKO = true;
1908     }
1909     else if ( !anIsIntCriterion && aCriterionType != SMESH::FT_GroupColor )
1910     {
1911       itemTypeKO = ( clrBtn || isComboItem || isIntSpinItem || isDoubleSpinItem );
1912     }
1913   }
1914
1915   // update the table row
1916
1917   bool isSignalsBlocked = aTable->signalsBlocked();
1918   aTable->blockSignals( true );
1919
1920   // update threshold table item
1921   if ( itemTypeKO )
1922   {
1923     aTable->removeCellWidget( row, 2 );
1924
1925     if ( aCriterionType == SMESH::FT_GroupColor ) // ---------------------- QtxColorButton
1926     {
1927       aTable->setCellWidget( row, 2, new QtxColorButton( aTable ) );
1928     }
1929     else if ( anIsComboCriterion ) // -------------------------------------------ComboItem
1930     {
1931       QString msgPrefix
1932         ( aCriterionType == SMESH::FT_ElemGeomType  ? "GEOM_TYPE_%1" :  "ENTITY_TYPE_%1" );
1933       QMap<int, QString> names;
1934       QList<int>::const_iterator id = comboIDs.begin();
1935       for ( ; id != comboIDs.end(); ++id )
1936       {
1937         QString name = msgPrefix.arg( *id );
1938         names[ *id ] = tr( name.toLatin1().data() );
1939       }
1940       ComboItem* comboBox = new ComboItem( names );
1941       aTable->setItem( row, 2, comboBox );
1942     }
1943     else if ( anIsIntCriterion ) // ------------------------------------------ IntSpinItem
1944     {
1945       IntSpinItem* intSpin = new IntSpinItem( 0 );
1946       aTable->setItem( row, 2, intSpin );
1947     }
1948     else if ( anIsDoubleCriterion ) // -------------------------------------DoubleSpinItem
1949     {
1950       DoubleSpinItem* dblSpin = new DoubleSpinItem( 0 );
1951       dblSpin->setPrecision( aPrecision );
1952       aTable->setItem( row, 2, dblSpin );
1953     }
1954     else // --------------------------------------------------------------QTableWidgetItem
1955     {
1956       aTable->setItem( row, 2, new QTableWidgetItem() );
1957     }
1958   }
1959
1960   // set Compare
1961   if ( anIsDoubleCriterion )
1962     nbCompareSigns = 3;
1963   if ( aCompareItem->count() != nbCompareSigns )
1964   {
1965     switch ( nbCompareSigns ) {
1966     case 0: {
1967       aCompareItem->clear();
1968       break;
1969     }
1970     case 1: {
1971       QMap<int, QString> aMap;
1972       aMap[ SMESH::FT_EqualTo ] = tr("EQUAL_TO");
1973       aCompareItem->setItems(aMap);
1974       break;
1975     }
1976     case 3: {
1977       int oldValue = aCompareItem->value();
1978       aCompareItem->setItems(getCompare());
1979       if ( oldValue >= 0 )
1980         aCompareItem->setValue( oldValue );
1981       break;
1982     }
1983     }
1984   }
1985   aTable->setEditable( nbCompareSigns == 3, row, 1);
1986
1987   // enable/desable Threshold
1988   if ( aCriterionType == SMESH::FT_GroupColor ||
1989        anIsComboCriterion ||
1990        anIsIntCriterion ||
1991        anIsDoubleCriterion )
1992   {
1993     isThresholdEditable = true;
1994   }
1995   if ( !isThresholdEditable )
1996   {
1997     aTable->setItem( row, 2, new QTableWidgetItem() );
1998   }
1999   aTable->setEditable( isThresholdEditable, row, 2);
2000
2001
2002   aTable->blockSignals( isSignalsBlocked );
2003
2004   updateAdditionalWidget();
2005
2006   emit CriterionChanged(row, entityType);
2007 }
2008
2009 //=======================================================================
2010 // name    : SMESHGUI_FilterTable::onCriterionChanged()
2011 // Purpose : SLOT. Called then contents of table changed
2012 //           Provides reaction on change of criterion
2013 //=======================================================================
2014 void SMESHGUI_FilterTable::onCriterionChanged (int row, int col)
2015 {
2016   if( col == 0 )
2017     onCriterionChanged(row, col, -1);
2018   else if ( col == 2 )
2019     emit ThresholdChanged(row, GetType());
2020 }
2021
2022 //=======================================================================
2023 // name    : SMESHGUI_FilterTable::getFirstSelectedRow
2024 // Purpose : Get first selected row
2025 //=======================================================================
2026 int SMESHGUI_FilterTable::getFirstSelectedRow() const
2027 {
2028   Table* aTable = myTables[ GetType() ];
2029
2030   QList<int> selRows = aTable->selectedRows(); // already sorted
2031   int aRow = selRows.count() > 0 ? selRows[0] : aTable->currentRow();
2032
2033   return aRow >= 0 && aRow < aTable->rowCount() ? aRow : -1;
2034 }
2035
2036 //=======================================================================
2037 // name    : SMESHGUI_FilterTable::addRow
2038 // Purpose : Add row at the end of table
2039 //=======================================================================
2040 void SMESHGUI_FilterTable::addRow (Table* theTable, const int theType, const bool toTheEnd)
2041 {
2042   int aCurrRow = 0;
2043   int aSelectedRow = getFirstSelectedRow();
2044   int aCurrCol = theTable->currentColumn();
2045
2046   myIsLocked = true;
2047   if (toTheEnd || aSelectedRow == -1)
2048   {
2049     theTable->insertRows(theTable->rowCount());
2050     aCurrRow = theTable->rowCount() - 1;
2051   }
2052   else
2053   {
2054     theTable->insertRows(aSelectedRow);
2055     aCurrRow = aSelectedRow;
2056   }
2057   myIsLocked = false;
2058
2059   // IPAL19372 - to prevent calling onCriterionChaged() slot before completion of setItem()
2060   bool isSignalsBlocked = theTable->signalsBlocked();
2061   theTable->blockSignals( true );
2062
2063   // Criteria
2064   theTable->setItem(aCurrRow, 0, getCriterionItem(theType));
2065
2066   // Compare
2067   theTable->setItem(aCurrRow, 1, getCompareItem());
2068
2069   // Threshold
2070   theTable->setItem(aCurrRow, 2, new QTableWidgetItem());
2071
2072   // Logical operation NOT
2073   theTable->setItem(aCurrRow, 3, getUnaryItem());
2074
2075   // Logical operation AND / OR
2076   theTable->setItem(aCurrRow, 4, new QTableWidgetItem());
2077
2078   theTable->setItem(aCurrRow, 5, new QTableWidgetItem());
2079     
2080   theTable->blockSignals( isSignalsBlocked );
2081
2082   // Logical binary operation for previous value
2083   int anAddBinOpStr = -1;
2084   if (aCurrRow == theTable->rowCount() - 1)
2085     anAddBinOpStr = aCurrRow - 1;
2086   else if (aCurrRow >= 0 )
2087     anAddBinOpStr = aCurrRow;
2088
2089   if (theTable->item(aCurrRow, 4) == 0 ||
2090        theTable->item(aCurrRow, 4)->type() != ComboItem::Type())
2091   {
2092     if (anAddBinOpStr >= 0 &&
2093          (theTable->item(anAddBinOpStr, 4) == 0 ||
2094            theTable->item(anAddBinOpStr, 4)->type() != ComboItem::Type()))
2095       theTable->setItem(anAddBinOpStr, 4, getBinaryItem());
2096   }
2097
2098   theTable->setEditable(false, theTable->rowCount() - 1, 4);
2099   
2100   if (aCurrRow >=0 && aCurrRow < theTable->rowCount() &&
2101        aCurrCol >=0 && aCurrCol < theTable->rowCount())
2102   theTable->setCurrentCell(aCurrRow, aCurrCol);
2103
2104   onCriterionChanged(aCurrRow, 0);
2105
2106   updateBtnState();
2107 }
2108
2109 //=======================================================================
2110 // name    : SMESHGUI_FilterTable::getCriterionItem
2111 // Purpose : Get combo table item for criteria of specified type
2112 //=======================================================================
2113 QTableWidgetItem* SMESHGUI_FilterTable::getCriterionItem (const int theType) const
2114 {
2115   return new ComboItem(getCriteria(theType));
2116 }
2117
2118 //=======================================================================
2119 // name    : SMESHGUI_FilterTable::getCompareItem
2120 // Purpose : Get combo table item for operation of comparison
2121 //=======================================================================
2122 QTableWidgetItem* SMESHGUI_FilterTable::getCompareItem () const
2123 {
2124   return new ComboItem(getCompare());
2125 }
2126
2127 //=======================================================================
2128 // name    : SMESHGUI_FilterTable::getBinaryItem
2129 // Purpose :
2130 //=======================================================================
2131 QTableWidgetItem* SMESHGUI_FilterTable::getBinaryItem () const
2132 {
2133   static QMap<int, QString> aMap;
2134   if (aMap.isEmpty())
2135   {
2136     aMap[ SMESH::FT_LogicalAND ] = tr("AND");
2137     aMap[ SMESH::FT_LogicalOR  ] = tr("OR");
2138   }
2139
2140   return new ComboItem(aMap);
2141 }
2142
2143 //=======================================================================
2144 // name    : SMESHGUI_FilterTable::getUnaryItem
2145 // Purpose : Get check table item
2146 //=======================================================================
2147 QTableWidgetItem* SMESHGUI_FilterTable::getUnaryItem () const
2148 {
2149   return new CheckItem(tr("NOT"));
2150 }
2151
2152 //=======================================================================
2153 // name    : SMESHGUI_FilterTable::getSupportedTypes
2154 // Purpose : Get all supported type
2155 //=======================================================================
2156 const QMap<int, QString>& SMESHGUI_FilterTable::getSupportedTypes() const
2157 {
2158   static QMap<int, QString> aTypes;
2159   if (aTypes.isEmpty())
2160   {
2161     aTypes[ SMESH::NODE   ] = tr("NODES");
2162     aTypes[ SMESH::ELEM0D ] = tr("ELEM0D");
2163     aTypes[ SMESH::BALL   ] = tr("BALLS");
2164     aTypes[ SMESH::EDGE   ] = tr("EDGES");
2165     aTypes[ SMESH::FACE   ] = tr("FACES");
2166     aTypes[ SMESH::VOLUME ] = tr("VOLUMES");
2167     aTypes[ SMESH::ALL ]    = tr("ELEMENTS");
2168   }
2169
2170   return aTypes;
2171 }
2172
2173 //=======================================================================
2174 // name    : SMESHGUI_FilterTable::getCriteria
2175 // Purpose : Get criteria for specified type
2176 //=======================================================================
2177 const QMap<int, QString>& SMESHGUI_FilterTable::getCriteria (const int theType) const
2178 {
2179   if (theType == SMESH::NODE)
2180   {
2181     static QMap<int, QString> aCriteria;
2182     if (aCriteria.isEmpty())
2183     {
2184       aCriteria[ SMESH::FT_RangeOfIds         ] = tr("RANGE_OF_IDS");
2185       aCriteria[ SMESH::FT_BelongToMeshGroup  ] = tr("BELONG_TO_MESH_GROUP");
2186       aCriteria[ SMESH::FT_BelongToGeom       ] = tr("BELONG_TO_GEOM");
2187       aCriteria[ SMESH::FT_BelongToPlane      ] = tr("BELONG_TO_PLANE");
2188       aCriteria[ SMESH::FT_BelongToCylinder   ] = tr("BELONG_TO_CYLINDER");
2189       aCriteria[ SMESH::FT_BelongToGenSurface ] = tr("BELONG_TO_GENSURFACE");
2190       aCriteria[ SMESH::FT_LyingOnGeom        ] = tr("LYING_ON_GEOM");
2191       aCriteria[ SMESH::FT_FreeNodes          ] = tr("FREE_NODES");
2192       aCriteria[ SMESH::FT_GroupColor         ] = tr("GROUP_COLOR");
2193       aCriteria[ SMESH::FT_EqualNodes         ] = tr("EQUAL_NODE");
2194       aCriteria[ SMESH::FT_ConnectedElements  ] = tr("CONNECTED_ELEMS");
2195       aCriteria[ SMESH::FT_NodeConnectivityNumber ] = tr("NODE_CONN_NUMBER");
2196     }
2197     return aCriteria;
2198   }
2199   else if (theType == SMESH::EDGE)
2200   {
2201     static QMap<int, QString> aCriteria;
2202     if (aCriteria.isEmpty())
2203     {
2204       aCriteria[ SMESH::FT_FreeBorders        ] = tr("FREE_BORDERS");
2205       aCriteria[ SMESH::FT_MultiConnection    ] = tr("MULTI_BORDERS");
2206       aCriteria[ SMESH::FT_Length             ] = tr("LENGTH");
2207       aCriteria[ SMESH::FT_RangeOfIds         ] = tr("RANGE_OF_IDS");
2208       aCriteria[ SMESH::FT_BelongToMeshGroup  ] = tr("BELONG_TO_MESH_GROUP");
2209       aCriteria[ SMESH::FT_BelongToGeom       ] = tr("BELONG_TO_GEOM");
2210       aCriteria[ SMESH::FT_BelongToPlane      ] = tr("BELONG_TO_PLANE");
2211       aCriteria[ SMESH::FT_BelongToCylinder   ] = tr("BELONG_TO_CYLINDER");
2212       aCriteria[ SMESH::FT_BelongToGenSurface ] = tr("BELONG_TO_GENSURFACE");
2213       aCriteria[ SMESH::FT_LyingOnGeom        ] = tr("LYING_ON_GEOM");
2214       aCriteria[ SMESH::FT_LinearOrQuadratic  ] = tr("LINEAR");
2215       aCriteria[ SMESH::FT_GroupColor         ] = tr("GROUP_COLOR");
2216       aCriteria[ SMESH::FT_ElemGeomType       ] = tr("GEOM_TYPE");
2217       aCriteria[ SMESH::FT_EqualEdges         ] = tr("EQUAL_EDGE");
2218       aCriteria[ SMESH::FT_EntityType         ] = tr("ENTITY_TYPE");
2219       aCriteria[ SMESH::FT_ConnectedElements  ] = tr("CONNECTED_ELEMS");
2220     }
2221     return aCriteria;
2222   }
2223   else if (theType == SMESH::FACE)
2224   {
2225     static QMap<int, QString> aCriteria;
2226     if (aCriteria.isEmpty())
2227     {
2228       aCriteria[ SMESH::FT_AspectRatio        ] = tr("ASPECT_RATIO");
2229       aCriteria[ SMESH::FT_Warping            ] = tr("WARPING");
2230       aCriteria[ SMESH::FT_MinimumAngle       ] = tr("MINIMUM_ANGLE");
2231       aCriteria[ SMESH::FT_Taper              ] = tr("TAPER");
2232       aCriteria[ SMESH::FT_Skew               ] = tr("SKEW");
2233       aCriteria[ SMESH::FT_Area               ] = tr("AREA");
2234       aCriteria[ SMESH::FT_MaxElementLength2D ] = tr("MAX_ELEMENT_LENGTH_2D");
2235       aCriteria[ SMESH::FT_FreeEdges          ] = tr("FREE_EDGES");
2236       aCriteria[ SMESH::FT_RangeOfIds         ] = tr("RANGE_OF_IDS");
2237       aCriteria[ SMESH::FT_BelongToMeshGroup  ] = tr("BELONG_TO_MESH_GROUP");
2238       aCriteria[ SMESH::FT_BelongToGeom       ] = tr("BELONG_TO_GEOM");
2239       aCriteria[ SMESH::FT_BelongToPlane      ] = tr("BELONG_TO_PLANE");
2240       aCriteria[ SMESH::FT_BelongToCylinder   ] = tr("BELONG_TO_CYLINDER");
2241       aCriteria[ SMESH::FT_BelongToGenSurface ] = tr("BELONG_TO_GENSURFACE");
2242       aCriteria[ SMESH::FT_LyingOnGeom        ] = tr("LYING_ON_GEOM");
2243       aCriteria[ SMESH::FT_Length2D           ] = tr("LENGTH2D");
2244       aCriteria[ SMESH::FT_MultiConnection2D  ] = tr("MULTI2D_BORDERS");
2245       aCriteria[ SMESH::FT_FreeFaces          ] = tr("FREE_FACES");
2246       aCriteria[ SMESH::FT_BareBorderFace     ] = tr("BARE_BORDER_FACE");
2247       aCriteria[ SMESH::FT_OverConstrainedFace] = tr("OVER_CONSTRAINED_FACE");
2248       aCriteria[ SMESH::FT_LinearOrQuadratic  ] = tr("LINEAR");
2249       aCriteria[ SMESH::FT_GroupColor         ] = tr("GROUP_COLOR");
2250       aCriteria[ SMESH::FT_ElemGeomType       ] = tr("GEOM_TYPE");
2251       aCriteria[ SMESH::FT_CoplanarFaces      ] = tr("COPLANAR_FACES");
2252       aCriteria[ SMESH::FT_EqualFaces         ] = tr("EQUAL_FACE");
2253       aCriteria[ SMESH::FT_EntityType         ] = tr("ENTITY_TYPE");
2254       aCriteria[ SMESH::FT_ConnectedElements  ] = tr("CONNECTED_ELEMS");
2255     }
2256     return aCriteria;
2257   }
2258   else if (theType == SMESH::VOLUME)
2259   {
2260     static QMap<int, QString> aCriteria;
2261     if (aCriteria.isEmpty())
2262     {
2263       aCriteria[ SMESH::FT_AspectRatio3D        ] = tr("ASPECT_RATIO_3D");
2264       aCriteria[ SMESH::FT_RangeOfIds           ] = tr("RANGE_OF_IDS");
2265       aCriteria[ SMESH::FT_BelongToMeshGroup    ] = tr("BELONG_TO_MESH_GROUP");
2266       aCriteria[ SMESH::FT_BelongToGeom         ] = tr("BELONG_TO_GEOM");
2267       aCriteria[ SMESH::FT_LyingOnGeom          ] = tr("LYING_ON_GEOM");
2268       aCriteria[ SMESH::FT_BadOrientedVolume    ] = tr("BAD_ORIENTED_VOLUME");
2269       aCriteria[ SMESH::FT_BareBorderVolume     ] = tr("BARE_BORDER_VOLUME");
2270       aCriteria[ SMESH::FT_OverConstrainedVolume] = tr("OVER_CONSTRAINED_VOLUME");
2271       aCriteria[ SMESH::FT_Volume3D             ] = tr("VOLUME_3D");
2272       aCriteria[ SMESH::FT_MaxElementLength3D   ] = tr("MAX_ELEMENT_LENGTH_3D");
2273       aCriteria[ SMESH::FT_LinearOrQuadratic    ] = tr("LINEAR");
2274       aCriteria[ SMESH::FT_GroupColor           ] = tr("GROUP_COLOR");
2275       aCriteria[ SMESH::FT_ElemGeomType         ] = tr("GEOM_TYPE");
2276       aCriteria[ SMESH::FT_EqualVolumes         ] = tr("EQUAL_VOLUME");
2277       aCriteria[ SMESH::FT_EntityType           ] = tr("ENTITY_TYPE");
2278       aCriteria[ SMESH::FT_ConnectedElements    ] = tr("CONNECTED_ELEMS");
2279     }
2280     return aCriteria;
2281   }
2282   else if (theType == SMESH::ELEM0D)
2283   {
2284     static QMap<int, QString> aCriteria;
2285     if (aCriteria.isEmpty())
2286     {
2287       aCriteria[ SMESH::FT_RangeOfIds         ] = tr("RANGE_OF_IDS");
2288       aCriteria[ SMESH::FT_BelongToMeshGroup  ] = tr("BELONG_TO_MESH_GROUP");
2289       aCriteria[ SMESH::FT_BelongToGeom       ] = tr("BELONG_TO_GEOM");
2290       aCriteria[ SMESH::FT_BelongToPlane      ] = tr("BELONG_TO_PLANE");
2291       aCriteria[ SMESH::FT_BelongToCylinder   ] = tr("BELONG_TO_CYLINDER");
2292       aCriteria[ SMESH::FT_BelongToGenSurface ] = tr("BELONG_TO_GENSURFACE");
2293       aCriteria[ SMESH::FT_GroupColor         ] = tr("GROUP_COLOR");
2294       aCriteria[ SMESH::FT_ConnectedElements  ] = tr("CONNECTED_ELEMS");
2295     }
2296     return aCriteria;
2297   }
2298   else if (theType == SMESH::BALL)
2299   {
2300     static QMap<int, QString> aCriteria;
2301     if (aCriteria.isEmpty())
2302     {
2303       aCriteria[ SMESH::FT_BallDiameter       ] = tr("BALL_DIAMETER");
2304       aCriteria[ SMESH::FT_RangeOfIds         ] = tr("RANGE_OF_IDS");
2305       aCriteria[ SMESH::FT_BelongToMeshGroup  ] = tr("BELONG_TO_MESH_GROUP");
2306       aCriteria[ SMESH::FT_BelongToGeom       ] = tr("BELONG_TO_GEOM");
2307       aCriteria[ SMESH::FT_BelongToPlane      ] = tr("BELONG_TO_PLANE");
2308       aCriteria[ SMESH::FT_BelongToCylinder   ] = tr("BELONG_TO_CYLINDER");
2309       aCriteria[ SMESH::FT_BelongToGenSurface ] = tr("BELONG_TO_GENSURFACE");
2310       aCriteria[ SMESH::FT_GroupColor         ] = tr("GROUP_COLOR");
2311       aCriteria[ SMESH::FT_ConnectedElements  ] = tr("CONNECTED_ELEMS");
2312     }
2313     return aCriteria;
2314   }
2315   else if (theType == SMESH::ELEM0D)
2316   {
2317     static QMap<int, QString> aCriteria;
2318     if (aCriteria.isEmpty())
2319     {
2320       aCriteria[ SMESH::FT_RangeOfIds         ] = tr("RANGE_OF_IDS");
2321       aCriteria[ SMESH::FT_BelongToMeshGroup  ] = tr("BELONG_TO_MESH_GROUP");
2322       aCriteria[ SMESH::FT_BelongToGeom       ] = tr("BELONG_TO_GEOM");
2323       aCriteria[ SMESH::FT_BelongToPlane      ] = tr("BELONG_TO_PLANE");
2324       aCriteria[ SMESH::FT_BelongToCylinder   ] = tr("BELONG_TO_CYLINDER");
2325       aCriteria[ SMESH::FT_BelongToGenSurface ] = tr("BELONG_TO_GENSURFACE");
2326       aCriteria[ SMESH::FT_GroupColor         ] = tr("GROUP_COLOR");
2327       aCriteria[ SMESH::FT_ConnectedElements  ] = tr("CONNECTED_ELEMS");
2328     }
2329     return aCriteria;
2330   }
2331   else // SMESH::ALL
2332   {
2333     static QMap<int, QString> aCriteria;
2334     if (aCriteria.isEmpty())
2335     {
2336       aCriteria[ SMESH::FT_RangeOfIds         ] = tr("RANGE_OF_IDS");
2337       aCriteria[ SMESH::FT_BelongToMeshGroup  ] = tr("BELONG_TO_MESH_GROUP");
2338       aCriteria[ SMESH::FT_BelongToGeom       ] = tr("BELONG_TO_GEOM");
2339       aCriteria[ SMESH::FT_LyingOnGeom        ] = tr("LYING_ON_GEOM");
2340       aCriteria[ SMESH::FT_LinearOrQuadratic  ] = tr("LINEAR");
2341       aCriteria[ SMESH::FT_GroupColor         ] = tr("GROUP_COLOR");
2342       aCriteria[ SMESH::FT_ElemGeomType       ] = tr("GEOM_TYPE");
2343       aCriteria[ SMESH::FT_ConnectedElements  ] = tr("CONNECTED_ELEMS");
2344     }
2345
2346     return aCriteria;
2347   }
2348 }
2349
2350
2351 //=======================================================================
2352 // name    : SMESHGUI_FilterTable::getCompare
2353 // Purpose : Get operation of comparison
2354 //=======================================================================
2355 const QMap<int, QString>& SMESHGUI_FilterTable::getCompare() const
2356 {
2357   static QMap<int, QString> aMap;
2358
2359   if (aMap.isEmpty())
2360   {
2361     aMap[ SMESH::FT_LessThan ] = tr("LESS_THAN");
2362     aMap[ SMESH::FT_MoreThan ] = tr("MORE_THAN");
2363     aMap[ SMESH::FT_EqualTo  ] = tr("EQUAL_TO" );
2364   }
2365
2366   return aMap;
2367 }
2368
2369 //=======================================================================
2370 // name    : SMESHGUI_FilterTable::createTable
2371 // Purpose : Create table
2372 //=======================================================================
2373 SMESHGUI_FilterTable::Table* SMESHGUI_FilterTable::createTable (QWidget*  theParent,
2374                                                                 const int theType)
2375 {
2376   // create table
2377   Table* aTable= new Table(0, 6, theParent);
2378
2379   QHeaderView* aHeaders = aTable->horizontalHeader();
2380
2381   QFontMetrics aMetrics(aHeaders->font());
2382
2383   // append spaces to the header of criteria in order to
2384   // provide visibility of criterion inside comboboxes
2385   static int aMaxLenCr = 0;
2386
2387   if (aMaxLenCr == 0)
2388   {
2389     const QMap<int, QString>& aSupportedTypes = getSupportedTypes();
2390     QMap<int, QString>::const_iterator anIter;
2391     for (anIter = aSupportedTypes.begin(); anIter != aSupportedTypes.end(); ++anIter)
2392       aMaxLenCr = qMax(maxLength(getCriteria(anIter.key()), aMetrics), aMaxLenCr);
2393   }
2394
2395   static int aLenCr = qAbs( aMaxLenCr -
2396                             aMetrics.width(tr("CRITERION"))) / aMetrics.width(' ') + 5;
2397
2398   QString aCrStr;
2399   aCrStr.fill(' ', aLenCr);
2400   QString aCoStr;
2401   aCoStr.fill(' ', 10);
2402
2403   QStringList aHeaderLabels;
2404   aHeaderLabels.append( tr("CRITERION") + aCrStr );
2405   aHeaderLabels.append( tr("COMPARE")   + aCoStr );
2406   aHeaderLabels.append( tr("THRESHOLD_VALUE") );
2407   aHeaderLabels.append( tr("UNARY") );
2408   aHeaderLabels.append( tr("BINARY") + "  " );
2409   aHeaderLabels.append( tr("ID") );
2410   aTable->setHorizontalHeaderLabels( aHeaderLabels );
2411   
2412   // set geometry of the table
2413   for (int i = 0; i <= 4; i++)
2414     aTable->resizeColumnToContents(i);
2415
2416   // set the ID column invisible
2417   aTable->hideColumn( 5 );
2418
2419   aTable->updateGeometry();
2420   QSize aSize = aTable->sizeHint();
2421   int aWidth = aSize.width();
2422   aTable->setMinimumSize(QSize(aWidth, aWidth / 2));
2423   aTable->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));
2424
2425   connect(aTable, SIGNAL(cellChanged(int, int)),
2426           this,   SLOT(onCriterionChanged(int, int)));
2427
2428   connect(aTable, SIGNAL(currentCellChanged(int, int, int, int)),
2429           this,   SLOT(onCurrentChanged(int, int)));
2430   
2431   return aTable;
2432 }
2433
2434 //=======================================================================
2435 // name    : SMESHGUI_FilterTable::updateBtnState
2436 // Purpose : Update button state
2437 //=======================================================================
2438 void SMESHGUI_FilterTable::updateBtnState()
2439 {
2440   myRemoveBtn->setEnabled(myTables[ GetType() ]->rowCount() > 0);
2441   myClearBtn->setEnabled(myTables[ GetType() ]->rowCount() > 0);
2442 }
2443
2444 //=======================================================================
2445 // name    : SMESHGUI_FilterTable::SetEditable
2446 // Purpose : Set read only flag for tables. Show/hide buttons for work with rows
2447 //=======================================================================
2448 void SMESHGUI_FilterTable::SetEditable (const bool isEditable)
2449 {
2450   TableMap::iterator anIter;
2451   for (anIter = myTables.begin(); anIter != myTables.end(); ++anIter)
2452   {
2453     anIter.value()->setReadOnly(!isEditable);
2454
2455     // Set Flags for CheckItems directly IPAL 19974
2456     Table* aTable = anIter.value();
2457     for (int i = 0, n = aTable->rowCount(); i < n; i++)
2458       for (int j = 0, m = aTable->columnCount(); j < m; j++)
2459         {
2460           QTableWidgetItem* anItem = aTable->item(i, j);
2461           if ( dynamic_cast<SMESHGUI_FilterTable::CheckItem*>( anItem ) ) {
2462             Qt::ItemFlags f = anItem->flags();
2463             if (!isEditable) f = f & ~Qt::ItemIsUserCheckable;
2464             else f = f | Qt::ItemIsUserCheckable;
2465             anItem->setFlags( f );
2466           }
2467         }
2468     //end of IPAL19974
2469
2470     if (isEditable)
2471     {
2472       myAddBtn->show();
2473       myInsertBtn->show();
2474       myRemoveBtn->show();
2475       myClearBtn->show();
2476     }
2477     else
2478     {
2479       myAddBtn->hide();
2480       myInsertBtn->hide();
2481       myRemoveBtn->hide();
2482       myClearBtn->hide();
2483     }
2484   }
2485
2486   QMap<QTableWidgetItem*, AdditionalWidget*>::iterator anIter2;
2487   for (anIter2 = myAddWidgets.begin(); anIter2 != myAddWidgets.end(); ++anIter2)
2488     anIter2.value()->SetEditable(isEditable);
2489 }
2490
2491 //=======================================================================
2492 // name    : SMESHGUI_FilterTable::SetEnabled
2493 // Purpose : Enable/Disable table. Switching type of elements already enabled
2494 //=======================================================================
2495 void SMESHGUI_FilterTable::SetEnabled (const bool isEnabled)
2496 {
2497   myAddBtn->setEnabled(isEnabled);
2498   myInsertBtn->setEnabled(isEnabled);
2499   myRemoveBtn->setEnabled(isEnabled);
2500   myClearBtn->setEnabled(isEnabled);
2501
2502   if (isEnabled)
2503     updateBtnState();
2504
2505   QMap<QTableWidgetItem*, AdditionalWidget*>::iterator anIter2;
2506   for (anIter2 = myAddWidgets.begin(); anIter2 != myAddWidgets.end(); ++anIter2)
2507     anIter2.value()->setEnabled(isEnabled);
2508 }
2509
2510 //=======================================================================
2511 // name    : SMESHGUI_FilterTable::IsEditable
2512 // Purpose : Verify whether table is editable
2513 //=======================================================================
2514 bool SMESHGUI_FilterTable::IsEditable() const
2515 {
2516   return !myTables[ GetType() ]->isReadOnly();
2517 }
2518
2519 //=======================================================================
2520 // name    : SMESHGUI_FilterTable::SetLibsEnabled
2521 // Purpose : Show/hide buttons for work with libraries
2522 //=======================================================================
2523 void SMESHGUI_FilterTable::SetLibsEnabled (const bool isEnabled)
2524 {
2525   if (isEnabled)
2526   {
2527     myCopyFromBtn->show();
2528     myAddToBtn->show();
2529   }
2530   else
2531   {
2532     myCopyFromBtn->hide();
2533     myAddToBtn->hide();
2534   }
2535 }
2536
2537 //=======================================================================
2538 // name    : SMESHGUI_FilterTable::onCopyFromBtn
2539 // Purpose : SLOT. Called the "Copy from ..." button clicked
2540 //           Display filter library dialog
2541 //=======================================================================
2542 void SMESHGUI_FilterTable::onCopyFromBtn()
2543 {
2544   if (myLibDlg == 0)
2545     myLibDlg = new SMESHGUI_FilterLibraryDlg(
2546       mySMESHGUI, this, GetType(), SMESHGUI_FilterLibraryDlg::COPY_FROM);
2547   else
2548     myLibDlg->Init(GetType(), SMESHGUI_FilterLibraryDlg::COPY_FROM);
2549
2550   if (myLibDlg->exec() == QDialog::Accepted)
2551   {
2552     Copy(myLibDlg->GetTable());
2553     Update();
2554   }
2555 }
2556
2557 //=======================================================================
2558 // name    : SMESHGUI_FilterTable::onAddToBtn
2559 // Purpose : SLOT. Called the "Add to ..." button clicked
2560 //           Display filter library dialog
2561 //=======================================================================
2562 void SMESHGUI_FilterTable::onAddToBtn()
2563 {
2564   if (!IsValid(true))
2565     return;
2566   if (myLibDlg == 0)
2567     myLibDlg = new SMESHGUI_FilterLibraryDlg(
2568       mySMESHGUI, this, GetType(), SMESHGUI_FilterLibraryDlg::ADD_TO);
2569   else
2570     myLibDlg->Init(GetType(), SMESHGUI_FilterLibraryDlg::ADD_TO);
2571
2572   myLibDlg->SetTable(this);
2573
2574   myLibDlg->exec();
2575 }
2576
2577 //=======================================================================
2578 // name    : SMESHGUI_FilterTable::Copy
2579 // Purpose : Initialise table with values of other table
2580 //=======================================================================
2581 void SMESHGUI_FilterTable::Copy (const SMESHGUI_FilterTable* theTable)
2582 {
2583   Clear();
2584
2585   for (int i = 0, n = theTable->NumRows(); i < n; i++)
2586   {
2587     SMESH::Filter::Criterion aCriterion = SMESHGUI_FilterDlg::createCriterion();
2588     theTable->GetCriterion(i, aCriterion);
2589     AddCriterion(aCriterion);
2590   }
2591 }
2592
2593 //=======================================================================
2594 // name    : SMESHGUI_FilterTable::CurrentCell
2595 // Purpose : Returns current cell
2596 //=======================================================================
2597 bool SMESHGUI_FilterTable::CurrentCell (int& theRow, int& theCol) const
2598 {
2599   theRow = myTables[ GetType() ]->currentRow();
2600   theCol = myTables[ GetType() ]->currentColumn();
2601   return theRow >= 0 && theCol >= 0;
2602 }
2603
2604 //=======================================================================
2605 // name    : SMESHGUI_FilterTable::SetText
2606 // Purpose : Set text and internal value in cell of threshold value
2607 //=======================================================================
2608 void SMESHGUI_FilterTable::SetThreshold (const int      theRow,
2609                                          const QString& theText,
2610                                          const int      theEntityType)
2611 {
2612   Table* aTable = myTables[ theEntityType == -1 ? GetType() : theEntityType ];
2613
2614   bool isSignalsBlocked = aTable->signalsBlocked();
2615   aTable->blockSignals(true);
2616   
2617   aTable->item( theRow, 2 )->setText(theText);
2618
2619   aTable->blockSignals(isSignalsBlocked);
2620 }
2621
2622 //=======================================================================
2623 // name    : SMESHGUI_FilterTable::SetText
2624 // Purpose : Get text and internal value from cell of threshold value
2625 //=======================================================================
2626 bool SMESHGUI_FilterTable::GetThreshold (const int      theRow,
2627                                          QString&       theText,
2628                                          const int      theEntityType)
2629 {
2630   Table* aTable = myTables[ theEntityType == -1 ? GetType() : theEntityType ];
2631   QTableWidgetItem* anItem = aTable->item(theRow, 2);
2632   if (anItem != 0)
2633   {
2634     theText = anItem->text();
2635     return true;
2636   }
2637   else
2638    return false;
2639 }
2640
2641 //=======================================================================
2642 // name    : SMESHGUI_FilterTable::SetID
2643 // Purpose : Set text and internal value in cell of ID value 
2644 //=======================================================================
2645 void SMESHGUI_FilterTable::SetID( const int      theRow,
2646                                   const QString& theText,
2647                                   const int      theEntityType )
2648 {
2649   Table* aTable = myTables[ theEntityType == -1 ? GetType() : theEntityType ];
2650   aTable->item( theRow, 5 )->setText( theText );
2651 }
2652
2653 //=======================================================================
2654 // name    : SMESHGUI_FilterTable::GetID
2655 // Purpose : Get text and internal value from cell of ID value
2656 //=======================================================================
2657 bool SMESHGUI_FilterTable::GetID( const int      theRow,
2658                                   QString&       theText,
2659                                   const int      theEntityType )
2660 {
2661   Table* aTable = myTables[ theEntityType == -1 ? GetType() : theEntityType ];
2662   QTableWidgetItem* anItem = aTable->item( theRow, 5 );
2663   if ( anItem != 0 )
2664     {
2665       theText = anItem->text();
2666       return true;    
2667     }
2668   else
2669     return false;
2670
2671
2672 /*
2673   Class       : SMESHGUI_FilterDlg
2674   Description : Dialog to specify filters for VTK viewer
2675 */
2676
2677
2678 //=======================================================================
2679 // name    : SMESHGUI_FilterDlg::SMESHGUI_FilterDlg
2680 // Purpose : Constructor
2681 //=======================================================================
2682 SMESHGUI_FilterDlg::SMESHGUI_FilterDlg( SMESHGUI*         theModule,
2683                                         const QList<int>& theTypes )
2684 : QDialog( SMESH::GetDesktop( theModule ) ),
2685   mySMESHGUI( theModule ),
2686   mySelectionMgr( SMESH::GetSelectionMgr( theModule ) ),
2687   myInitSourceWgOnApply( true ),
2688   myInsertEnabled( true ),
2689   myDiffSourcesEnabled( true )
2690 {
2691   if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
2692     mySelector = aViewWindow->GetSelector();
2693
2694   construct(theTypes);
2695 }
2696
2697 //=======================================================================
2698 // name    : SMESHGUI_FilterDlg::SMESHGUI_FilterDlg
2699 // Purpose : Constructor
2700 //=======================================================================
2701 SMESHGUI_FilterDlg::SMESHGUI_FilterDlg( SMESHGUI*   theModule,
2702                                         const int   theType )
2703 : QDialog( SMESH::GetDesktop( theModule ) ),
2704   mySMESHGUI( theModule ),
2705   mySelectionMgr( SMESH::GetSelectionMgr( theModule ) ),
2706   myInitSourceWgOnApply( true ),
2707   myInsertEnabled( true ),
2708   myDiffSourcesEnabled( true )
2709 {
2710   if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
2711     mySelector = aViewWindow->GetSelector();
2712   QList<int> aTypes;
2713   aTypes.append(theType);
2714   construct(aTypes);
2715 }
2716
2717 //=======================================================================
2718 // name    : SMESHGUI_FilterDlg::construct
2719 // Purpose : Construct dialog (called by constructor)
2720 //=======================================================================
2721 void SMESHGUI_FilterDlg::construct (const QList<int>& theTypes)
2722 {
2723   myTypes = theTypes;
2724
2725   setModal(false);
2726   //setAttribute(Qt::WA_DeleteOnClose, true); // VSR ??? is it required?
2727   setWindowTitle(tr("CAPTION"));
2728
2729   QVBoxLayout* aDlgLay = new QVBoxLayout (this);
2730   aDlgLay->setMargin(MARGIN);
2731   aDlgLay->setSpacing(SPACING);
2732
2733   myMainFrame         = createMainFrame  (this);
2734   QWidget* aBtnFrame  = createButtonFrame(this);
2735
2736   aDlgLay->addWidget(myMainFrame);
2737   aDlgLay->addWidget(aBtnFrame);
2738
2739   aDlgLay->setStretchFactor(myMainFrame, 1);
2740
2741   myHelpFileName = "selection_filter_library_page.html";
2742
2743   Init(myTypes);
2744 }
2745
2746 //=======================================================================
2747 // name    : SMESHGUI_FilterDlg::createMainFrame
2748 // Purpose : Create frame containing dialog's input fields
2749 //=======================================================================
2750 QWidget* SMESHGUI_FilterDlg::createMainFrame (QWidget* theParent)
2751 {
2752   QWidget* aMainFrame = new QWidget(theParent);
2753   QVBoxLayout* aMainLay = new QVBoxLayout(aMainFrame);
2754   aMainLay->setMargin(0);
2755   aMainLay->setSpacing(SPACING);
2756
2757   // filter frame
2758
2759   myTable = new SMESHGUI_FilterTable( mySMESHGUI, aMainFrame, myTypes );
2760   myTable->SetLibsEnabled(true);
2761
2762   QGroupBox* aGrp = myTable->GetTableGrp();
2763   QGridLayout* aLay = qobject_cast<QGridLayout*>( aGrp->layout() );
2764   int rows = aLay->rowCount();
2765   int cols = aLay->columnCount();
2766
2767   // This line looks strange when all additional parameters and mySetInViewer are hidden
2768   QFrame* aLine = new QFrame(aGrp);
2769   aLine->setFrameStyle(QFrame::HLine | QFrame::Sunken);
2770   aLay->addWidget(aLine, rows++, 0, 1, cols);
2771
2772   mySetInViewer = new QCheckBox(tr("SET_IN_VIEWER"), aGrp);
2773   mySetInViewer->setChecked(true);
2774   aLay->addWidget(mySetInViewer, rows++, 0, 1, cols);
2775
2776   // other controls
2777   QWidget* aSourceGrp = createSourceGroup(aMainFrame);
2778
2779   connect(myTable, SIGNAL(CriterionChanged(const int, const int)),
2780                     SLOT(onCriterionChanged(const int, const int)));
2781
2782   connect(myTable, SIGNAL(CurrentChanged(int, int)),
2783                     SLOT(onCurrentChanged(int, int)));
2784
2785   aMainLay->addWidget(myTable);
2786   aMainLay->addWidget(aSourceGrp);
2787   
2788   return aMainFrame;
2789 }
2790
2791 //=======================================================================
2792 // name    : SMESHGUI_FilterDlg::createSourceFrame
2793 // Purpose : Create frame containing source radio button
2794 //=======================================================================
2795 QWidget* SMESHGUI_FilterDlg::createSourceGroup (QWidget* theParent)
2796 {
2797   QGroupBox* aBox = new QGroupBox(tr("SOURCE"), theParent);
2798   QHBoxLayout* aLay = new QHBoxLayout(aBox);
2799   aLay->setMargin(MARGIN);
2800   aLay->setSpacing(SPACING);
2801
2802   mySourceGrp = new QButtonGroup(theParent);
2803
2804   QRadioButton* aMeshBtn = new QRadioButton(tr("MESH"),          aBox);
2805   QRadioButton* aSelBtn  = new QRadioButton(tr("SELECTION"),     aBox);
2806   QRadioButton* aDlgBtn  = new QRadioButton(tr("CURRENT_DIALOG"),aBox);
2807
2808   aLay->addWidget(aMeshBtn);
2809   aLay->addWidget(aSelBtn);
2810   aLay->addWidget(aDlgBtn);
2811
2812   mySourceGrp->addButton(aMeshBtn, Mesh);
2813   mySourceGrp->addButton(aSelBtn,  Selection);
2814   mySourceGrp->addButton(aDlgBtn,  Dialog);
2815
2816   aMeshBtn->setChecked(true);
2817
2818   return aBox;
2819 }
2820
2821 //=======================================================================
2822 // name    : SMESHGUI_FilterDlg::updateMainButtons
2823 // Purpose : Update visibility of main buttons (OK, Cancel, Close ...)
2824 //=======================================================================
2825 void SMESHGUI_FilterDlg::updateMainButtons()
2826 {
2827   myButtons[ BTN_Close  ]->show();
2828   if (myTypes.count() == 1)
2829   {
2830     myButtons[ BTN_Apply  ]->hide();
2831   }
2832   else
2833   {
2834     myButtons[ BTN_Apply  ]->show();
2835   }
2836 //  updateGeometry();
2837 }
2838
2839 //=======================================================================
2840 // name    : SMESHGUI_FilterDlg::createButtonFrame
2841 // Purpose : Create frame containing buttons
2842 //=======================================================================
2843 QWidget* SMESHGUI_FilterDlg::createButtonFrame (QWidget* theParent)
2844 {
2845   QGroupBox* aGrp = new QGroupBox(theParent);
2846   QHBoxLayout* aLay = new QHBoxLayout(aGrp);
2847   aLay->setMargin(MARGIN);
2848   aLay->setSpacing(SPACING);
2849
2850   myButtons[ BTN_OK     ] = new QPushButton(tr("SMESH_BUT_APPLY_AND_CLOSE"), aGrp);
2851   myButtons[ BTN_Apply  ] = new QPushButton(tr("SMESH_BUT_APPLY"),           aGrp);
2852   myButtons[ BTN_Close  ] = new QPushButton(tr("SMESH_BUT_CLOSE"),           aGrp);
2853   myButtons[ BTN_Help   ] = new QPushButton(tr("SMESH_BUT_HELP"),            aGrp);
2854
2855   aLay->addWidget(myButtons[ BTN_OK     ]);
2856   aLay->addSpacing(10);
2857   aLay->addWidget(myButtons[ BTN_Apply  ]);
2858   aLay->addSpacing(10);
2859   aLay->addStretch();
2860   aLay->addWidget(myButtons[ BTN_Close  ]);
2861   aLay->addWidget(myButtons[ BTN_Help   ]);
2862
2863   connect(myButtons[ BTN_OK     ], SIGNAL(clicked()), SLOT(onOk()));
2864   connect(myButtons[ BTN_Close  ], SIGNAL(clicked()), SLOT(reject()));
2865   connect(myButtons[ BTN_Apply  ], SIGNAL(clicked()), SLOT(onApply()));
2866   connect(myButtons[ BTN_Help   ], SIGNAL(clicked()), SLOT(onHelp()));
2867
2868   updateMainButtons();
2869
2870   return aGrp;
2871 }
2872
2873 //=======================================================================
2874 // name    : SMESHGUI_FilterDlg::~SMESHGUI_FilterDlg
2875 // Purpose : Destructor
2876 //=======================================================================
2877 SMESHGUI_FilterDlg::~SMESHGUI_FilterDlg()
2878 {
2879 }
2880
2881 //=======================================================================
2882 // name    : SMESHGUI_FilterDlg::Init
2883 // Purpose : Init dialog fields, connect signals and slots, show dialog
2884 //=======================================================================
2885 void SMESHGUI_FilterDlg::Init (const int type, const bool setInViewer)
2886 {
2887   QList<int> aTypes;
2888   aTypes.append(type);
2889   Init(aTypes,setInViewer);
2890 }
2891
2892 //=======================================================================
2893 // name    : SMESHGUI_FilterDlg::Init
2894 // Purpose : Init dialog fields, connect signals and slots, show dialog
2895 //=======================================================================
2896 void SMESHGUI_FilterDlg::Init (const QList<int>& theTypes, const bool setInViewer)
2897 {
2898   if ( theTypes.empty() )
2899   {
2900     Init( SMESH::ALL, setInViewer );
2901     return;
2902   }
2903   mySourceWg  = 0;
2904   myTypes     = theTypes;
2905   myMesh      = SMESH::SMESH_Mesh::_nil();
2906   myGroup     = SMESH::SMESH_GroupOnFilter::_nil();
2907   myIObjects.Clear();
2908   myIsSelectionChanged = false;
2909   myToRestoreSelMode = false;
2910
2911   myTable->Init(theTypes);
2912
2913   // set caption
2914   if (theTypes.count() == 1)
2915   {
2916     int aType = theTypes.first();
2917     if      (aType == SMESH::NODE  ) setWindowTitle(tr("NODES_TLT"));
2918     else if (aType == SMESH::ELEM0D) setWindowTitle(tr("ELEM0D_TLT"));
2919     else if (aType == SMESH::BALL  ) setWindowTitle(tr("BALL_TLT"));
2920     else if (aType == SMESH::EDGE  ) setWindowTitle(tr("EDGES_TLT"));
2921     else if (aType == SMESH::FACE  ) setWindowTitle(tr("FACES_TLT"));
2922     else if (aType == SMESH::VOLUME) setWindowTitle(tr("VOLUMES_TLT"));
2923     else if (aType == SMESH::ALL)    setWindowTitle(tr("TLT"));
2924   }
2925   else
2926     setWindowTitle(tr("TLT"));
2927
2928   qApp->processEvents();
2929   updateGeometry();
2930   adjustSize();
2931   setEnabled(true);
2932
2933   mySMESHGUI->SetActiveDialogBox((QDialog*)this);
2934
2935   connect(mySMESHGUI, SIGNAL(SignalDeactivateActiveDialog()), SLOT(onDeactivate()));
2936   connect(mySMESHGUI, SIGNAL(SignalCloseAllDialogs()), SLOT(reject()));
2937   connect(mySMESHGUI, SIGNAL(SignalActivatedViewManager()), SLOT(onOpenView()));
2938   connect(mySMESHGUI, SIGNAL(SignalCloseView()), SLOT(onCloseView()));
2939   
2940   updateMainButtons();
2941   updateSelection();
2942
2943   // Initialise filter table with values of previous filter
2944   QList<int>::const_iterator anIter;
2945   for (anIter = theTypes.begin(); anIter != theTypes.end(); ++anIter)
2946   {
2947     myTable->Clear(*anIter);
2948     if (!myFilter[ *anIter ]->_is_nil())
2949     {
2950       SMESH::Filter::Criteria_var aCriteria = new SMESH::Filter::Criteria;
2951       if (myFilter[ *anIter ]->GetCriteria(aCriteria))
2952       {
2953         for (int i = 0, n = aCriteria->length(); i < n; i++)
2954           myTable->AddCriterion(aCriteria[ i ], *anIter);
2955       }
2956     }
2957   }
2958
2959   if (myInsertState.contains(theTypes.first()))
2960     mySetInViewer->setChecked(myInsertState[ theTypes.first() ]);
2961   else
2962     mySetInViewer->setChecked(setInViewer);
2963
2964   mySourceGrp->button(myApplyToState.contains(theTypes.first()) ? 
2965                       myApplyToState[ theTypes.first() ] :
2966                       Mesh)->setChecked(true);
2967 }
2968
2969 //=======================================================================
2970 // name    : SMESHGUI_FilterDlg::onOk
2971 // Purpose : SLOT called when "Ok" button pressed.
2972 //           Assign filters VTK viewer and close dialog
2973 //=======================================================================
2974 void SMESHGUI_FilterDlg::onOk()
2975 {
2976   if (onApply())
2977   {
2978     restoreSelMode();
2979     mySelectionMgr->clearFilters();
2980     disconnect(mySMESHGUI, 0, this, 0);
2981     disconnect(mySelectionMgr, 0, this, 0);
2982     mySMESHGUI->ResetState();
2983     accept();
2984     emit Accepted();
2985   }
2986 }
2987
2988 //=======================================================================
2989 // name    : SMESHGUI_FilterDlg::reject
2990 // Purpose : SLOT called when "Close" button pressed. Close dialog
2991 //=======================================================================
2992 void SMESHGUI_FilterDlg::reject()
2993 {
2994   restoreSelMode();
2995   // Restore previously selected object
2996   if (mySelectionMgr)
2997   {
2998     SALOME_ListIO aList;
2999     mySelectionMgr->clearFilters();
3000     mySelectionMgr->clearSelected();
3001     SALOME_DataMapIteratorOfDataMapOfIOMapOfInteger anIter (myIObjects);
3002     for ( ; anIter.More(); anIter.Next())
3003     {
3004       aList.Append(anIter.Key());
3005
3006       TColStd_MapOfInteger aResMap;
3007       const TColStd_IndexedMapOfInteger& anIndMap = anIter.Value();
3008       for (int i = 1, n = anIndMap.Extent(); i <= n; i++)
3009         aResMap.Add(anIndMap(i));
3010
3011       mySelector->AddOrRemoveIndex( anIter.Key(), aResMap, false);
3012       if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
3013         aViewWindow->highlight( anIter.Key(), true, true );
3014     }
3015     mySelectionMgr->setSelectedObjects(aList, false);
3016   }
3017
3018   disconnect(mySMESHGUI, 0, this, 0);
3019   disconnect(mySelectionMgr, 0, this, 0);
3020   mySMESHGUI->ResetState();
3021   QDialog::reject();
3022 }
3023
3024 //=================================================================================
3025 // function : onOpenView()
3026 // purpose  :
3027 //=================================================================================
3028 void SMESHGUI_FilterDlg::onOpenView()
3029 {
3030   if ( mySelector ) {
3031     SMESH::SetPointRepresentation(false);
3032   }
3033   else {
3034     mySelector = SMESH::GetViewWindow( mySMESHGUI )->GetSelector();
3035   }
3036 }
3037
3038 //=================================================================================
3039 // function : onCloseView()
3040 // purpose  :
3041 //=================================================================================
3042 void SMESHGUI_FilterDlg::onCloseView()
3043 {
3044   mySelector = 0;
3045 }
3046
3047 //=================================================================================
3048 // function : onHelp()
3049 // purpose  :
3050 //=================================================================================
3051 void SMESHGUI_FilterDlg::onHelp()
3052 {
3053   LightApp_Application* app = (LightApp_Application*)(SUIT_Session::session()->activeApplication());
3054   if (app) 
3055     app->onHelpContextModule(mySMESHGUI ? app->moduleName(mySMESHGUI->moduleName()) : QString(""), myHelpFileName);
3056   else {
3057     QString platform;
3058 #ifdef WIN32
3059     platform = "winapplication";
3060 #else
3061     platform = "application";
3062 #endif
3063     SUIT_MessageBox::warning(this, tr("WRN_WARNING"),
3064                              tr("EXTERNAL_BROWSER_CANNOT_SHOW_PAGE").
3065                              arg(app->resourceMgr()->stringValue("ExternalBrowser", 
3066                                                                  platform)).
3067                              arg(myHelpFileName));
3068   }
3069 }
3070
3071 //=======================================================================
3072 // name    : SMESHGUI_FilterDlg::onDeactivate
3073 // Purpose : SLOT called when dialog must be deativated
3074 //=======================================================================
3075 void SMESHGUI_FilterDlg::onDeactivate()
3076 {
3077   setEnabled(false);
3078 }
3079
3080 //=======================================================================
3081 // name    : SMESHGUI_FilterDlg::enterEvent
3082 // Purpose : Event filter
3083 //=======================================================================
3084 void SMESHGUI_FilterDlg::enterEvent (QEvent*)
3085 {
3086 //  mySMESHGUI->EmitSignalDeactivateDialog();
3087   mySMESHGUI->SetActiveDialogBox((QDialog*)this);
3088   mySMESHGUI->ResetState();
3089   setEnabled(true);
3090 }
3091
3092 //=======================================================================
3093 // name    : SMESHGUI_FilterDlg::getIdsFromWg
3094 // Purpose : Retrieve list of ids from given widget
3095 //=======================================================================
3096 void SMESHGUI_FilterDlg::getIdsFromWg (const QWidget* theWg, QList<int>& theRes) const
3097 {
3098   theRes.clear();
3099   if (theWg == 0)
3100     return;
3101
3102   if (theWg->inherits("QListWidget"))
3103   {
3104     const QListWidget* aListBox = qobject_cast<const QListWidget*>( theWg );
3105     bool b;
3106     for (int i = 0, n = aListBox->count(); i < n; i++)
3107     {
3108       int anId = aListBox->item(i)->text().toInt(&b);
3109       if (b)
3110         theRes.append(anId);
3111     }
3112   }
3113   else if (theWg->inherits("QLineEdit"))
3114   {
3115     const QLineEdit* aLineEdit = qobject_cast<const QLineEdit*>( theWg );
3116     QString aStr = aLineEdit->text();
3117     QRegExp aRegExp("(\\d+)");
3118     bool b;
3119     int aPos = 0;
3120     while (aPos >= 0)
3121     {
3122       aPos = aRegExp.indexIn(aStr, aPos);
3123       if (aPos > -1)
3124       {
3125         int anId = aRegExp.cap(1).toInt(&b);
3126         if (b)
3127           theRes.append(anId);
3128         aPos += aRegExp.matchedLength();
3129       }
3130     }
3131   }
3132 }
3133
3134 //=======================================================================
3135 // name    : SMESHGUI_FilterDlg::getSelMode
3136 // Purpose : Get selection mode of specified type
3137 //=======================================================================
3138 Selection_Mode SMESHGUI_FilterDlg::getSelMode (const int theType) const
3139 {
3140   switch (theType)
3141   {
3142     case SMESH::NODE   : return NodeSelection;
3143     case SMESH::ELEM0D : return Elem0DSelection;
3144     case SMESH::BALL   : return BallSelection;
3145     case SMESH::EDGE   : return EdgeSelection;
3146     case SMESH::FACE   : return FaceSelection;
3147     case SMESH::VOLUME : return VolumeSelection;
3148     case SMESH::ALL    : return CellSelection;
3149     default            : return ActorSelection;
3150   }
3151
3152 }
3153
3154 //=======================================================================
3155 // name    : SMESHGUI_FilterDlg::setIdsToWg
3156 // Purpose : Insert identifiers in specified widgets
3157 //=======================================================================
3158 void SMESHGUI_FilterDlg::setIdsToWg (QWidget* theWg, const QList<int>& theIds)
3159 {
3160   if (theWg == 0)
3161     return;
3162
3163   QStringList aStrList;
3164   foreach(int id, theIds)
3165     aStrList << QString::number(id);
3166
3167   if (theWg->inherits("QListWidget"))
3168   {
3169     qobject_cast<QListWidget*>(theWg)->clear();
3170     qobject_cast<QListWidget*>(theWg)->addItems(aStrList);
3171   }
3172   else if (theWg->inherits("QLineEdit"))
3173   {
3174     qobject_cast<QLineEdit*>( theWg )->setText(aStrList.join(" "));
3175   }
3176 }
3177
3178 //=======================================================================
3179 // name    : SMESHGUI_FilterDlg::isValid
3180 // Purpose : Verify validity of input data
3181 //=======================================================================
3182 bool SMESHGUI_FilterDlg::isValid() const
3183 {
3184   if (!myTable->IsValid())
3185     return false;
3186
3187   for (int i = 0, n = myTable->NumRows(); i < n; i++)
3188   {
3189     int aType = myTable->GetCriterionType(i);
3190     if (aType == SMESH::FT_BelongToGeom ||
3191         aType == SMESH::FT_BelongToPlane ||
3192         aType == SMESH::FT_BelongToCylinder ||
3193         aType == SMESH::FT_BelongToGenSurface ||
3194         aType == SMESH::FT_LyingOnGeom)
3195     {
3196       QString aName;
3197       myTable->GetThreshold(i, aName);
3198
3199       std::vector<_PTR(SObject)> aList =
3200         SMESH::GetActiveStudyDocument()->FindObjectByName(aName.toLatin1().constData(), "GEOM");
3201       if (aList.size() == 0) {
3202         SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
3203                                      tr("BAD_SHAPE_NAME").arg(aName));
3204         return false;
3205       }
3206
3207       if (aType == SMESH::FT_BelongToCylinder ||
3208           aType == SMESH::FT_BelongToPlane    ||
3209           aType == SMESH::FT_BelongToGenSurface ) {
3210         CORBA::Object_var     anObject = SMESH::SObjectToObject(aList[ 0 ]);
3211         GEOM::GEOM_Object_var aGeomObj = GEOM::GEOM_Object::_narrow(anObject);
3212         if (!aGeomObj->_is_nil()) {
3213           TopoDS_Shape aFace;
3214           if (!GEOMBase::GetShape(aGeomObj, aFace) ||
3215                aFace.IsNull() ||
3216                aFace.ShapeType() != TopAbs_FACE) {
3217             SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
3218                                          tr("SHAPE_IS_NOT_A_FACE").arg(aName));
3219             return false;
3220           }
3221
3222           Handle(Geom_Surface) aSurf = BRep_Tool::Surface(TopoDS::Face(aFace));
3223           if (aSurf.IsNull()) {
3224             SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
3225                                          tr("SHAPE_IS_NOT_A_FACE").arg(aName));
3226             return false;
3227           }
3228
3229           if (aType == SMESH::FT_BelongToPlane && !aSurf->IsKind(STANDARD_TYPE(Geom_Plane))) {
3230             SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
3231                                          tr("SHAPE_IS_NOT_A_PLANE").arg(aName));
3232             return false;
3233           }
3234
3235           if (aType == SMESH::FT_BelongToCylinder && !aSurf->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
3236             SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
3237                                          tr("SHAPE_IS_NOT_A_CYLINDER").arg(aName));
3238             return false;
3239           }
3240         }
3241       }
3242     }
3243     else if (aType == SMESH::FT_CoplanarFaces)
3244     {
3245       QString faceID;
3246       myTable->GetThreshold(i, faceID);
3247       if ( faceID.isEmpty() )
3248       {
3249         SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
3250                                      tr("FACE_ID_NOT_SELECTED"));
3251         return false;
3252       }
3253       if ( myMesh->_is_nil() )
3254       {
3255         SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
3256                                      tr("MESH_IS_NOT_SELECTED"));
3257         return false;
3258       }
3259       if ( myMesh->GetElementType( faceID.toLong(), /*iselem=*/true) != SMESH::FACE )
3260       {
3261         SUIT_MessageBox::information(SMESHGUI::desktop(), tr("SMESH_INSUFFICIENT_DATA"),
3262                                      tr("NOT_FACE_ID").arg(faceID));
3263         return false;
3264       }
3265     }
3266   }
3267
3268   return true;
3269 }
3270
3271 //=======================================================================
3272 // name    : SMESHGUI_FilterDlg::SetSourceWg
3273 // Purpose : Set widget of parent dialog containing ids to be filtered if
3274 //           user select corresponding source radio button
3275 //=======================================================================
3276 void SMESHGUI_FilterDlg::SetSourceWg (QWidget* theWg,
3277                                       const bool initOnApply)
3278 {
3279   mySourceWg = theWg;
3280   myInitSourceWgOnApply = initOnApply;
3281 }
3282
3283 //=======================================================================
3284 //function : EnableFiltering
3285 //purpose  : Enables "Insert filter in the viewer"
3286 //           and different "Source"s (Mesh, Initial Selection, Current Group)
3287 //=======================================================================
3288
3289 void SMESHGUI_FilterDlg::SetEnabled( bool setInViewer, bool diffSources )
3290 {
3291   myInsertEnabled = setInViewer;
3292   myDiffSourcesEnabled = diffSources;
3293
3294   mySetInViewer->setVisible( myInsertEnabled );
3295   mySourceGrp->button(0)->parentWidget()->setVisible( myDiffSourcesEnabled );
3296 }
3297
3298 //=======================================================================
3299 // name    : SMESHGUI_FilterDlg::SetMesh
3300 // Purpose : Set mesh
3301 //=======================================================================
3302 void SMESHGUI_FilterDlg::SetMesh (SMESH::SMESH_Mesh_var theMesh)
3303 {
3304   if ( !theMesh->_is_nil() ) {
3305     myMesh = theMesh;
3306     if ( !myFilter[ myTable->GetType() ]->_is_nil())
3307       myFilter[ myTable->GetType() ]->SetMesh( theMesh );
3308   }
3309   const bool isEnable = !(myMesh->_is_nil());
3310   myButtons[BTN_OK]->setEnabled(isEnable);
3311   myButtons[BTN_Apply]->setEnabled(isEnable);
3312 }
3313
3314 //=======================================================================
3315 // name    : SMESHGUI_FilterDlg::SetGroup
3316 // Purpose : Set a group being edited
3317 //=======================================================================
3318 void SMESHGUI_FilterDlg::SetGroup(SMESH::SMESH_GroupOnFilter_var group)
3319 {
3320   myGroup = group;
3321 }
3322
3323 //=======================================================================
3324 // name    : SMESHGUI_FilterDlg::SetSelection
3325 // Purpose : Get filtered ids
3326 //=======================================================================
3327 void SMESHGUI_FilterDlg::SetSelection()
3328 {
3329   if (mySelectionMgr)
3330     disconnect(mySelectionMgr, SIGNAL(currentSelectionChanged()), this, SLOT(onSelectionDone()));
3331
3332   if (mySelectionMgr) {
3333     myIObjects.Clear();
3334     const SALOME_ListIO& anObjs = mySelector->StoredIObjects(); 
3335     SALOME_ListIteratorOfListIO anIter (anObjs);
3336     for ( ; anIter.More(); anIter.Next()) {
3337       TColStd_IndexedMapOfInteger aMap;
3338       mySelector->GetIndex(anIter.Value(), aMap);
3339       myIObjects.Bind(anIter.Value(), aMap);
3340     }
3341
3342     connect(mySelectionMgr, SIGNAL(currentSelectionChanged()), SLOT(onSelectionDone()));
3343
3344     updateSelection();
3345   }
3346   else
3347     myIObjects.Clear();
3348 }
3349
3350 //=======================================================================
3351 // name    : SMESHGUI_FilterDlg::onApply
3352 // Purpose : SLOT called when "Apply" button pressed.
3353 //           Assign filters to VTK viewer
3354 //=======================================================================
3355 bool SMESHGUI_FilterDlg::onApply()
3356 {
3357   if (!isValid())
3358     return false;
3359
3360   SUIT_OverrideCursor wc;
3361   try {
3362     int aCurrType = myTable->GetType();
3363
3364     if (!createFilter(aCurrType))
3365       return false;
3366
3367     insertFilterInViewer();
3368
3369     if (!myFilter[ aCurrType ]->GetPredicate()->_is_nil()) {
3370       //
3371       bool toFilter = (( getActor() ) ||
3372                        ( myInitSourceWgOnApply && mySourceWg ) ||
3373                        ( mySourceGrp->checkedId() == Dialog && mySourceWg ));
3374       if ( toFilter ) {
3375         QList<int> aResultIds;
3376         filterSource(aCurrType, aResultIds);
3377         // select in viewer
3378         selectInViewer(aCurrType, aResultIds);
3379         // set ids to the dialog
3380         if ( myInitSourceWgOnApply || mySourceGrp->checkedId() == Dialog )
3381           setIdsToWg(mySourceWg, aResultIds);
3382       }
3383     }
3384
3385     myInsertState[ aCurrType ] = mySetInViewer->isChecked();
3386     myApplyToState[ aCurrType ] = mySourceGrp->checkedId();
3387   }
3388   catch(const SALOME::SALOME_Exception& S_ex)
3389   {
3390     SalomeApp_Tools::QtCatchCorbaException(S_ex);
3391     return false;
3392   }
3393   catch(...)
3394   {
3395     return false;
3396   }
3397
3398   return true;
3399 }
3400
3401 //=======================================================================
3402 // name    : SMESHGUI_FilterDlg::createFilter
3403 // Purpose : Create predicate for given type
3404 //=======================================================================
3405 bool SMESHGUI_FilterDlg::createFilter (const int theType)
3406 {
3407   SMESH::FilterManager_var aFilterMgr = SMESH::GetFilterManager();
3408   if (aFilterMgr->_is_nil())
3409     return false;
3410
3411   int n = myTable->NumRows();
3412
3413   SMESH::Filter::Criteria_var aCriteria = new SMESH::Filter::Criteria;
3414   aCriteria->length(n);
3415
3416   long aPrecision = -1;
3417   SUIT_ResourceMgr* mgr = SMESH::GetResourceMgr( mySMESHGUI );
3418
3419   if ( mgr && mgr->booleanValue( "SMESH", "use_precision", false ) )
3420     aPrecision = mgr->integerValue( "SMESH", "controls_precision", aPrecision );
3421
3422   for ( int i = 0; i < n; i++) {
3423     SMESH::Filter::Criterion aCriterion = createCriterion();
3424     myTable->GetCriterion(i, aCriterion);
3425     aCriterion.Precision = aPrecision;
3426     aCriteria[ i ] = aCriterion;
3427   }
3428
3429   if ( !myFilter[ theType ]->_is_nil() )
3430     myFilter[ theType ]->UnRegister();
3431   myFilter[ theType ] = aFilterMgr->CreateFilter();
3432   myFilter[ theType ]->SetCriteria(aCriteria.inout());
3433
3434   return true;
3435 }
3436
3437 //================================================================================
3438 /*!
3439  * \brief Return the current filter
3440  */
3441 //================================================================================
3442
3443 SMESH::Filter_var SMESHGUI_FilterDlg::GetFilter() const
3444 {
3445   SMESH::Filter_var filter;
3446   try {
3447     int aCurrType = myTable->GetType();
3448     filter = myFilter[ aCurrType ];
3449   }
3450   catch(...)
3451   {
3452   }
3453   return filter._retn();
3454 }
3455
3456 //================================================================================
3457 /*!
3458  * \brief Sets a filter to the table
3459  */
3460 //================================================================================
3461
3462 void SMESHGUI_FilterDlg::SetFilter(SMESH::Filter_var filter, int type)
3463 {
3464   if ( !filter->_is_nil() )
3465     filter->Register();
3466   if ( !myFilter[ type ]->_is_nil() )
3467     myFilter[ type ]->UnRegister();
3468
3469   myFilter[ type ] = filter;
3470 }
3471
3472 //================================================================================
3473 /*!
3474  * \brief call UnRegister() for myFilter's
3475  */
3476 //================================================================================
3477
3478 void SMESHGUI_FilterDlg::UnRegisterFilters()
3479 {
3480   QMap< int, SMESH::Filter_var >::iterator i_f = myFilter.begin();
3481   for ( ; i_f != myFilter.end(); ++i_f )
3482     if ( !i_f.value()->_is_nil() )
3483       i_f.value()->UnRegister();
3484   myFilter.clear();
3485 }
3486
3487 //=======================================================================
3488 // name    : SMESHGUI_FilterDlg::insertFilterInViewer
3489 // Purpose : Insert filter in viewer
3490 //=======================================================================
3491 void SMESHGUI_FilterDlg::insertFilterInViewer()
3492 {
3493   if (SVTK_Selector* aSelector = SMESH::GetSelector())
3494   {
3495     SMESH::ElementType anEntType = (SMESH::ElementType)myTable->GetType();
3496
3497     if (myFilter[ myTable->GetType() ]->_is_nil() ||
3498         myFilter[ myTable->GetType() ]->GetPredicate()->_is_nil() ||
3499         !mySetInViewer->isChecked() ||
3500         !myInsertEnabled )
3501     {
3502       SMESH::RemoveFilter(getFilterId(anEntType), aSelector);
3503     }
3504     else
3505     {
3506       Handle(SMESHGUI_PredicateFilter) aFilter = new SMESHGUI_PredicateFilter();
3507       aFilter->SetPredicate(myFilter[ myTable->GetType() ]->GetPredicate());
3508       SMESH::RemoveFilter(getFilterId(anEntType), aSelector); //skl for IPAL12631
3509       SMESH::SetFilter(aFilter, aSelector);
3510     }
3511   }
3512 }
3513
3514 //=======================================================================
3515 // name    : SMESHGUI_FilterDlg::filterSource
3516 // Purpose : Filter source ids
3517 //=======================================================================
3518 void SMESHGUI_FilterDlg::filterSource (const int theType,
3519                                        QList<int>& theResIds)
3520 {
3521   theResIds.clear();
3522   if (myFilter[ theType ]->_is_nil())
3523     return;
3524
3525   int aSourceId = mySourceGrp->checkedId();
3526
3527   if (aSourceId == Mesh || !myDiffSourcesEnabled )
3528   {
3529     if (myMesh->_is_nil())
3530       return;
3531     SMESH::long_array_var anIds = myFilter[ theType ]->GetElementsId(myMesh);
3532     for (int i = 0, n = anIds->length(); i < n; i++)
3533       theResIds.append(anIds[ i ]);
3534   }
3535   else if (aSourceId == Selection)
3536   {
3537     filterSelectionSource(theType, theResIds);
3538   }
3539   else if (aSourceId == Dialog)
3540   {
3541     // retrieve ids from dialog
3542     QList<int> aDialogIds;
3543     getIdsFromWg(mySourceWg, aDialogIds);
3544
3545     if (myMesh->_is_nil())
3546     {
3547       theResIds = aDialogIds;
3548       return;
3549     }
3550
3551     // filter ids
3552     SMESH::Predicate_ptr aPred = myFilter[ theType ]->GetPredicate();
3553     myFilter[ theType ]->SetMesh(myMesh);
3554     QList<int>::const_iterator anIter;
3555     for (anIter = aDialogIds.begin(); anIter != aDialogIds.end(); ++ anIter)
3556       if (aPred->IsSatisfy(*anIter))
3557         theResIds.append(*anIter);
3558   }
3559 }
3560
3561 //=======================================================================
3562 // name    : SMESHGUI_FilterDlg::filterSelectionSource
3563 // Purpose : Filter source selection
3564 //=======================================================================
3565 void SMESHGUI_FilterDlg::filterSelectionSource (const int theType,
3566                                                 QList<int>& theResIds)
3567 {
3568   theResIds.clear();
3569   if (myMesh->_is_nil() || mySelectionMgr == 0)
3570     return;
3571
3572   // Create map of entities to be filtered
3573   TColStd_MapOfInteger aToBeFiltered;
3574   SALOME_DataMapIteratorOfDataMapOfIOMapOfInteger anIter(myIObjects);
3575
3576   for ( ; anIter.More(); anIter.Next())
3577   {
3578     // process sub mesh
3579     SMESH::SMESH_subMesh_var aSubMesh = SMESH::IObjectToInterface<SMESH::SMESH_subMesh>(anIter.Key());
3580     if (!aSubMesh->_is_nil())
3581     {
3582       if (aSubMesh->GetFather()->GetId() == myMesh->GetId())
3583       {
3584         SMESH::long_array_var anIds =
3585           theType == SMESH::NODE ? aSubMesh->GetNodesId() : aSubMesh->GetElementsId();
3586         for (int i = 0, n = anIds->length(); i < n; i++)
3587           aToBeFiltered.Add(anIds[ i ]);
3588       }
3589     }
3590
3591     // process group
3592     SMESH::SMESH_GroupBase_var aGroup =
3593       SMESH::IObjectToInterface<SMESH::SMESH_GroupBase>(anIter.Key());
3594     if (!aGroup->_is_nil())
3595     {
3596       if (aGroup->GetType() == theType && aGroup->GetMesh()->GetId() == myMesh->GetId())
3597       {
3598         SMESH::long_array_var anIds = aGroup->GetListOfID();
3599         for (int i = 0, n = anIds->length(); i < n; i++)
3600           aToBeFiltered.Add(anIds[ i ]);
3601       }
3602     }
3603
3604     // process mesh
3605     SMESH::SMESH_Mesh_var aMeshPtr = SMESH::IObjectToInterface<SMESH::SMESH_Mesh>(anIter.Key());
3606     if (!aMeshPtr->_is_nil() && aMeshPtr->GetId() == myMesh->GetId())
3607     {
3608       const TColStd_IndexedMapOfInteger& aSelMap = anIter.Value();
3609
3610       if (aSelMap.Extent() > 0)
3611       {
3612         if(SMESH::FindActorByEntry(anIter.Key()->getEntry()))
3613         {
3614           for (int i = 1; i <= aSelMap.Extent(); i++)
3615             aToBeFiltered.Add(aSelMap(i));
3616         }
3617       }
3618     }
3619   }
3620
3621   // Filter entities
3622   SMESH::Predicate_ptr aPred = myFilter[ theType ]->GetPredicate();
3623   myFilter[ theType ]->SetMesh(myMesh);
3624   TColStd_MapIteratorOfMapOfInteger aResIter(aToBeFiltered);
3625   for ( ; aResIter.More(); aResIter.Next())
3626     if (aPred->IsSatisfy(aResIter.Key()))
3627       theResIds.append(aResIter.Key());
3628 }
3629
3630 //=======================================================================
3631 //function : getActor
3632 //purpose  : Returns an actor to show filtered entities
3633 //=======================================================================
3634
3635 SMESH_Actor* SMESHGUI_FilterDlg::getActor()
3636 {
3637   SMESH_Actor* meshActor = SMESH::FindActorByObject( myMesh );
3638   if ( meshActor && meshActor->GetVisibility() )
3639     return meshActor;
3640
3641   SALOME_DataMapIteratorOfDataMapOfIOMapOfInteger anIter(myIObjects);
3642   for ( ; anIter.More(); anIter.Next())
3643   {
3644     Handle(SALOME_InteractiveObject) io = anIter.Key();
3645     if ( io->hasEntry() )
3646     {
3647       SMESH_Actor* actor = SMESH::FindActorByEntry( io->getEntry() );
3648       if ( !actor )
3649         continue;
3650       if ( actor->GetVisibility() )
3651         return actor;
3652       if ( !meshActor )
3653         meshActor = actor;
3654     }
3655   }
3656   return meshActor;
3657 }
3658
3659 //=======================================================================
3660 // name    : SMESHGUI_FilterDlg::selectInViewer
3661 // Purpose : Select given entities in viewer
3662 //=======================================================================
3663 void SMESHGUI_FilterDlg::selectInViewer (const int theType, const QList<int>& theIds)
3664 {
3665   if (mySelectionMgr == 0 || myMesh->_is_nil() )
3666     return;
3667
3668   mySelectionMgr->clearFilters();
3669
3670   // Set new selection mode if necessary
3671   Selection_Mode aSelMode = getSelMode(theType);
3672   SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI );
3673   if ( aViewWindow && aViewWindow->SelectionMode() != aSelMode )
3674   {
3675     mySelectionMgr->clearSelected();
3676     mySelectionMgr->clearFilters();
3677     SMESH::SetPointRepresentation( aSelMode == NodeSelection );
3678     aViewWindow->SetSelectionMode(aSelMode);
3679   }
3680
3681   // Clear selection
3682   SMESH_Actor* anActor = getActor();
3683   if ( !anActor || !anActor->hasIO() )
3684     return;
3685
3686   Handle(SALOME_InteractiveObject) anIO = anActor->getIO();
3687   SALOME_ListIO aList;
3688   aList.Append(anIO);
3689   mySelectionMgr->setSelectedObjects(aList, false);
3690
3691   // Remove filter corresponding to the current type from viewer
3692   int aType = myTable->GetType();
3693   int aFilterId = SMESH::UnknownFilter;
3694   if      (aType == SMESH::EDGE  ) aFilterId = SMESH::EdgeFilter;
3695   else if (aType == SMESH::FACE  ) aFilterId = SMESH::FaceFilter;
3696   else if (aType == SMESH::VOLUME) aFilterId = SMESH::VolumeFilter;
3697   Handle(VTKViewer_Filter) aFilter = SMESH::GetFilter(aFilterId);
3698   SMESH::RemoveFilter(aFilterId);
3699
3700   // get vtk ids
3701   TColStd_MapOfInteger aMap;
3702   QList<int>::const_iterator anIter;
3703   for (anIter = theIds.begin(); anIter != theIds.end(); ++anIter) {
3704     aMap.Add(*anIter);
3705   }
3706
3707   // Set new selection
3708   mySelector->AddOrRemoveIndex(anIO, aMap, false);
3709   if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
3710     aViewWindow->highlight( anIO, true, true );
3711
3712   // insert previously stored filter in viewer if necessary
3713   if (!aFilter.IsNull())
3714     SMESH::SetFilter(aFilter);
3715 }
3716
3717 //=======================================================================
3718 // name    : SMESHGUI_FilterDlg::createCriterion
3719 // Purpose : Create criterion structure with default values
3720 //=======================================================================
3721 SMESH::Filter::Criterion SMESHGUI_FilterDlg::createCriterion()
3722 {
3723    SMESH::Filter::Criterion aCriterion;
3724
3725   aCriterion.Type          = SMESH::FT_Undefined;
3726   aCriterion.Compare       = SMESH::FT_Undefined;
3727   aCriterion.Threshold     = 0;
3728   aCriterion.UnaryOp       = SMESH::FT_Undefined;
3729   aCriterion.BinaryOp      = SMESH::FT_Undefined;
3730   aCriterion.ThresholdStr  = "";
3731   aCriterion.ThresholdID   = "";
3732   aCriterion.TypeOfElement = SMESH::ALL;
3733
3734   return aCriterion;
3735 }
3736
3737 //=======================================================================
3738 // name    : SMESHGUI_FilterDlg::onSelectionDone
3739 // Purpose : SLOT called when selection changed.
3740 //           If current cell corresponds to the threshold value of
3741 //           BelongToGeom criterion name of selected object is set in this cell
3742 //=======================================================================
3743 void SMESHGUI_FilterDlg::onSelectionDone()
3744 {
3745   const SALOME_ListIO& aList = mySelector->StoredIObjects();
3746   if ( myMesh->_is_nil() && aList.Extent()>0 )
3747   {
3748     myMesh = SMESH::IObjectToInterface<SMESH::SMESH_Mesh>(aList.First());
3749     if ( !(myMesh->_is_nil()) ) {
3750       myButtons[BTN_OK]->setEnabled(true);
3751       myButtons[BTN_Apply]->setEnabled(true);
3752     }
3753   }
3754   int aRow, aCol;
3755   if (aList.Extent() != 1 || !myTable->CurrentCell(aRow, aCol))
3756     return;
3757
3758   const int type = myTable->GetCriterionType(aRow);
3759   QList<int> types; 
3760   types << SMESH::FT_BelongToGeom      << SMESH::FT_BelongToPlane 
3761         << SMESH::FT_BelongToCylinder  << SMESH::FT_BelongToGenSurface
3762         << SMESH::FT_LyingOnGeom       << SMESH::FT_CoplanarFaces
3763         << SMESH::FT_ConnectedElements << SMESH::FT_BelongToMeshGroup;
3764   if ( !types.contains( type ))
3765     return;
3766
3767   Handle(SALOME_InteractiveObject) anIO = aList.First();
3768   switch ( type )
3769   {
3770   case SMESH::FT_CoplanarFaces: // get ID of a selected mesh face
3771     {
3772       QString aString;
3773       int nbElems = SMESH::GetNameOfSelectedElements(mySelector, anIO, aString);
3774       if (nbElems == 1)
3775         myTable->SetThreshold(aRow, aString);
3776       break;
3777     }
3778   case SMESH::FT_ConnectedElements: // get either VERTEX or a node ID
3779     {
3780       GEOM::GEOM_Object_var anObj = SMESH::IObjectToInterface<GEOM::GEOM_Object>(anIO);
3781       if (!anObj->_is_nil())
3782       {
3783         myTable->SetThreshold(aRow, GEOMBase::GetName(anObj));
3784         myTable->SetID       (aRow, anIO->getEntry());
3785       }
3786       else
3787       {
3788         QString aString;
3789         int nbElems = SMESH::GetNameOfSelectedElements(mySelector, anIO, aString);
3790         if (nbElems == 1)
3791           myTable->SetThreshold(aRow, aString);
3792       }
3793       break;
3794     }
3795   case SMESH::FT_BelongToMeshGroup: // get a group Name and Entry
3796     {
3797       SMESH::SMESH_GroupBase_var grp = SMESH::IObjectToInterface<SMESH::SMESH_GroupBase>(anIO);
3798       if ( !grp->_is_nil() )
3799       {
3800         if ( !myMesh->_is_nil() )
3801         {
3802           SMESH::SMESH_Mesh_var mesh = grp->GetMesh();
3803           if ( ! myMesh->_is_equivalent( mesh ))
3804             return;
3805         }
3806         if ( !myGroup->_is_nil() && myGroup->IsInDependency( grp ))
3807           return; // avoid cyclic dependencies between Groups on Filter
3808
3809         myTable->SetThreshold(aRow, SMESH::toQStr( grp->GetName() ));
3810         myTable->SetID       (aRow, anIO->getEntry() );
3811       }
3812     }
3813   default: // get a GEOM object
3814     {
3815       GEOM::GEOM_Object_var anObj = SMESH::IObjectToInterface<GEOM::GEOM_Object>(anIO);
3816       if (!anObj->_is_nil())
3817       {
3818         myTable->SetThreshold(aRow, GEOMBase::GetName(anObj));
3819         myTable->SetID       (aRow, anIO->getEntry());
3820       }
3821     }
3822   }
3823 }
3824
3825
3826 //=======================================================================
3827 // name    : SMESHGUI_FilterDlg::onCriterionChanged
3828 // Purpose : SLOT called when cretarion of current row changed. Update selection
3829 //=======================================================================
3830 void SMESHGUI_FilterDlg::onCriterionChanged (const int, const int)
3831 {
3832   updateSelection();
3833 }
3834
3835 //=======================================================================
3836 // name    : SMESHGUI_FilterDlg::onThresholdChanged
3837 // Purpose : SLOT called when a threshold value is changed by the user and
3838 //           not by myTable->SetThreshold()
3839 //=======================================================================
3840 void SMESHGUI_FilterDlg::onThresholdChanged( const int row, const int type )
3841 {
3842   if ( myTable->GetCriterionType( row, type ) == SMESH::FT_ConnectedElements )
3843   {
3844     // to differ the text entered by the user from that got from selection
3845     myTable->SetID( row, "", type );
3846   }
3847 }
3848
3849 //=======================================================================
3850 // name    : SMESHGUI_FilterDlg::onCurrentChanged
3851 // Purpose : SLOT called when current row changed. Update selection
3852 //=======================================================================
3853 void SMESHGUI_FilterDlg::onCurrentChanged (int, int)
3854 {
3855   updateSelection();
3856 }
3857
3858 //=======================================================================
3859 // name    : SMESHGUI_FilterDlg::updateSelection
3860 // Purpose : UpdateSelection in accordance with current row
3861 //=======================================================================
3862 void SMESHGUI_FilterDlg::updateSelection()
3863 {
3864   if (mySelectionMgr == 0)
3865     return;
3866
3867 //   TColStd_MapOfInteger allTypes;
3868 //   for( int i=0; i<10; i++ )
3869 //     allTypes.Add( i );
3870   SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>( mySMESHGUI->application()->activeStudy() );
3871   if( !aStudy )
3872     return;
3873
3874   restoreSelMode();
3875
3876   mySelectionMgr->clearFilters();
3877
3878   int aRow, aCol;
3879   
3880   bool isCurrentCell = myTable->CurrentCell(aRow, aCol);
3881   int aCriterionType = myTable->GetCriterionType(aRow);
3882   if ( isCurrentCell &&
3883       (aCriterionType == SMESH::FT_BelongToGeom ||
3884        aCriterionType == SMESH::FT_BelongToPlane ||
3885        aCriterionType == SMESH::FT_BelongToCylinder ||
3886        aCriterionType == SMESH::FT_BelongToGenSurface ||
3887        aCriterionType == SMESH::FT_LyingOnGeom))
3888   {
3889     if (aCriterionType == SMESH::FT_BelongToGeom ||
3890         aCriterionType == SMESH::FT_BelongToGenSurface ||
3891         aCriterionType == SMESH::FT_LyingOnGeom) {
3892
3893       mySelectionMgr->installFilter(new GEOM_SelectionFilter( aStudy, true ));
3894
3895     } else if (aCriterionType == SMESH::FT_BelongToPlane) {
3896       mySelectionMgr->installFilter(new GEOM_FaceFilter( aStudy, StdSelect_Plane ) );
3897
3898     } else if (aCriterionType == SMESH::FT_BelongToCylinder) {
3899       mySelectionMgr->installFilter(new GEOM_FaceFilter( aStudy, StdSelect_Cylinder ) );
3900     }
3901     myIsSelectionChanged = true;
3902
3903   }
3904   else if ( aCriterionType == SMESH::FT_BelongToMeshGroup )
3905   {
3906     SMESH_TypeFilter* typeFilter = 0;
3907     switch ( myTable->GetType() )
3908     {
3909     case SMESH::NODE   : typeFilter = new SMESH_TypeFilter( SMESH::GROUP_NODE   ); break;
3910     case SMESH::ELEM0D : typeFilter = new SMESH_TypeFilter( SMESH::GROUP_0D     ); break;
3911     case SMESH::BALL   : typeFilter = new SMESH_TypeFilter( SMESH::GROUP_BALL   ); break;
3912     case SMESH::EDGE   : typeFilter = new SMESH_TypeFilter( SMESH::GROUP_EDGE   ); break;
3913     case SMESH::FACE   : typeFilter = new SMESH_TypeFilter( SMESH::GROUP_FACE   ); break;
3914     case SMESH::VOLUME : typeFilter = new SMESH_TypeFilter( SMESH::GROUP_VOLUME ); break;
3915     case SMESH::ALL    : typeFilter = new SMESH_TypeFilter( SMESH::GROUP        ); break;
3916     default            : typeFilter = 0;
3917     }
3918     if ( typeFilter )
3919       mySelectionMgr->installFilter( typeFilter );
3920   }
3921   else if ( aCriterionType == SMESH::FT_ConnectedElements )
3922   {
3923     QList<SUIT_SelectionFilter*> fList;
3924     fList.push_back( new SMESH_NumberFilter( "GEOM", TopAbs_SHAPE, 1, TopAbs_VERTEX ));
3925     fList.push_back( new SMESH_TypeFilter( SMESH::IDSOURCE ));
3926     mySelectionMgr->installFilter
3927       ( new SMESH_LogicalFilter( fList, SMESH_LogicalFilter::LO_OR,
3928                                  !mySelectionMgr->autoDeleteFilter() ));
3929
3930     if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
3931     {
3932       mySelModeToRestore = aViewWindow->SelectionMode();
3933       aViewWindow->SetSelectionMode( NodeSelection );
3934       myToRestoreSelMode = ( mySelModeToRestore != NodeSelection );
3935       if ( myToRestoreSelMode )
3936         SMESH::SetPointRepresentation( true );
3937     }
3938   }
3939   else
3940   {
3941     mySelector->SetSelectionMode( getSelMode( myTable->GetType() ));
3942
3943     if (myIsSelectionChanged) {
3944       // mySelectionMgr->installFilter( new GEOM_TypeFilter( aStudy, -1 ) ); // This filter deactivates selection
3945       // Impossible to select any object in the OB on the second opening of FilterDlg
3946     }
3947   }
3948 }
3949
3950 //=================================================================================
3951 // function : keyPressEvent()
3952 // purpose  :
3953 //=================================================================================
3954 void SMESHGUI_FilterDlg::keyPressEvent( QKeyEvent* e )
3955 {
3956   QDialog::keyPressEvent( e );
3957   if ( e->isAccepted() )
3958     return;
3959
3960   if ( e->key() == Qt::Key_F1 ) {
3961     e->accept();
3962     onHelp();
3963   }
3964 }
3965
3966 //================================================================================
3967 /*!
3968  * \brief Restores a selection mode if it was changed to set up some criterion
3969  */
3970 //================================================================================
3971
3972 void SMESHGUI_FilterDlg::restoreSelMode()
3973 {
3974   if ( myToRestoreSelMode )
3975   {
3976     SMESH::SetPointRepresentation( mySelModeToRestore == NodeSelection );
3977
3978     if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ))
3979       aViewWindow->SetSelectionMode( mySelModeToRestore );
3980
3981     myToRestoreSelMode = false;
3982   }
3983 }