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