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