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