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.AlignViewportI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.api.FeatureColourI;
26 import jalview.bin.Console;
27 import jalview.datamodel.GraphLine;
28 import jalview.datamodel.features.FeatureAttributes;
29 import jalview.datamodel.features.FeatureAttributes.Datatype;
30 import jalview.datamodel.features.FeatureMatcher;
31 import jalview.datamodel.features.FeatureMatcherI;
32 import jalview.datamodel.features.FeatureMatcherSet;
33 import jalview.datamodel.features.FeatureMatcherSetI;
34 import jalview.gui.JalviewColourChooser.ColourChooserListener;
35 import jalview.schemes.FeatureColour;
36 import jalview.util.ColorUtils;
37 import jalview.util.MessageManager;
38 import jalview.util.matcher.Condition;
40 import java.awt.BorderLayout;
41 import java.awt.Color;
42 import java.awt.Dimension;
43 import java.awt.FlowLayout;
44 import java.awt.GridLayout;
45 import java.awt.event.ActionEvent;
46 import java.awt.event.ActionListener;
47 import java.awt.event.FocusAdapter;
48 import java.awt.event.FocusEvent;
49 import java.awt.event.ItemEvent;
50 import java.awt.event.ItemListener;
51 import java.awt.event.MouseAdapter;
52 import java.awt.event.MouseEvent;
53 import java.math.BigDecimal;
54 import java.math.MathContext;
55 import java.text.DecimalFormat;
56 import java.util.ArrayList;
57 import java.util.List;
59 import javax.swing.BorderFactory;
60 import javax.swing.BoxLayout;
61 import javax.swing.ButtonGroup;
62 import javax.swing.JButton;
63 import javax.swing.JCheckBox;
64 import javax.swing.JComboBox;
65 import javax.swing.JLabel;
66 import javax.swing.JPanel;
67 import javax.swing.JRadioButton;
68 import javax.swing.JTextField;
69 import javax.swing.border.EmptyBorder;
70 import javax.swing.border.LineBorder;
71 import javax.swing.event.ChangeEvent;
72 import javax.swing.event.ChangeListener;
75 * A dialog where the user can configure colour scheme, and any filters, for one
78 * (Was FeatureColourChooser prior to Jalview 1.11, renamed with the addition of
81 public class FeatureTypeSettings extends JalviewDialog
83 private final static MathContext FOUR_SIG_FIG = new MathContext(4);
85 private final static String LABEL_18N = MessageManager
86 .getString("label.label");
88 private final static String SCORE_18N = MessageManager
89 .getString("label.score");
91 private static final int RADIO_WIDTH = 130;
93 private static final String COLON = ":";
95 private static final int MAX_TOOLTIP_LENGTH = 50;
97 private static final int NO_COLOUR_OPTION = 0;
99 private static final int MIN_COLOUR_OPTION = 1;
101 private static final int MAX_COLOUR_OPTION = 2;
103 private static final int ABOVE_THRESHOLD_OPTION = 1;
105 private static final int BELOW_THRESHOLD_OPTION = 2;
107 private static final DecimalFormat DECFMT_2_2 = new DecimalFormat(
111 * FeatureRenderer holds colour scheme and filters for feature types
113 private final FeatureRenderer fr; // todo refactor to allow interface type
117 * the view panel to update when settings change
119 final AlignmentViewPanel ap;
121 final String featureType;
124 * the colour and filters to reset to on Cancel
126 private final FeatureColourI originalColour;
128 private final FeatureMatcherSetI originalFilter;
131 * set flag to true when setting values programmatically,
132 * to avoid invocation of action handlers
134 boolean adjusting = false;
137 * minimum of the value range for graduated colour
138 * (may be for feature score or for a numeric attribute)
143 * maximum of the value range for graduated colour
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<Object> threshold = new JComboBox<>();
169 private Slider slider;
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<Object> 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;
207 public boolean originalDisplay;
215 * - visibility of feature prior to adjustment
217 public FeatureTypeSettings(FeatureRenderer frender, String theType,
221 this.featureType = theType;
223 originalFilter = fr.getFeatureFilter(theType);
224 originalColour = fr.getFeatureColours().get(theType);
225 originalDisplay = last;
231 } catch (Exception ex)
233 ex.printStackTrace();
237 updateColoursPanel();
239 updateFiltersPanel();
243 colourChanged(false);
245 String title = MessageManager
246 .formatMessage("label.display_settings_for", new String[]
248 initDialogFrame(this, true, false, title, 580, 500);
253 * Configures the widgets on the Colours panel according to the current
254 * feature colour scheme
256 private void updateColoursPanel()
258 FeatureColourI fc = fr.getFeatureColours().get(featureType);
261 * suppress action handling while updating values programmatically
269 if (fc.isSimpleColour())
271 singleColour.setBackground(fc.getColour());
272 singleColour.setForeground(fc.getColour());
273 simpleColour.setSelected(true);
277 * colour by text (Label or attribute text)
279 if (fc.isColourByLabel())
281 byCategory.setSelected(true);
282 colourByTextCombo.setEnabled(colourByTextCombo.getItemCount() > 1);
283 if (fc.isColourByAttribute())
285 String[] attributeName = fc.getAttributeName();
286 colourByTextCombo.setSelectedItem(
287 FeatureMatcher.toAttributeDisplayName(attributeName));
291 colourByTextCombo.setSelectedItem(LABEL_18N);
296 colourByTextCombo.setEnabled(false);
299 if (!fc.isGraduatedColour())
301 colourByRangeCombo.setEnabled(false);
302 minColour.setEnabled(false);
303 maxColour.setEnabled(false);
304 noValueCombo.setEnabled(false);
305 threshold.setEnabled(false);
306 slider.setEnabled(false);
307 thresholdValue.setEnabled(false);
308 thresholdIsMin.setEnabled(false);
313 * Graduated colour, by score or attribute value range
315 graduatedColour.setSelected(true);
316 updateColourMinMax(); // ensure min, max are set
317 colourByRangeCombo.setEnabled(colourByRangeCombo.getItemCount() > 1);
318 minColour.setEnabled(true);
319 maxColour.setEnabled(true);
320 noValueCombo.setEnabled(true);
321 threshold.setEnabled(true);
322 minColour.setBackground(fc.getMinColour());
323 maxColour.setBackground(fc.getMaxColour());
325 if (fc.isColourByAttribute())
327 String[] attributeName = fc.getAttributeName();
328 colourByRangeCombo.setSelectedItem(
329 FeatureMatcher.toAttributeDisplayName(attributeName));
333 colourByRangeCombo.setSelectedItem(SCORE_18N);
335 Color noColour = fc.getNoColour();
336 if (noColour == null)
338 noValueCombo.setSelectedIndex(NO_COLOUR_OPTION);
340 else if (noColour.equals(fc.getMinColour()))
342 noValueCombo.setSelectedIndex(MIN_COLOUR_OPTION);
344 else if (noColour.equals(fc.getMaxColour()))
346 noValueCombo.setSelectedIndex(MAX_COLOUR_OPTION);
350 * update min-max scaling if there is a range to work with,
351 * else disable the widgets (this shouldn't happen if only
352 * valid options are offered in the combo box)
353 * offset slider to have only non-negative values if necessary (JAL-2983)
355 slider.setSliderModel(min, max, min);
356 slider.setMajorTickSpacing(
357 (int) ((slider.getMaximum() - slider.getMinimum()) / 10f));
359 threshline = new GraphLine((max - min) / 2f, "Threshold",
361 threshline.value = fc.getThreshold();
363 if (fc.hasThreshold())
365 threshold.setSelectedIndex(
366 fc.isAboveThreshold() ? ABOVE_THRESHOLD_OPTION
367 : BELOW_THRESHOLD_OPTION);
368 slider.setEnabled(true);
369 slider.setSliderValue(fc.getThreshold());
370 setThresholdValueText(fc.getThreshold());
371 thresholdValue.setEnabled(true);
372 thresholdIsMin.setEnabled(true);
376 slider.setEnabled(false);
377 thresholdValue.setEnabled(false);
378 thresholdIsMin.setEnabled(false);
380 thresholdIsMin.setSelected(!fc.isAutoScaled());
388 * Configures the initial layout
390 private void initialise()
392 this.setLayout(new BorderLayout());
395 * an ActionListener that applies colour changes
397 changeColourAction = new ActionListener()
400 public void actionPerformed(ActionEvent e)
407 * first panel: colour options
409 JPanel coloursPanel = initialiseColoursPanel();
410 this.add(coloursPanel, BorderLayout.NORTH);
413 * second panel: filter options
415 JPanel filtersPanel = initialiseFiltersPanel();
416 this.add(filtersPanel, BorderLayout.CENTER);
418 JPanel okCancelPanel = initialiseOkCancelPanel();
420 this.add(okCancelPanel, BorderLayout.SOUTH);
424 * Updates the min-max range if Colour By selected item is Score, or an
425 * attribute, with a min-max range
427 protected void updateColourMinMax()
429 if (!graduatedColour.isSelected())
434 String colourBy = (String) colourByRangeCombo.getSelectedItem();
435 float[] minMax = getMinMax(colourBy);
445 * Retrieves the min-max range:
447 * <li>of feature score, if colour or filter is by Score</li>
448 * <li>else of the selected attribute</li>
454 private float[] getMinMax(String attName)
456 float[] minMax = null;
457 if (SCORE_18N.equals(attName))
459 minMax = fr.getMinMax().get(featureType)[0];
463 // colour by attribute range
464 minMax = FeatureAttributes.getInstance().getMinMax(featureType,
465 FeatureMatcher.fromAttributeDisplayName(attName));
471 * Lay out fields for graduated colour (by score or attribute value)
475 private JPanel initialiseGraduatedColourPanel()
477 JPanel graduatedColourPanel = new JPanel();
478 graduatedColourPanel.setLayout(
479 new BoxLayout(graduatedColourPanel, BoxLayout.Y_AXIS));
480 JvSwingUtils.createTitledBorder(graduatedColourPanel,
481 MessageManager.getString("label.graduated_colour"), true);
482 graduatedColourPanel.setBackground(Color.white);
485 * first row: graduated colour radio button, score/attribute drop-down
487 JPanel graduatedChoicePanel = new JPanel(
488 new FlowLayout(FlowLayout.LEFT));
489 graduatedChoicePanel.setBackground(Color.white);
490 graduatedColour = new JRadioButton(
491 MessageManager.getString("label.by_range_of") + COLON);
492 graduatedColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
493 graduatedColour.setOpaque(false);
494 graduatedColour.addItemListener(new ItemListener()
497 public void itemStateChanged(ItemEvent e)
499 if (graduatedColour.isSelected())
505 graduatedChoicePanel.add(graduatedColour);
507 List<String[]> attNames = FeatureAttributes.getInstance()
508 .getAttributes(featureType);
509 colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
510 colourByRangeCombo.addItemListener(new ItemListener()
513 public void itemStateChanged(ItemEvent e)
520 * disable graduated colour option if no range found
522 graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
524 graduatedChoicePanel.add(colourByRangeCombo);
525 graduatedColourPanel.add(graduatedChoicePanel);
528 * second row - min/max/no colours
530 JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
531 colourRangePanel.setBackground(Color.white);
532 graduatedColourPanel.add(colourRangePanel);
534 minColour.setFont(JvSwingUtils.getLabelFont());
535 minColour.setBorder(BorderFactory.createLineBorder(Color.black));
536 minColour.setPreferredSize(new Dimension(40, 20));
537 minColour.setToolTipText(MessageManager.getString("label.min_colour"));
538 minColour.addMouseListener(new MouseAdapter()
541 public void mousePressed(MouseEvent e)
543 if (minColour.isEnabled())
545 String ttl = MessageManager
546 .getString("label.select_colour_minimum_value");
547 showColourChooser(minColour, ttl);
552 maxColour.setFont(JvSwingUtils.getLabelFont());
553 maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
554 maxColour.setPreferredSize(new Dimension(40, 20));
555 maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
556 maxColour.addMouseListener(new MouseAdapter()
559 public void mousePressed(MouseEvent e)
561 if (maxColour.isEnabled())
563 String ttl = MessageManager
564 .getString("label.select_colour_maximum_value");
565 showColourChooser(maxColour, ttl);
569 maxColour.setBorder(new LineBorder(Color.black));
572 * if not set, default max colour to last plain colour,
573 * and make min colour a pale version of max colour
575 Color max = originalColour.getMaxColour();
578 max = originalColour.getColour();
579 minColour.setBackground(ColorUtils.bleachColour(max, 0.9f));
583 maxColour.setBackground(max);
584 minColour.setBackground(originalColour.getMinColour());
587 noValueCombo = new JComboBox<>();
588 noValueCombo.addItem(MessageManager.getString("label.no_colour"));
589 noValueCombo.addItem(MessageManager.getString("label.min_colour"));
590 noValueCombo.addItem(MessageManager.getString("label.max_colour"));
591 noValueCombo.addItemListener(new ItemListener()
594 public void itemStateChanged(ItemEvent e)
600 JLabel minText = new JLabel(
601 MessageManager.getString("label.min_value") + COLON);
602 minText.setFont(JvSwingUtils.getLabelFont());
603 JLabel maxText = new JLabel(
604 MessageManager.getString("label.max_value") + COLON);
605 maxText.setFont(JvSwingUtils.getLabelFont());
606 JLabel noText = new JLabel(
607 MessageManager.getString("label.no_value") + COLON);
608 noText.setFont(JvSwingUtils.getLabelFont());
610 colourRangePanel.add(minText);
611 colourRangePanel.add(minColour);
612 colourRangePanel.add(maxText);
613 colourRangePanel.add(maxColour);
614 colourRangePanel.add(noText);
615 colourRangePanel.add(noValueCombo);
618 * third row - threshold options and value
620 JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
621 thresholdPanel.setBackground(Color.white);
622 graduatedColourPanel.add(thresholdPanel);
624 threshold.addActionListener(changeColourAction);
625 threshold.setToolTipText(MessageManager
626 .getString("label.threshold_feature_display_by_score"));
627 threshold.addItem(MessageManager
628 .getString("label.threshold_feature_no_threshold")); // index 0
629 threshold.addItem(MessageManager
630 .getString("label.threshold_feature_above_threshold")); // index 1
631 threshold.addItem(MessageManager
632 .getString("label.threshold_feature_below_threshold")); // index 2
634 thresholdValue.addActionListener(new ActionListener()
637 public void actionPerformed(ActionEvent e)
639 thresholdValue_actionPerformed();
642 thresholdValue.addFocusListener(new FocusAdapter()
645 public void focusLost(FocusEvent e)
647 thresholdValue_actionPerformed();
650 slider = new Slider(0f, 100f, 50f);
651 slider.setPaintLabels(false);
652 slider.setPaintTicks(true);
653 slider.setBackground(Color.white);
654 slider.setEnabled(false);
655 slider.setOpaque(false);
656 slider.setPreferredSize(new Dimension(100, 32));
657 slider.setToolTipText(
658 MessageManager.getString("label.adjust_threshold"));
660 slider.addChangeListener(new ChangeListener()
663 public void stateChanged(ChangeEvent evt)
667 setThresholdValueText(slider.getSliderValue());
668 thresholdValue.setBackground(Color.white); // to reset red for invalid
669 sliderValueChanged();
673 slider.addMouseListener(new MouseAdapter()
676 public void mouseReleased(MouseEvent evt)
679 * only update Overview and/or structure colouring
680 * when threshold slider drag ends (mouse up)
684 refreshDisplay(true);
689 thresholdValue.setEnabled(false);
690 thresholdValue.setColumns(7);
692 thresholdPanel.add(threshold);
693 thresholdPanel.add(slider);
694 thresholdPanel.add(thresholdValue);
696 thresholdIsMin.setBackground(Color.white);
698 .setText(MessageManager.getString("label.threshold_minmax"));
699 thresholdIsMin.setToolTipText(MessageManager
700 .getString("label.toggle_absolute_relative_display_threshold"));
701 thresholdIsMin.addActionListener(changeColourAction);
702 thresholdPanel.add(thresholdIsMin);
704 return graduatedColourPanel;
708 * Lay out OK and Cancel buttons
712 private JPanel initialiseOkCancelPanel()
714 JPanel okCancelPanel = new JPanel();
715 // okCancelPanel.setBackground(Color.white);
716 okCancelPanel.add(ok);
717 okCancelPanel.add(cancel);
718 return okCancelPanel;
722 * Lay out Colour options panel, containing
724 * <li>plain colour, with colour picker</li>
725 * <li>colour by text, with choice of Label or other attribute</li>
726 * <li>colour by range, of score or other attribute, when available</li>
731 private JPanel initialiseColoursPanel()
733 JPanel colourByPanel = new JPanel();
734 colourByPanel.setBackground(Color.white);
735 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
736 JvSwingUtils.createTitledBorder(colourByPanel,
737 MessageManager.getString("action.colour"), true);
740 * simple colour radio button and colour picker
742 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
743 simpleColourPanel.setBackground(Color.white);
744 colourByPanel.add(simpleColourPanel);
746 simpleColour = new JRadioButton(
747 MessageManager.getString("label.simple_colour"));
748 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
749 simpleColour.setOpaque(false);
750 simpleColour.addItemListener(new ItemListener()
753 public void itemStateChanged(ItemEvent e)
755 if (simpleColour.isSelected() && !adjusting)
762 singleColour.setFont(JvSwingUtils.getLabelFont());
763 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
764 singleColour.setPreferredSize(new Dimension(40, 20));
765 // if (originalColour.isGraduatedColour())
767 // singleColour.setBackground(originalColour.getMaxColour());
768 // singleColour.setForeground(originalColour.getMaxColour());
772 singleColour.setBackground(originalColour.getColour());
773 singleColour.setForeground(originalColour.getColour());
775 singleColour.addMouseListener(new MouseAdapter()
778 public void mousePressed(MouseEvent e)
780 if (simpleColour.isSelected())
782 String ttl = MessageManager
783 .formatMessage("label.select_colour_for", featureType);
784 showColourChooser(singleColour, ttl);
788 simpleColourPanel.add(simpleColour); // radio button
789 simpleColourPanel.add(singleColour); // colour picker button
792 * colour by text (category) radio button and drop-down choice list
794 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
795 byTextPanel.setBackground(Color.white);
796 JvSwingUtils.createTitledBorder(byTextPanel,
797 MessageManager.getString("label.colour_by_text"), true);
798 colourByPanel.add(byTextPanel);
799 byCategory = new JRadioButton(
800 MessageManager.getString("label.by_text_of") + COLON);
801 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
802 byCategory.setOpaque(false);
803 byCategory.addItemListener(new ItemListener()
806 public void itemStateChanged(ItemEvent e)
808 if (byCategory.isSelected())
814 byTextPanel.add(byCategory);
816 List<String[]> attNames = FeatureAttributes.getInstance()
817 .getAttributes(featureType);
818 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
819 colourByTextCombo.addItemListener(new ItemListener()
822 public void itemStateChanged(ItemEvent e)
827 byTextPanel.add(colourByTextCombo);
830 * graduated colour panel
832 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
833 colourByPanel.add(graduatedColourPanel);
836 * 3 radio buttons select between simple colour,
837 * by category (text), or graduated
839 ButtonGroup bg = new ButtonGroup();
840 bg.add(simpleColour);
842 bg.add(graduatedColour);
844 return colourByPanel;
848 * Shows a colour chooser dialog, and if a selection is made, updates the
849 * colour of the given panel
852 * the panel whose background colour is being picked
855 void showColourChooser(JPanel colourPanel, String title)
857 ColourChooserListener listener = new ColourChooserListener()
860 public void colourSelected(Color col)
862 colourPanel.setBackground(col);
863 colourPanel.setForeground(col);
864 colourPanel.repaint();
868 JalviewColourChooser.showColourChooser(this, title,
869 colourPanel.getBackground(), listener);
873 * Constructs and sets the selected colour options as the colour for the
874 * feature type, and repaints the alignment, and optionally the Overview
875 * and/or structure viewer if open
877 * @param updateStructsAndOverview
879 void colourChanged(boolean updateStructsAndOverview)
884 * ignore action handlers while setting values programmatically
890 * ensure min-max range is for the latest choice of
891 * 'graduated colour by'
893 updateColourMinMax();
895 FeatureColourI acg = makeColourFromInputs();
898 * save the colour, and repaint stuff
900 fr.setColour(featureType, acg);
901 refreshDisplay(updateStructsAndOverview);
903 updateColoursPanel();
907 * Converts the input values into an instance of FeatureColour
911 private FeatureColourI makeColourFromInputs()
914 * min-max range is to (or from) threshold value if
915 * 'threshold is min/max' is selected
921 thresh = Float.valueOf(thresholdValue.getText());
922 } catch (NumberFormatException e)
924 // invalid inputs are already handled on entry
926 float minValue = min;
927 float maxValue = max;
928 int thresholdOption = threshold.getSelectedIndex();
929 if (thresholdIsMin.isSelected()
930 && thresholdOption == ABOVE_THRESHOLD_OPTION)
934 if (thresholdIsMin.isSelected()
935 && thresholdOption == BELOW_THRESHOLD_OPTION)
939 Color noColour = null;
940 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
942 noColour = minColour.getBackground();
944 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
946 noColour = maxColour.getBackground();
950 * construct a colour that 'remembers' all the options, including
951 * those not currently selected
953 FeatureColourI fc = new FeatureColour(singleColour.getBackground(),
954 minColour.getBackground(), maxColour.getBackground(), noColour,
958 * easiest case - a single colour
960 if (simpleColour.isSelected())
962 ((FeatureColour) fc).setGraduatedColour(false);
967 * next easiest case - colour by Label, or attribute text
969 if (byCategory.isSelected())
971 fc.setColourByLabel(true);
972 String byWhat = (String) colourByTextCombo.getSelectedItem();
973 if (!LABEL_18N.equals(byWhat))
976 FeatureMatcher.fromAttributeDisplayName(byWhat));
982 * remaining case - graduated colour by score, or attribute value;
983 * set attribute to colour by if selected
985 String byWhat = (String) colourByRangeCombo.getSelectedItem();
986 if (!SCORE_18N.equals(byWhat))
988 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
992 * set threshold options and 'autoscaled' which is
993 * false if 'threshold is min/max' is selected
994 * else true (colour range is on actual range of values)
996 fc.setThreshold(thresh);
997 fc.setAutoScaled(!thresholdIsMin.isSelected());
998 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
999 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
1001 if (threshline == null)
1004 * todo not yet implemented: visual indication of feature threshold
1006 threshline = new GraphLine((max - min) / 2f, "Threshold",
1014 protected void raiseClosed()
1016 if (this.featureSettings != null)
1018 featureSettings.actionPerformed(new ActionEvent(this, 0, "CLOSED"));
1023 * Action on OK is just to dismiss the dialog - any changes have already been
1027 public void okPressed()
1032 * Action on Cancel is to restore colour scheme and filters as they were when
1033 * the dialog was opened
1036 public void cancelPressed()
1038 fr.setColour(featureType, originalColour);
1039 fr.setFeatureFilter(featureType, originalFilter);
1040 if (!originalDisplay)
1042 fr.getFeaturesDisplayed().setHidden(featureType);
1044 refreshDisplay(true);
1048 * Action on text entry of a threshold value
1050 protected void thresholdValue_actionPerformed()
1055 * set 'adjusting' flag while moving the slider, so it
1056 * doesn't then in turn change the value (with rounding)
1059 float f = Float.parseFloat(thresholdValue.getText());
1060 f = Float.max(f, this.min);
1061 f = Float.min(f, this.max);
1062 setThresholdValueText(f);
1063 slider.setSliderValue(f);
1064 threshline.value = f;
1065 thresholdValue.setBackground(Color.white); // ok
1067 colourChanged(true);
1068 } catch (NumberFormatException ex)
1070 thresholdValue.setBackground(Color.red); // not ok
1076 * Sets the text field for threshold value, rounded to four significant
1081 void setThresholdValueText(float f)
1083 BigDecimal formatted = new BigDecimal(f).round(FOUR_SIG_FIG)
1084 .stripTrailingZeros();
1085 thresholdValue.setText(formatted.toPlainString());
1089 * Action on change of threshold slider value. This may be done interactively
1090 * (by moving the slider), or programmatically (to update the slider after
1091 * manual input of a threshold value).
1093 protected void sliderValueChanged()
1095 threshline.value = slider.getSliderValue();
1098 * repaint alignment, but not Overview or structure,
1099 * to avoid overload while dragging the slider
1101 colourChanged(false);
1104 void addActionListener(ActionListener listener)
1106 if (featureSettings != null)
1108 jalview.bin.Console.errPrintln(
1109 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1111 featureSettings = listener;
1115 * A helper method to build the drop-down choice of attributes for a feature.
1116 * If 'withRange' is true, then Score, and any attributes with a min-max
1117 * range, are added. If 'withText' is true, Label and any known attributes are
1118 * added. This allows 'categorical numerical' attributes e.g. codon position
1119 * to be coloured by text.
1121 * Where metadata is available with a description for an attribute, that is
1122 * added as a tooltip.
1124 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1125 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1127 * This method does not add any ActionListener to the JComboBox.
1133 protected JComboBox<Object> populateAttributesDropdown(
1134 List<String[]> attNames, boolean withRange, boolean withText)
1136 List<String> displayAtts = new ArrayList<>();
1137 List<String> tooltips = new ArrayList<>();
1141 displayAtts.add(LABEL_18N);
1142 tooltips.add(MessageManager.getString("label.description"));
1146 float[][] minMax = fr.getMinMax().get(featureType);
1147 if (minMax != null && minMax[0][0] != minMax[0][1])
1149 displayAtts.add(SCORE_18N);
1150 tooltips.add(SCORE_18N);
1154 FeatureAttributes fa = FeatureAttributes.getInstance();
1155 for (String[] attName : attNames)
1157 float[] minMax = fa.getMinMax(featureType, attName);
1158 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1159 if (!withText && !hasRange)
1163 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1164 String desc = fa.getDescription(featureType, attName);
1165 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1167 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1169 tooltips.add(desc == null ? "" : desc);
1172 // now convert String List to Object List for buildComboWithTooltips
1173 List<Object> displayAttsObjects = new ArrayList<>(displayAtts);
1174 JComboBox<Object> attCombo = JvSwingUtils
1175 .buildComboWithTooltips(displayAttsObjects, tooltips);
1181 * Populates initial layout of the feature attribute filters panel
1183 private JPanel initialiseFiltersPanel()
1185 filters = new ArrayList<>();
1187 JPanel filtersPanel = new JPanel();
1188 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1189 filtersPanel.setBackground(Color.white);
1190 JvSwingUtils.createTitledBorder(filtersPanel,
1191 MessageManager.getString("label.filters"), true);
1193 JPanel andOrPanel = initialiseAndOrPanel();
1194 filtersPanel.add(andOrPanel);
1197 * panel with filters - populated by refreshFiltersDisplay,
1198 * which also sets the layout manager
1200 chooseFiltersPanel = new JPanel();
1201 chooseFiltersPanel.setBackground(Color.white);
1202 filtersPanel.add(chooseFiltersPanel);
1204 return filtersPanel;
1208 * Lays out the panel with radio buttons to AND or OR filter conditions
1212 private JPanel initialiseAndOrPanel()
1214 JPanel andOrPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
1215 andOrPanel.setBackground(Color.white);
1216 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1217 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1218 andFilters.setOpaque(false);
1219 orFilters.setOpaque(false);
1220 ActionListener actionListener = new ActionListener()
1223 public void actionPerformed(ActionEvent e)
1228 andFilters.addActionListener(actionListener);
1229 orFilters.addActionListener(actionListener);
1230 ButtonGroup andOr = new ButtonGroup();
1231 andOr.add(andFilters);
1232 andOr.add(orFilters);
1233 andFilters.setSelected(true);
1235 new JLabel(MessageManager.getString("label.join_conditions")));
1236 andOrPanel.add(andFilters);
1237 andOrPanel.add(orFilters);
1242 * Refreshes the display to show any filters currently configured for the
1243 * selected feature type (editable, with 'remove' option), plus one extra row
1244 * for adding a condition. This should be called after a filter has been
1245 * removed, added or amended.
1247 private void updateFiltersPanel()
1250 * clear the panel and list of filter conditions
1252 chooseFiltersPanel.removeAll();
1256 * look up attributes known for feature type
1258 List<String[]> attNames = FeatureAttributes.getInstance()
1259 .getAttributes(featureType);
1262 * if this feature type has filters set, load them first
1264 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1265 if (featureFilters != null)
1267 if (!featureFilters.isAnded())
1269 orFilters.setSelected(true);
1271 // avoid use of lambda expression to keep SwingJS happy
1272 // featureFilters.getMatchers().forEach(item -> filters.add(item));
1273 for (FeatureMatcherI matcher : featureFilters.getMatchers())
1275 filters.add(matcher);
1280 * and an empty filter for the user to populate (add)
1282 filters.add(FeatureMatcher.NULL_MATCHER);
1285 * use GridLayout to 'justify' rows to the top of the panel, until
1286 * there are too many to fit in, then fall back on BoxLayout
1288 if (filters.size() <= 5)
1290 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1294 chooseFiltersPanel.setLayout(
1295 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1299 * render the conditions in rows, each in its own JPanel
1301 int filterIndex = 0;
1302 for (FeatureMatcherI filter : filters)
1304 JPanel row = addFilter(filter, attNames, filterIndex);
1305 chooseFiltersPanel.add(row);
1314 * A helper method that constructs a row (panel) with one filter condition:
1316 * <li>a drop-down list of Label, Score and attribute names to choose
1318 * <li>a drop-down list of conditions to choose from</li>
1319 * <li>a text field for input of a match pattern</li>
1320 * <li>optionally, a 'remove' button</li>
1322 * The filter values are set as defaults for the input fields. The 'remove'
1323 * button is added unless the pattern is empty (incomplete filter condition).
1325 * Action handlers on these fields provide for
1327 * <li>validate pattern field - should be numeric if condition is numeric</li>
1328 * <li>save filters and refresh display on any (valid) change</li>
1329 * <li>remove filter and refresh on 'Remove'</li>
1330 * <li>update conditions list on change of Label/Score/Attribute</li>
1331 * <li>refresh value field tooltip with min-max range on change of
1337 * @param filterIndex
1340 protected JPanel addFilter(FeatureMatcherI filter,
1341 List<String[]> attNames, int filterIndex)
1343 String[] attName = filter.getAttribute();
1344 Condition cond = filter.getMatcher().getCondition();
1345 String pattern = filter.getMatcher().getPattern();
1347 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1348 filterRow.setBackground(Color.white);
1351 * drop-down choice of attribute, with description as a tooltip
1352 * if we can obtain it
1354 final JComboBox<Object> attCombo = populateAttributesDropdown(attNames,
1356 String filterBy = setSelectedAttribute(attCombo, filter);
1358 JComboBox<Condition> condCombo = new JComboBox<>();
1360 JTextField patternField = new JTextField(8);
1361 patternField.setText(pattern);
1364 * action handlers that validate and (if valid) apply changes
1366 ActionListener actionListener = new ActionListener()
1369 public void actionPerformed(ActionEvent e)
1371 if (validateFilter(patternField, condCombo))
1373 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1380 ItemListener itemListener = new ItemListener()
1383 public void itemStateChanged(ItemEvent e)
1385 actionListener.actionPerformed(null);
1389 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1391 attCombo.setSelectedIndex(0);
1395 attCombo.setSelectedItem(
1396 FeatureMatcher.toAttributeDisplayName(attName));
1398 attCombo.addItemListener(new ItemListener()
1401 public void itemStateChanged(ItemEvent e)
1404 * on change of attribute, refresh the conditions list to
1405 * ensure it is appropriate for the attribute datatype
1407 populateConditions((String) attCombo.getSelectedItem(),
1408 (Condition) condCombo.getSelectedItem(), condCombo,
1410 actionListener.actionPerformed(null);
1414 filterRow.add(attCombo);
1417 * drop-down choice of test condition
1419 populateConditions(filterBy, cond, condCombo, patternField);
1420 condCombo.setPreferredSize(new Dimension(150, 20));
1421 condCombo.addItemListener(itemListener);
1422 filterRow.add(condCombo);
1425 * pattern to match against
1427 patternField.addActionListener(actionListener);
1428 patternField.addFocusListener(new FocusAdapter()
1431 public void focusLost(FocusEvent e)
1433 actionListener.actionPerformed(null);
1436 filterRow.add(patternField);
1439 * disable pattern field for condition 'Present / NotPresent'
1441 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1442 patternField.setEnabled(selectedCondition.needsAPattern());
1445 * if a numeric condition is selected, show the value range
1446 * as a tooltip on the value input field
1448 setNumericHints(filterBy, selectedCondition, patternField);
1451 * add remove button if filter is populated (non-empty pattern)
1453 if (!patternField.isEnabled()
1454 || (pattern != null && pattern.trim().length() > 0))
1456 JButton removeCondition = new JButton("\u2717");
1457 // Dingbats cursive x
1458 removeCondition.setBorder(new EmptyBorder(0, 0, 0, 0));
1459 removeCondition.setBackground(Color.WHITE);
1460 removeCondition.setPreferredSize(new Dimension(23, 17));
1461 removeCondition.setToolTipText(
1462 MessageManager.getString("label.delete_condition"));
1463 removeCondition.addActionListener(new ActionListener()
1466 public void actionPerformed(ActionEvent e)
1468 filters.remove(filterIndex);
1472 filterRow.add(removeCondition);
1479 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1485 private String setSelectedAttribute(JComboBox<Object> attCombo,
1486 FeatureMatcherI filter)
1489 if (filter.isByScore())
1493 else if (filter.isByLabel())
1499 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1501 attCombo.setSelectedItem(item);
1506 * If a numeric comparison condition is selected, retrieves the min-max range
1507 * for the value (score or attribute), and sets it as a tooltip on the value
1508 * field. If the field is currently empty, then pre-populates it with
1510 * <li>the minimum value, if condition is > or >=</li>
1511 * <li>the maximum value, if condition is < or <=</li>
1515 * @param selectedCondition
1516 * @param patternField
1518 private void setNumericHints(String attName, Condition selectedCondition,
1519 JTextField patternField)
1521 patternField.setToolTipText("");
1523 if (selectedCondition.isNumeric())
1525 float[] minMax = getMinMax(attName);
1528 String minFormatted = DECFMT_2_2.format(minMax[0]);
1529 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1530 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1531 patternField.setToolTipText(tip);
1532 if (patternField.getText().isEmpty())
1534 if (selectedCondition == Condition.GE
1535 || selectedCondition == Condition.GT)
1537 patternField.setText(minFormatted);
1541 if (selectedCondition == Condition.LE
1542 || selectedCondition == Condition.LT)
1544 patternField.setText(maxFormatted);
1553 * Populates the drop-down list of comparison conditions for the given
1554 * attribute name. The conditions added depend on the datatype of the
1555 * attribute values. The supplied condition is set as the selected item in the
1556 * list, provided it is in the list. If the pattern is now invalid
1557 * (non-numeric pattern for a numeric condition), it is cleared.
1562 * @param patternField
1564 void populateConditions(String attName, Condition cond,
1565 JComboBox<Condition> condCombo, JTextField patternField)
1567 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1568 FeatureMatcher.fromAttributeDisplayName(attName));
1569 if (LABEL_18N.equals(attName))
1571 type = Datatype.Character;
1573 else if (SCORE_18N.equals(attName))
1575 type = Datatype.Number;
1579 * remove itemListener before starting
1581 ItemListener listener = condCombo.getItemListeners()[0];
1582 condCombo.removeItemListener(listener);
1583 boolean condIsValid = false;
1585 condCombo.removeAllItems();
1586 for (Condition c : Condition.values())
1588 if ((c.isNumeric() && type == Datatype.Number)
1589 || (!c.isNumeric() && type != Datatype.Number))
1591 condCombo.addItem(c);
1600 * set the selected condition (does nothing if not in the list)
1604 condCombo.setSelectedItem(cond);
1608 condCombo.setSelectedIndex(0);
1612 * clear pattern if it is now invalid for condition
1614 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1618 String pattern = patternField.getText().trim();
1619 if (pattern.length() > 0)
1621 Float.valueOf(pattern);
1623 } catch (NumberFormatException e)
1625 patternField.setText("");
1630 * restore the listener
1632 condCombo.addItemListener(listener);
1636 * Answers true unless a numeric condition has been selected with a
1637 * non-numeric value. Sets the value field to RED with a tooltip if in error.
1639 * If the pattern is expected but is empty, this method returns false, but
1640 * does not mark the field as invalid. This supports selecting an attribute
1641 * for a new condition before a match pattern has been entered.
1646 protected boolean validateFilter(JTextField value,
1647 JComboBox<Condition> condCombo)
1649 if (value == null || condCombo == null)
1651 return true; // fields not populated
1654 Condition cond = (Condition) condCombo.getSelectedItem();
1655 if (!cond.needsAPattern())
1660 value.setBackground(Color.white);
1661 value.setToolTipText("");
1662 String v1 = value.getText().trim();
1663 if (v1.length() == 0)
1668 if (cond.isNumeric() && v1.length() > 0)
1673 } catch (NumberFormatException e)
1675 value.setBackground(Color.red);
1676 value.setToolTipText(
1677 MessageManager.getString("label.numeric_required"));
1686 * Constructs a filter condition from the given input fields, and replaces the
1687 * condition at filterIndex with the new one. Does nothing if the pattern
1688 * field is blank (unless the match condition is one that doesn't require a
1689 * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1692 * This method may update the tooltip on the filter value field to show the
1693 * value range, if a numeric condition is selected. This ensures the tooltip
1694 * is updated when a numeric valued attribute is chosen on the last 'add a
1700 * @param filterIndex
1702 protected boolean updateFilter(JComboBox<Object> attCombo,
1703 JComboBox<Condition> condCombo, JTextField valueField,
1709 attName = (String) attCombo.getSelectedItem();
1710 } catch (Exception e)
1712 Console.error("Problem casting Combo box entry to String");
1713 attName = attCombo.getSelectedItem().toString();
1715 Condition cond = (Condition) condCombo.getSelectedItem();
1716 String pattern = valueField.getText().trim();
1718 setNumericHints(attName, cond, valueField);
1720 if (pattern.length() == 0 && cond.needsAPattern())
1722 valueField.setEnabled(true); // ensure pattern field is enabled!
1727 * Construct a matcher that operates on Label, Score,
1728 * or named attribute
1730 FeatureMatcherI km = null;
1731 if (LABEL_18N.equals(attName))
1733 km = FeatureMatcher.byLabel(cond, pattern);
1735 else if (SCORE_18N.equals(attName))
1737 km = FeatureMatcher.byScore(cond, pattern);
1741 km = FeatureMatcher.byAttribute(cond, pattern,
1742 FeatureMatcher.fromAttributeDisplayName(attName));
1745 filters.set(filterIndex, km);
1751 * Action on any change to feature filtering, namely
1753 * <li>change of selected attribute</li>
1754 * <li>change of selected condition</li>
1755 * <li>change of match pattern</li>
1756 * <li>removal of a condition</li>
1758 * The inputs are parsed into a combined filter and this is set for the
1759 * feature type, and the alignment redrawn.
1761 protected void filtersChanged()
1764 * update the filter conditions for the feature type
1766 boolean anded = andFilters.isSelected();
1767 FeatureMatcherSetI combined = new FeatureMatcherSet();
1769 for (FeatureMatcherI filter : filters)
1771 String pattern = filter.getMatcher().getPattern();
1772 Condition condition = filter.getMatcher().getCondition();
1773 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1777 combined.and(filter);
1781 combined.or(filter);
1787 * save the filter conditions in the FeatureRenderer
1788 * (note this might now be an empty filter with no conditions)
1790 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1791 refreshDisplay(true);
1793 updateFiltersPanel();
1797 * Repaints alignment, structure and overview (if shown). If there is a
1798 * complementary view which is showing this view's features, then also
1801 * @param updateStructsAndOverview
1803 void refreshDisplay(boolean updateStructsAndOverview)
1805 ap.paintAlignment(true, updateStructsAndOverview);
1806 AlignViewportI complement = ap.getAlignViewport().getCodingComplement();
1807 if (complement != null && complement.isShowComplementFeatures())
1809 AlignFrame af2 = Desktop.getAlignFrameFor(complement);
1810 af2.alignPanel.paintAlignment(true, updateStructsAndOverview);