JAL-3010 getColumnClass() never return null
[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     singleColour.addMouseListener(new MouseAdapter()
800     {
801       @Override
802       public void mousePressed(MouseEvent e)
803       {
804         if (simpleColour.isSelected())
805         {
806           showColourChooser(singleColour, "label.select_colour");
807         }
808       }
809     });
810     simpleColourPanel.add(simpleColour); // radio button
811     simpleColourPanel.add(singleColour); // colour picker button
812
813     /*
814      * colour by text (category) radio button and drop-down choice list
815      */
816     JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
817     byTextPanel.setBackground(Color.white);
818     JvSwingUtils.createTitledBorder(byTextPanel,
819             MessageManager.getString("label.colour_by_text"), true);
820     colourByPanel.add(byTextPanel);
821     byCategory = new JRadioButton(
822             MessageManager.getString("label.by_text_of") + COLON);
823     byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
824     byCategory.addItemListener(new ItemListener()
825     {
826       @Override
827       public void itemStateChanged(ItemEvent e)
828       {
829         if (byCategory.isSelected())
830         {
831           colourChanged(true);
832         }
833       }
834     });
835     byTextPanel.add(byCategory);
836
837     List<String[]> attNames = FeatureAttributes.getInstance()
838             .getAttributes(featureType);
839     colourByTextCombo = populateAttributesDropdown(attNames, false, true);
840     colourByTextCombo.addItemListener(new ItemListener()
841     {
842       @Override
843       public void itemStateChanged(ItemEvent e)
844       {
845         colourChanged(true);
846       }
847     });
848     byTextPanel.add(colourByTextCombo);
849
850     /*
851      * graduated colour panel
852      */
853     JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
854     colourByPanel.add(graduatedColourPanel);
855
856     /*
857      * 3 radio buttons select between simple colour, 
858      * by category (text), or graduated
859      */
860     ButtonGroup bg = new ButtonGroup();
861     bg.add(simpleColour);
862     bg.add(byCategory);
863     bg.add(graduatedColour);
864
865     return colourByPanel;
866   }
867
868   /**
869    * Constructs and returns a panel with a checkbox for the option to apply any
870    * changes also to sub-types of the feature type
871    * 
872    * @return
873    */
874   protected JPanel initSubtypesPanel(final boolean forFilters)
875   {
876     JPanel toSubtypes = new JPanel(new FlowLayout(FlowLayout.LEFT));
877     toSubtypes.setBackground(Color.WHITE);
878     JCheckBox applyToSubtypesCB = new JCheckBox(MessageManager
879             .formatMessage("label.apply_to_subtypes", featureType));
880     applyToSubtypesCB.setToolTipText(getSubtypesTooltip());
881     applyToSubtypesCB.addActionListener(new ActionListener()
882     {
883       /*
884        * reset and reapply settings on toggle of checkbox
885        */
886       @Override
887       public void actionPerformed(ActionEvent e)
888       {
889         if (forFilters)
890         {
891           applyFiltersToSubtypes = applyToSubtypesCB.isSelected();
892           restoreOriginalFilters();
893           filtersChanged();
894         }
895         else
896         {
897           applyColourToSubtypes = applyToSubtypesCB.isSelected();
898           restoreOriginalColours();
899           colourChanged(true);
900         }
901       }
902     });
903     toSubtypes.add(applyToSubtypesCB);
904
905     return toSubtypes;
906   }
907
908   private void showColourChooser(JPanel colourPanel, String key)
909   {
910     Color col = JColorChooser.showDialog(this,
911             MessageManager.getString(key), colourPanel.getBackground());
912     if (col != null)
913     {
914       colourPanel.setBackground(col);
915       colourPanel.setForeground(col);
916     }
917     colourPanel.repaint();
918     colourChanged(true);
919   }
920
921   /**
922    * Constructs and sets the selected colour options as the colour for the
923    * feature type, and repaints the alignment, and optionally the Overview
924    * and/or structure viewer if open
925    * 
926    * @param updateStructsAndOverview
927    */
928   void colourChanged(boolean updateStructsAndOverview)
929   {
930     if (adjusting)
931     {
932       /*
933        * ignore action handlers while setting values programmatically
934        */
935       return;
936     }
937
938     /*
939      * ensure min-max range is for the latest choice of 
940      * 'graduated colour by'
941      */
942     updateColourMinMax();
943
944     FeatureColourI acg = makeColourFromInputs();
945
946     /*
947      * save the colour, and set on subtypes if selected
948      */
949     fr.setColour(featureType, acg);
950     if (applyColourToSubtypes)
951     {
952       for (String child : subTypes)
953       {
954         fr.setColour(child, acg);
955       }
956     }
957     refreshFeatureSettings();
958     ap.paintAlignment(updateStructsAndOverview, updateStructsAndOverview);
959
960     updateColoursTab();
961   }
962
963   /**
964    * Converts the input values into an instance of FeatureColour
965    * 
966    * @return
967    */
968   private FeatureColourI makeColourFromInputs()
969   {
970     /*
971      * easiest case - a single colour
972      */
973     if (simpleColour.isSelected())
974     {
975       return new FeatureColour(singleColour.getBackground());
976     }
977
978     /*
979      * next easiest case - colour by Label, or attribute text
980      */
981     if (byCategory.isSelected())
982     {
983       Color c = singleColour.getBackground();
984       FeatureColourI fc = new FeatureColour(c);
985       fc.setColourByLabel(true);
986       String byWhat = (String) colourByTextCombo.getSelectedItem();
987       if (!LABEL_18N.equals(byWhat))
988       {
989         fc.setAttributeName(
990                 FeatureMatcher.fromAttributeDisplayName(byWhat));
991       }
992       return fc;
993     }
994
995     /*
996      * remaining case - graduated colour by score, or attribute value
997      */
998     Color noColour = null;
999     if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
1000     {
1001       noColour = minColour.getBackground();
1002     }
1003     else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
1004     {
1005       noColour = maxColour.getBackground();
1006     }
1007
1008     float thresh = 0f;
1009     try
1010     {
1011       thresh = Float.valueOf(thresholdValue.getText());
1012     } catch (NumberFormatException e)
1013     {
1014       // invalid inputs are already handled on entry
1015     }
1016
1017     /*
1018      * min-max range is to (or from) threshold value if 
1019      * 'threshold is min/max' is selected 
1020      */
1021     float minValue = min;
1022     float maxValue = max;
1023     final int thresholdOption = threshold.getSelectedIndex();
1024     if (thresholdIsMin.isSelected()
1025             && thresholdOption == ABOVE_THRESHOLD_OPTION)
1026     {
1027       minValue = thresh;
1028     }
1029     if (thresholdIsMin.isSelected()
1030             && thresholdOption == BELOW_THRESHOLD_OPTION)
1031     {
1032       maxValue = thresh;
1033     }
1034
1035     /*
1036      * make the graduated colour
1037      */
1038     FeatureColourI fc = new FeatureColour(minColour.getBackground(),
1039             maxColour.getBackground(), noColour, minValue, maxValue);
1040
1041     /*
1042      * set attribute to colour by if selected
1043      */
1044     String byWhat = (String) colourByRangeCombo.getSelectedItem();
1045     if (!SCORE_18N.equals(byWhat))
1046     {
1047       fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
1048     }
1049
1050     /*
1051      * set threshold options and 'autoscaled' which is
1052      * false if 'threshold is min/max' is selected
1053      * else true (colour range is on actual range of values)
1054      */
1055     fc.setThreshold(thresh);
1056     fc.setAutoScaled(!thresholdIsMin.isSelected());
1057     fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
1058     fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
1059
1060     if (threshline == null)
1061     {
1062       /*
1063        * todo not yet implemented: visual indication of feature threshold
1064        */
1065       threshline = new GraphLine((max - min) / 2f, "Threshold",
1066               Color.black);
1067     }
1068
1069     return fc;
1070   }
1071
1072   @Override
1073   protected void raiseClosed()
1074   {
1075     refreshFeatureSettings();
1076   }
1077
1078   protected void refreshFeatureSettings()
1079   {
1080     if (this.featureSettings != null)
1081     {
1082       featureSettings.actionPerformed(new ActionEvent(this, 0, "REFRESH"));
1083     }
1084   }
1085
1086   /**
1087    * Action on OK is just to dismiss the dialog - any changes have already been
1088    * applied
1089    */
1090   @Override
1091   public void okPressed()
1092   {
1093   }
1094
1095   /**
1096    * Action on Cancel is to restore colour scheme and filters as they were when
1097    * the dialog was opened (including any feature sub-types that may have been
1098    * changed)
1099    */
1100   @Override
1101   public void cancelPressed()
1102   {
1103     restoreOriginalColours();
1104     restoreOriginalFilters();
1105     ap.paintAlignment(true, true);
1106   }
1107
1108   protected void restoreOriginalFilters()
1109   {
1110     for (Entry<String, FeatureMatcherSetI> entry : originalFilters
1111             .entrySet())
1112     {
1113       fr.setFeatureFilter(entry.getKey(), entry.getValue());
1114     }
1115   }
1116
1117   protected void restoreOriginalColours()
1118   {
1119     for (Entry<String, FeatureColourI> entry : originalColours.entrySet())
1120     {
1121       fr.setColour(entry.getKey(), entry.getValue());
1122     }
1123   }
1124
1125   /**
1126    * Action on text entry of a threshold value
1127    */
1128   protected void thresholdValue_actionPerformed()
1129   {
1130     try
1131     {
1132       adjusting = true;
1133       float f = Float.parseFloat(thresholdValue.getText());
1134       slider.setValue((int) (f * scaleFactor));
1135       threshline.value = f;
1136       thresholdValue.setBackground(Color.white); // ok
1137
1138       /*
1139        * force repaint of any Overview window or structure
1140        */
1141       ap.paintAlignment(true, true);
1142     } catch (NumberFormatException ex)
1143     {
1144       thresholdValue.setBackground(Color.red); // not ok
1145     } finally
1146     {
1147       adjusting = false;
1148     }
1149   }
1150
1151   /**
1152    * Action on change of threshold slider value. This may be done interactively
1153    * (by moving the slider), or programmatically (to update the slider after
1154    * manual input of a threshold value).
1155    */
1156   protected void sliderValueChanged()
1157   {
1158     threshline.value = getRoundedSliderValue();
1159
1160     /*
1161      * repaint alignment, but not Overview or structure,
1162      * to avoid overload while dragging the slider
1163      */
1164     colourChanged(false);
1165   }
1166
1167   /**
1168    * Converts the slider value to its absolute value by dividing by the
1169    * scaleFactor. Rounding errors are squashed by forcing min/max of slider
1170    * range to the actual min/max of feature score range
1171    * 
1172    * @return
1173    */
1174   private float getRoundedSliderValue()
1175   {
1176     int value = slider.getValue();
1177     float f = value == slider.getMaximum() ? max
1178             : (value == slider.getMinimum() ? min : value / scaleFactor);
1179     return f;
1180   }
1181
1182   void addActionListener(ActionListener listener)
1183   {
1184     if (featureSettings != null)
1185     {
1186       System.err.println(
1187               "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1188     }
1189     featureSettings = listener;
1190   }
1191
1192   /**
1193    * A helper method to build the drop-down choice of attributes for a feature.
1194    * If 'withRange' is true, then Score, and any attributes with a min-max
1195    * range, are added. If 'withText' is true, Label and any known attributes are
1196    * added. This allows 'categorical numerical' attributes e.g. codon position
1197    * to be coloured by text.
1198    * <p>
1199    * Where metadata is available with a description for an attribute, that is
1200    * added as a tooltip.
1201    * <p>
1202    * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1203    * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1204    * <p>
1205    * This method does not add any ActionListener to the JComboBox.
1206    * 
1207    * @param attNames
1208    * @param withRange
1209    * @param withText
1210    */
1211   protected JComboBox<String> populateAttributesDropdown(
1212           List<String[]> attNames, boolean withRange, boolean withText)
1213   {
1214     List<String> displayAtts = new ArrayList<>();
1215     List<String> tooltips = new ArrayList<>();
1216
1217     if (withText)
1218     {
1219       displayAtts.add(LABEL_18N);
1220       tooltips.add(MessageManager.getString("label.description"));
1221     }
1222     if (withRange)
1223     {
1224       float[][] minMax = fr.getMinMax().get(featureType);
1225       if (minMax != null && minMax[0][0] != minMax[0][1])
1226       {
1227         displayAtts.add(SCORE_18N);
1228         tooltips.add(SCORE_18N);
1229       }
1230     }
1231
1232     FeatureAttributes fa = FeatureAttributes.getInstance();
1233     for (String[] attName : attNames)
1234     {
1235       float[] minMax = fa.getMinMax(featureType, attName);
1236       boolean hasRange = minMax != null && minMax[0] != minMax[1];
1237       if (!withText && !hasRange)
1238       {
1239         continue;
1240       }
1241       displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1242       String desc = fa.getDescription(featureType, attName);
1243       if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1244       {
1245         desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1246       }
1247       tooltips.add(desc == null ? "" : desc);
1248     }
1249
1250     JComboBox<String> attCombo = JvSwingUtils
1251             .buildComboWithTooltips(displayAtts, tooltips);
1252
1253     return attCombo;
1254   }
1255
1256   /**
1257    * Populates initial layout of the feature attribute filters panel
1258    */
1259   private JPanel initialiseFiltersPanel()
1260   {
1261     filters = new ArrayList<>();
1262
1263     JPanel outerPanel = new JPanel();
1264     outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
1265     outerPanel.setBackground(Color.white);
1266
1267     /*
1268      * option to apply colour to sub-types as well (if there are any)
1269      */
1270     if (!subTypes.isEmpty())
1271     {
1272       applyFiltersToSubtypes = false;
1273       outerPanel.add(initSubtypesPanel(true));
1274     }
1275
1276     JPanel filtersPanel = new JPanel();
1277     filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1278     filtersPanel.setBackground(Color.white);
1279     JvSwingUtils.createTitledBorder(filtersPanel,
1280             MessageManager.getString("label.filters"), true);
1281     outerPanel.add(filtersPanel);
1282
1283     JPanel andOrPanel = initialiseAndOrPanel();
1284     filtersPanel.add(andOrPanel);
1285
1286     /*
1287      * panel with filters - populated by refreshFiltersDisplay, 
1288      * which also sets the layout manager
1289      */
1290     chooseFiltersPanel = new JPanel();
1291     chooseFiltersPanel.setBackground(Color.white);
1292     filtersPanel.add(chooseFiltersPanel);
1293
1294     return outerPanel;
1295   }
1296
1297   /**
1298    * Lays out the panel with radio buttons to AND or OR filter conditions
1299    * 
1300    * @return
1301    */
1302   private JPanel initialiseAndOrPanel()
1303   {
1304     JPanel andOrPanel = new JPanel(new BorderLayout());
1305     andOrPanel.setBackground(Color.white);
1306
1307 //    JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
1308 //    andOrPanel.add(panel1, BorderLayout.WEST);
1309 //    panel1.setBackground(Color.white);
1310 //    panel1.setBorder(BorderFactory.createLineBorder(debugBorderColour));
1311     andFilters = new JRadioButton(MessageManager.getString("label.and"));
1312     orFilters = new JRadioButton(MessageManager.getString("label.or"));
1313     ActionListener actionListener = new ActionListener()
1314     {
1315       @Override
1316       public void actionPerformed(ActionEvent e)
1317       {
1318         filtersChanged();
1319       }
1320     };
1321     andFilters.addActionListener(actionListener);
1322     orFilters.addActionListener(actionListener);
1323     ButtonGroup andOr = new ButtonGroup();
1324     andOr.add(andFilters);
1325     andOr.add(orFilters);
1326     andFilters.setSelected(true);
1327     andOrPanel.add(
1328             new JLabel(MessageManager.getString("label.join_conditions")));
1329     andOrPanel.add(andFilters);
1330     andOrPanel.add(orFilters);
1331
1332     return andOrPanel;
1333   }
1334
1335   /**
1336    * Builds a tooltip for the 'Apply to subtypes' checkbox with a list of
1337    * subtypes of this feature type
1338    * 
1339    * @return
1340    */
1341   protected String getSubtypesTooltip()
1342   {
1343     StringBuilder sb = new StringBuilder(20 * subTypes.size());
1344     sb.append(MessageManager.getString("label.apply_also_to"));
1345     for (String child : subTypes)
1346     {
1347       sb.append("<br>").append(child);
1348     }
1349     String tooltip = JvSwingUtils.wrapTooltip(true, sb.toString());
1350     return tooltip;
1351   }
1352
1353   /**
1354    * Refreshes the display to show any filters currently configured for the
1355    * selected feature type (editable, with 'remove' option), plus one extra row
1356    * for adding a condition. This should be called after a filter has been
1357    * removed, added or amended.
1358    */
1359   private void updateFiltersTab()
1360   {
1361     /*
1362      * clear the panel and list of filter conditions
1363      */
1364     chooseFiltersPanel.removeAll();
1365     filters.clear();
1366
1367     /*
1368      * look up attributes known for feature type
1369      */
1370     List<String[]> attNames = FeatureAttributes.getInstance()
1371             .getAttributes(featureType);
1372
1373     /*
1374      * if this feature type has filters set, load them first
1375      */
1376     FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1377     if (featureFilters != null)
1378     {
1379       if (!featureFilters.isAnded())
1380       {
1381         orFilters.setSelected(true);
1382       }
1383       featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1384     }
1385
1386     /*
1387      * and an empty filter for the user to populate (add)
1388      */
1389     filters.add(FeatureMatcher.NULL_MATCHER);
1390
1391     /*
1392      * use GridLayout to 'justify' rows to the top of the panel, until
1393      * there are too many to fit in, then fall back on BoxLayout
1394      */
1395     if (filters.size() <= 5)
1396     {
1397       chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1398     }
1399     else
1400     {
1401       chooseFiltersPanel.setLayout(
1402               new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1403     }
1404
1405     /*
1406      * render the conditions in rows, each in its own JPanel
1407      */
1408     int filterIndex = 0;
1409     for (FeatureMatcherI filter : filters)
1410     {
1411       JPanel row = addFilter(filter, attNames, filterIndex);
1412       chooseFiltersPanel.add(row);
1413       filterIndex++;
1414     }
1415
1416     this.validate();
1417     this.repaint();
1418   }
1419
1420   /**
1421    * A helper method that constructs a row (panel) with one filter condition:
1422    * <ul>
1423    * <li>a drop-down list of Label, Score and attribute names to choose
1424    * from</li>
1425    * <li>a drop-down list of conditions to choose from</li>
1426    * <li>a text field for input of a match pattern</li>
1427    * <li>optionally, a 'remove' button</li>
1428    * </ul>
1429    * The filter values are set as defaults for the input fields. The 'remove'
1430    * button is added unless the pattern is empty (incomplete filter condition).
1431    * <p>
1432    * Action handlers on these fields provide for
1433    * <ul>
1434    * <li>validate pattern field - should be numeric if condition is numeric</li>
1435    * <li>save filters and refresh display on any (valid) change</li>
1436    * <li>remove filter and refresh on 'Remove'</li>
1437    * <li>update conditions list on change of Label/Score/Attribute</li>
1438    * <li>refresh value field tooltip with min-max range on change of
1439    * attribute</li>
1440    * </ul>
1441    * 
1442    * @param filter
1443    * @param attNames
1444    * @param filterIndex
1445    * @return
1446    */
1447   protected JPanel addFilter(FeatureMatcherI filter,
1448           List<String[]> attNames, int filterIndex)
1449   {
1450     String[] attName = filter.getAttribute();
1451     Condition cond = filter.getMatcher().getCondition();
1452     String pattern = filter.getMatcher().getPattern();
1453
1454     JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1455     filterRow.setBackground(Color.white);
1456
1457     /*
1458      * drop-down choice of attribute, with description as a tooltip 
1459      * if we can obtain it
1460      */
1461     final JComboBox<String> attCombo = populateAttributesDropdown(attNames,
1462             true, true);
1463     String filterBy = setSelectedAttribute(attCombo, filter);
1464
1465     JComboBox<Condition> condCombo = new JComboBox<>();
1466
1467     JTextField patternField = new JTextField(8);
1468     patternField.setText(pattern);
1469
1470     /*
1471      * action handlers that validate and (if valid) apply changes
1472      */
1473     ActionListener actionListener = new ActionListener()
1474     {
1475       @Override
1476       public void actionPerformed(ActionEvent e)
1477       {
1478         if (validateFilter(patternField, condCombo))
1479         {
1480           if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1481           {
1482             filtersChanged();
1483           }
1484         }
1485       }
1486     };
1487     ItemListener itemListener = new ItemListener()
1488     {
1489       @Override
1490       public void itemStateChanged(ItemEvent e)
1491       {
1492         actionListener.actionPerformed(null);
1493       }
1494     };
1495
1496     if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1497     {
1498       attCombo.setSelectedIndex(0);
1499     }
1500     else
1501     {
1502       attCombo.setSelectedItem(
1503               FeatureMatcher.toAttributeDisplayName(attName));
1504     }
1505     attCombo.addItemListener(new ItemListener()
1506     {
1507       @Override
1508       public void itemStateChanged(ItemEvent e)
1509       {
1510         /*
1511          * on change of attribute, refresh the conditions list to
1512          * ensure it is appropriate for the attribute datatype
1513          */
1514         populateConditions((String) attCombo.getSelectedItem(),
1515                 (Condition) condCombo.getSelectedItem(), condCombo,
1516                 patternField);
1517         actionListener.actionPerformed(null);
1518       }
1519     });
1520
1521     filterRow.add(attCombo);
1522
1523     /*
1524      * drop-down choice of test condition
1525      */
1526     populateConditions(filterBy, cond, condCombo, patternField);
1527     condCombo.setPreferredSize(new Dimension(150, 20));
1528     condCombo.addItemListener(itemListener);
1529     filterRow.add(condCombo);
1530
1531     /*
1532      * pattern to match against
1533      */
1534     patternField.addActionListener(actionListener);
1535     patternField.addFocusListener(new FocusAdapter()
1536     {
1537       @Override
1538       public void focusLost(FocusEvent e)
1539       {
1540         actionListener.actionPerformed(null);
1541       }
1542     });
1543     filterRow.add(patternField);
1544
1545     /*
1546      * disable pattern field for condition 'Present / NotPresent'
1547      */
1548     Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1549     patternField.setEnabled(selectedCondition.needsAPattern());
1550
1551     /*
1552      * if a numeric condition is selected, show the value range
1553      * as a tooltip on the value input field
1554      */
1555     setNumericHints(filterBy, selectedCondition, patternField);
1556
1557     /*
1558      * add remove button if filter is populated (non-empty pattern)
1559      */
1560     if (!patternField.isEnabled()
1561             || (pattern != null && pattern.trim().length() > 0))
1562     {
1563       // todo: gif for button drawing '-' or 'x'
1564       JButton removeCondition = new BasicArrowButton(SwingConstants.WEST);
1565       removeCondition
1566               .setToolTipText(MessageManager.getString("label.delete_row"));
1567       removeCondition.addActionListener(new ActionListener()
1568       {
1569         @Override
1570         public void actionPerformed(ActionEvent e)
1571         {
1572           filters.remove(filterIndex);
1573           filtersChanged();
1574         }
1575       });
1576       filterRow.add(removeCondition);
1577     }
1578
1579     return filterRow;
1580   }
1581
1582   /**
1583    * Sets the selected item in the Label/Score/Attribute drop-down to match the
1584    * filter
1585    * 
1586    * @param attCombo
1587    * @param filter
1588    */
1589   private String setSelectedAttribute(JComboBox<String> attCombo,
1590           FeatureMatcherI filter)
1591   {
1592     String item = null;
1593     if (filter.isByScore())
1594     {
1595       item = SCORE_18N;
1596     }
1597     else if (filter.isByLabel())
1598     {
1599       item = LABEL_18N;
1600     }
1601     else
1602     {
1603       item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1604     }
1605     attCombo.setSelectedItem(item);
1606     return item;
1607   }
1608
1609   /**
1610    * If a numeric comparison condition is selected, retrieves the min-max range
1611    * for the value (score or attribute), and sets it as a tooltip on the value
1612    * field. If the field is currently empty, then pre-populates it with
1613    * <ul>
1614    * <li>the minimum value, if condition is > or >=</li>
1615    * <li>the maximum value, if condition is < or <=</li>
1616    * </ul>
1617    * 
1618    * @param attName
1619    * @param selectedCondition
1620    * @param patternField
1621    */
1622   private void setNumericHints(String attName, Condition selectedCondition,
1623           JTextField patternField)
1624   {
1625     patternField.setToolTipText("");
1626
1627     if (selectedCondition.isNumeric())
1628     {
1629       float[] minMax = getMinMax(attName);
1630       if (minMax != null)
1631       {
1632         String minFormatted = DECFMT_2_2.format(minMax[0]);
1633         String maxFormatted = DECFMT_2_2.format(minMax[1]);
1634         String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1635         patternField.setToolTipText(tip);
1636         if (patternField.getText().isEmpty())
1637         {
1638           if (selectedCondition == Condition.GE
1639                   || selectedCondition == Condition.GT)
1640           {
1641             patternField.setText(minFormatted);
1642           }
1643           else
1644           {
1645             if (selectedCondition == Condition.LE
1646                     || selectedCondition == Condition.LT)
1647             {
1648               patternField.setText(maxFormatted);
1649             }
1650           }
1651         }
1652       }
1653     }
1654   }
1655
1656   /**
1657    * Populates the drop-down list of comparison conditions for the given
1658    * attribute name. The conditions added depend on the datatype of the
1659    * attribute values. The supplied condition is set as the selected item in the
1660    * list, provided it is in the list. If the pattern is now invalid
1661    * (non-numeric pattern for a numeric condition), it is cleared.
1662    * 
1663    * @param attName
1664    * @param cond
1665    * @param condCombo
1666    * @param patternField
1667    */
1668   private void populateConditions(String attName, Condition cond,
1669           JComboBox<Condition> condCombo, JTextField patternField)
1670   {
1671     Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1672             FeatureMatcher.fromAttributeDisplayName(attName));
1673     if (LABEL_18N.equals(attName))
1674     {
1675       type = Datatype.Character;
1676     }
1677     else if (SCORE_18N.equals(attName))
1678     {
1679       type = Datatype.Number;
1680     }
1681
1682     /*
1683      * remove itemListener before starting
1684      */
1685     ItemListener listener = condCombo.getItemListeners()[0];
1686     condCombo.removeItemListener(listener);
1687     boolean condIsValid = false;
1688
1689     condCombo.removeAllItems();
1690     for (Condition c : Condition.values())
1691     {
1692       if ((c.isNumeric() && type == Datatype.Number)
1693               || (!c.isNumeric() && type != Datatype.Number))
1694       {
1695         condCombo.addItem(c);
1696         if (c == cond)
1697         {
1698           condIsValid = true;
1699         }
1700       }
1701     }
1702
1703     /*
1704      * set the selected condition (does nothing if not in the list)
1705      */
1706     if (condIsValid)
1707     {
1708       condCombo.setSelectedItem(cond);
1709     }
1710     else
1711     {
1712       condCombo.setSelectedIndex(0);
1713     }
1714
1715     /*
1716      * clear pattern if it is now invalid for condition
1717      */
1718     if (((Condition) condCombo.getSelectedItem()).isNumeric())
1719     {
1720       try
1721       {
1722         String pattern = patternField.getText().trim();
1723         if (pattern.length() > 0)
1724         {
1725           Float.valueOf(pattern);
1726         }
1727       } catch (NumberFormatException e)
1728       {
1729         patternField.setText("");
1730       }
1731     }
1732
1733     /*
1734      * restore the listener
1735      */
1736     condCombo.addItemListener(listener);
1737   }
1738
1739   /**
1740    * Answers true unless a numeric condition has been selected with a
1741    * non-numeric value. Sets the value field to RED with a tooltip if in error.
1742    * <p>
1743    * If the pattern is expected but is empty, this method returns false, but
1744    * does not mark the field as invalid. This supports selecting an attribute
1745    * for a new condition before a match pattern has been entered.
1746    * 
1747    * @param value
1748    * @param condCombo
1749    */
1750   protected boolean validateFilter(JTextField value,
1751           JComboBox<Condition> condCombo)
1752   {
1753     if (value == null || condCombo == null)
1754     {
1755       return true; // fields not populated
1756     }
1757
1758     Condition cond = (Condition) condCombo.getSelectedItem();
1759     if (!cond.needsAPattern())
1760     {
1761       return true;
1762     }
1763
1764     value.setBackground(Color.white);
1765     value.setToolTipText("");
1766     String v1 = value.getText().trim();
1767     if (v1.length() == 0)
1768     {
1769       // return false;
1770     }
1771
1772     if (cond.isNumeric() && v1.length() > 0)
1773     {
1774       try
1775       {
1776         Float.valueOf(v1);
1777       } catch (NumberFormatException e)
1778       {
1779         value.setBackground(Color.red);
1780         value.setToolTipText(
1781                 MessageManager.getString("label.numeric_required"));
1782         return false;
1783       }
1784     }
1785
1786     return true;
1787   }
1788
1789   /**
1790    * Constructs a filter condition from the given input fields, and replaces the
1791    * condition at filterIndex with the new one. Does nothing if the pattern
1792    * field is blank (unless the match condition is one that doesn't require a
1793    * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1794    * false.
1795    * <p>
1796    * This method may update the tooltip on the filter value field to show the
1797    * value range, if a numeric condition is selected. This ensures the tooltip
1798    * is updated when a numeric valued attribute is chosen on the last 'add a
1799    * filter' row.
1800    * 
1801    * @param attCombo
1802    * @param condCombo
1803    * @param valueField
1804    * @param filterIndex
1805    */
1806   protected boolean updateFilter(JComboBox<String> attCombo,
1807           JComboBox<Condition> condCombo, JTextField valueField,
1808           int filterIndex)
1809   {
1810     String attName = (String) attCombo.getSelectedItem();
1811     Condition cond = (Condition) condCombo.getSelectedItem();
1812     String pattern = valueField.getText().trim();
1813
1814     setNumericHints(attName, cond, valueField);
1815
1816     if (pattern.length() == 0 && cond.needsAPattern())
1817     {
1818       valueField.setEnabled(true); // ensure pattern field is enabled!
1819       return false;
1820     }
1821
1822     /*
1823      * Construct a matcher that operates on Label, Score, 
1824      * or named attribute
1825      */
1826     FeatureMatcherI km = null;
1827     if (LABEL_18N.equals(attName))
1828     {
1829       km = FeatureMatcher.byLabel(cond, pattern);
1830     }
1831     else if (SCORE_18N.equals(attName))
1832     {
1833       km = FeatureMatcher.byScore(cond, pattern);
1834     }
1835     else
1836     {
1837       km = FeatureMatcher.byAttribute(cond, pattern,
1838               FeatureMatcher.fromAttributeDisplayName(attName));
1839     }
1840
1841     filters.set(filterIndex, km);
1842
1843     return true;
1844   }
1845
1846   /**
1847    * Action on any change to feature filtering, namely
1848    * <ul>
1849    * <li>change of selected attribute</li>
1850    * <li>change of selected condition</li>
1851    * <li>change of match pattern</li>
1852    * <li>removal of a condition</li>
1853    * </ul>
1854    * The inputs are parsed into a combined filter and this is set for the
1855    * feature type, and the alignment redrawn.
1856    */
1857   protected void filtersChanged()
1858   {
1859     /*
1860      * update the filter conditions for the feature type
1861      */
1862     boolean anded = andFilters.isSelected();
1863     FeatureMatcherSetI combined = new FeatureMatcherSet();
1864
1865     for (FeatureMatcherI filter : filters)
1866     {
1867       String pattern = filter.getMatcher().getPattern();
1868       Condition condition = filter.getMatcher().getCondition();
1869       if (pattern.trim().length() > 0 || !condition.needsAPattern())
1870       {
1871         if (anded)
1872         {
1873           combined.and(filter);
1874         }
1875         else
1876         {
1877           combined.or(filter);
1878         }
1879       }
1880     }
1881
1882     /*
1883      * save the filter conditions in the FeatureRenderer
1884      * (note this might now be an empty filter with no conditions)
1885      */
1886     fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1887     if (applyFiltersToSubtypes)
1888     {
1889       for (String child : subTypes)
1890       {
1891         fr.setFeatureFilter(child, combined.isEmpty() ? null : combined);
1892       }
1893     }
1894
1895     refreshFeatureSettings();
1896     ap.paintAlignment(true, true);
1897
1898     updateFiltersTab();
1899   }
1900 }