a2194f4d366f6451a51da73ddd18954f06c2ab56
[jalview.git] / src / jalview / gui / FeatureTypeSettings.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.api.AlignmentViewPanel;
24 import jalview.api.FeatureColourI;
25 import jalview.datamodel.GraphLine;
26 import jalview.datamodel.features.FeatureAttributes;
27 import jalview.datamodel.features.FeatureAttributes.Datatype;
28 import jalview.datamodel.features.FeatureMatcher;
29 import jalview.datamodel.features.FeatureMatcherI;
30 import jalview.datamodel.features.FeatureMatcherSet;
31 import jalview.datamodel.features.FeatureMatcherSetI;
32 import jalview.schemes.FeatureColour;
33 import jalview.util.ColorUtils;
34 import jalview.util.MessageManager;
35 import jalview.util.matcher.Condition;
36
37 import java.awt.BorderLayout;
38 import java.awt.Color;
39 import java.awt.Dimension;
40 import java.awt.FlowLayout;
41 import java.awt.GridLayout;
42 import java.awt.event.ActionEvent;
43 import java.awt.event.ActionListener;
44 import java.awt.event.FocusAdapter;
45 import java.awt.event.FocusEvent;
46 import java.awt.event.ItemEvent;
47 import java.awt.event.ItemListener;
48 import java.awt.event.MouseAdapter;
49 import java.awt.event.MouseEvent;
50 import java.text.DecimalFormat;
51 import java.util.ArrayList;
52 import java.util.List;
53
54 import javax.swing.BorderFactory;
55 import javax.swing.BoxLayout;
56 import javax.swing.ButtonGroup;
57 import javax.swing.JButton;
58 import javax.swing.JCheckBox;
59 import javax.swing.JColorChooser;
60 import javax.swing.JComboBox;
61 import javax.swing.JLabel;
62 import javax.swing.JPanel;
63 import javax.swing.JRadioButton;
64 import javax.swing.JSlider;
65 import javax.swing.JTextField;
66 import javax.swing.border.EmptyBorder;
67 import javax.swing.border.LineBorder;
68 import javax.swing.event.ChangeEvent;
69 import javax.swing.event.ChangeListener;
70
71 /**
72  * A dialog where the user can configure colour scheme, and any filters, for one
73  * feature type
74  * <p>
75  * (Was FeatureColourChooser prior to Jalview 1.11, renamed with the addition of
76  * filter options)
77  */
78 public class FeatureTypeSettings extends JalviewDialog
79 {
80   private final static String LABEL_18N = MessageManager
81           .getString("label.label");
82
83   private final static String SCORE_18N = MessageManager
84           .getString("label.score");
85
86   private static final int RADIO_WIDTH = 130;
87
88   private static final String COLON = ":";
89
90   private static final int MAX_TOOLTIP_LENGTH = 50;
91
92   private static final int NO_COLOUR_OPTION = 0;
93
94   private static final int MIN_COLOUR_OPTION = 1;
95
96   private static final int MAX_COLOUR_OPTION = 2;
97
98   private static final int ABOVE_THRESHOLD_OPTION = 1;
99
100   private static final int BELOW_THRESHOLD_OPTION = 2;
101
102   private static final DecimalFormat DECFMT_2_2 = new DecimalFormat(
103           "##.##");
104
105   /*
106    * FeatureRenderer holds colour scheme and filters for feature types
107    */
108   private final FeatureRenderer fr; // todo refactor to allow interface type
109                                     // here
110
111   /*
112    * the view panel to update when settings change
113    */
114   private final AlignmentViewPanel ap;
115
116   private final String featureType;
117
118   /*
119    * the colour and filters to reset to on Cancel
120    */
121   private final FeatureColourI originalColour;
122
123   private final FeatureMatcherSetI originalFilter;
124
125   /*
126    * set flag to true when setting values programmatically,
127    * to avoid invocation of action handlers
128    */
129   private boolean adjusting = false;
130
131   /*
132    * minimum of the value range for graduated colour
133    * (may be for feature score or for a numeric attribute)
134    */
135   private float min;
136
137   /*
138    * maximum of the value range for graduated colour
139    */
140   private float max;
141
142   /*
143    * scale factor for conversion between absolute min-max and slider
144    */
145   private float scaleFactor;
146
147   /*
148    * radio button group, to select what to colour by:
149    * simple colour, by category (text), or graduated
150    */
151   private JRadioButton simpleColour = new JRadioButton();
152
153   private JRadioButton byCategory = new JRadioButton();
154
155   private JRadioButton graduatedColour = new JRadioButton();
156
157   /**
158    * colours and filters are shown in tabbed view or single content pane
159    */
160   JPanel coloursPanel, filtersPanel;
161
162   JPanel singleColour = new JPanel();
163
164   private JPanel minColour = new JPanel();
165
166   private JPanel maxColour = new JPanel();
167
168   private JComboBox<String> threshold = new JComboBox<>();
169
170   private JSlider slider = new JSlider();
171
172   private JTextField thresholdValue = new JTextField(20);
173
174   private JCheckBox thresholdIsMin = new JCheckBox();
175
176   private GraphLine threshline;
177
178   private ActionListener featureSettings = null;
179
180   private ActionListener changeColourAction;
181
182   /*
183    * choice of option for 'colour for no value'
184    */
185   private JComboBox<String> noValueCombo;
186
187   /*
188    * choice of what to colour by text (Label or attribute)
189    */
190   private JComboBox<String> colourByTextCombo;
191
192   /*
193    * choice of what to colour by range (Score or attribute)
194    */
195   private JComboBox<String> colourByRangeCombo;
196
197   private JRadioButton andFilters;
198
199   private JRadioButton orFilters;
200
201   /*
202    * filters for the currently selected feature type
203    */
204   private List<FeatureMatcherI> filters;
205
206   private JPanel chooseFiltersPanel;
207
208   /**
209    * Constructor
210    * 
211    * @param frender
212    * @param theType
213    */
214   public FeatureTypeSettings(FeatureRenderer frender, String theType)
215   {
216     this.fr = frender;
217     this.featureType = theType;
218     ap = fr.ap;
219     originalFilter = fr.getFeatureFilter(theType);
220     originalColour = fr.getFeatureColours().get(theType);
221     
222     adjusting = true;
223     
224     try
225     {
226       initialise();
227     } catch (Exception ex)
228     {
229       ex.printStackTrace();
230       return;
231     }
232     
233     updateColoursTab();
234     
235     updateFiltersTab();
236     
237     adjusting = false;
238     
239     colourChanged(false);
240     
241     String title = MessageManager
242             .formatMessage("label.display_settings_for", new String[]
243             { theType });
244     initDialogFrame(this, true, false, title, 580, 500);
245     waitForInput();
246   }
247
248   /**
249    * Configures the widgets on the Colours tab according to the current feature
250    * colour scheme
251    */
252   private void updateColoursTab()
253   {
254     FeatureColourI fc = fr.getFeatureColours().get(featureType);
255
256     /*
257      * suppress action handling while updating values programmatically
258      */
259     adjusting = true;
260     try
261     {
262       /*
263        * single colour
264        */
265       if (fc.isSimpleColour())
266       {
267         singleColour.setBackground(fc.getColour());
268         singleColour.setForeground(fc.getColour());
269         simpleColour.setSelected(true);
270       }
271
272       /*
273        * colour by text (Label or attribute text)
274        */
275       if (fc.isColourByLabel())
276       {
277         byCategory.setSelected(true);
278         colourByTextCombo.setEnabled(colourByTextCombo.getItemCount() > 1);
279         if (fc.isColourByAttribute())
280         {
281           String[] attributeName = fc.getAttributeName();
282           colourByTextCombo.setSelectedItem(
283                   FeatureMatcher.toAttributeDisplayName(attributeName));
284         }
285         else
286         {
287           colourByTextCombo.setSelectedItem(LABEL_18N);
288         }
289       }
290       else
291       {
292         colourByTextCombo.setEnabled(false);
293       }
294
295       if (!fc.isGraduatedColour())
296       {
297         colourByRangeCombo.setEnabled(false);
298         minColour.setEnabled(false);
299         maxColour.setEnabled(false);
300         noValueCombo.setEnabled(false);
301         threshold.setEnabled(false);
302         slider.setEnabled(false);
303         thresholdValue.setEnabled(false);
304         thresholdIsMin.setEnabled(false);
305         return;
306       }
307
308       /*
309        * Graduated colour, by score or attribute value range
310        */
311       graduatedColour.setSelected(true);
312       updateColourMinMax(); // ensure min, max are set
313       colourByRangeCombo.setEnabled(colourByRangeCombo.getItemCount() > 1);
314       minColour.setEnabled(true);
315       maxColour.setEnabled(true);
316       noValueCombo.setEnabled(true);
317       threshold.setEnabled(true);
318       minColour.setBackground(fc.getMinColour());
319       maxColour.setBackground(fc.getMaxColour());
320
321       if (fc.isColourByAttribute())
322       {
323         String[] attributeName = fc.getAttributeName();
324         colourByRangeCombo.setSelectedItem(
325                 FeatureMatcher.toAttributeDisplayName(attributeName));
326       }
327       else
328       {
329         colourByRangeCombo.setSelectedItem(SCORE_18N);
330       }
331       Color noColour = fc.getNoColour();
332       if (noColour == null)
333       {
334         noValueCombo.setSelectedIndex(NO_COLOUR_OPTION);
335       }
336       else if (noColour.equals(fc.getMinColour()))
337       {
338         noValueCombo.setSelectedIndex(MIN_COLOUR_OPTION);
339       }
340       else if (noColour.equals(fc.getMaxColour()))
341       {
342         noValueCombo.setSelectedIndex(MAX_COLOUR_OPTION);
343       }
344
345       /*
346        * update min-max scaling if there is a range to work with,
347        * else disable the widgets (this shouldn't happen if only 
348        * valid options are offered in the combo box)
349        */
350       scaleFactor = (max == min) ? 1f : 100f / (max - min);
351       float range = (max - min) * scaleFactor;
352       slider.setMinimum((int) (min * scaleFactor));
353       slider.setMaximum((int) (max * scaleFactor));
354       slider.setMajorTickSpacing((int) (range / 10f));
355
356       threshline = new GraphLine((max - min) / 2f, "Threshold",
357               Color.black);
358       threshline.value = fc.getThreshold();
359
360       if (fc.hasThreshold())
361       {
362         threshold.setSelectedIndex(
363                 fc.isAboveThreshold() ? ABOVE_THRESHOLD_OPTION
364                         : BELOW_THRESHOLD_OPTION);
365         slider.setEnabled(true);
366         slider.setValue((int) (fc.getThreshold() * scaleFactor));
367         thresholdValue.setText(String.valueOf(fc.getThreshold()));
368         thresholdValue.setEnabled(true);
369         thresholdIsMin.setEnabled(true);
370       }
371       else
372       {
373         slider.setEnabled(false);
374         thresholdValue.setEnabled(false);
375         thresholdIsMin.setEnabled(false);
376       }
377       thresholdIsMin.setSelected(!fc.isAutoScaled());
378     } finally
379     {
380       adjusting = false;
381     }
382   }
383
384   /**
385    * Configures the initial layout
386    */
387   private void initialise()
388   {
389     this.setLayout(new BorderLayout());
390
391     /*
392      * an ActionListener that applies colour changes
393      */
394     changeColourAction = new ActionListener()
395     {
396       @Override
397       public void actionPerformed(ActionEvent e)
398       {
399         colourChanged(true);
400       }
401     };
402
403     /*
404      * first panel/tab: colour options
405      */
406     JPanel coloursPanel = initialiseColoursPanel();
407     this.add(coloursPanel, BorderLayout.NORTH);
408
409     /*
410      * second panel/tab: filter options
411      */
412     JPanel filtersPanel = initialiseFiltersPanel();
413     this.add(filtersPanel, BorderLayout.CENTER);
414
415     JPanel okCancelPanel = initialiseOkCancelPanel();
416
417     this.add(okCancelPanel, BorderLayout.SOUTH);
418   }
419
420   /**
421    * Updates the min-max range if Colour By selected item is Score, or an
422    * attribute, with a min-max range
423    */
424   protected void updateColourMinMax()
425   {
426     if (!graduatedColour.isSelected())
427     {
428       return;
429     }
430
431     String colourBy = (String) colourByRangeCombo.getSelectedItem();
432     float[] minMax = getMinMax(colourBy);
433
434     if (minMax != null)
435     {
436       min = minMax[0];
437       max = minMax[1];
438     }
439   }
440
441   /**
442    * Retrieves the min-max range:
443    * <ul>
444    * <li>of feature score, if colour or filter is by Score</li>
445    * <li>else of the selected attribute</li>
446    * </ul>
447    * 
448    * @param attName
449    * @return
450    */
451   private float[] getMinMax(String attName)
452   {
453     float[] minMax = null;
454     if (SCORE_18N.equals(attName))
455     {
456       minMax = fr.getMinMax().get(featureType)[0];
457     }
458     else
459     {
460       // colour by attribute range
461       minMax = FeatureAttributes.getInstance().getMinMax(featureType,
462               FeatureMatcher.fromAttributeDisplayName(attName));
463     }
464     return minMax;
465   }
466
467   /**
468    * Lay out fields for graduated colour (by score or attribute value)
469    * 
470    * @return
471    */
472   private JPanel initialiseGraduatedColourPanel()
473   {
474     JPanel graduatedColourPanel = new JPanel();
475     graduatedColourPanel.setLayout(
476             new BoxLayout(graduatedColourPanel, BoxLayout.Y_AXIS));
477     JvSwingUtils.createTitledBorder(graduatedColourPanel,
478             MessageManager.getString("label.graduated_colour"), true);
479     graduatedColourPanel.setBackground(Color.white);
480
481     /*
482      * first row: graduated colour radio button, score/attribute drop-down
483      */
484     JPanel graduatedChoicePanel = new JPanel(
485             new FlowLayout(FlowLayout.LEFT));
486     graduatedChoicePanel.setBackground(Color.white);
487     graduatedColour = new JRadioButton(
488             MessageManager.getString("label.by_range_of") + COLON);
489     graduatedColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
490     graduatedColour.addItemListener(new ItemListener()
491     {
492       @Override
493       public void itemStateChanged(ItemEvent e)
494       {
495         if (graduatedColour.isSelected())
496         {
497           colourChanged(true);
498         }
499       }
500     });
501     graduatedChoicePanel.add(graduatedColour);
502
503     List<String[]> attNames = FeatureAttributes.getInstance()
504             .getAttributes(featureType);
505     colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
506     colourByRangeCombo.addItemListener(new ItemListener()
507     {
508       @Override
509       public void itemStateChanged(ItemEvent e)
510       {
511         colourChanged(true);
512       }
513     });
514
515     /*
516      * disable graduated colour option if no range found
517      */
518     graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
519
520     graduatedChoicePanel.add(colourByRangeCombo);
521     graduatedColourPanel.add(graduatedChoicePanel);
522
523     /*
524      * second row - min/max/no colours
525      */
526     JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
527     colourRangePanel.setBackground(Color.white);
528     graduatedColourPanel.add(colourRangePanel);
529
530     minColour.setFont(JvSwingUtils.getLabelFont());
531     minColour.setBorder(BorderFactory.createLineBorder(Color.black));
532     minColour.setPreferredSize(new Dimension(40, 20));
533     minColour.setToolTipText(MessageManager.getString("label.min_colour"));
534     minColour.addMouseListener(new MouseAdapter()
535     {
536       @Override
537       public void mousePressed(MouseEvent e)
538       {
539         if (minColour.isEnabled())
540         {
541           showColourChooser(minColour, "label.select_colour_minimum_value");
542         }
543       }
544     });
545
546     maxColour.setFont(JvSwingUtils.getLabelFont());
547     maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
548     maxColour.setPreferredSize(new Dimension(40, 20));
549     maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
550     maxColour.addMouseListener(new MouseAdapter()
551     {
552       @Override
553       public void mousePressed(MouseEvent e)
554       {
555         if (maxColour.isEnabled())
556         {
557           showColourChooser(maxColour, "label.select_colour_maximum_value");
558         }
559       }
560     });
561     maxColour.setBorder(new LineBorder(Color.black));
562
563     /*
564      * if not set, default max colour to last plain colour,
565      * and make min colour a pale version of max colour
566      */
567     Color max = originalColour.getMaxColour();
568     if (max == null)
569     {
570       max = originalColour.getColour();
571       minColour.setBackground(ColorUtils.bleachColour(max, 0.9f));
572     }
573     else
574     {
575       maxColour.setBackground(max);
576       minColour.setBackground(originalColour.getMinColour());
577     }
578
579     noValueCombo = new JComboBox<>();
580     noValueCombo.addItem(MessageManager.getString("label.no_colour"));
581     noValueCombo.addItem(MessageManager.getString("label.min_colour"));
582     noValueCombo.addItem(MessageManager.getString("label.max_colour"));
583     noValueCombo.addItemListener(new ItemListener()
584     {
585       @Override
586       public void itemStateChanged(ItemEvent e)
587       {
588         colourChanged(true);
589       }
590     });
591
592     JLabel minText = new JLabel(
593             MessageManager.getString("label.min_value") + COLON);
594     minText.setFont(JvSwingUtils.getLabelFont());
595     JLabel maxText = new JLabel(
596             MessageManager.getString("label.max_value") + COLON);
597     maxText.setFont(JvSwingUtils.getLabelFont());
598     JLabel noText = new JLabel(
599             MessageManager.getString("label.no_value") + COLON);
600     noText.setFont(JvSwingUtils.getLabelFont());
601
602     colourRangePanel.add(minText);
603     colourRangePanel.add(minColour);
604     colourRangePanel.add(maxText);
605     colourRangePanel.add(maxColour);
606     colourRangePanel.add(noText);
607     colourRangePanel.add(noValueCombo);
608
609     /*
610      * third row - threshold options and value
611      */
612     JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
613     thresholdPanel.setBackground(Color.white);
614     graduatedColourPanel.add(thresholdPanel);
615
616     threshold.addActionListener(changeColourAction);
617     threshold.setToolTipText(MessageManager
618             .getString("label.threshold_feature_display_by_score"));
619     threshold.addItem(MessageManager
620             .getString("label.threshold_feature_no_threshold")); // index 0
621     threshold.addItem(MessageManager
622             .getString("label.threshold_feature_above_threshold")); // index 1
623     threshold.addItem(MessageManager
624             .getString("label.threshold_feature_below_threshold")); // index 2
625
626     thresholdValue.addActionListener(new ActionListener()
627     {
628       @Override
629       public void actionPerformed(ActionEvent e)
630       {
631         thresholdValue_actionPerformed();
632       }
633     });
634     thresholdValue.addFocusListener(new FocusAdapter()
635     {
636       @Override
637       public void focusLost(FocusEvent e)
638       {
639         thresholdValue_actionPerformed();
640       }
641     });
642     slider.setPaintLabels(false);
643     slider.setPaintTicks(true);
644     slider.setBackground(Color.white);
645     slider.setEnabled(false);
646     slider.setOpaque(false);
647     slider.setPreferredSize(new Dimension(100, 32));
648     slider.setToolTipText(
649             MessageManager.getString("label.adjust_threshold"));
650
651     slider.addChangeListener(new ChangeListener()
652     {
653       @Override
654       public void stateChanged(ChangeEvent evt)
655       {
656         if (!adjusting)
657         {
658           thresholdValue
659                   .setText(String.valueOf(slider.getValue() / scaleFactor));
660           thresholdValue.setBackground(Color.white); // to reset red for invalid
661           sliderValueChanged();
662         }
663       }
664     });
665     slider.addMouseListener(new MouseAdapter()
666     {
667       @Override
668       public void mouseReleased(MouseEvent evt)
669       {
670         /*
671          * only update Overview and/or structure colouring
672          * when threshold slider drag ends (mouse up)
673          */
674         if (ap != null)
675         {
676           ap.paintAlignment(true, true);
677         }
678       }
679     });
680
681     thresholdValue.setEnabled(false);
682     thresholdValue.setColumns(7);
683
684     thresholdPanel.add(threshold);
685     thresholdPanel.add(slider);
686     thresholdPanel.add(thresholdValue);
687
688     thresholdIsMin.setBackground(Color.white);
689     thresholdIsMin
690             .setText(MessageManager.getString("label.threshold_minmax"));
691     thresholdIsMin.setToolTipText(MessageManager
692             .getString("label.toggle_absolute_relative_display_threshold"));
693     thresholdIsMin.addActionListener(changeColourAction);
694     thresholdPanel.add(thresholdIsMin);
695
696     return graduatedColourPanel;
697   }
698
699   /**
700    * Lay out OK and Cancel buttons
701    * 
702    * @return
703    */
704   private JPanel initialiseOkCancelPanel()
705   {
706     JPanel okCancelPanel = new JPanel();
707     // okCancelPanel.setBackground(Color.white);
708     okCancelPanel.add(ok);
709     okCancelPanel.add(cancel);
710     return okCancelPanel;
711   }
712
713   /**
714    * Lay out Colour options panel, containing
715    * <ul>
716    * <li>plain colour, with colour picker</li>
717    * <li>colour by text, with choice of Label or other attribute</li>
718    * <li>colour by range, of score or other attribute, when available</li>
719    * </ul>
720    * 
721    * @return
722    */
723   private JPanel initialiseColoursPanel()
724   {
725     JPanel colourByPanel = new JPanel();
726     colourByPanel.setBackground(Color.white);
727     colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
728     JvSwingUtils.createTitledBorder(colourByPanel,
729             MessageManager.getString("action.colour"), true);
730
731     /*
732      * simple colour radio button and colour picker
733      */
734     JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
735     simpleColourPanel.setBackground(Color.white);
736     colourByPanel.add(simpleColourPanel);
737
738     simpleColour = new JRadioButton(
739             MessageManager.getString("label.simple_colour"));
740     simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
741     simpleColour.addItemListener(new ItemListener()
742     {
743       @Override
744       public void itemStateChanged(ItemEvent e)
745       {
746         if (simpleColour.isSelected() && !adjusting)
747         {
748           colourChanged(true);
749         }
750       }
751     });
752
753     singleColour.setFont(JvSwingUtils.getLabelFont());
754     singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
755     singleColour.setPreferredSize(new Dimension(40, 20));
756     // if (originalColour.isGraduatedColour())
757     // {
758     // singleColour.setBackground(originalColour.getMaxColour());
759     // singleColour.setForeground(originalColour.getMaxColour());
760     // }
761     // else
762     // {
763       singleColour.setBackground(originalColour.getColour());
764       singleColour.setForeground(originalColour.getColour());
765     // }
766     singleColour.addMouseListener(new MouseAdapter()
767     {
768       @Override
769       public void mousePressed(MouseEvent e)
770       {
771         if (simpleColour.isSelected())
772         {
773           showColourChooser(singleColour, "label.select_colour");
774         }
775       }
776     });
777     simpleColourPanel.add(simpleColour); // radio button
778     simpleColourPanel.add(singleColour); // colour picker button
779
780     /*
781      * colour by text (category) radio button and drop-down choice list
782      */
783     JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
784     byTextPanel.setBackground(Color.white);
785     JvSwingUtils.createTitledBorder(byTextPanel,
786             MessageManager.getString("label.colour_by_text"), true);
787     colourByPanel.add(byTextPanel);
788     byCategory = new JRadioButton(
789             MessageManager.getString("label.by_text_of") + COLON);
790     byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
791     byCategory.addItemListener(new ItemListener()
792     {
793       @Override
794       public void itemStateChanged(ItemEvent e)
795       {
796         if (byCategory.isSelected())
797         {
798           colourChanged(true);
799         }
800       }
801     });
802     byTextPanel.add(byCategory);
803
804     List<String[]> attNames = FeatureAttributes.getInstance()
805             .getAttributes(featureType);
806     colourByTextCombo = populateAttributesDropdown(attNames, false, true);
807     colourByTextCombo.addItemListener(new ItemListener()
808     {
809       @Override
810       public void itemStateChanged(ItemEvent e)
811       {
812         colourChanged(true);
813       }
814     });
815     byTextPanel.add(colourByTextCombo);
816
817     /*
818      * graduated colour panel
819      */
820     JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
821     colourByPanel.add(graduatedColourPanel);
822
823     /*
824      * 3 radio buttons select between simple colour, 
825      * by category (text), or graduated
826      */
827     ButtonGroup bg = new ButtonGroup();
828     bg.add(simpleColour);
829     bg.add(byCategory);
830     bg.add(graduatedColour);
831
832     return colourByPanel;
833   }
834
835   private void showColourChooser(JPanel colourPanel, String key)
836   {
837     Color col = JColorChooser.showDialog(this,
838             MessageManager.getString(key), colourPanel.getBackground());
839     if (col != null)
840     {
841       colourPanel.setBackground(col);
842       colourPanel.setForeground(col);
843     }
844     colourPanel.repaint();
845     colourChanged(true);
846   }
847
848   /**
849    * Constructs and sets the selected colour options as the colour for the
850    * feature type, and repaints the alignment, and optionally the Overview
851    * and/or structure viewer if open
852    * 
853    * @param updateStructsAndOverview
854    */
855   void colourChanged(boolean updateStructsAndOverview)
856   {
857     if (adjusting)
858     {
859       /*
860        * ignore action handlers while setting values programmatically
861        */
862       return;
863     }
864
865     /*
866      * ensure min-max range is for the latest choice of 
867      * 'graduated colour by'
868      */
869     updateColourMinMax();
870
871     FeatureColourI acg = makeColourFromInputs();
872
873     /*
874      * save the colour, and repaint stuff
875      */
876     fr.setColour(featureType, acg);
877     ap.paintAlignment(updateStructsAndOverview, updateStructsAndOverview);
878
879     updateColoursTab();
880   }
881
882   /**
883    * Converts the input values into an instance of FeatureColour
884    * 
885    * @return
886    */
887   private FeatureColourI makeColourFromInputs()
888   {
889     /*
890      * min-max range is to (or from) threshold value if 
891      * 'threshold is min/max' is selected 
892      */
893
894     float thresh = 0f;
895     try
896     {
897       thresh = Float.valueOf(thresholdValue.getText());
898     } catch (NumberFormatException e)
899     {
900       // invalid inputs are already handled on entry
901     }
902     float minValue = min;
903     float maxValue = max;
904     final int thresholdOption = threshold.getSelectedIndex();
905     if (thresholdIsMin.isSelected()
906             && thresholdOption == ABOVE_THRESHOLD_OPTION)
907     {
908       minValue = thresh;
909     }
910     if (thresholdIsMin.isSelected()
911             && thresholdOption == BELOW_THRESHOLD_OPTION)
912     {
913       maxValue = thresh;
914     }
915     Color noColour = null;
916     if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
917     {
918       noColour = minColour.getBackground();
919     }
920     else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
921     {
922       noColour = maxColour.getBackground();
923     }
924
925     /*
926      * construct a colour that 'remembers' all the options, including
927      * those not currently selected
928      */
929     FeatureColourI fc = new FeatureColour(singleColour.getBackground(),
930             minColour.getBackground(), maxColour.getBackground(), noColour,
931             minValue, maxValue);
932
933     /*
934      * easiest case - a single colour
935      */
936     if (simpleColour.isSelected())
937     {
938       ((FeatureColour) fc).setGraduatedColour(false);
939       return fc;
940     }
941
942     /*
943      * next easiest case - colour by Label, or attribute text
944      */
945     if (byCategory.isSelected())
946     {
947       fc.setColourByLabel(true);
948       String byWhat = (String) colourByTextCombo.getSelectedItem();
949       if (!LABEL_18N.equals(byWhat))
950       {
951         fc.setAttributeName(
952                 FeatureMatcher.fromAttributeDisplayName(byWhat));
953       }
954       return fc;
955     }
956
957     /*
958      * remaining case - graduated colour by score, or attribute value;
959      * set attribute to colour by if selected
960      */
961     String byWhat = (String) colourByRangeCombo.getSelectedItem();
962     if (!SCORE_18N.equals(byWhat))
963     {
964       fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
965     }
966
967     /*
968      * set threshold options and 'autoscaled' which is
969      * false if 'threshold is min/max' is selected
970      * else true (colour range is on actual range of values)
971      */
972     fc.setThreshold(thresh);
973     fc.setAutoScaled(!thresholdIsMin.isSelected());
974     fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
975     fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
976
977     if (threshline == null)
978     {
979       /*
980        * todo not yet implemented: visual indication of feature threshold
981        */
982       threshline = new GraphLine((max - min) / 2f, "Threshold",
983               Color.black);
984     }
985
986     return fc;
987   }
988
989   @Override
990   protected void raiseClosed()
991   {
992     if (this.featureSettings != null)
993     {
994       featureSettings.actionPerformed(new ActionEvent(this, 0, "CLOSED"));
995     }
996   }
997
998   /**
999    * Action on OK is just to dismiss the dialog - any changes have already been
1000    * applied
1001    */
1002   @Override
1003   public void okPressed()
1004   {
1005   }
1006
1007   /**
1008    * Action on Cancel is to restore colour scheme and filters as they were when
1009    * the dialog was opened
1010    */
1011   @Override
1012   public void cancelPressed()
1013   {
1014     fr.setColour(featureType, originalColour);
1015     fr.setFeatureFilter(featureType, originalFilter);
1016     ap.paintAlignment(true, true);
1017   }
1018
1019   /**
1020    * Action on text entry of a threshold value
1021    */
1022   protected void thresholdValue_actionPerformed()
1023   {
1024     try
1025     {
1026       /*
1027        * set 'adjusting' flag while moving the slider, so it 
1028        * doesn't then in turn change the value (with rounding)
1029        */
1030       adjusting = true;
1031       float f = Float.parseFloat(thresholdValue.getText());
1032       f = Float.max(f,  this.min);
1033       f = Float.min(f, this.max);
1034       thresholdValue.setText(String.valueOf(f));
1035       slider.setValue((int) (f * scaleFactor));
1036       threshline.value = f;
1037       thresholdValue.setBackground(Color.white); // ok
1038       adjusting = false;
1039       colourChanged(true);
1040     } catch (NumberFormatException ex)
1041     {
1042       thresholdValue.setBackground(Color.red); // not ok
1043       adjusting = false;
1044     }
1045   }
1046
1047   /**
1048    * Action on change of threshold slider value. This may be done interactively
1049    * (by moving the slider), or programmatically (to update the slider after
1050    * manual input of a threshold value).
1051    */
1052   protected void sliderValueChanged()
1053   {
1054     threshline.value = getRoundedSliderValue();
1055
1056     /*
1057      * repaint alignment, but not Overview or structure,
1058      * to avoid overload while dragging the slider
1059      */
1060     colourChanged(false);
1061   }
1062
1063   /**
1064    * Converts the slider value to its absolute value by dividing by the
1065    * scaleFactor. Rounding errors are squashed by forcing min/max of slider
1066    * range to the actual min/max of feature score range
1067    * 
1068    * @return
1069    */
1070   private float getRoundedSliderValue()
1071   {
1072     int value = slider.getValue();
1073     float f = value == slider.getMaximum() ? max
1074             : (value == slider.getMinimum() ? min : value / scaleFactor);
1075     return f;
1076   }
1077
1078   void addActionListener(ActionListener listener)
1079   {
1080     if (featureSettings != null)
1081     {
1082       System.err.println(
1083               "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1084     }
1085     featureSettings = listener;
1086   }
1087
1088   /**
1089    * A helper method to build the drop-down choice of attributes for a feature.
1090    * If 'withRange' is true, then Score, and any attributes with a min-max
1091    * range, are added. If 'withText' is true, Label and any known attributes are
1092    * added. This allows 'categorical numerical' attributes e.g. codon position
1093    * to be coloured by text.
1094    * <p>
1095    * Where metadata is available with a description for an attribute, that is
1096    * added as a tooltip.
1097    * <p>
1098    * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1099    * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1100    * <p>
1101    * This method does not add any ActionListener to the JComboBox.
1102    * 
1103    * @param attNames
1104    * @param withRange
1105    * @param withText
1106    */
1107   protected JComboBox<String> populateAttributesDropdown(
1108           List<String[]> attNames, boolean withRange, boolean withText)
1109   {
1110     List<String> displayAtts = new ArrayList<>();
1111     List<String> tooltips = new ArrayList<>();
1112
1113     if (withText)
1114     {
1115       displayAtts.add(LABEL_18N);
1116       tooltips.add(MessageManager.getString("label.description"));
1117     }
1118     if (withRange)
1119     {
1120       float[][] minMax = fr.getMinMax().get(featureType);
1121       if (minMax != null && minMax[0][0] != minMax[0][1])
1122       {
1123         displayAtts.add(SCORE_18N);
1124         tooltips.add(SCORE_18N);
1125       }
1126     }
1127
1128     FeatureAttributes fa = FeatureAttributes.getInstance();
1129     for (String[] attName : attNames)
1130     {
1131       float[] minMax = fa.getMinMax(featureType, attName);
1132       boolean hasRange = minMax != null && minMax[0] != minMax[1];
1133       if (!withText && !hasRange)
1134       {
1135         continue;
1136       }
1137       displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1138       String desc = fa.getDescription(featureType, attName);
1139       if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1140       {
1141         desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1142       }
1143       tooltips.add(desc == null ? "" : desc);
1144     }
1145
1146     JComboBox<String> attCombo = JvSwingUtils
1147             .buildComboWithTooltips(displayAtts, tooltips);
1148
1149     return attCombo;
1150   }
1151
1152   /**
1153    * Populates initial layout of the feature attribute filters panel
1154    */
1155   private JPanel initialiseFiltersPanel()
1156   {
1157     filters = new ArrayList<>();
1158
1159     JPanel filtersPanel = new JPanel();
1160     filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1161     filtersPanel.setBackground(Color.white);
1162     JvSwingUtils.createTitledBorder(filtersPanel,
1163             MessageManager.getString("label.filters"), true);
1164
1165     JPanel andOrPanel = initialiseAndOrPanel();
1166     filtersPanel.add(andOrPanel);
1167
1168     /*
1169      * panel with filters - populated by refreshFiltersDisplay, 
1170      * which also sets the layout manager
1171      */
1172     chooseFiltersPanel = new JPanel();
1173     chooseFiltersPanel.setBackground(Color.white);
1174     filtersPanel.add(chooseFiltersPanel);
1175
1176     return filtersPanel;
1177   }
1178
1179   /**
1180    * Lays out the panel with radio buttons to AND or OR filter conditions
1181    * 
1182    * @return
1183    */
1184   private JPanel initialiseAndOrPanel()
1185   {
1186     JPanel andOrPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
1187     andOrPanel.setBackground(Color.white);
1188     andFilters = new JRadioButton(MessageManager.getString("label.and"));
1189     orFilters = new JRadioButton(MessageManager.getString("label.or"));
1190     ActionListener actionListener = new ActionListener()
1191     {
1192       @Override
1193       public void actionPerformed(ActionEvent e)
1194       {
1195         filtersChanged();
1196       }
1197     };
1198     andFilters.addActionListener(actionListener);
1199     orFilters.addActionListener(actionListener);
1200     ButtonGroup andOr = new ButtonGroup();
1201     andOr.add(andFilters);
1202     andOr.add(orFilters);
1203     andFilters.setSelected(true);
1204     andOrPanel.add(
1205             new JLabel(MessageManager.getString("label.join_conditions")));
1206     andOrPanel.add(andFilters);
1207     andOrPanel.add(orFilters);
1208     return andOrPanel;
1209   }
1210
1211   /**
1212    * Refreshes the display to show any filters currently configured for the
1213    * selected feature type (editable, with 'remove' option), plus one extra row
1214    * for adding a condition. This should be called after a filter has been
1215    * removed, added or amended.
1216    */
1217   private void updateFiltersTab()
1218   {
1219     /*
1220      * clear the panel and list of filter conditions
1221      */
1222     chooseFiltersPanel.removeAll();
1223     filters.clear();
1224
1225     /*
1226      * look up attributes known for feature type
1227      */
1228     List<String[]> attNames = FeatureAttributes.getInstance()
1229             .getAttributes(featureType);
1230
1231     /*
1232      * if this feature type has filters set, load them first
1233      */
1234     FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1235     if (featureFilters != null)
1236     {
1237       if (!featureFilters.isAnded())
1238       {
1239         orFilters.setSelected(true);
1240       }
1241       featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1242     }
1243
1244     /*
1245      * and an empty filter for the user to populate (add)
1246      */
1247     filters.add(FeatureMatcher.NULL_MATCHER);
1248
1249     /*
1250      * use GridLayout to 'justify' rows to the top of the panel, until
1251      * there are too many to fit in, then fall back on BoxLayout
1252      */
1253     if (filters.size() <= 5)
1254     {
1255       chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1256     }
1257     else
1258     {
1259       chooseFiltersPanel.setLayout(
1260               new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1261     }
1262
1263     /*
1264      * render the conditions in rows, each in its own JPanel
1265      */
1266     int filterIndex = 0;
1267     for (FeatureMatcherI filter : filters)
1268     {
1269       JPanel row = addFilter(filter, attNames, filterIndex);
1270       chooseFiltersPanel.add(row);
1271       filterIndex++;
1272     }
1273
1274     this.validate();
1275     this.repaint();
1276   }
1277
1278   /**
1279    * A helper method that constructs a row (panel) with one filter condition:
1280    * <ul>
1281    * <li>a drop-down list of Label, Score and attribute names to choose
1282    * from</li>
1283    * <li>a drop-down list of conditions to choose from</li>
1284    * <li>a text field for input of a match pattern</li>
1285    * <li>optionally, a 'remove' button</li>
1286    * </ul>
1287    * The filter values are set as defaults for the input fields. The 'remove'
1288    * button is added unless the pattern is empty (incomplete filter condition).
1289    * <p>
1290    * Action handlers on these fields provide for
1291    * <ul>
1292    * <li>validate pattern field - should be numeric if condition is numeric</li>
1293    * <li>save filters and refresh display on any (valid) change</li>
1294    * <li>remove filter and refresh on 'Remove'</li>
1295    * <li>update conditions list on change of Label/Score/Attribute</li>
1296    * <li>refresh value field tooltip with min-max range on change of
1297    * attribute</li>
1298    * </ul>
1299    * 
1300    * @param filter
1301    * @param attNames
1302    * @param filterIndex
1303    * @return
1304    */
1305   protected JPanel addFilter(FeatureMatcherI filter,
1306           List<String[]> attNames, int filterIndex)
1307   {
1308     String[] attName = filter.getAttribute();
1309     Condition cond = filter.getMatcher().getCondition();
1310     String pattern = filter.getMatcher().getPattern();
1311
1312     JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1313     filterRow.setBackground(Color.white);
1314
1315     /*
1316      * drop-down choice of attribute, with description as a tooltip 
1317      * if we can obtain it
1318      */
1319     final JComboBox<String> attCombo = populateAttributesDropdown(attNames,
1320             true, true);
1321     String filterBy = setSelectedAttribute(attCombo, filter);
1322
1323     JComboBox<Condition> condCombo = new JComboBox<>();
1324
1325     JTextField patternField = new JTextField(8);
1326     patternField.setText(pattern);
1327
1328     /*
1329      * action handlers that validate and (if valid) apply changes
1330      */
1331     ActionListener actionListener = new ActionListener()
1332     {
1333       @Override
1334       public void actionPerformed(ActionEvent e)
1335       {
1336         if (validateFilter(patternField, condCombo))
1337         {
1338           if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1339           {
1340             filtersChanged();
1341           }
1342         }
1343       }
1344     };
1345     ItemListener itemListener = new ItemListener()
1346     {
1347       @Override
1348       public void itemStateChanged(ItemEvent e)
1349       {
1350         actionListener.actionPerformed(null);
1351       }
1352     };
1353
1354     if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1355     {
1356       attCombo.setSelectedIndex(0);
1357     }
1358     else
1359     {
1360       attCombo.setSelectedItem(
1361               FeatureMatcher.toAttributeDisplayName(attName));
1362     }
1363     attCombo.addItemListener(new ItemListener()
1364     {
1365       @Override
1366       public void itemStateChanged(ItemEvent e)
1367       {
1368         /*
1369          * on change of attribute, refresh the conditions list to
1370          * ensure it is appropriate for the attribute datatype
1371          */
1372         populateConditions((String) attCombo.getSelectedItem(),
1373                 (Condition) condCombo.getSelectedItem(), condCombo,
1374                 patternField);
1375         actionListener.actionPerformed(null);
1376       }
1377     });
1378
1379     filterRow.add(attCombo);
1380
1381     /*
1382      * drop-down choice of test condition
1383      */
1384     populateConditions(filterBy, cond, condCombo, patternField);
1385     condCombo.setPreferredSize(new Dimension(150, 20));
1386     condCombo.addItemListener(itemListener);
1387     filterRow.add(condCombo);
1388
1389     /*
1390      * pattern to match against
1391      */
1392     patternField.addActionListener(actionListener);
1393     patternField.addFocusListener(new FocusAdapter()
1394     {
1395       @Override
1396       public void focusLost(FocusEvent e)
1397       {
1398         actionListener.actionPerformed(null);
1399       }
1400     });
1401     filterRow.add(patternField);
1402
1403     /*
1404      * disable pattern field for condition 'Present / NotPresent'
1405      */
1406     Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1407     patternField.setEnabled(selectedCondition.needsAPattern());
1408
1409     /*
1410      * if a numeric condition is selected, show the value range
1411      * as a tooltip on the value input field
1412      */
1413     setNumericHints(filterBy, selectedCondition, patternField);
1414
1415     /*
1416      * add remove button if filter is populated (non-empty pattern)
1417      */
1418     if (!patternField.isEnabled()
1419             || (pattern != null && pattern.trim().length() > 0))
1420     {
1421       JButton removeCondition = new JButton("\u2717"); // Dingbats cursive x
1422       removeCondition.setToolTipText(
1423               MessageManager.getString("label.delete_condition"));
1424       removeCondition.setBorder(new EmptyBorder(0, 0, 0, 0));
1425       removeCondition.addActionListener(new ActionListener()
1426       {
1427         @Override
1428         public void actionPerformed(ActionEvent e)
1429         {
1430           filters.remove(filterIndex);
1431           filtersChanged();
1432         }
1433       });
1434       filterRow.add(removeCondition);
1435     }
1436
1437     return filterRow;
1438   }
1439
1440   /**
1441    * Sets the selected item in the Label/Score/Attribute drop-down to match the
1442    * filter
1443    * 
1444    * @param attCombo
1445    * @param filter
1446    */
1447   private String setSelectedAttribute(JComboBox<String> attCombo,
1448           FeatureMatcherI filter)
1449   {
1450     String item = null;
1451     if (filter.isByScore())
1452     {
1453       item = SCORE_18N;
1454     }
1455     else if (filter.isByLabel())
1456     {
1457       item = LABEL_18N;
1458     }
1459     else
1460     {
1461       item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1462     }
1463     attCombo.setSelectedItem(item);
1464     return item;
1465   }
1466
1467   /**
1468    * If a numeric comparison condition is selected, retrieves the min-max range
1469    * for the value (score or attribute), and sets it as a tooltip on the value
1470    * field. If the field is currently empty, then pre-populates it with
1471    * <ul>
1472    * <li>the minimum value, if condition is > or >=</li>
1473    * <li>the maximum value, if condition is < or <=</li>
1474    * </ul>
1475    * 
1476    * @param attName
1477    * @param selectedCondition
1478    * @param patternField
1479    */
1480   private void setNumericHints(String attName, Condition selectedCondition,
1481           JTextField patternField)
1482   {
1483     patternField.setToolTipText("");
1484
1485     if (selectedCondition.isNumeric())
1486     {
1487       float[] minMax = getMinMax(attName);
1488       if (minMax != null)
1489       {
1490         String minFormatted = DECFMT_2_2.format(minMax[0]);
1491         String maxFormatted = DECFMT_2_2.format(minMax[1]);
1492         String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1493         patternField.setToolTipText(tip);
1494         if (patternField.getText().isEmpty())
1495         {
1496           if (selectedCondition == Condition.GE
1497                   || selectedCondition == Condition.GT)
1498           {
1499             patternField.setText(minFormatted);
1500           }
1501           else
1502           {
1503             if (selectedCondition == Condition.LE
1504                     || selectedCondition == Condition.LT)
1505             {
1506               patternField.setText(maxFormatted);
1507             }
1508           }
1509         }
1510       }
1511     }
1512   }
1513
1514   /**
1515    * Populates the drop-down list of comparison conditions for the given
1516    * attribute name. The conditions added depend on the datatype of the
1517    * attribute values. The supplied condition is set as the selected item in the
1518    * list, provided it is in the list. If the pattern is now invalid
1519    * (non-numeric pattern for a numeric condition), it is cleared.
1520    * 
1521    * @param attName
1522    * @param cond
1523    * @param condCombo
1524    * @param patternField
1525    */
1526   private void populateConditions(String attName, Condition cond,
1527           JComboBox<Condition> condCombo, JTextField patternField)
1528   {
1529     Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1530             FeatureMatcher.fromAttributeDisplayName(attName));
1531     if (LABEL_18N.equals(attName))
1532     {
1533       type = Datatype.Character;
1534     }
1535     else if (SCORE_18N.equals(attName))
1536     {
1537       type = Datatype.Number;
1538     }
1539
1540     /*
1541      * remove itemListener before starting
1542      */
1543     ItemListener listener = condCombo.getItemListeners()[0];
1544     condCombo.removeItemListener(listener);
1545     boolean condIsValid = false;
1546
1547     condCombo.removeAllItems();
1548     for (Condition c : Condition.values())
1549     {
1550       if ((c.isNumeric() && type == Datatype.Number)
1551               || (!c.isNumeric() && type != Datatype.Number))
1552       {
1553         condCombo.addItem(c);
1554         if (c == cond)
1555         {
1556           condIsValid = true;
1557         }
1558       }
1559     }
1560
1561     /*
1562      * set the selected condition (does nothing if not in the list)
1563      */
1564     if (condIsValid)
1565     {
1566       condCombo.setSelectedItem(cond);
1567     }
1568     else
1569     {
1570       condCombo.setSelectedIndex(0);
1571     }
1572
1573     /*
1574      * clear pattern if it is now invalid for condition
1575      */
1576     if (((Condition) condCombo.getSelectedItem()).isNumeric())
1577     {
1578       try
1579       {
1580         String pattern = patternField.getText().trim();
1581         if (pattern.length() > 0)
1582         {
1583           Float.valueOf(pattern);
1584         }
1585       } catch (NumberFormatException e)
1586       {
1587         patternField.setText("");
1588       }
1589     }
1590
1591     /*
1592      * restore the listener
1593      */
1594     condCombo.addItemListener(listener);
1595   }
1596
1597   /**
1598    * Answers true unless a numeric condition has been selected with a
1599    * non-numeric value. Sets the value field to RED with a tooltip if in error.
1600    * <p>
1601    * If the pattern is expected but is empty, this method returns false, but
1602    * does not mark the field as invalid. This supports selecting an attribute
1603    * for a new condition before a match pattern has been entered.
1604    * 
1605    * @param value
1606    * @param condCombo
1607    */
1608   protected boolean validateFilter(JTextField value,
1609           JComboBox<Condition> condCombo)
1610   {
1611     if (value == null || condCombo == null)
1612     {
1613       return true; // fields not populated
1614     }
1615
1616     Condition cond = (Condition) condCombo.getSelectedItem();
1617     if (!cond.needsAPattern())
1618     {
1619       return true;
1620     }
1621
1622     value.setBackground(Color.white);
1623     value.setToolTipText("");
1624     String v1 = value.getText().trim();
1625     if (v1.length() == 0)
1626     {
1627       // return false;
1628     }
1629
1630     if (cond.isNumeric() && v1.length() > 0)
1631     {
1632       try
1633       {
1634         Float.valueOf(v1);
1635       } catch (NumberFormatException e)
1636       {
1637         value.setBackground(Color.red);
1638         value.setToolTipText(
1639                 MessageManager.getString("label.numeric_required"));
1640         return false;
1641       }
1642     }
1643
1644     return true;
1645   }
1646
1647   /**
1648    * Constructs a filter condition from the given input fields, and replaces the
1649    * condition at filterIndex with the new one. Does nothing if the pattern
1650    * field is blank (unless the match condition is one that doesn't require a
1651    * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1652    * false.
1653    * <p>
1654    * This method may update the tooltip on the filter value field to show the
1655    * value range, if a numeric condition is selected. This ensures the tooltip
1656    * is updated when a numeric valued attribute is chosen on the last 'add a
1657    * filter' row.
1658    * 
1659    * @param attCombo
1660    * @param condCombo
1661    * @param valueField
1662    * @param filterIndex
1663    */
1664   protected boolean updateFilter(JComboBox<String> attCombo,
1665           JComboBox<Condition> condCombo, JTextField valueField,
1666           int filterIndex)
1667   {
1668     String attName = (String) attCombo.getSelectedItem();
1669     Condition cond = (Condition) condCombo.getSelectedItem();
1670     String pattern = valueField.getText().trim();
1671
1672     setNumericHints(attName, cond, valueField);
1673
1674     if (pattern.length() == 0 && cond.needsAPattern())
1675     {
1676       valueField.setEnabled(true); // ensure pattern field is enabled!
1677       return false;
1678     }
1679
1680     /*
1681      * Construct a matcher that operates on Label, Score, 
1682      * or named attribute
1683      */
1684     FeatureMatcherI km = null;
1685     if (LABEL_18N.equals(attName))
1686     {
1687       km = FeatureMatcher.byLabel(cond, pattern);
1688     }
1689     else if (SCORE_18N.equals(attName))
1690     {
1691       km = FeatureMatcher.byScore(cond, pattern);
1692     }
1693     else
1694     {
1695       km = FeatureMatcher.byAttribute(cond, pattern,
1696               FeatureMatcher.fromAttributeDisplayName(attName));
1697     }
1698
1699     filters.set(filterIndex, km);
1700
1701     return true;
1702   }
1703
1704   /**
1705    * Action on any change to feature filtering, namely
1706    * <ul>
1707    * <li>change of selected attribute</li>
1708    * <li>change of selected condition</li>
1709    * <li>change of match pattern</li>
1710    * <li>removal of a condition</li>
1711    * </ul>
1712    * The inputs are parsed into a combined filter and this is set for the
1713    * feature type, and the alignment redrawn.
1714    */
1715   protected void filtersChanged()
1716   {
1717     /*
1718      * update the filter conditions for the feature type
1719      */
1720     boolean anded = andFilters.isSelected();
1721     FeatureMatcherSetI combined = new FeatureMatcherSet();
1722
1723     for (FeatureMatcherI filter : filters)
1724     {
1725       String pattern = filter.getMatcher().getPattern();
1726       Condition condition = filter.getMatcher().getCondition();
1727       if (pattern.trim().length() > 0 || !condition.needsAPattern())
1728       {
1729         if (anded)
1730         {
1731           combined.and(filter);
1732         }
1733         else
1734         {
1735           combined.or(filter);
1736         }
1737       }
1738     }
1739
1740     /*
1741      * save the filter conditions in the FeatureRenderer
1742      * (note this might now be an empty filter with no conditions)
1743      */
1744     fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1745     ap.paintAlignment(true, true);
1746
1747     updateFiltersTab();
1748   }
1749 }