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