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