2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
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;
38 import java.awt.BorderLayout;
39 import java.awt.Color;
40 import java.awt.Dimension;
41 import java.awt.FlowLayout;
42 import java.awt.Graphics;
43 import java.awt.GridLayout;
44 import java.awt.event.ActionEvent;
45 import java.awt.event.ActionListener;
46 import java.awt.event.FocusAdapter;
47 import java.awt.event.FocusEvent;
48 import java.awt.event.ItemEvent;
49 import java.awt.event.ItemListener;
50 import java.awt.event.MouseAdapter;
51 import java.awt.event.MouseEvent;
52 import java.text.DecimalFormat;
53 import java.util.ArrayList;
54 import java.util.List;
56 import javax.swing.BorderFactory;
57 import javax.swing.BoxLayout;
58 import javax.swing.ButtonGroup;
59 import javax.swing.JButton;
60 import javax.swing.JCheckBox;
61 import javax.swing.JComboBox;
62 import javax.swing.JLabel;
63 import javax.swing.JPanel;
64 import javax.swing.JRadioButton;
65 import javax.swing.JSlider;
66 import javax.swing.JTextField;
67 import javax.swing.border.LineBorder;
68 import javax.swing.event.ChangeEvent;
69 import javax.swing.event.ChangeListener;
72 * A dialog where the user can configure colour scheme, and any filters, for one
75 * (Was FeatureColourChooser prior to Jalview 1.11, renamed with the addition of
78 public class FeatureTypeSettings extends JalviewDialog
80 private final static String LABEL_18N = MessageManager
81 .getString("label.label");
83 private final static String SCORE_18N = MessageManager
84 .getString("label.score");
86 private static final int RADIO_WIDTH = 130;
88 private static final String COLON = ":";
90 private static final int MAX_TOOLTIP_LENGTH = 50;
92 private static final int NO_COLOUR_OPTION = 0;
94 private static final int MIN_COLOUR_OPTION = 1;
96 private static final int MAX_COLOUR_OPTION = 2;
98 private static final int ABOVE_THRESHOLD_OPTION = 1;
100 private static final int BELOW_THRESHOLD_OPTION = 2;
102 private static final DecimalFormat DECFMT_2_2 = new DecimalFormat(
106 * FeatureRenderer holds colour scheme and filters for feature types
108 private final FeatureRenderer fr; // todo refactor to allow interface type
112 * the view panel to update when settings change
114 final AlignmentViewPanel ap;
116 final String featureType;
119 * the colour and filters to reset to on Cancel
121 private final FeatureColourI originalColour;
123 private final FeatureMatcherSetI originalFilter;
126 * set flag to true when setting values programmatically,
127 * to avoid invocation of action handlers
129 boolean adjusting = false;
132 * minimum of the value range for graduated colour
133 * (may be for feature score or for a numeric attribute)
138 * maximum of the value range for graduated colour
143 * scale factor for conversion between absolute min-max and slider
148 * radio button group, to select what to colour by:
149 * simple colour, by category (text), or graduated
151 JRadioButton simpleColour = new JRadioButton();
153 JRadioButton byCategory = new JRadioButton();
155 JRadioButton graduatedColour = new JRadioButton();
161 JPanel singleColour = new JPanel();
163 JPanel minColour = new JPanel();
165 JPanel maxColour = new JPanel();
167 private JComboBox<String> threshold = new JComboBox<>();
169 JSlider slider = new JSlider();
171 JTextField thresholdValue = new JTextField(20);
173 private JCheckBox thresholdIsMin = new JCheckBox();
175 private GraphLine threshline;
177 private ActionListener featureSettings = null;
179 private ActionListener changeColourAction;
182 * choice of option for 'colour for no value'
184 private JComboBox<String> noValueCombo;
187 * choice of what to colour by text (Label or attribute)
189 private JComboBox<Object> colourByTextCombo;
192 * choice of what to colour by range (Score or attribute)
194 private JComboBox<Object> colourByRangeCombo;
196 private JRadioButton andFilters;
198 private JRadioButton orFilters;
201 * filters for the currently selected feature type
203 List<FeatureMatcherI> filters;
205 private JPanel chooseFiltersPanel;
213 public FeatureTypeSettings(FeatureRenderer frender, String theType)
216 this.featureType = theType;
218 originalFilter = fr.getFeatureFilter(theType);
219 originalColour = fr.getFeatureColours().get(theType);
226 } catch (Exception ex)
228 ex.printStackTrace();
232 updateColoursPanel();
234 updateFiltersPanel();
238 colourChanged(false);
240 String title = MessageManager
241 .formatMessage("label.display_settings_for", new String[]
243 initDialogFrame(this, true, false, title, 580, 500);
248 * Configures the widgets on the Colours panel according to the current feature
251 private void updateColoursPanel()
253 FeatureColourI fc = fr.getFeatureColours().get(featureType);
256 * suppress action handling while updating values programmatically
264 if (fc.isSimpleColour())
266 singleColour.setBackground(fc.getColour());
267 singleColour.setForeground(fc.getColour());
268 simpleColour.setSelected(true);
272 * colour by text (Label or attribute text)
274 if (fc.isColourByLabel())
276 byCategory.setSelected(true);
277 colourByTextCombo.setEnabled(colourByTextCombo.getItemCount() > 1);
278 if (fc.isColourByAttribute())
280 String[] attributeName = fc.getAttributeName();
281 colourByTextCombo.setSelectedItem(
282 FeatureMatcher.toAttributeDisplayName(attributeName));
286 colourByTextCombo.setSelectedItem(LABEL_18N);
291 colourByTextCombo.setEnabled(false);
294 if (!fc.isGraduatedColour())
296 colourByRangeCombo.setEnabled(false);
297 minColour.setEnabled(false);
298 maxColour.setEnabled(false);
299 noValueCombo.setEnabled(false);
300 threshold.setEnabled(false);
301 slider.setEnabled(false);
302 thresholdValue.setEnabled(false);
303 thresholdIsMin.setEnabled(false);
308 * Graduated colour, by score or attribute value range
310 graduatedColour.setSelected(true);
311 updateColourMinMax(); // ensure min, max are set
312 colourByRangeCombo.setEnabled(colourByRangeCombo.getItemCount() > 1);
313 minColour.setEnabled(true);
314 maxColour.setEnabled(true);
315 noValueCombo.setEnabled(true);
316 threshold.setEnabled(true);
317 minColour.setBackground(fc.getMinColour());
318 maxColour.setBackground(fc.getMaxColour());
320 if (fc.isColourByAttribute())
322 String[] attributeName = fc.getAttributeName();
323 colourByRangeCombo.setSelectedItem(
324 FeatureMatcher.toAttributeDisplayName(attributeName));
328 colourByRangeCombo.setSelectedItem(SCORE_18N);
330 Color noColour = fc.getNoColour();
331 if (noColour == null)
333 noValueCombo.setSelectedIndex(NO_COLOUR_OPTION);
335 else if (noColour.equals(fc.getMinColour()))
337 noValueCombo.setSelectedIndex(MIN_COLOUR_OPTION);
339 else if (noColour.equals(fc.getMaxColour()))
341 noValueCombo.setSelectedIndex(MAX_COLOUR_OPTION);
345 * update min-max scaling if there is a range to work with,
346 * else disable the widgets (this shouldn't happen if only
347 * valid options are offered in the combo box)
349 scaleFactor = (max == min) ? 1f : 100f / (max - min);
350 float range = (max - min) * scaleFactor;
351 slider.setMinimum((int) (min * scaleFactor));
352 slider.setMaximum((int) (max * scaleFactor));
353 slider.setMajorTickSpacing((int) (range / 10f));
355 threshline = new GraphLine((max - min) / 2f, "Threshold",
357 threshline.value = fc.getThreshold();
359 if (fc.hasThreshold())
361 threshold.setSelectedIndex(
362 fc.isAboveThreshold() ? ABOVE_THRESHOLD_OPTION
363 : BELOW_THRESHOLD_OPTION);
364 slider.setEnabled(true);
365 slider.setValue((int) (fc.getThreshold() * scaleFactor));
366 thresholdValue.setText(String.valueOf(fc.getThreshold()));
367 thresholdValue.setEnabled(true);
368 thresholdIsMin.setEnabled(true);
372 slider.setEnabled(false);
373 thresholdValue.setEnabled(false);
374 thresholdIsMin.setEnabled(false);
376 thresholdIsMin.setSelected(!fc.isAutoScaled());
384 * Configures the initial layout
386 private void initialise()
388 this.setLayout(new BorderLayout());
391 * an ActionListener that applies colour changes
393 changeColourAction = new ActionListener()
396 public void actionPerformed(ActionEvent e)
403 * first panel: colour options
405 JPanel coloursPanel = initialiseColoursPanel();
406 this.add(coloursPanel, BorderLayout.NORTH);
409 * second panel: filter options
411 JPanel filtersPanel = initialiseFiltersPanel();
412 this.add(filtersPanel, BorderLayout.CENTER);
414 JPanel okCancelPanel = initialiseOkCancelPanel();
416 this.add(okCancelPanel, BorderLayout.SOUTH);
420 * Updates the min-max range if Colour By selected item is Score, or an
421 * attribute, with a min-max range
423 protected void updateColourMinMax()
425 if (!graduatedColour.isSelected())
430 String colourBy = (String) colourByRangeCombo.getSelectedItem();
431 float[] minMax = getMinMax(colourBy);
441 * Retrieves the min-max range:
443 * <li>of feature score, if colour or filter is by Score</li>
444 * <li>else of the selected attribute</li>
450 private float[] getMinMax(String attName)
452 float[] minMax = null;
453 if (SCORE_18N.equals(attName))
455 minMax = fr.getMinMax().get(featureType)[0];
459 // colour by attribute range
460 minMax = FeatureAttributes.getInstance().getMinMax(featureType,
461 FeatureMatcher.fromAttributeDisplayName(attName));
467 * Lay out fields for graduated colour (by score or attribute value)
471 private JPanel initialiseGraduatedColourPanel()
473 JPanel graduatedColourPanel = new JPanel();
474 graduatedColourPanel.setLayout(
475 new BoxLayout(graduatedColourPanel, BoxLayout.Y_AXIS));
476 JvSwingUtils.createTitledBorder(graduatedColourPanel,
477 MessageManager.getString("label.graduated_colour"), true);
478 graduatedColourPanel.setBackground(Color.white);
481 * first row: graduated colour radio button, score/attribute drop-down
483 JPanel graduatedChoicePanel = new JPanel(
484 new FlowLayout(FlowLayout.LEFT));
485 graduatedChoicePanel.setBackground(Color.white);
486 graduatedColour = new JRadioButton(
487 MessageManager.getString("label.by_range_of") + COLON);
488 graduatedColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
489 graduatedColour.setOpaque(false);
490 graduatedColour.addItemListener(new ItemListener()
493 public void itemStateChanged(ItemEvent e)
495 if (graduatedColour.isSelected())
501 graduatedChoicePanel.add(graduatedColour);
503 List<String[]> attNames = FeatureAttributes.getInstance()
504 .getAttributes(featureType);
505 colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
506 colourByRangeCombo.addItemListener(new ItemListener()
509 public void itemStateChanged(ItemEvent e)
516 * disable graduated colour option if no range found
518 graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
520 graduatedChoicePanel.add(colourByRangeCombo);
521 graduatedColourPanel.add(graduatedChoicePanel);
524 * second row - min/max/no colours
526 JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
527 colourRangePanel.setBackground(Color.white);
528 graduatedColourPanel.add(colourRangePanel);
530 minColour.setFont(JvSwingUtils.getLabelFont());
531 minColour.setBorder(BorderFactory.createLineBorder(Color.black));
532 minColour.setPreferredSize(new Dimension(40, 20));
533 minColour.setToolTipText(MessageManager.getString("label.min_colour"));
534 minColour.addMouseListener(new MouseAdapter()
537 public void mousePressed(MouseEvent e)
539 if (minColour.isEnabled())
541 String ttl = MessageManager.getString("label.select_colour_minimum_value");
542 showColourChooser(minColour, ttl);
547 maxColour.setFont(JvSwingUtils.getLabelFont());
548 maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
549 maxColour.setPreferredSize(new Dimension(40, 20));
550 maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
551 maxColour.addMouseListener(new MouseAdapter()
554 public void mousePressed(MouseEvent e)
556 if (maxColour.isEnabled())
558 String ttl = MessageManager.getString("label.select_colour_maximum_value");
559 showColourChooser(maxColour, ttl);
563 maxColour.setBorder(new LineBorder(Color.black));
566 * if not set, default max colour to last plain colour,
567 * and make min colour a pale version of max colour
569 Color max = originalColour.getMaxColour();
572 max = originalColour.getColour();
573 minColour.setBackground(ColorUtils.bleachColour(max, 0.9f));
577 maxColour.setBackground(max);
578 minColour.setBackground(originalColour.getMinColour());
581 noValueCombo = new JComboBox<>();
582 noValueCombo.addItem(MessageManager.getString("label.no_colour"));
583 noValueCombo.addItem(MessageManager.getString("label.min_colour"));
584 noValueCombo.addItem(MessageManager.getString("label.max_colour"));
585 noValueCombo.addItemListener(new ItemListener()
588 public void itemStateChanged(ItemEvent e)
594 JLabel minText = new JLabel(
595 MessageManager.getString("label.min_value") + COLON);
596 minText.setFont(JvSwingUtils.getLabelFont());
597 JLabel maxText = new JLabel(
598 MessageManager.getString("label.max_value") + COLON);
599 maxText.setFont(JvSwingUtils.getLabelFont());
600 JLabel noText = new JLabel(
601 MessageManager.getString("label.no_value") + COLON);
602 noText.setFont(JvSwingUtils.getLabelFont());
604 colourRangePanel.add(minText);
605 colourRangePanel.add(minColour);
606 colourRangePanel.add(maxText);
607 colourRangePanel.add(maxColour);
608 colourRangePanel.add(noText);
609 colourRangePanel.add(noValueCombo);
612 * third row - threshold options and value
614 JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
615 thresholdPanel.setBackground(Color.white);
616 graduatedColourPanel.add(thresholdPanel);
618 threshold.addActionListener(changeColourAction);
619 threshold.setToolTipText(MessageManager
620 .getString("label.threshold_feature_display_by_score"));
621 threshold.addItem(MessageManager
622 .getString("label.threshold_feature_no_threshold")); // index 0
623 threshold.addItem(MessageManager
624 .getString("label.threshold_feature_above_threshold")); // index 1
625 threshold.addItem(MessageManager
626 .getString("label.threshold_feature_below_threshold")); // index 2
628 thresholdValue.addActionListener(new ActionListener()
631 public void actionPerformed(ActionEvent e)
633 thresholdValue_actionPerformed();
636 thresholdValue.addFocusListener(new FocusAdapter()
639 public void focusLost(FocusEvent e)
641 thresholdValue_actionPerformed();
644 slider.setPaintLabels(false);
645 slider.setPaintTicks(true);
646 slider.setBackground(Color.white);
647 slider.setEnabled(false);
648 slider.setOpaque(false);
649 slider.setPreferredSize(new Dimension(100, 32));
650 slider.setToolTipText(
651 MessageManager.getString("label.adjust_threshold"));
653 slider.addChangeListener(new ChangeListener()
656 public void stateChanged(ChangeEvent evt)
661 .setText(String.valueOf(slider.getValue() / scaleFactor));
662 thresholdValue.setBackground(Color.white); // to reset red for invalid
663 sliderValueChanged();
667 slider.addMouseListener(new MouseAdapter()
670 public void mouseReleased(MouseEvent evt)
673 * only update Overview and/or structure colouring
674 * when threshold slider drag ends (mouse up)
678 ap.paintAlignment(true, true);
683 thresholdValue.setEnabled(false);
684 thresholdValue.setColumns(7);
686 thresholdPanel.add(threshold);
687 thresholdPanel.add(slider);
688 thresholdPanel.add(thresholdValue);
690 thresholdIsMin.setBackground(Color.white);
692 .setText(MessageManager.getString("label.threshold_minmax"));
693 thresholdIsMin.setToolTipText(MessageManager
694 .getString("label.toggle_absolute_relative_display_threshold"));
695 thresholdIsMin.addActionListener(changeColourAction);
696 thresholdPanel.add(thresholdIsMin);
698 return graduatedColourPanel;
702 * Lay out OK and Cancel buttons
706 private JPanel initialiseOkCancelPanel()
708 JPanel okCancelPanel = new JPanel();
709 // okCancelPanel.setBackground(Color.white);
710 okCancelPanel.add(ok);
711 okCancelPanel.add(cancel);
712 return okCancelPanel;
716 * Lay out Colour options panel, containing
718 * <li>plain colour, with colour picker</li>
719 * <li>colour by text, with choice of Label or other attribute</li>
720 * <li>colour by range, of score or other attribute, when available</li>
725 private JPanel initialiseColoursPanel()
727 JPanel colourByPanel = new JPanel();
728 colourByPanel.setBackground(Color.white);
729 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
730 JvSwingUtils.createTitledBorder(colourByPanel,
731 MessageManager.getString("action.colour"), true);
734 * simple colour radio button and colour picker
736 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
737 simpleColourPanel.setBackground(Color.white);
738 colourByPanel.add(simpleColourPanel);
740 simpleColour = new JRadioButton(
741 MessageManager.getString("label.simple_colour"));
742 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
743 simpleColour.setOpaque(false);
744 simpleColour.addItemListener(new ItemListener()
747 public void itemStateChanged(ItemEvent e)
749 if (simpleColour.isSelected() && !adjusting)
756 singleColour.setFont(JvSwingUtils.getLabelFont());
757 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
758 singleColour.setPreferredSize(new Dimension(40, 20));
759 // if (originalColour.isGraduatedColour())
761 // singleColour.setBackground(originalColour.getMaxColour());
762 // singleColour.setForeground(originalColour.getMaxColour());
766 singleColour.setBackground(originalColour.getColour());
767 singleColour.setForeground(originalColour.getColour());
769 singleColour.addMouseListener(new MouseAdapter()
772 public void mousePressed(MouseEvent e)
774 if (simpleColour.isSelected())
776 String ttl = MessageManager.formatMessage("label.select_colour_for", featureType);
777 showColourChooser(singleColour, ttl);
781 simpleColourPanel.add(simpleColour); // radio button
782 simpleColourPanel.add(singleColour); // colour picker button
785 * colour by text (category) radio button and drop-down choice list
787 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
788 byTextPanel.setBackground(Color.white);
789 JvSwingUtils.createTitledBorder(byTextPanel,
790 MessageManager.getString("label.colour_by_text"), true);
791 colourByPanel.add(byTextPanel);
792 byCategory = new JRadioButton(
793 MessageManager.getString("label.by_text_of") + COLON);
794 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
795 byCategory.setOpaque(false);
796 byCategory.addItemListener(new ItemListener()
799 public void itemStateChanged(ItemEvent e)
801 if (byCategory.isSelected())
807 byTextPanel.add(byCategory);
809 List<String[]> attNames = FeatureAttributes.getInstance()
810 .getAttributes(featureType);
811 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
812 colourByTextCombo.addItemListener(new ItemListener()
815 public void itemStateChanged(ItemEvent e)
820 byTextPanel.add(colourByTextCombo);
823 * graduated colour panel
825 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
826 colourByPanel.add(graduatedColourPanel);
829 * 3 radio buttons select between simple colour,
830 * by category (text), or graduated
832 ButtonGroup bg = new ButtonGroup();
833 bg.add(simpleColour);
835 bg.add(graduatedColour);
837 return colourByPanel;
841 * Shows a colour chooser dialog, and if a selection is made, updates the
842 * colour of the given panel
845 * the panel whose background colour is being picked
848 void showColourChooser(JPanel colourPanel, String title)
850 ColourChooserListener listener = new ColourChooserListener()
853 public void colourSelected(Color col)
855 colourPanel.setBackground(col);
856 colourPanel.setForeground(col);
857 colourPanel.repaint();
861 JalviewColourChooser.showColourChooser(this, title,
862 colourPanel.getBackground(), listener);
866 * Constructs and sets the selected colour options as the colour for the
867 * feature type, and repaints the alignment, and optionally the Overview
868 * and/or structure viewer if open
870 * @param updateStructsAndOverview
872 void colourChanged(boolean updateStructsAndOverview)
877 * ignore action handlers while setting values programmatically
883 * ensure min-max range is for the latest choice of
884 * 'graduated colour by'
886 updateColourMinMax();
888 FeatureColourI acg = makeColourFromInputs();
891 * save the colour, and repaint stuff
893 fr.setColour(featureType, acg);
894 ap.paintAlignment(updateStructsAndOverview, updateStructsAndOverview);
896 updateColoursPanel();
900 * Converts the input values into an instance of FeatureColour
904 private FeatureColourI makeColourFromInputs()
907 * min-max range is to (or from) threshold value if
908 * 'threshold is min/max' is selected
914 thresh = Float.valueOf(thresholdValue.getText());
915 } catch (NumberFormatException e)
917 // invalid inputs are already handled on entry
919 float minValue = min;
920 float maxValue = max;
921 int thresholdOption = threshold.getSelectedIndex();
922 if (thresholdIsMin.isSelected()
923 && thresholdOption == ABOVE_THRESHOLD_OPTION)
927 if (thresholdIsMin.isSelected()
928 && thresholdOption == BELOW_THRESHOLD_OPTION)
932 Color noColour = null;
933 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
935 noColour = minColour.getBackground();
937 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
939 noColour = maxColour.getBackground();
943 * construct a colour that 'remembers' all the options, including
944 * those not currently selected
946 FeatureColourI fc = new FeatureColour(singleColour.getBackground(),
947 minColour.getBackground(), maxColour.getBackground(), noColour,
951 * easiest case - a single colour
953 if (simpleColour.isSelected())
955 ((FeatureColour) fc).setGraduatedColour(false);
960 * next easiest case - colour by Label, or attribute text
962 if (byCategory.isSelected())
964 fc.setColourByLabel(true);
965 String byWhat = (String) colourByTextCombo.getSelectedItem();
966 if (!LABEL_18N.equals(byWhat))
969 FeatureMatcher.fromAttributeDisplayName(byWhat));
975 * remaining case - graduated colour by score, or attribute value;
976 * set attribute to colour by if selected
978 String byWhat = (String) colourByRangeCombo.getSelectedItem();
979 if (!SCORE_18N.equals(byWhat))
981 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
985 * set threshold options and 'autoscaled' which is
986 * false if 'threshold is min/max' is selected
987 * else true (colour range is on actual range of values)
989 fc.setThreshold(thresh);
990 fc.setAutoScaled(!thresholdIsMin.isSelected());
991 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
992 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
994 if (threshline == null)
997 * todo not yet implemented: visual indication of feature threshold
999 threshline = new GraphLine((max - min) / 2f, "Threshold",
1007 protected void raiseClosed()
1009 if (this.featureSettings != null)
1011 featureSettings.actionPerformed(new ActionEvent(this, 0, "CLOSED"));
1016 * Action on OK is just to dismiss the dialog - any changes have already been
1020 public void okPressed()
1025 * Action on Cancel is to restore colour scheme and filters as they were when
1026 * the dialog was opened
1029 public void cancelPressed()
1031 fr.setColour(featureType, originalColour);
1032 fr.setFeatureFilter(featureType, originalFilter);
1033 ap.paintAlignment(true, true);
1037 * Action on text entry of a threshold value
1039 protected void thresholdValue_actionPerformed()
1044 * set 'adjusting' flag while moving the slider, so it
1045 * doesn't then in turn change the value (with rounding)
1048 float f = Float.parseFloat(thresholdValue.getText());
1049 f = Float.max(f, this.min);
1050 f = Float.min(f, this.max);
1051 thresholdValue.setText(String.valueOf(f));
1052 slider.setValue((int) (f * scaleFactor));
1053 threshline.value = f;
1054 thresholdValue.setBackground(Color.white); // ok
1056 colourChanged(true);
1057 } catch (NumberFormatException ex)
1059 thresholdValue.setBackground(Color.red); // not ok
1065 * Action on change of threshold slider value. This may be done interactively
1066 * (by moving the slider), or programmatically (to update the slider after
1067 * manual input of a threshold value).
1069 protected void sliderValueChanged()
1071 threshline.value = getRoundedSliderValue();
1074 * repaint alignment, but not Overview or structure,
1075 * to avoid overload while dragging the slider
1077 colourChanged(false);
1081 * Converts the slider value to its absolute value by dividing by the
1082 * scaleFactor. Rounding errors are squashed by forcing min/max of slider
1083 * range to the actual min/max of feature score range
1087 private float getRoundedSliderValue()
1089 int value = slider.getValue();
1090 float f = value == slider.getMaximum() ? max
1091 : (value == slider.getMinimum() ? min : value / scaleFactor);
1095 void addActionListener(ActionListener listener)
1097 if (featureSettings != null)
1100 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1102 featureSettings = listener;
1106 * A helper method to build the drop-down choice of attributes for a feature.
1107 * If 'withRange' is true, then Score, and any attributes with a min-max
1108 * range, are added. If 'withText' is true, Label and any known attributes are
1109 * added. This allows 'categorical numerical' attributes e.g. codon position
1110 * to be coloured by text.
1112 * Where metadata is available with a description for an attribute, that is
1113 * added as a tooltip.
1115 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1116 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1118 * This method does not add any ActionListener to the JComboBox.
1124 protected JComboBox<Object> populateAttributesDropdown(
1125 List<String[]> attNames, boolean withRange, boolean withText)
1127 List<Object> displayAtts = new ArrayList<>();
1128 List<String> tooltips = new ArrayList<>();
1132 displayAtts.add(LABEL_18N);
1133 tooltips.add(MessageManager.getString("label.description"));
1137 float[][] minMax = fr.getMinMax().get(featureType);
1138 if (minMax != null && minMax[0][0] != minMax[0][1])
1140 displayAtts.add(SCORE_18N);
1141 tooltips.add(SCORE_18N);
1145 FeatureAttributes fa = FeatureAttributes.getInstance();
1146 for (String[] attName : attNames)
1148 float[] minMax = fa.getMinMax(featureType, attName);
1149 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1150 if (!withText && !hasRange)
1154 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1155 String desc = fa.getDescription(featureType, attName);
1156 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1158 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1160 tooltips.add(desc == null ? "" : desc);
1163 JComboBox<Object> attCombo = JvSwingUtils
1164 .buildComboWithTooltips(displayAtts, tooltips);
1170 * Populates initial layout of the feature attribute filters panel
1172 private JPanel initialiseFiltersPanel()
1174 filters = new ArrayList<>();
1176 JPanel filtersPanel = new JPanel();
1177 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1178 filtersPanel.setBackground(Color.white);
1179 JvSwingUtils.createTitledBorder(filtersPanel,
1180 MessageManager.getString("label.filters"), true);
1182 JPanel andOrPanel = initialiseAndOrPanel();
1183 filtersPanel.add(andOrPanel);
1186 * panel with filters - populated by refreshFiltersDisplay,
1187 * which also sets the layout manager
1189 chooseFiltersPanel = new JPanel();
1190 chooseFiltersPanel.setBackground(Color.white);
1191 filtersPanel.add(chooseFiltersPanel);
1193 return filtersPanel;
1197 * Lays out the panel with radio buttons to AND or OR filter conditions
1201 private JPanel initialiseAndOrPanel()
1203 JPanel andOrPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
1204 andOrPanel.setBackground(Color.white);
1205 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1206 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1207 andFilters.setOpaque(false);
1208 orFilters.setOpaque(false);
1209 ActionListener actionListener = new ActionListener()
1212 public void actionPerformed(ActionEvent e)
1217 andFilters.addActionListener(actionListener);
1218 orFilters.addActionListener(actionListener);
1219 ButtonGroup andOr = new ButtonGroup();
1220 andOr.add(andFilters);
1221 andOr.add(orFilters);
1222 andFilters.setSelected(true);
1224 new JLabel(MessageManager.getString("label.join_conditions")));
1225 andOrPanel.add(andFilters);
1226 andOrPanel.add(orFilters);
1231 * Refreshes the display to show any filters currently configured for the
1232 * selected feature type (editable, with 'remove' option), plus one extra row
1233 * for adding a condition. This should be called after a filter has been
1234 * removed, added or amended.
1236 private void updateFiltersPanel()
1239 * clear the panel and list of filter conditions
1241 chooseFiltersPanel.removeAll();
1245 * look up attributes known for feature type
1247 List<String[]> attNames = FeatureAttributes.getInstance()
1248 .getAttributes(featureType);
1251 * if this feature type has filters set, load them first
1253 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1254 if (featureFilters != null)
1256 if (!featureFilters.isAnded())
1258 orFilters.setSelected(true);
1260 // avoid use of lambda expression to keep SwingJS happy
1261 // featureFilters.getMatchers().forEach(item -> filters.add(item));
1262 for (FeatureMatcherI matcher : featureFilters.getMatchers())
1264 filters.add(matcher);
1269 * and an empty filter for the user to populate (add)
1271 filters.add(FeatureMatcher.NULL_MATCHER);
1274 * use GridLayout to 'justify' rows to the top of the panel, until
1275 * there are too many to fit in, then fall back on BoxLayout
1277 if (filters.size() <= 5)
1279 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1283 chooseFiltersPanel.setLayout(
1284 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1288 * render the conditions in rows, each in its own JPanel
1290 int filterIndex = 0;
1291 for (FeatureMatcherI filter : filters)
1293 JPanel row = addFilter(filter, attNames, filterIndex);
1294 chooseFiltersPanel.add(row);
1303 * A helper method that constructs a row (panel) with one filter condition:
1305 * <li>a drop-down list of Label, Score and attribute names to choose
1307 * <li>a drop-down list of conditions to choose from</li>
1308 * <li>a text field for input of a match pattern</li>
1309 * <li>optionally, a 'remove' button</li>
1311 * The filter values are set as defaults for the input fields. The 'remove'
1312 * button is added unless the pattern is empty (incomplete filter condition).
1314 * Action handlers on these fields provide for
1316 * <li>validate pattern field - should be numeric if condition is numeric</li>
1317 * <li>save filters and refresh display on any (valid) change</li>
1318 * <li>remove filter and refresh on 'Remove'</li>
1319 * <li>update conditions list on change of Label/Score/Attribute</li>
1320 * <li>refresh value field tooltip with min-max range on change of
1326 * @param filterIndex
1329 protected JPanel addFilter(FeatureMatcherI filter,
1330 List<String[]> attNames, int filterIndex)
1332 String[] attName = filter.getAttribute();
1333 Condition cond = filter.getMatcher().getCondition();
1334 String pattern = filter.getMatcher().getPattern();
1336 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1337 filterRow.setBackground(Color.white);
1340 * drop-down choice of attribute, with description as a tooltip
1341 * if we can obtain it
1343 JComboBox<Object> attCombo = populateAttributesDropdown(attNames, true,
1345 String filterBy = setSelectedAttribute(attCombo, filter);
1347 JComboBox<Condition> condCombo = new JComboBox<>();
1349 JTextField patternField = new JTextField(8);
1350 patternField.setText(pattern);
1353 * action handlers that validate and (if valid) apply changes
1355 ActionListener actionListener = new ActionListener()
1358 public void actionPerformed(ActionEvent e)
1360 if (validateFilter(patternField, condCombo))
1362 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1369 ItemListener itemListener = new ItemListener()
1372 public void itemStateChanged(ItemEvent e)
1374 actionListener.actionPerformed(null);
1378 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1380 attCombo.setSelectedIndex(0);
1384 attCombo.setSelectedItem(
1385 FeatureMatcher.toAttributeDisplayName(attName));
1387 attCombo.addItemListener(new ItemListener()
1390 public void itemStateChanged(ItemEvent e)
1393 * on change of attribute, refresh the conditions list to
1394 * ensure it is appropriate for the attribute datatype
1396 populateConditions((String) attCombo.getSelectedItem(),
1397 (Condition) condCombo.getSelectedItem(), condCombo,
1399 actionListener.actionPerformed(null);
1403 filterRow.add(attCombo);
1406 * drop-down choice of test condition
1408 populateConditions(filterBy, cond, condCombo, patternField);
1409 condCombo.setPreferredSize(new Dimension(150, 20));
1410 condCombo.addItemListener(itemListener);
1411 filterRow.add(condCombo);
1414 * pattern to match against
1416 patternField.addActionListener(actionListener);
1417 patternField.addFocusListener(new FocusAdapter()
1420 public void focusLost(FocusEvent e)
1422 actionListener.actionPerformed(null);
1425 filterRow.add(patternField);
1428 * disable pattern field for condition 'Present / NotPresent'
1430 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1431 patternField.setEnabled(selectedCondition.needsAPattern());
1434 * if a numeric condition is selected, show the value range
1435 * as a tooltip on the value input field
1437 setNumericHints(filterBy, selectedCondition, patternField);
1440 * add remove button if filter is populated (non-empty pattern)
1442 if (!patternField.isEnabled()
1443 || (pattern != null && pattern.trim().length() > 0))
1445 JButton removeCondition = new JButton("\u2717")
1448 public void paint(Graphics g)
1450 g.setColor(Color.black);
1451 g.drawString("\u2717", 2, 14); // Dingbats cursive x
1454 removeCondition.setBackground(Color.WHITE);
1455 removeCondition.setOpaque(true);
1456 removeCondition.setPreferredSize(new Dimension(23, 17));
1458 .setToolTipText(MessageManager.getString("label.delete_row"));
1459 removeCondition.addActionListener(new ActionListener()
1462 public void actionPerformed(ActionEvent e)
1464 filters.remove(filterIndex);
1468 filterRow.add(removeCondition);
1475 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1481 private String setSelectedAttribute(JComboBox<Object> attCombo,
1482 FeatureMatcherI filter)
1485 if (filter.isByScore())
1489 else if (filter.isByLabel())
1495 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1497 attCombo.setSelectedItem(item);
1502 * If a numeric comparison condition is selected, retrieves the min-max range
1503 * for the value (score or attribute), and sets it as a tooltip on the value
1504 * field. If the field is currently empty, then pre-populates it with
1506 * <li>the minimum value, if condition is > or >=</li>
1507 * <li>the maximum value, if condition is < or <=</li>
1511 * @param selectedCondition
1512 * @param patternField
1514 private void setNumericHints(String attName, Condition selectedCondition,
1515 JTextField patternField)
1517 patternField.setToolTipText("");
1519 if (selectedCondition.isNumeric())
1521 float[] minMax = getMinMax(attName);
1524 String minFormatted = DECFMT_2_2.format(minMax[0]);
1525 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1526 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1527 patternField.setToolTipText(tip);
1528 if (patternField.getText().isEmpty())
1530 if (selectedCondition == Condition.GE
1531 || selectedCondition == Condition.GT)
1533 patternField.setText(minFormatted);
1537 if (selectedCondition == Condition.LE
1538 || selectedCondition == Condition.LT)
1540 patternField.setText(maxFormatted);
1549 * Populates the drop-down list of comparison conditions for the given
1550 * attribute name. The conditions added depend on the datatype of the
1551 * attribute values. The supplied condition is set as the selected item in the
1552 * list, provided it is in the list. If the pattern is now invalid
1553 * (non-numeric pattern for a numeric condition), it is cleared.
1558 * @param patternField
1560 void populateConditions(String attName, Condition cond,
1561 JComboBox<Condition> condCombo, JTextField patternField)
1563 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1564 FeatureMatcher.fromAttributeDisplayName(attName));
1565 if (LABEL_18N.equals(attName))
1567 type = Datatype.Character;
1569 else if (SCORE_18N.equals(attName))
1571 type = Datatype.Number;
1575 * remove itemListener before starting
1577 ItemListener listener = condCombo.getItemListeners()[0];
1578 condCombo.removeItemListener(listener);
1579 boolean condIsValid = false;
1581 condCombo.removeAllItems();
1582 for (Condition c : Condition.values())
1584 if ((c.isNumeric() && type == Datatype.Number)
1585 || (!c.isNumeric() && type != Datatype.Number))
1587 condCombo.addItem(c);
1596 * set the selected condition (does nothing if not in the list)
1600 condCombo.setSelectedItem(cond);
1604 condCombo.setSelectedIndex(0);
1608 * clear pattern if it is now invalid for condition
1610 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1614 String pattern = patternField.getText().trim();
1615 if (pattern.length() > 0)
1617 Float.valueOf(pattern);
1619 } catch (NumberFormatException e)
1621 patternField.setText("");
1626 * restore the listener
1628 condCombo.addItemListener(listener);
1632 * Answers true unless a numeric condition has been selected with a
1633 * non-numeric value. Sets the value field to RED with a tooltip if in error.
1635 * If the pattern is expected but is empty, this method returns false, but
1636 * does not mark the field as invalid. This supports selecting an attribute
1637 * for a new condition before a match pattern has been entered.
1642 protected boolean validateFilter(JTextField value,
1643 JComboBox<Condition> condCombo)
1645 if (value == null || condCombo == null)
1647 return true; // fields not populated
1650 Condition cond = (Condition) condCombo.getSelectedItem();
1651 if (!cond.needsAPattern())
1656 value.setBackground(Color.white);
1657 value.setToolTipText("");
1658 String v1 = value.getText().trim();
1659 if (v1.length() == 0)
1664 if (cond.isNumeric() && v1.length() > 0)
1669 } catch (NumberFormatException e)
1671 value.setBackground(Color.red);
1672 value.setToolTipText(
1673 MessageManager.getString("label.numeric_required"));
1682 * Constructs a filter condition from the given input fields, and replaces the
1683 * condition at filterIndex with the new one. Does nothing if the pattern
1684 * field is blank (unless the match condition is one that doesn't require a
1685 * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1688 * This method may update the tooltip on the filter value field to show the
1689 * value range, if a numeric condition is selected. This ensures the tooltip
1690 * is updated when a numeric valued attribute is chosen on the last 'add a
1696 * @param filterIndex
1698 protected boolean updateFilter(JComboBox<Object> attCombo,
1699 JComboBox<Condition> condCombo, JTextField valueField,
1702 String attName = (String) attCombo.getSelectedItem();
1703 Condition cond = (Condition) condCombo.getSelectedItem();
1704 String pattern = valueField.getText().trim();
1706 setNumericHints(attName, cond, valueField);
1708 if (pattern.length() == 0 && cond.needsAPattern())
1710 valueField.setEnabled(true); // ensure pattern field is enabled!
1715 * Construct a matcher that operates on Label, Score,
1716 * or named attribute
1718 FeatureMatcherI km = null;
1719 if (LABEL_18N.equals(attName))
1721 km = FeatureMatcher.byLabel(cond, pattern);
1723 else if (SCORE_18N.equals(attName))
1725 km = FeatureMatcher.byScore(cond, pattern);
1729 km = FeatureMatcher.byAttribute(cond, pattern,
1730 FeatureMatcher.fromAttributeDisplayName(attName));
1733 filters.set(filterIndex, km);
1739 * Action on any change to feature filtering, namely
1741 * <li>change of selected attribute</li>
1742 * <li>change of selected condition</li>
1743 * <li>change of match pattern</li>
1744 * <li>removal of a condition</li>
1746 * The inputs are parsed into a combined filter and this is set for the
1747 * feature type, and the alignment redrawn.
1749 protected void filtersChanged()
1752 * update the filter conditions for the feature type
1754 boolean anded = andFilters.isSelected();
1755 FeatureMatcherSetI combined = new FeatureMatcherSet();
1757 for (FeatureMatcherI filter : filters)
1759 String pattern = filter.getMatcher().getPattern();
1760 Condition condition = filter.getMatcher().getCondition();
1761 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1765 combined.and(filter);
1769 combined.or(filter);
1775 * save the filter conditions in the FeatureRenderer
1776 * (note this might now be an empty filter with no conditions)
1778 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1779 ap.paintAlignment(true, true);
1781 updateFiltersPanel();