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