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