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