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