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