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