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