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.Cache;
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.text.DecimalFormat;
54 import java.util.ArrayList;
55 import java.util.List;
57 import javax.swing.BorderFactory;
58 import javax.swing.BoxLayout;
59 import javax.swing.ButtonGroup;
60 import javax.swing.JButton;
61 import javax.swing.JCheckBox;
62 import javax.swing.JComboBox;
63 import javax.swing.JLabel;
64 import javax.swing.JPanel;
65 import javax.swing.JRadioButton;
66 import javax.swing.JSlider;
67 import javax.swing.JTextField;
68 import javax.swing.border.EmptyBorder;
69 import javax.swing.border.LineBorder;
70 import javax.swing.event.ChangeEvent;
71 import javax.swing.event.ChangeListener;
74 * A dialog where the user can configure colour scheme, and any filters, for one
77 * (Was FeatureColourChooser prior to Jalview 1.11, renamed with the addition of
80 public class FeatureTypeSettings extends JalviewDialog
82 private final static String LABEL_18N = MessageManager
83 .getString("label.label");
85 private final static String SCORE_18N = MessageManager
86 .getString("label.score");
88 private static final int RADIO_WIDTH = 130;
90 private static final String COLON = ":";
92 private static final int MAX_TOOLTIP_LENGTH = 50;
94 private static final int NO_COLOUR_OPTION = 0;
96 private static final int MIN_COLOUR_OPTION = 1;
98 private static final int MAX_COLOUR_OPTION = 2;
100 private static final int ABOVE_THRESHOLD_OPTION = 1;
102 private static final int BELOW_THRESHOLD_OPTION = 2;
104 private static final DecimalFormat DECFMT_2_2 = new DecimalFormat(
108 * FeatureRenderer holds colour scheme and filters for feature types
110 private final FeatureRenderer fr; // todo refactor to allow interface type
114 * the view panel to update when settings change
116 final AlignmentViewPanel ap;
118 final String featureType;
121 * the colour and filters to reset to on Cancel
123 private final FeatureColourI originalColour;
125 private final FeatureMatcherSetI originalFilter;
128 * set flag to true when setting values programmatically,
129 * to avoid invocation of action handlers
131 boolean adjusting = false;
134 * minimum of the value range for graduated colour
135 * (may be for feature score or for a numeric attribute)
140 * maximum of the value range for graduated colour
145 * scale factor for conversion between absolute min-max and slider
150 * radio button group, to select what to colour by:
151 * simple colour, by category (text), or graduated
153 JRadioButton simpleColour = new JRadioButton();
155 JRadioButton byCategory = new JRadioButton();
157 JRadioButton graduatedColour = new JRadioButton();
163 JPanel singleColour = new JPanel();
165 JPanel minColour = new JPanel();
167 JPanel maxColour = new JPanel();
169 private JComboBox<Object> threshold = new JComboBox<>();
171 JSlider slider = new JSlider();
173 JTextField thresholdValue = new JTextField(20);
175 private JCheckBox thresholdIsMin = new JCheckBox();
177 private GraphLine threshline;
179 private ActionListener featureSettings = null;
181 private ActionListener changeColourAction;
184 * choice of option for 'colour for no value'
186 private JComboBox<Object> noValueCombo;
189 * choice of what to colour by text (Label or attribute)
191 private JComboBox<Object> colourByTextCombo;
194 * choice of what to colour by range (Score or attribute)
196 private JComboBox<Object> colourByRangeCombo;
198 private JRadioButton andFilters;
200 private JRadioButton orFilters;
203 * filters for the currently selected feature type
205 List<FeatureMatcherI> filters;
207 private JPanel chooseFiltersPanel;
215 public FeatureTypeSettings(FeatureRenderer frender, String theType)
218 this.featureType = theType;
220 originalFilter = fr.getFeatureFilter(theType);
221 originalColour = fr.getFeatureColours().get(theType);
228 } catch (Exception ex)
230 ex.printStackTrace();
234 updateColoursPanel();
236 updateFiltersPanel();
240 colourChanged(false);
242 String title = MessageManager
243 .formatMessage("label.display_settings_for", new String[]
245 initDialogFrame(this, true, false, title, 580, 500);
250 * Configures the widgets on the Colours panel according to the current feature
253 private void updateColoursPanel()
255 FeatureColourI fc = fr.getFeatureColours().get(featureType);
258 * suppress action handling while updating values programmatically
266 if (fc.isSimpleColour())
268 singleColour.setBackground(fc.getColour());
269 singleColour.setForeground(fc.getColour());
270 simpleColour.setSelected(true);
274 * colour by text (Label or attribute text)
276 if (fc.isColourByLabel())
278 byCategory.setSelected(true);
279 colourByTextCombo.setEnabled(colourByTextCombo.getItemCount() > 1);
280 if (fc.isColourByAttribute())
282 String[] attributeName = fc.getAttributeName();
283 colourByTextCombo.setSelectedItem(
284 FeatureMatcher.toAttributeDisplayName(attributeName));
288 colourByTextCombo.setSelectedItem(LABEL_18N);
293 colourByTextCombo.setEnabled(false);
296 if (!fc.isGraduatedColour())
298 colourByRangeCombo.setEnabled(false);
299 minColour.setEnabled(false);
300 maxColour.setEnabled(false);
301 noValueCombo.setEnabled(false);
302 threshold.setEnabled(false);
303 slider.setEnabled(false);
304 thresholdValue.setEnabled(false);
305 thresholdIsMin.setEnabled(false);
310 * Graduated colour, by score or attribute value range
312 graduatedColour.setSelected(true);
313 updateColourMinMax(); // ensure min, max are set
314 colourByRangeCombo.setEnabled(colourByRangeCombo.getItemCount() > 1);
315 minColour.setEnabled(true);
316 maxColour.setEnabled(true);
317 noValueCombo.setEnabled(true);
318 threshold.setEnabled(true);
319 minColour.setBackground(fc.getMinColour());
320 maxColour.setBackground(fc.getMaxColour());
322 if (fc.isColourByAttribute())
324 String[] attributeName = fc.getAttributeName();
325 colourByRangeCombo.setSelectedItem(
326 FeatureMatcher.toAttributeDisplayName(attributeName));
330 colourByRangeCombo.setSelectedItem(SCORE_18N);
332 Color noColour = fc.getNoColour();
333 if (noColour == null)
335 noValueCombo.setSelectedIndex(NO_COLOUR_OPTION);
337 else if (noColour.equals(fc.getMinColour()))
339 noValueCombo.setSelectedIndex(MIN_COLOUR_OPTION);
341 else if (noColour.equals(fc.getMaxColour()))
343 noValueCombo.setSelectedIndex(MAX_COLOUR_OPTION);
347 * update min-max scaling if there is a range to work with,
348 * else disable the widgets (this shouldn't happen if only
349 * valid options are offered in the combo box)
351 scaleFactor = (max == min) ? 1f : 100f / (max - min);
352 float range = (max - min) * scaleFactor;
353 slider.setMinimum((int) (min * scaleFactor));
354 slider.setMaximum((int) (max * scaleFactor));
355 slider.setMajorTickSpacing((int) (range / 10f));
357 threshline = new GraphLine((max - min) / 2f, "Threshold",
359 threshline.value = fc.getThreshold();
361 if (fc.hasThreshold())
363 threshold.setSelectedIndex(
364 fc.isAboveThreshold() ? ABOVE_THRESHOLD_OPTION
365 : BELOW_THRESHOLD_OPTION);
366 slider.setEnabled(true);
367 slider.setValue((int) (fc.getThreshold() * scaleFactor));
368 thresholdValue.setText(String.valueOf(fc.getThreshold()));
369 thresholdValue.setEnabled(true);
370 thresholdIsMin.setEnabled(true);
374 slider.setEnabled(false);
375 thresholdValue.setEnabled(false);
376 thresholdIsMin.setEnabled(false);
378 thresholdIsMin.setSelected(!fc.isAutoScaled());
386 * Configures the initial layout
388 private void initialise()
390 this.setLayout(new BorderLayout());
393 * an ActionListener that applies colour changes
395 changeColourAction = new ActionListener()
398 public void actionPerformed(ActionEvent e)
405 * first panel: colour options
407 JPanel coloursPanel = initialiseColoursPanel();
408 this.add(coloursPanel, BorderLayout.NORTH);
411 * second panel: filter options
413 JPanel filtersPanel = initialiseFiltersPanel();
414 this.add(filtersPanel, BorderLayout.CENTER);
416 JPanel okCancelPanel = initialiseOkCancelPanel();
418 this.add(okCancelPanel, BorderLayout.SOUTH);
422 * Updates the min-max range if Colour By selected item is Score, or an
423 * attribute, with a min-max range
425 protected void updateColourMinMax()
427 if (!graduatedColour.isSelected())
432 String colourBy = (String) colourByRangeCombo.getSelectedItem();
433 float[] minMax = getMinMax(colourBy);
443 * Retrieves the min-max range:
445 * <li>of feature score, if colour or filter is by Score</li>
446 * <li>else of the selected attribute</li>
452 private float[] getMinMax(String attName)
454 float[] minMax = null;
455 if (SCORE_18N.equals(attName))
457 minMax = fr.getMinMax().get(featureType)[0];
461 // colour by attribute range
462 minMax = FeatureAttributes.getInstance().getMinMax(featureType,
463 FeatureMatcher.fromAttributeDisplayName(attName));
469 * Lay out fields for graduated colour (by score or attribute value)
473 private JPanel initialiseGraduatedColourPanel()
475 JPanel graduatedColourPanel = new JPanel();
476 graduatedColourPanel.setLayout(
477 new BoxLayout(graduatedColourPanel, BoxLayout.Y_AXIS));
478 JvSwingUtils.createTitledBorder(graduatedColourPanel,
479 MessageManager.getString("label.graduated_colour"), true);
480 graduatedColourPanel.setBackground(Color.white);
483 * first row: graduated colour radio button, score/attribute drop-down
485 JPanel graduatedChoicePanel = new JPanel(
486 new FlowLayout(FlowLayout.LEFT));
487 graduatedChoicePanel.setBackground(Color.white);
488 graduatedColour = new JRadioButton(
489 MessageManager.getString("label.by_range_of") + COLON);
490 graduatedColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
491 graduatedColour.setOpaque(false);
492 graduatedColour.addItemListener(new ItemListener()
495 public void itemStateChanged(ItemEvent e)
497 if (graduatedColour.isSelected())
503 graduatedChoicePanel.add(graduatedColour);
505 List<String[]> attNames = FeatureAttributes.getInstance()
506 .getAttributes(featureType);
507 colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
508 colourByRangeCombo.addItemListener(new ItemListener()
511 public void itemStateChanged(ItemEvent e)
518 * disable graduated colour option if no range found
520 graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
522 graduatedChoicePanel.add(colourByRangeCombo);
523 graduatedColourPanel.add(graduatedChoicePanel);
526 * second row - min/max/no colours
528 JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
529 colourRangePanel.setBackground(Color.white);
530 graduatedColourPanel.add(colourRangePanel);
532 minColour.setFont(JvSwingUtils.getLabelFont());
533 minColour.setBorder(BorderFactory.createLineBorder(Color.black));
534 minColour.setPreferredSize(new Dimension(40, 20));
535 minColour.setToolTipText(MessageManager.getString("label.min_colour"));
536 minColour.addMouseListener(new MouseAdapter()
539 public void mousePressed(MouseEvent e)
541 if (minColour.isEnabled())
543 String ttl = MessageManager.getString("label.select_colour_minimum_value");
544 showColourChooser(minColour, ttl);
549 maxColour.setFont(JvSwingUtils.getLabelFont());
550 maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
551 maxColour.setPreferredSize(new Dimension(40, 20));
552 maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
553 maxColour.addMouseListener(new MouseAdapter()
556 public void mousePressed(MouseEvent e)
558 if (maxColour.isEnabled())
560 String ttl = MessageManager.getString("label.select_colour_maximum_value");
561 showColourChooser(maxColour, ttl);
565 maxColour.setBorder(new LineBorder(Color.black));
568 * if not set, default max colour to last plain colour,
569 * and make min colour a pale version of max colour
571 Color max = originalColour.getMaxColour();
574 max = originalColour.getColour();
575 minColour.setBackground(ColorUtils.bleachColour(max, 0.9f));
579 maxColour.setBackground(max);
580 minColour.setBackground(originalColour.getMinColour());
583 noValueCombo = new JComboBox<>();
584 noValueCombo.addItem(MessageManager.getString("label.no_colour"));
585 noValueCombo.addItem(MessageManager.getString("label.min_colour"));
586 noValueCombo.addItem(MessageManager.getString("label.max_colour"));
587 noValueCombo.addItemListener(new ItemListener()
590 public void itemStateChanged(ItemEvent e)
596 JLabel minText = new JLabel(
597 MessageManager.getString("label.min_value") + COLON);
598 minText.setFont(JvSwingUtils.getLabelFont());
599 JLabel maxText = new JLabel(
600 MessageManager.getString("label.max_value") + COLON);
601 maxText.setFont(JvSwingUtils.getLabelFont());
602 JLabel noText = new JLabel(
603 MessageManager.getString("label.no_value") + COLON);
604 noText.setFont(JvSwingUtils.getLabelFont());
606 colourRangePanel.add(minText);
607 colourRangePanel.add(minColour);
608 colourRangePanel.add(maxText);
609 colourRangePanel.add(maxColour);
610 colourRangePanel.add(noText);
611 colourRangePanel.add(noValueCombo);
614 * third row - threshold options and value
616 JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
617 thresholdPanel.setBackground(Color.white);
618 graduatedColourPanel.add(thresholdPanel);
620 threshold.addActionListener(changeColourAction);
621 threshold.setToolTipText(MessageManager
622 .getString("label.threshold_feature_display_by_score"));
623 threshold.addItem(MessageManager
624 .getString("label.threshold_feature_no_threshold")); // index 0
625 threshold.addItem(MessageManager
626 .getString("label.threshold_feature_above_threshold")); // index 1
627 threshold.addItem(MessageManager
628 .getString("label.threshold_feature_below_threshold")); // index 2
630 thresholdValue.addActionListener(new ActionListener()
633 public void actionPerformed(ActionEvent e)
635 thresholdValue_actionPerformed();
638 thresholdValue.addFocusListener(new FocusAdapter()
641 public void focusLost(FocusEvent e)
643 thresholdValue_actionPerformed();
646 slider.setPaintLabels(false);
647 slider.setPaintTicks(true);
648 slider.setBackground(Color.white);
649 slider.setEnabled(false);
650 slider.setOpaque(false);
651 slider.setPreferredSize(new Dimension(100, 32));
652 slider.setToolTipText(
653 MessageManager.getString("label.adjust_threshold"));
655 slider.addChangeListener(new ChangeListener()
658 public void stateChanged(ChangeEvent evt)
663 .setText(String.valueOf(slider.getValue() / scaleFactor));
664 thresholdValue.setBackground(Color.white); // to reset red for invalid
665 sliderValueChanged();
669 slider.addMouseListener(new MouseAdapter()
672 public void mouseReleased(MouseEvent evt)
675 * only update Overview and/or structure colouring
676 * when threshold slider drag ends (mouse up)
680 refreshDisplay(true);
685 thresholdValue.setEnabled(false);
686 thresholdValue.setColumns(7);
688 thresholdPanel.add(threshold);
689 thresholdPanel.add(slider);
690 thresholdPanel.add(thresholdValue);
692 thresholdIsMin.setBackground(Color.white);
694 .setText(MessageManager.getString("label.threshold_minmax"));
695 thresholdIsMin.setToolTipText(MessageManager
696 .getString("label.toggle_absolute_relative_display_threshold"));
697 thresholdIsMin.addActionListener(changeColourAction);
698 thresholdPanel.add(thresholdIsMin);
700 return graduatedColourPanel;
704 * Lay out OK and Cancel buttons
708 private JPanel initialiseOkCancelPanel()
710 JPanel okCancelPanel = new JPanel();
711 // okCancelPanel.setBackground(Color.white);
712 okCancelPanel.add(ok);
713 okCancelPanel.add(cancel);
714 return okCancelPanel;
718 * Lay out Colour options panel, containing
720 * <li>plain colour, with colour picker</li>
721 * <li>colour by text, with choice of Label or other attribute</li>
722 * <li>colour by range, of score or other attribute, when available</li>
727 private JPanel initialiseColoursPanel()
729 JPanel colourByPanel = new JPanel();
730 colourByPanel.setBackground(Color.white);
731 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
732 JvSwingUtils.createTitledBorder(colourByPanel,
733 MessageManager.getString("action.colour"), true);
736 * simple colour radio button and colour picker
738 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
739 simpleColourPanel.setBackground(Color.white);
740 colourByPanel.add(simpleColourPanel);
742 simpleColour = new JRadioButton(
743 MessageManager.getString("label.simple_colour"));
744 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
745 simpleColour.setOpaque(false);
746 simpleColour.addItemListener(new ItemListener()
749 public void itemStateChanged(ItemEvent e)
751 if (simpleColour.isSelected() && !adjusting)
758 singleColour.setFont(JvSwingUtils.getLabelFont());
759 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
760 singleColour.setPreferredSize(new Dimension(40, 20));
761 // if (originalColour.isGraduatedColour())
763 // singleColour.setBackground(originalColour.getMaxColour());
764 // singleColour.setForeground(originalColour.getMaxColour());
768 singleColour.setBackground(originalColour.getColour());
769 singleColour.setForeground(originalColour.getColour());
771 singleColour.addMouseListener(new MouseAdapter()
774 public void mousePressed(MouseEvent e)
776 if (simpleColour.isSelected())
778 String ttl = MessageManager.formatMessage("label.select_colour_for", featureType);
779 showColourChooser(singleColour, ttl);
783 simpleColourPanel.add(simpleColour); // radio button
784 simpleColourPanel.add(singleColour); // colour picker button
787 * colour by text (category) radio button and drop-down choice list
789 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
790 byTextPanel.setBackground(Color.white);
791 JvSwingUtils.createTitledBorder(byTextPanel,
792 MessageManager.getString("label.colour_by_text"), true);
793 colourByPanel.add(byTextPanel);
794 byCategory = new JRadioButton(
795 MessageManager.getString("label.by_text_of") + COLON);
796 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
797 byCategory.setOpaque(false);
798 byCategory.addItemListener(new ItemListener()
801 public void itemStateChanged(ItemEvent e)
803 if (byCategory.isSelected())
809 byTextPanel.add(byCategory);
811 List<String[]> attNames = FeatureAttributes.getInstance()
812 .getAttributes(featureType);
813 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
814 colourByTextCombo.addItemListener(new ItemListener()
817 public void itemStateChanged(ItemEvent e)
822 byTextPanel.add(colourByTextCombo);
825 * graduated colour panel
827 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
828 colourByPanel.add(graduatedColourPanel);
831 * 3 radio buttons select between simple colour,
832 * by category (text), or graduated
834 ButtonGroup bg = new ButtonGroup();
835 bg.add(simpleColour);
837 bg.add(graduatedColour);
839 return colourByPanel;
843 * Shows a colour chooser dialog, and if a selection is made, updates the
844 * colour of the given panel
847 * the panel whose background colour is being picked
850 void showColourChooser(JPanel colourPanel, String title)
852 ColourChooserListener listener = new ColourChooserListener()
855 public void colourSelected(Color col)
857 colourPanel.setBackground(col);
858 colourPanel.setForeground(col);
859 colourPanel.repaint();
863 JalviewColourChooser.showColourChooser(this, title,
864 colourPanel.getBackground(), listener);
868 * Constructs and sets the selected colour options as the colour for the
869 * feature type, and repaints the alignment, and optionally the Overview
870 * and/or structure viewer if open
872 * @param updateStructsAndOverview
874 void colourChanged(boolean updateStructsAndOverview)
879 * ignore action handlers while setting values programmatically
885 * ensure min-max range is for the latest choice of
886 * 'graduated colour by'
888 updateColourMinMax();
890 FeatureColourI acg = makeColourFromInputs();
893 * save the colour, and repaint stuff
895 fr.setColour(featureType, acg);
896 refreshDisplay(updateStructsAndOverview);
898 updateColoursPanel();
902 * Converts the input values into an instance of FeatureColour
906 private FeatureColourI makeColourFromInputs()
909 * min-max range is to (or from) threshold value if
910 * 'threshold is min/max' is selected
916 thresh = Float.valueOf(thresholdValue.getText());
917 } catch (NumberFormatException e)
919 // invalid inputs are already handled on entry
921 float minValue = min;
922 float maxValue = max;
923 int thresholdOption = threshold.getSelectedIndex();
924 if (thresholdIsMin.isSelected()
925 && thresholdOption == ABOVE_THRESHOLD_OPTION)
929 if (thresholdIsMin.isSelected()
930 && thresholdOption == BELOW_THRESHOLD_OPTION)
934 Color noColour = null;
935 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
937 noColour = minColour.getBackground();
939 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
941 noColour = maxColour.getBackground();
945 * construct a colour that 'remembers' all the options, including
946 * those not currently selected
948 FeatureColourI fc = new FeatureColour(singleColour.getBackground(),
949 minColour.getBackground(), maxColour.getBackground(), noColour,
953 * easiest case - a single colour
955 if (simpleColour.isSelected())
957 ((FeatureColour) fc).setGraduatedColour(false);
962 * next easiest case - colour by Label, or attribute text
964 if (byCategory.isSelected())
966 fc.setColourByLabel(true);
967 String byWhat = (String) colourByTextCombo.getSelectedItem();
968 if (!LABEL_18N.equals(byWhat))
971 FeatureMatcher.fromAttributeDisplayName(byWhat));
977 * remaining case - graduated colour by score, or attribute value;
978 * set attribute to colour by if selected
980 String byWhat = (String) colourByRangeCombo.getSelectedItem();
981 if (!SCORE_18N.equals(byWhat))
983 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
987 * set threshold options and 'autoscaled' which is
988 * false if 'threshold is min/max' is selected
989 * else true (colour range is on actual range of values)
991 fc.setThreshold(thresh);
992 fc.setAutoScaled(!thresholdIsMin.isSelected());
993 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
994 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
996 if (threshline == null)
999 * todo not yet implemented: visual indication of feature threshold
1001 threshline = new GraphLine((max - min) / 2f, "Threshold",
1009 protected void raiseClosed()
1011 if (this.featureSettings != null)
1013 featureSettings.actionPerformed(new ActionEvent(this, 0, "CLOSED"));
1018 * Action on OK is just to dismiss the dialog - any changes have already been
1022 public void okPressed()
1027 * Action on Cancel is to restore colour scheme and filters as they were when
1028 * the dialog was opened
1031 public void cancelPressed()
1033 fr.setColour(featureType, originalColour);
1034 fr.setFeatureFilter(featureType, originalFilter);
1035 refreshDisplay(true);
1039 * Action on text entry of a threshold value
1041 protected void thresholdValue_actionPerformed()
1046 * set 'adjusting' flag while moving the slider, so it
1047 * doesn't then in turn change the value (with rounding)
1050 float f = Float.parseFloat(thresholdValue.getText());
1051 f = Float.max(f, this.min);
1052 f = Float.min(f, this.max);
1053 thresholdValue.setText(String.valueOf(f));
1054 slider.setValue((int) (f * scaleFactor));
1055 threshline.value = f;
1056 thresholdValue.setBackground(Color.white); // ok
1058 colourChanged(true);
1059 } catch (NumberFormatException ex)
1061 thresholdValue.setBackground(Color.red); // not ok
1067 * Action on change of threshold slider value. This may be done interactively
1068 * (by moving the slider), or programmatically (to update the slider after
1069 * manual input of a threshold value).
1071 protected void sliderValueChanged()
1073 threshline.value = getRoundedSliderValue();
1076 * repaint alignment, but not Overview or structure,
1077 * to avoid overload while dragging the slider
1079 colourChanged(false);
1083 * Converts the slider value to its absolute value by dividing by the
1084 * scaleFactor. Rounding errors are squashed by forcing min/max of slider
1085 * range to the actual min/max of feature score range
1089 private float getRoundedSliderValue()
1091 int value = slider.getValue();
1092 float f = value == slider.getMaximum() ? max
1093 : (value == slider.getMinimum() ? min : value / scaleFactor);
1097 void addActionListener(ActionListener listener)
1099 if (featureSettings != null)
1102 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1104 featureSettings = listener;
1108 * A helper method to build the drop-down choice of attributes for a feature.
1109 * If 'withRange' is true, then Score, and any attributes with a min-max
1110 * range, are added. If 'withText' is true, Label and any known attributes are
1111 * added. This allows 'categorical numerical' attributes e.g. codon position
1112 * to be coloured by text.
1114 * Where metadata is available with a description for an attribute, that is
1115 * added as a tooltip.
1117 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1118 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1120 * This method does not add any ActionListener to the JComboBox.
1126 protected JComboBox<Object> populateAttributesDropdown(
1127 List<String[]> attNames, boolean withRange, boolean withText)
1129 List<String> displayAtts = new ArrayList<>();
1130 List<String> tooltips = new ArrayList<>();
1134 displayAtts.add(LABEL_18N);
1135 tooltips.add(MessageManager.getString("label.description"));
1139 float[][] minMax = fr.getMinMax().get(featureType);
1140 if (minMax != null && minMax[0][0] != minMax[0][1])
1142 displayAtts.add(SCORE_18N);
1143 tooltips.add(SCORE_18N);
1147 FeatureAttributes fa = FeatureAttributes.getInstance();
1148 for (String[] attName : attNames)
1150 float[] minMax = fa.getMinMax(featureType, attName);
1151 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1152 if (!withText && !hasRange)
1156 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1157 String desc = fa.getDescription(featureType, attName);
1158 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1160 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1162 tooltips.add(desc == null ? "" : desc);
1165 // now convert String List to Object List for buildComboWithTooltips
1166 List<Object> displayAttsObjects = new ArrayList<>(displayAtts);
1167 JComboBox<Object> attCombo = JvSwingUtils
1168 .buildComboWithTooltips(displayAttsObjects, tooltips);
1174 * Populates initial layout of the feature attribute filters panel
1176 private JPanel initialiseFiltersPanel()
1178 filters = new ArrayList<>();
1180 JPanel filtersPanel = new JPanel();
1181 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1182 filtersPanel.setBackground(Color.white);
1183 JvSwingUtils.createTitledBorder(filtersPanel,
1184 MessageManager.getString("label.filters"), true);
1186 JPanel andOrPanel = initialiseAndOrPanel();
1187 filtersPanel.add(andOrPanel);
1190 * panel with filters - populated by refreshFiltersDisplay,
1191 * which also sets the layout manager
1193 chooseFiltersPanel = new JPanel();
1194 chooseFiltersPanel.setBackground(Color.white);
1195 filtersPanel.add(chooseFiltersPanel);
1197 return filtersPanel;
1201 * Lays out the panel with radio buttons to AND or OR filter conditions
1205 private JPanel initialiseAndOrPanel()
1207 JPanel andOrPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
1208 andOrPanel.setBackground(Color.white);
1209 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1210 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1211 andFilters.setOpaque(false);
1212 orFilters.setOpaque(false);
1213 ActionListener actionListener = new ActionListener()
1216 public void actionPerformed(ActionEvent e)
1221 andFilters.addActionListener(actionListener);
1222 orFilters.addActionListener(actionListener);
1223 ButtonGroup andOr = new ButtonGroup();
1224 andOr.add(andFilters);
1225 andOr.add(orFilters);
1226 andFilters.setSelected(true);
1228 new JLabel(MessageManager.getString("label.join_conditions")));
1229 andOrPanel.add(andFilters);
1230 andOrPanel.add(orFilters);
1235 * Refreshes the display to show any filters currently configured for the
1236 * selected feature type (editable, with 'remove' option), plus one extra row
1237 * for adding a condition. This should be called after a filter has been
1238 * removed, added or amended.
1240 private void updateFiltersPanel()
1243 * clear the panel and list of filter conditions
1245 chooseFiltersPanel.removeAll();
1249 * look up attributes known for feature type
1251 List<String[]> attNames = FeatureAttributes.getInstance()
1252 .getAttributes(featureType);
1255 * if this feature type has filters set, load them first
1257 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1258 if (featureFilters != null)
1260 if (!featureFilters.isAnded())
1262 orFilters.setSelected(true);
1264 // avoid use of lambda expression to keep SwingJS happy
1265 // featureFilters.getMatchers().forEach(item -> filters.add(item));
1266 for (FeatureMatcherI matcher : featureFilters.getMatchers())
1268 filters.add(matcher);
1273 * and an empty filter for the user to populate (add)
1275 filters.add(FeatureMatcher.NULL_MATCHER);
1278 * use GridLayout to 'justify' rows to the top of the panel, until
1279 * there are too many to fit in, then fall back on BoxLayout
1281 if (filters.size() <= 5)
1283 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1287 chooseFiltersPanel.setLayout(
1288 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1292 * render the conditions in rows, each in its own JPanel
1294 int filterIndex = 0;
1295 for (FeatureMatcherI filter : filters)
1297 JPanel row = addFilter(filter, attNames, filterIndex);
1298 chooseFiltersPanel.add(row);
1307 * A helper method that constructs a row (panel) with one filter condition:
1309 * <li>a drop-down list of Label, Score and attribute names to choose
1311 * <li>a drop-down list of conditions to choose from</li>
1312 * <li>a text field for input of a match pattern</li>
1313 * <li>optionally, a 'remove' button</li>
1315 * The filter values are set as defaults for the input fields. The 'remove'
1316 * button is added unless the pattern is empty (incomplete filter condition).
1318 * Action handlers on these fields provide for
1320 * <li>validate pattern field - should be numeric if condition is numeric</li>
1321 * <li>save filters and refresh display on any (valid) change</li>
1322 * <li>remove filter and refresh on 'Remove'</li>
1323 * <li>update conditions list on change of Label/Score/Attribute</li>
1324 * <li>refresh value field tooltip with min-max range on change of
1330 * @param filterIndex
1333 protected JPanel addFilter(FeatureMatcherI filter,
1334 List<String[]> attNames, int filterIndex)
1336 String[] attName = filter.getAttribute();
1337 Condition cond = filter.getMatcher().getCondition();
1338 String pattern = filter.getMatcher().getPattern();
1340 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1341 filterRow.setBackground(Color.white);
1344 * drop-down choice of attribute, with description as a tooltip
1345 * if we can obtain it
1347 final JComboBox<Object> attCombo = populateAttributesDropdown(attNames,
1349 String filterBy = setSelectedAttribute(attCombo, filter);
1351 JComboBox<Condition> condCombo = new JComboBox<>();
1353 JTextField patternField = new JTextField(8);
1354 patternField.setText(pattern);
1357 * action handlers that validate and (if valid) apply changes
1359 ActionListener actionListener = new ActionListener()
1362 public void actionPerformed(ActionEvent e)
1364 if (validateFilter(patternField, condCombo))
1366 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1373 ItemListener itemListener = new ItemListener()
1376 public void itemStateChanged(ItemEvent e)
1378 actionListener.actionPerformed(null);
1382 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1384 attCombo.setSelectedIndex(0);
1388 attCombo.setSelectedItem(
1389 FeatureMatcher.toAttributeDisplayName(attName));
1391 attCombo.addItemListener(new ItemListener()
1394 public void itemStateChanged(ItemEvent e)
1397 * on change of attribute, refresh the conditions list to
1398 * ensure it is appropriate for the attribute datatype
1400 populateConditions((String) attCombo.getSelectedItem(),
1401 (Condition) condCombo.getSelectedItem(), condCombo,
1403 actionListener.actionPerformed(null);
1407 filterRow.add(attCombo);
1410 * drop-down choice of test condition
1412 populateConditions(filterBy, cond, condCombo, patternField);
1413 condCombo.setPreferredSize(new Dimension(150, 20));
1414 condCombo.addItemListener(itemListener);
1415 filterRow.add(condCombo);
1418 * pattern to match against
1420 patternField.addActionListener(actionListener);
1421 patternField.addFocusListener(new FocusAdapter()
1424 public void focusLost(FocusEvent e)
1426 actionListener.actionPerformed(null);
1429 filterRow.add(patternField);
1432 * disable pattern field for condition 'Present / NotPresent'
1434 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1435 patternField.setEnabled(selectedCondition.needsAPattern());
1438 * if a numeric condition is selected, show the value range
1439 * as a tooltip on the value input field
1441 setNumericHints(filterBy, selectedCondition, patternField);
1444 * add remove button if filter is populated (non-empty pattern)
1446 if (!patternField.isEnabled()
1447 || (pattern != null && pattern.trim().length() > 0))
1449 JButton removeCondition = new JButton("\u2717");
1450 // Dingbats cursive x
1451 removeCondition.setBorder(new EmptyBorder(0, 0, 0, 0));
1452 removeCondition.setBackground(Color.WHITE);
1453 removeCondition.setPreferredSize(new Dimension(23, 17));
1454 removeCondition.setToolTipText(
1455 MessageManager.getString("label.delete_condition"));
1456 removeCondition.addActionListener(new ActionListener()
1459 public void actionPerformed(ActionEvent e)
1461 filters.remove(filterIndex);
1465 filterRow.add(removeCondition);
1472 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1478 private String setSelectedAttribute(JComboBox<Object> attCombo,
1479 FeatureMatcherI filter)
1482 if (filter.isByScore())
1486 else if (filter.isByLabel())
1492 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1494 attCombo.setSelectedItem(item);
1499 * If a numeric comparison condition is selected, retrieves the min-max range
1500 * for the value (score or attribute), and sets it as a tooltip on the value
1501 * field. If the field is currently empty, then pre-populates it with
1503 * <li>the minimum value, if condition is > or >=</li>
1504 * <li>the maximum value, if condition is < or <=</li>
1508 * @param selectedCondition
1509 * @param patternField
1511 private void setNumericHints(String attName, Condition selectedCondition,
1512 JTextField patternField)
1514 patternField.setToolTipText("");
1516 if (selectedCondition.isNumeric())
1518 float[] minMax = getMinMax(attName);
1521 String minFormatted = DECFMT_2_2.format(minMax[0]);
1522 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1523 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1524 patternField.setToolTipText(tip);
1525 if (patternField.getText().isEmpty())
1527 if (selectedCondition == Condition.GE
1528 || selectedCondition == Condition.GT)
1530 patternField.setText(minFormatted);
1534 if (selectedCondition == Condition.LE
1535 || selectedCondition == Condition.LT)
1537 patternField.setText(maxFormatted);
1546 * Populates the drop-down list of comparison conditions for the given
1547 * attribute name. The conditions added depend on the datatype of the
1548 * attribute values. The supplied condition is set as the selected item in the
1549 * list, provided it is in the list. If the pattern is now invalid
1550 * (non-numeric pattern for a numeric condition), it is cleared.
1555 * @param patternField
1557 void populateConditions(String attName, Condition cond,
1558 JComboBox<Condition> condCombo, JTextField patternField)
1560 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1561 FeatureMatcher.fromAttributeDisplayName(attName));
1562 if (LABEL_18N.equals(attName))
1564 type = Datatype.Character;
1566 else if (SCORE_18N.equals(attName))
1568 type = Datatype.Number;
1572 * remove itemListener before starting
1574 ItemListener listener = condCombo.getItemListeners()[0];
1575 condCombo.removeItemListener(listener);
1576 boolean condIsValid = false;
1578 condCombo.removeAllItems();
1579 for (Condition c : Condition.values())
1581 if ((c.isNumeric() && type == Datatype.Number)
1582 || (!c.isNumeric() && type != Datatype.Number))
1584 condCombo.addItem(c);
1593 * set the selected condition (does nothing if not in the list)
1597 condCombo.setSelectedItem(cond);
1601 condCombo.setSelectedIndex(0);
1605 * clear pattern if it is now invalid for condition
1607 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1611 String pattern = patternField.getText().trim();
1612 if (pattern.length() > 0)
1614 Float.valueOf(pattern);
1616 } catch (NumberFormatException e)
1618 patternField.setText("");
1623 * restore the listener
1625 condCombo.addItemListener(listener);
1629 * Answers true unless a numeric condition has been selected with a
1630 * non-numeric value. Sets the value field to RED with a tooltip if in error.
1632 * If the pattern is expected but is empty, this method returns false, but
1633 * does not mark the field as invalid. This supports selecting an attribute
1634 * for a new condition before a match pattern has been entered.
1639 protected boolean validateFilter(JTextField value,
1640 JComboBox<Condition> condCombo)
1642 if (value == null || condCombo == null)
1644 return true; // fields not populated
1647 Condition cond = (Condition) condCombo.getSelectedItem();
1648 if (!cond.needsAPattern())
1653 value.setBackground(Color.white);
1654 value.setToolTipText("");
1655 String v1 = value.getText().trim();
1656 if (v1.length() == 0)
1661 if (cond.isNumeric() && v1.length() > 0)
1666 } catch (NumberFormatException e)
1668 value.setBackground(Color.red);
1669 value.setToolTipText(
1670 MessageManager.getString("label.numeric_required"));
1679 * Constructs a filter condition from the given input fields, and replaces the
1680 * condition at filterIndex with the new one. Does nothing if the pattern
1681 * field is blank (unless the match condition is one that doesn't require a
1682 * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1685 * This method may update the tooltip on the filter value field to show the
1686 * value range, if a numeric condition is selected. This ensures the tooltip
1687 * is updated when a numeric valued attribute is chosen on the last 'add a
1693 * @param filterIndex
1695 protected boolean updateFilter(JComboBox<Object> attCombo,
1696 JComboBox<Condition> condCombo, JTextField valueField,
1702 attName = (String) attCombo.getSelectedItem();
1703 } catch (Exception e)
1705 Cache.log.error("Problem casting Combo box entry to String");
1706 attName = attCombo.getSelectedItem().toString();
1708 Condition cond = (Condition) condCombo.getSelectedItem();
1709 String pattern = valueField.getText().trim();
1711 setNumericHints(attName, cond, valueField);
1713 if (pattern.length() == 0 && cond.needsAPattern())
1715 valueField.setEnabled(true); // ensure pattern field is enabled!
1720 * Construct a matcher that operates on Label, Score,
1721 * or named attribute
1723 FeatureMatcherI km = null;
1724 if (LABEL_18N.equals(attName))
1726 km = FeatureMatcher.byLabel(cond, pattern);
1728 else if (SCORE_18N.equals(attName))
1730 km = FeatureMatcher.byScore(cond, pattern);
1734 km = FeatureMatcher.byAttribute(cond, pattern,
1735 FeatureMatcher.fromAttributeDisplayName(attName));
1738 filters.set(filterIndex, km);
1744 * Action on any change to feature filtering, namely
1746 * <li>change of selected attribute</li>
1747 * <li>change of selected condition</li>
1748 * <li>change of match pattern</li>
1749 * <li>removal of a condition</li>
1751 * The inputs are parsed into a combined filter and this is set for the
1752 * feature type, and the alignment redrawn.
1754 protected void filtersChanged()
1757 * update the filter conditions for the feature type
1759 boolean anded = andFilters.isSelected();
1760 FeatureMatcherSetI combined = new FeatureMatcherSet();
1762 for (FeatureMatcherI filter : filters)
1764 String pattern = filter.getMatcher().getPattern();
1765 Condition condition = filter.getMatcher().getCondition();
1766 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1770 combined.and(filter);
1774 combined.or(filter);
1780 * save the filter conditions in the FeatureRenderer
1781 * (note this might now be an empty filter with no conditions)
1783 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1784 refreshDisplay(true);
1786 updateFiltersPanel();
1790 * Repaints alignment, structure and overview (if shown). If there is a
1791 * complementary view which is showing this view's features, then also
1794 * @param updateStructsAndOverview
1796 void refreshDisplay(boolean updateStructsAndOverview)
1798 ap.paintAlignment(true, updateStructsAndOverview);
1799 AlignViewportI complement = ap.getAlignViewport().getCodingComplement();
1800 if (complement != null && complement.isShowComplementFeatures())
1802 AlignFrame af2 = Desktop.getAlignFrameFor(complement);
1803 af2.alignPanel.paintAlignment(true, updateStructsAndOverview);