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