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