Merge branch 'develop' into features/JAL-3010ontologyFeatureSettings
[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.border.EmptyBorder;
74 import javax.swing.border.LineBorder;
75 import javax.swing.event.ChangeEvent;
76 import javax.swing.event.ChangeListener;
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
116                                     // here
117
118   /*
119    * the view panel to update when settings change
120    */
121   private final AlignmentViewPanel ap;
122
123   private final String featureType;
124
125   /*
126    * the colour and filters to reset to on Cancel
127    * (including feature sub-types if modified)
128    */
129   private Map<String, FeatureColourI> originalColours;
130
131   private Map<String, FeatureMatcherSetI> originalFilters;
132
133   /*
134    * set flag to true when setting values programmatically,
135    * to avoid invocation of action handlers
136    */
137   private boolean adjusting = false;
138
139   /*
140    * minimum of the value range for graduated colour
141    * (may be for feature score or for a numeric attribute)
142    */
143   private float min;
144
145   /*
146    * maximum of the value range for graduated colour
147    */
148   private float max;
149
150   /*
151    * scale factor for conversion between absolute min-max and slider
152    */
153   private float scaleFactor;
154
155   /*
156    * radio button group, to select what to colour by:
157    * simple colour, by category (text), or graduated
158    */
159   private JRadioButton simpleColour = new JRadioButton();
160
161   private JRadioButton byCategory = new JRadioButton();
162
163   private JRadioButton graduatedColour = new JRadioButton();
164
165   /**
166    * colours and filters are shown in tabbed view or single content pane
167    */
168   JPanel coloursPanel, filtersPanel;
169
170   JPanel singleColour = new JPanel();
171
172   private JPanel minColour = new JPanel();
173
174   private JPanel maxColour = new JPanel();
175
176   private JComboBox<String> threshold = new JComboBox<>();
177
178   private JSlider slider = new JSlider();
179
180   private JTextField thresholdValue = new JTextField(20);
181
182   private JCheckBox thresholdIsMin = new JCheckBox();
183
184   private GraphLine threshline;
185
186   private ActionListener featureSettings = null;
187
188   private ActionListener changeColourAction;
189
190   /*
191    * choice of option for 'colour for no value'
192    */
193   private JComboBox<String> noValueCombo;
194
195   /*
196    * choice of what to colour by text (Label or attribute)
197    */
198   private JComboBox<String> colourByTextCombo;
199
200   /*
201    * choice of what to colour by range (Score or attribute)
202    */
203   private JComboBox<String> colourByRangeCombo;
204
205   private JRadioButton andFilters;
206
207   private JRadioButton orFilters;
208
209   /*
210    * filters for the currently selected feature type
211    */
212   private List<FeatureMatcherI> filters;
213
214   private JPanel chooseFiltersPanel;
215
216   /*
217    * the root Sequence Ontology terms (if any) that is a parent of
218    * the current feature type
219    */
220   private String rootSOTerm;
221
222   /*
223    * a map whose keys are Sequence Ontology terms - selected from the
224    * current term and its parents in the SO - whose subterms include
225    * additional feature types; the map entry is the list of additional
226    * feature types that match the key or have it as a parent term; in
227    * other words, distinct 'aggregations' that include the current feature type
228    */
229   private final Map<String, List<String>> relatedSoTerms;
230
231   /*
232    * if true, filter or colour settings are also applied to 
233    * any sub-types of parentTerm in the Sequence Ontology
234    */
235   private boolean applyFiltersToSubtypes;
236
237   private boolean applyColourToSubtypes;
238
239   private String parentSOTerm;
240
241   /**
242    * Constructor
243    * 
244    * @param frender
245    * @param theType
246    */
247   public FeatureTypeSettings(FeatureRenderer frender, String theType)
248   {
249     this.fr = frender;
250     this.featureType = theType;
251     ap = fr.ap;
252
253     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
254     relatedSoTerms = so.findSequenceOntologyGroupings(
255             this.featureType, 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     toSubtypes
963             .setToolTipText(MessageManager.getString("label.group_by_so"));
964
965     /*
966      * combobox to choose 'parent' of sub-types
967      */
968     List<String> soTerms = new ArrayList<>();
969     for (String term : relatedSoTerms.keySet())
970     {
971       soTerms.add(term);
972     }
973     // sort from most restrictive to most inclusive
974     Collections.sort(soTerms, new Comparator<String>()
975     {
976       @Override
977       public int compare(String o1, String o2)
978       {
979         return Integer.compare(relatedSoTerms.get(o1).size(),
980                 relatedSoTerms.get(o2).size());
981       }
982     });
983     List<String> tooltips = new ArrayList<>();
984     for (String term : soTerms)
985     {
986       tooltips.add(getSOTermsTooltip(relatedSoTerms.get(term)));
987     }
988     JComboBox<String> parentType = JvSwingUtils
989             .buildComboWithTooltips(soTerms, tooltips);
990     toSubtypes.add(parentType);
991
992     /*
993      * on toggle of checkbox, or change of parent SO term,
994      * reset and then reapply filters to the selected scope
995      */
996     final ActionListener action = new ActionListener()
997     {
998       /*
999        * reset and reapply settings on toggle of checkbox
1000        */
1001       @Override
1002       public void actionPerformed(ActionEvent e)
1003       {
1004         parentSOTerm = (String) parentType.getSelectedItem();
1005         if (forFilters)
1006         {
1007           applyFiltersToSubtypes = applyToSubtypesCB.isSelected();
1008           restoreOriginalFilters();
1009           filtersChanged();
1010         }
1011         else
1012         {
1013           applyColourToSubtypes = applyToSubtypesCB.isSelected();
1014           restoreOriginalColours();
1015           colourChanged(true);
1016         }
1017       }
1018     };
1019     applyToSubtypesCB.addActionListener(action);
1020     parentType.addActionListener(action);
1021
1022     return toSubtypes;
1023   }
1024
1025   private void showColourChooser(JPanel colourPanel, String key)
1026   {
1027     Color col = JColorChooser.showDialog(this,
1028             MessageManager.getString(key), colourPanel.getBackground());
1029     if (col != null)
1030     {
1031       colourPanel.setBackground(col);
1032       colourPanel.setForeground(col);
1033     }
1034     colourPanel.repaint();
1035     colourChanged(true);
1036   }
1037
1038   /**
1039    * Constructs and sets the selected colour options as the colour for the
1040    * feature type, and repaints the alignment, and optionally the Overview
1041    * and/or structure viewer if open
1042    * 
1043    * @param updateStructsAndOverview
1044    */
1045   void colourChanged(boolean updateStructsAndOverview)
1046   {
1047     if (adjusting)
1048     {
1049       /*
1050        * ignore action handlers while setting values programmatically
1051        */
1052       return;
1053     }
1054
1055     /*
1056      * ensure min-max range is for the latest choice of 
1057      * 'graduated colour by'
1058      */
1059     updateColourMinMax();
1060
1061     FeatureColourI acg = makeColourFromInputs();
1062
1063     /*
1064      * save the colour, and set on subtypes if selected
1065      */
1066     fr.setColour(featureType, acg);
1067     if (applyColourToSubtypes)
1068     {
1069       for (String child : relatedSoTerms.get(parentSOTerm))
1070       {
1071         fr.setColour(child, acg);
1072       }
1073     }
1074     refreshFeatureSettings();
1075     ap.paintAlignment(updateStructsAndOverview, updateStructsAndOverview);
1076
1077     updateColoursTab();
1078   }
1079
1080   /**
1081    * Converts the input values into an instance of FeatureColour
1082    * 
1083    * @return
1084    */
1085   private FeatureColourI makeColourFromInputs()
1086   {
1087     /*
1088      * min-max range is to (or from) threshold value if 
1089      * 'threshold is min/max' is selected 
1090      */
1091
1092     float thresh = 0f;
1093     try
1094     {
1095       thresh = Float.valueOf(thresholdValue.getText());
1096     } catch (NumberFormatException e)
1097     {
1098       // invalid inputs are already handled on entry
1099     }
1100     float minValue = min;
1101     float maxValue = max;
1102     final int thresholdOption = threshold.getSelectedIndex();
1103     if (thresholdIsMin.isSelected()
1104             && thresholdOption == ABOVE_THRESHOLD_OPTION)
1105     {
1106       minValue = thresh;
1107     }
1108     if (thresholdIsMin.isSelected()
1109             && thresholdOption == BELOW_THRESHOLD_OPTION)
1110     {
1111       maxValue = thresh;
1112     }
1113     Color noColour = null;
1114     if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
1115     {
1116       noColour = minColour.getBackground();
1117     }
1118     else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
1119     {
1120       noColour = maxColour.getBackground();
1121     }
1122
1123     /*
1124      * construct a colour that 'remembers' all the options, including
1125      * those not currently selected
1126      */
1127     FeatureColourI fc = new FeatureColour(singleColour.getBackground(),
1128             minColour.getBackground(), maxColour.getBackground(), noColour,
1129             minValue, maxValue);
1130
1131     /*
1132      * easiest case - a single colour
1133      */
1134     if (simpleColour.isSelected())
1135     {
1136       ((FeatureColour) fc).setGraduatedColour(false);
1137       return fc;
1138     }
1139
1140     /*
1141      * next easiest case - colour by Label, or attribute text
1142      */
1143     if (byCategory.isSelected())
1144     {
1145       fc.setColourByLabel(true);
1146       String byWhat = (String) colourByTextCombo.getSelectedItem();
1147       if (!LABEL_18N.equals(byWhat))
1148       {
1149         fc.setAttributeName(
1150                 FeatureMatcher.fromAttributeDisplayName(byWhat));
1151       }
1152       return fc;
1153     }
1154
1155     /*
1156      * remaining case - graduated colour by score, or attribute value;
1157      * set attribute to colour by if selected
1158      */
1159     String byWhat = (String) colourByRangeCombo.getSelectedItem();
1160     if (!SCORE_18N.equals(byWhat))
1161     {
1162       fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
1163     }
1164
1165     /*
1166      * set threshold options and 'autoscaled' which is
1167      * false if 'threshold is min/max' is selected
1168      * else true (colour range is on actual range of values)
1169      */
1170     fc.setThreshold(thresh);
1171     fc.setAutoScaled(!thresholdIsMin.isSelected());
1172     fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
1173     fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
1174
1175     if (threshline == null)
1176     {
1177       /*
1178        * todo not yet implemented: visual indication of feature threshold
1179        */
1180       threshline = new GraphLine((max - min) / 2f, "Threshold",
1181               Color.black);
1182     }
1183
1184     return fc;
1185   }
1186
1187   @Override
1188   protected void raiseClosed()
1189   {
1190     refreshFeatureSettings();
1191   }
1192
1193   protected void refreshFeatureSettings()
1194   {
1195     if (this.featureSettings != null)
1196     {
1197       featureSettings.actionPerformed(new ActionEvent(this, 0, "REFRESH"));
1198     }
1199   }
1200
1201   /**
1202    * Action on OK is just to dismiss the dialog - any changes have already been
1203    * applied
1204    */
1205   @Override
1206   public void okPressed()
1207   {
1208   }
1209
1210   /**
1211    * Action on Cancel is to restore colour scheme and filters as they were when
1212    * the dialog was opened (including any feature sub-types that may have been
1213    * changed)
1214    */
1215   @Override
1216   public void cancelPressed()
1217   {
1218     restoreOriginalColours();
1219     restoreOriginalFilters();
1220     ap.paintAlignment(true, true);
1221   }
1222
1223   /**
1224    * Restores filters for all feature types to their values when the dialog was
1225    * opened
1226    */
1227   protected void restoreOriginalFilters()
1228   {
1229     for (Entry<String, FeatureMatcherSetI> entry : originalFilters
1230             .entrySet())
1231     {
1232       fr.setFeatureFilter(entry.getKey(), entry.getValue());
1233     }
1234   }
1235
1236   /**
1237    * Restores colours for all feature types to their values when the dialog was
1238    * opened
1239    */
1240   protected void restoreOriginalColours()
1241   {
1242     for (Entry<String, FeatureColourI> entry : originalColours.entrySet())
1243     {
1244       fr.setColour(entry.getKey(), entry.getValue());
1245     }
1246   }
1247
1248   /**
1249    * Action on text entry of a threshold value
1250    */
1251   protected void thresholdValue_actionPerformed()
1252   {
1253     try
1254     {
1255       /*
1256        * set 'adjusting' flag while moving the slider, so it 
1257        * doesn't then in turn change the value (with rounding)
1258        */
1259       adjusting = true;
1260       float f = Float.parseFloat(thresholdValue.getText());
1261       f = Float.max(f, this.min);
1262       f = Float.min(f, this.max);
1263       thresholdValue.setText(String.valueOf(f));
1264       slider.setValue((int) (f * scaleFactor));
1265       threshline.value = f;
1266       thresholdValue.setBackground(Color.white); // ok
1267       adjusting = false;
1268       colourChanged(true);
1269     } catch (NumberFormatException ex)
1270     {
1271       thresholdValue.setBackground(Color.red); // not ok
1272       adjusting = false;
1273     }
1274   }
1275
1276   /**
1277    * Action on change of threshold slider value. This may be done interactively
1278    * (by moving the slider), or programmatically (to update the slider after
1279    * manual input of a threshold value).
1280    */
1281   protected void sliderValueChanged()
1282   {
1283     threshline.value = getRoundedSliderValue();
1284
1285     /*
1286      * repaint alignment, but not Overview or structure,
1287      * to avoid overload while dragging the slider
1288      */
1289     colourChanged(false);
1290   }
1291
1292   /**
1293    * Converts the slider value to its absolute value by dividing by the
1294    * scaleFactor. Rounding errors are squashed by forcing min/max of slider
1295    * range to the actual min/max of feature score range
1296    * 
1297    * @return
1298    */
1299   private float getRoundedSliderValue()
1300   {
1301     int value = slider.getValue();
1302     float f = value == slider.getMaximum() ? max
1303             : (value == slider.getMinimum() ? min : value / scaleFactor);
1304     return f;
1305   }
1306
1307   void addActionListener(ActionListener listener)
1308   {
1309     if (featureSettings != null)
1310     {
1311       System.err.println(
1312               "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1313     }
1314     featureSettings = listener;
1315   }
1316
1317   /**
1318    * A helper method to build the drop-down choice of attributes for a feature.
1319    * If 'withRange' is true, then Score, and any attributes with a min-max
1320    * range, are added. If 'withText' is true, Label and any known attributes are
1321    * added. This allows 'categorical numerical' attributes e.g. codon position
1322    * to be coloured by text.
1323    * <p>
1324    * Where metadata is available with a description for an attribute, that is
1325    * added as a tooltip.
1326    * <p>
1327    * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1328    * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1329    * <p>
1330    * This method does not add any ActionListener to the JComboBox.
1331    * 
1332    * @param attNames
1333    * @param withRange
1334    * @param withText
1335    */
1336   protected JComboBox<String> populateAttributesDropdown(
1337           List<String[]> attNames, boolean withRange, boolean withText)
1338   {
1339     List<String> displayAtts = new ArrayList<>();
1340     List<String> tooltips = new ArrayList<>();
1341
1342     if (withText)
1343     {
1344       displayAtts.add(LABEL_18N);
1345       tooltips.add(MessageManager.getString("label.description"));
1346     }
1347     if (withRange)
1348     {
1349       float[][] minMax = fr.getMinMax().get(featureType);
1350       if (minMax != null && minMax[0][0] != minMax[0][1])
1351       {
1352         displayAtts.add(SCORE_18N);
1353         tooltips.add(SCORE_18N);
1354       }
1355     }
1356
1357     FeatureAttributes fa = FeatureAttributes.getInstance();
1358     for (String[] attName : attNames)
1359     {
1360       float[] minMax = fa.getMinMax(featureType, attName);
1361       boolean hasRange = minMax != null && minMax[0] != minMax[1];
1362       if (!withText && !hasRange)
1363       {
1364         continue;
1365       }
1366       displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1367       String desc = fa.getDescription(featureType, attName);
1368       if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1369       {
1370         desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1371       }
1372       tooltips.add(desc == null ? "" : desc);
1373     }
1374
1375     JComboBox<String> attCombo = JvSwingUtils
1376             .buildComboWithTooltips(displayAtts, tooltips);
1377
1378     return attCombo;
1379   }
1380
1381   /**
1382    * Populates initial layout of the feature attribute filters panel
1383    */
1384   private JPanel initialiseFiltersPanel()
1385   {
1386     filters = new ArrayList<>();
1387
1388     JPanel outerPanel = new JPanel();
1389     outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
1390     outerPanel.setBackground(Color.white);
1391
1392     /*
1393      * option to apply colour to other selected types as well
1394      */
1395     if (!relatedSoTerms.isEmpty())
1396     {
1397       applyFiltersToSubtypes = false;
1398       outerPanel.add(initSubtypesPanel(true));
1399     }
1400
1401     JPanel filtersPanel = new JPanel();
1402     filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1403     filtersPanel.setBackground(Color.white);
1404     JvSwingUtils.createTitledBorder(filtersPanel,
1405             MessageManager.getString("label.filters"), true);
1406     outerPanel.add(filtersPanel);
1407
1408     JPanel andOrPanel = initialiseAndOrPanel();
1409     filtersPanel.add(andOrPanel);
1410
1411     /*
1412      * panel with filters - populated by refreshFiltersDisplay, 
1413      * which also sets the layout manager
1414      */
1415     chooseFiltersPanel = new JPanel();
1416     chooseFiltersPanel.setBackground(Color.white);
1417     filtersPanel.add(chooseFiltersPanel);
1418
1419     return outerPanel;
1420   }
1421
1422   /**
1423    * Lays out the panel with radio buttons to AND or OR filter conditions
1424    * 
1425    * @return
1426    */
1427   private JPanel initialiseAndOrPanel()
1428   {
1429     JPanel andOrPanel = new JPanel(new BorderLayout());
1430     andOrPanel.setBackground(Color.white);
1431
1432     andFilters = new JRadioButton(MessageManager.getString("label.and"));
1433     orFilters = new JRadioButton(MessageManager.getString("label.or"));
1434     ActionListener actionListener = new ActionListener()
1435     {
1436       @Override
1437       public void actionPerformed(ActionEvent e)
1438       {
1439         filtersChanged();
1440       }
1441     };
1442     andFilters.addActionListener(actionListener);
1443     orFilters.addActionListener(actionListener);
1444     ButtonGroup andOr = new ButtonGroup();
1445     andOr.add(andFilters);
1446     andOr.add(orFilters);
1447     andFilters.setSelected(true);
1448     andOrPanel.add(
1449             new JLabel(MessageManager.getString("label.join_conditions")));
1450     andOrPanel.add(andFilters);
1451     andOrPanel.add(orFilters);
1452
1453     return andOrPanel;
1454   }
1455
1456   /**
1457    * Builds a tooltip for the 'Apply also to...' combobox with a list of known
1458    * feature types (excluding the current type) which are sub-types of the
1459    * selected Sequence Ontology term
1460    * 
1461    * @param
1462    * @return
1463    */
1464   protected String getSOTermsTooltip(List<String> list)
1465   {
1466     StringBuilder sb = new StringBuilder(20 * relatedSoTerms.size());
1467     sb.append(MessageManager.getString("label.apply_also_to"));
1468     for (String child : list)
1469     {
1470       sb.append("<br>").append(child);
1471     }
1472     String tooltip = JvSwingUtils.wrapTooltip(true, sb.toString());
1473     return tooltip;
1474   }
1475
1476   /**
1477    * Refreshes the display to show any filters currently configured for the
1478    * selected feature type (editable, with 'remove' option), plus one extra row
1479    * for adding a condition. This should be called after a filter has been
1480    * removed, added or amended.
1481    */
1482   private void updateFiltersTab()
1483   {
1484     /*
1485      * clear the panel and list of filter conditions
1486      */
1487     chooseFiltersPanel.removeAll();
1488     filters.clear();
1489
1490     /*
1491      * look up attributes known for feature type
1492      */
1493     List<String[]> attNames = FeatureAttributes.getInstance()
1494             .getAttributes(featureType);
1495
1496     /*
1497      * if this feature type has filters set, load them first
1498      */
1499     FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1500     if (featureFilters != null)
1501     {
1502       if (!featureFilters.isAnded())
1503       {
1504         orFilters.setSelected(true);
1505       }
1506       featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1507     }
1508
1509     /*
1510      * and an empty filter for the user to populate (add)
1511      */
1512     filters.add(FeatureMatcher.NULL_MATCHER);
1513
1514     /*
1515      * use GridLayout to 'justify' rows to the top of the panel, until
1516      * there are too many to fit in, then fall back on BoxLayout
1517      */
1518     if (filters.size() <= 5)
1519     {
1520       chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1521     }
1522     else
1523     {
1524       chooseFiltersPanel.setLayout(
1525               new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1526     }
1527
1528     /*
1529      * render the conditions in rows, each in its own JPanel
1530      */
1531     int filterIndex = 0;
1532     for (FeatureMatcherI filter : filters)
1533     {
1534       JPanel row = addFilter(filter, attNames, filterIndex);
1535       chooseFiltersPanel.add(row);
1536       filterIndex++;
1537     }
1538
1539     this.validate();
1540     this.repaint();
1541   }
1542
1543   /**
1544    * A helper method that constructs a row (panel) with one filter condition:
1545    * <ul>
1546    * <li>a drop-down list of Label, Score and attribute names to choose
1547    * from</li>
1548    * <li>a drop-down list of conditions to choose from</li>
1549    * <li>a text field for input of a match pattern</li>
1550    * <li>optionally, a 'remove' button</li>
1551    * </ul>
1552    * The filter values are set as defaults for the input fields. The 'remove'
1553    * button is added unless the pattern is empty (incomplete filter condition).
1554    * <p>
1555    * Action handlers on these fields provide for
1556    * <ul>
1557    * <li>validate pattern field - should be numeric if condition is numeric</li>
1558    * <li>save filters and refresh display on any (valid) change</li>
1559    * <li>remove filter and refresh on 'Remove'</li>
1560    * <li>update conditions list on change of Label/Score/Attribute</li>
1561    * <li>refresh value field tooltip with min-max range on change of
1562    * attribute</li>
1563    * </ul>
1564    * 
1565    * @param filter
1566    * @param attNames
1567    * @param filterIndex
1568    * @return
1569    */
1570   protected JPanel addFilter(FeatureMatcherI filter,
1571           List<String[]> attNames, int filterIndex)
1572   {
1573     String[] attName = filter.getAttribute();
1574     Condition cond = filter.getMatcher().getCondition();
1575     String pattern = filter.getMatcher().getPattern();
1576
1577     JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1578     filterRow.setBackground(Color.white);
1579
1580     /*
1581      * drop-down choice of attribute, with description as a tooltip 
1582      * if we can obtain it
1583      */
1584     final JComboBox<String> attCombo = populateAttributesDropdown(attNames,
1585             true, true);
1586     String filterBy = setSelectedAttribute(attCombo, filter);
1587
1588     JComboBox<Condition> condCombo = new JComboBox<>();
1589
1590     JTextField patternField = new JTextField(8);
1591     patternField.setText(pattern);
1592
1593     /*
1594      * action handlers that validate and (if valid) apply changes
1595      */
1596     ActionListener actionListener = new ActionListener()
1597     {
1598       @Override
1599       public void actionPerformed(ActionEvent e)
1600       {
1601         if (validateFilter(patternField, condCombo))
1602         {
1603           if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1604           {
1605             filtersChanged();
1606           }
1607         }
1608       }
1609     };
1610     ItemListener itemListener = new ItemListener()
1611     {
1612       @Override
1613       public void itemStateChanged(ItemEvent e)
1614       {
1615         actionListener.actionPerformed(null);
1616       }
1617     };
1618
1619     if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1620     {
1621       attCombo.setSelectedIndex(0);
1622     }
1623     else
1624     {
1625       attCombo.setSelectedItem(
1626               FeatureMatcher.toAttributeDisplayName(attName));
1627     }
1628     attCombo.addItemListener(new ItemListener()
1629     {
1630       @Override
1631       public void itemStateChanged(ItemEvent e)
1632       {
1633         /*
1634          * on change of attribute, refresh the conditions list to
1635          * ensure it is appropriate for the attribute datatype
1636          */
1637         populateConditions((String) attCombo.getSelectedItem(),
1638                 (Condition) condCombo.getSelectedItem(), condCombo,
1639                 patternField);
1640         actionListener.actionPerformed(null);
1641       }
1642     });
1643
1644     filterRow.add(attCombo);
1645
1646     /*
1647      * drop-down choice of test condition
1648      */
1649     populateConditions(filterBy, cond, condCombo, patternField);
1650     condCombo.setPreferredSize(new Dimension(150, 20));
1651     condCombo.addItemListener(itemListener);
1652     filterRow.add(condCombo);
1653
1654     /*
1655      * pattern to match against
1656      */
1657     patternField.addActionListener(actionListener);
1658     patternField.addFocusListener(new FocusAdapter()
1659     {
1660       @Override
1661       public void focusLost(FocusEvent e)
1662       {
1663         actionListener.actionPerformed(null);
1664       }
1665     });
1666     filterRow.add(patternField);
1667
1668     /*
1669      * disable pattern field for condition 'Present / NotPresent'
1670      */
1671     Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1672     patternField.setEnabled(selectedCondition.needsAPattern());
1673
1674     /*
1675      * if a numeric condition is selected, show the value range
1676      * as a tooltip on the value input field
1677      */
1678     setNumericHints(filterBy, selectedCondition, patternField);
1679
1680     /*
1681      * add remove button if filter is populated (non-empty pattern)
1682      */
1683     if (!patternField.isEnabled()
1684             || (pattern != null && pattern.trim().length() > 0))
1685     {
1686       JButton removeCondition = new JButton("\u2717"); // Dingbats cursive x
1687       removeCondition.setToolTipText(
1688               MessageManager.getString("label.delete_condition"));
1689       removeCondition.setBorder(new EmptyBorder(0, 0, 0, 0));
1690       removeCondition.addActionListener(new ActionListener()
1691       {
1692         @Override
1693         public void actionPerformed(ActionEvent e)
1694         {
1695           filters.remove(filterIndex);
1696           filtersChanged();
1697         }
1698       });
1699       filterRow.add(removeCondition);
1700     }
1701
1702     return filterRow;
1703   }
1704
1705   /**
1706    * Sets the selected item in the Label/Score/Attribute drop-down to match the
1707    * filter
1708    * 
1709    * @param attCombo
1710    * @param filter
1711    */
1712   private String setSelectedAttribute(JComboBox<String> attCombo,
1713           FeatureMatcherI filter)
1714   {
1715     String item = null;
1716     if (filter.isByScore())
1717     {
1718       item = SCORE_18N;
1719     }
1720     else if (filter.isByLabel())
1721     {
1722       item = LABEL_18N;
1723     }
1724     else
1725     {
1726       item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1727     }
1728     attCombo.setSelectedItem(item);
1729     return item;
1730   }
1731
1732   /**
1733    * If a numeric comparison condition is selected, retrieves the min-max range
1734    * for the value (score or attribute), and sets it as a tooltip on the value
1735    * field. If the field is currently empty, then pre-populates it with
1736    * <ul>
1737    * <li>the minimum value, if condition is > or >=</li>
1738    * <li>the maximum value, if condition is < or <=</li>
1739    * </ul>
1740    * 
1741    * @param attName
1742    * @param selectedCondition
1743    * @param patternField
1744    */
1745   private void setNumericHints(String attName, Condition selectedCondition,
1746           JTextField patternField)
1747   {
1748     patternField.setToolTipText("");
1749
1750     if (selectedCondition.isNumeric())
1751     {
1752       float[] minMax = getMinMax(attName);
1753       if (minMax != null)
1754       {
1755         String minFormatted = DECFMT_2_2.format(minMax[0]);
1756         String maxFormatted = DECFMT_2_2.format(minMax[1]);
1757         String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1758         patternField.setToolTipText(tip);
1759         if (patternField.getText().isEmpty())
1760         {
1761           if (selectedCondition == Condition.GE
1762                   || selectedCondition == Condition.GT)
1763           {
1764             patternField.setText(minFormatted);
1765           }
1766           else
1767           {
1768             if (selectedCondition == Condition.LE
1769                     || selectedCondition == Condition.LT)
1770             {
1771               patternField.setText(maxFormatted);
1772             }
1773           }
1774         }
1775       }
1776     }
1777   }
1778
1779   /**
1780    * Populates the drop-down list of comparison conditions for the given
1781    * attribute name. The conditions added depend on the datatype of the
1782    * attribute values. The supplied condition is set as the selected item in the
1783    * list, provided it is in the list. If the pattern is now invalid
1784    * (non-numeric pattern for a numeric condition), it is cleared.
1785    * 
1786    * @param attName
1787    * @param cond
1788    * @param condCombo
1789    * @param patternField
1790    */
1791   private void populateConditions(String attName, Condition cond,
1792           JComboBox<Condition> condCombo, JTextField patternField)
1793   {
1794     Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1795             FeatureMatcher.fromAttributeDisplayName(attName));
1796     if (LABEL_18N.equals(attName))
1797     {
1798       type = Datatype.Character;
1799     }
1800     else if (SCORE_18N.equals(attName))
1801     {
1802       type = Datatype.Number;
1803     }
1804
1805     /*
1806      * remove itemListener before starting
1807      */
1808     ItemListener listener = condCombo.getItemListeners()[0];
1809     condCombo.removeItemListener(listener);
1810     boolean condIsValid = false;
1811
1812     condCombo.removeAllItems();
1813     for (Condition c : Condition.values())
1814     {
1815       if ((c.isNumeric() && type == Datatype.Number)
1816               || (!c.isNumeric() && type != Datatype.Number))
1817       {
1818         condCombo.addItem(c);
1819         if (c == cond)
1820         {
1821           condIsValid = true;
1822         }
1823       }
1824     }
1825
1826     /*
1827      * set the selected condition (does nothing if not in the list)
1828      */
1829     if (condIsValid)
1830     {
1831       condCombo.setSelectedItem(cond);
1832     }
1833     else
1834     {
1835       condCombo.setSelectedIndex(0);
1836     }
1837
1838     /*
1839      * clear pattern if it is now invalid for condition
1840      */
1841     if (((Condition) condCombo.getSelectedItem()).isNumeric())
1842     {
1843       try
1844       {
1845         String pattern = patternField.getText().trim();
1846         if (pattern.length() > 0)
1847         {
1848           Float.valueOf(pattern);
1849         }
1850       } catch (NumberFormatException e)
1851       {
1852         patternField.setText("");
1853       }
1854     }
1855
1856     /*
1857      * restore the listener
1858      */
1859     condCombo.addItemListener(listener);
1860   }
1861
1862   /**
1863    * Answers true unless a numeric condition has been selected with a
1864    * non-numeric value. Sets the value field to RED with a tooltip if in error.
1865    * <p>
1866    * If the pattern is expected but is empty, this method returns false, but
1867    * does not mark the field as invalid. This supports selecting an attribute
1868    * for a new condition before a match pattern has been entered.
1869    * 
1870    * @param value
1871    * @param condCombo
1872    */
1873   protected boolean validateFilter(JTextField value,
1874           JComboBox<Condition> condCombo)
1875   {
1876     if (value == null || condCombo == null)
1877     {
1878       return true; // fields not populated
1879     }
1880
1881     Condition cond = (Condition) condCombo.getSelectedItem();
1882     if (!cond.needsAPattern())
1883     {
1884       return true;
1885     }
1886
1887     value.setBackground(Color.white);
1888     value.setToolTipText("");
1889     String v1 = value.getText().trim();
1890     if (v1.length() == 0)
1891     {
1892       // return false;
1893     }
1894
1895     if (cond.isNumeric() && v1.length() > 0)
1896     {
1897       try
1898       {
1899         Float.valueOf(v1);
1900       } catch (NumberFormatException e)
1901       {
1902         value.setBackground(Color.red);
1903         value.setToolTipText(
1904                 MessageManager.getString("label.numeric_required"));
1905         return false;
1906       }
1907     }
1908
1909     return true;
1910   }
1911
1912   /**
1913    * Constructs a filter condition from the given input fields, and replaces the
1914    * condition at filterIndex with the new one. Does nothing if the pattern
1915    * field is blank (unless the match condition is one that doesn't require a
1916    * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1917    * false.
1918    * <p>
1919    * This method may update the tooltip on the filter value field to show the
1920    * value range, if a numeric condition is selected. This ensures the tooltip
1921    * is updated when a numeric valued attribute is chosen on the last 'add a
1922    * filter' row.
1923    * 
1924    * @param attCombo
1925    * @param condCombo
1926    * @param valueField
1927    * @param filterIndex
1928    */
1929   protected boolean updateFilter(JComboBox<String> attCombo,
1930           JComboBox<Condition> condCombo, JTextField valueField,
1931           int filterIndex)
1932   {
1933     String attName = (String) attCombo.getSelectedItem();
1934     Condition cond = (Condition) condCombo.getSelectedItem();
1935     String pattern = valueField.getText().trim();
1936
1937     setNumericHints(attName, cond, valueField);
1938
1939     if (pattern.length() == 0 && cond.needsAPattern())
1940     {
1941       valueField.setEnabled(true); // ensure pattern field is enabled!
1942       return false;
1943     }
1944
1945     /*
1946      * Construct a matcher that operates on Label, Score, 
1947      * or named attribute
1948      */
1949     FeatureMatcherI km = null;
1950     if (LABEL_18N.equals(attName))
1951     {
1952       km = FeatureMatcher.byLabel(cond, pattern);
1953     }
1954     else if (SCORE_18N.equals(attName))
1955     {
1956       km = FeatureMatcher.byScore(cond, pattern);
1957     }
1958     else
1959     {
1960       km = FeatureMatcher.byAttribute(cond, pattern,
1961               FeatureMatcher.fromAttributeDisplayName(attName));
1962     }
1963
1964     filters.set(filterIndex, km);
1965
1966     return true;
1967   }
1968
1969   /**
1970    * Action on any change to feature filtering, namely
1971    * <ul>
1972    * <li>change of selected attribute</li>
1973    * <li>change of selected condition</li>
1974    * <li>change of match pattern</li>
1975    * <li>removal of a condition</li>
1976    * </ul>
1977    * The inputs are parsed into a combined filter and this is set for the
1978    * feature type, and the alignment redrawn.
1979    */
1980   protected void filtersChanged()
1981   {
1982     /*
1983      * update the filter conditions for the feature type
1984      */
1985     boolean anded = andFilters.isSelected();
1986     FeatureMatcherSetI combined = new FeatureMatcherSet();
1987
1988     for (FeatureMatcherI filter : filters)
1989     {
1990       String pattern = filter.getMatcher().getPattern();
1991       Condition condition = filter.getMatcher().getCondition();
1992       if (pattern.trim().length() > 0 || !condition.needsAPattern())
1993       {
1994         if (anded)
1995         {
1996           combined.and(filter);
1997         }
1998         else
1999         {
2000           combined.or(filter);
2001         }
2002       }
2003     }
2004
2005     /*
2006      * save the filter conditions in the FeatureRenderer
2007      * (note this might now be an empty filter with no conditions)
2008      */
2009     fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
2010     if (applyFiltersToSubtypes)
2011     {
2012       for (String child : relatedSoTerms.get(parentSOTerm))
2013       {
2014         fr.setFeatureFilter(child, combined.isEmpty() ? null : combined);
2015       }
2016     }
2017
2018     refreshFeatureSettings();
2019     ap.paintAlignment(true, true);
2020
2021     updateFiltersTab();
2022   }
2023 }