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.bin.Cache;
26 import jalview.datamodel.GraphLine;
27 import jalview.datamodel.features.FeatureAttributes;
28 import jalview.datamodel.features.FeatureAttributes.Datatype;
29 import jalview.datamodel.features.FeatureMatcher;
30 import jalview.datamodel.features.FeatureMatcherI;
31 import jalview.datamodel.features.FeatureMatcherSet;
32 import jalview.datamodel.features.FeatureMatcherSetI;
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.GridLayout;
43 import java.awt.event.ActionEvent;
44 import java.awt.event.ActionListener;
45 import java.awt.event.FocusAdapter;
46 import java.awt.event.FocusEvent;
47 import java.awt.event.ItemEvent;
48 import java.awt.event.ItemListener;
49 import java.awt.event.MouseAdapter;
50 import java.awt.event.MouseEvent;
51 import java.text.DecimalFormat;
52 import java.util.ArrayList;
53 import java.util.List;
55 import javax.swing.BorderFactory;
56 import javax.swing.BoxLayout;
57 import javax.swing.ButtonGroup;
58 import javax.swing.JButton;
59 import javax.swing.JCheckBox;
60 import javax.swing.JColorChooser;
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.EmptyBorder;
68 import javax.swing.border.LineBorder;
69 import javax.swing.event.ChangeEvent;
70 import javax.swing.event.ChangeListener;
73 * A dialog where the user can configure colour scheme, and any filters, for one
76 * (Was FeatureColourChooser prior to Jalview 1.11, renamed with the addition of
79 public class FeatureTypeSettings extends JalviewDialog
81 private final static String LABEL_18N = MessageManager
82 .getString("label.label");
84 private final static String SCORE_18N = MessageManager
85 .getString("label.score");
87 private static final int RADIO_WIDTH = 130;
89 private static final String COLON = ":";
91 private static final int MAX_TOOLTIP_LENGTH = 50;
93 private static final int NO_COLOUR_OPTION = 0;
95 private static final int MIN_COLOUR_OPTION = 1;
97 private static final int MAX_COLOUR_OPTION = 2;
99 private static final int ABOVE_THRESHOLD_OPTION = 1;
101 private static final int BELOW_THRESHOLD_OPTION = 2;
103 private static final DecimalFormat DECFMT_2_2 = new DecimalFormat(
107 * FeatureRenderer holds colour scheme and filters for feature types
109 private final FeatureRenderer fr; // todo refactor to allow interface type
113 * the view panel to update when settings change
115 private final AlignmentViewPanel ap;
117 private final String featureType;
120 * the colour and filters to reset to on Cancel
122 private final FeatureColourI originalColour;
124 private final FeatureMatcherSetI originalFilter;
127 * set flag to true when setting values programmatically,
128 * to avoid invocation of action handlers
130 private boolean adjusting = false;
133 * minimum of the value range for graduated colour
134 * (may be for feature score or for a numeric attribute)
139 * maximum of the value range for graduated colour
144 * scale factor for conversion between absolute min-max and slider
145 * slider value is true value * scale factor
147 private float sliderScaleFactor;
150 * value to subtract from slider value before conversion;
151 * normally zero, but >0 if min is negative
152 * true value = (slider value - offset) / scale factor
153 * slider value = true value * scale factor + offset
155 private int sliderOffset;
158 * radio button group, to select what to colour by:
159 * simple colour, by category (text), or graduated
161 private JRadioButton simpleColour = new JRadioButton();
163 private JRadioButton byCategory = new JRadioButton();
165 private JRadioButton graduatedColour = new JRadioButton();
168 * colours and filters are shown in tabbed view or single content pane
170 JPanel coloursPanel, filtersPanel;
172 JPanel singleColour = new JPanel();
174 private JPanel minColour = new JPanel();
176 private JPanel maxColour = new JPanel();
178 private JComboBox<Object> threshold = new JComboBox<>();
180 private JSlider slider = new JSlider();
182 private JTextField thresholdValue = new JTextField(20);
184 private JCheckBox thresholdIsMin = new JCheckBox();
186 private GraphLine threshline;
188 private ActionListener featureSettings = null;
190 private ActionListener changeColourAction;
193 * choice of option for 'colour for no value'
195 private JComboBox<Object> noValueCombo;
198 * choice of what to colour by text (Label or attribute)
200 private JComboBox<Object> colourByTextCombo;
203 * choice of what to colour by range (Score or attribute)
205 private JComboBox<Object> colourByRangeCombo;
207 private JRadioButton andFilters;
209 private JRadioButton orFilters;
212 * filters for the currently selected feature type
214 private List<FeatureMatcherI> filters;
216 private JPanel chooseFiltersPanel;
224 public FeatureTypeSettings(FeatureRenderer frender, String theType)
227 this.featureType = theType;
229 originalFilter = fr.getFeatureFilter(theType);
230 originalColour = fr.getFeatureColours().get(theType);
237 } catch (Exception ex)
239 ex.printStackTrace();
249 colourChanged(false);
251 String title = MessageManager
252 .formatMessage("label.display_settings_for", new String[]
254 initDialogFrame(this, true, false, title, 580, 500);
259 * Configures the widgets on the Colours tab according to the current feature
262 private void updateColoursTab()
264 FeatureColourI fc = fr.getFeatureColours().get(featureType);
267 * suppress action handling while updating values programmatically
275 if (fc.isSimpleColour())
277 singleColour.setBackground(fc.getColour());
278 singleColour.setForeground(fc.getColour());
279 simpleColour.setSelected(true);
283 * colour by text (Label or attribute text)
285 if (fc.isColourByLabel())
287 byCategory.setSelected(true);
288 colourByTextCombo.setEnabled(colourByTextCombo.getItemCount() > 1);
289 if (fc.isColourByAttribute())
291 String[] attributeName = fc.getAttributeName();
292 colourByTextCombo.setSelectedItem(
293 FeatureMatcher.toAttributeDisplayName(attributeName));
297 colourByTextCombo.setSelectedItem(LABEL_18N);
302 colourByTextCombo.setEnabled(false);
305 if (!fc.isGraduatedColour())
307 colourByRangeCombo.setEnabled(false);
308 minColour.setEnabled(false);
309 maxColour.setEnabled(false);
310 noValueCombo.setEnabled(false);
311 threshold.setEnabled(false);
312 slider.setEnabled(false);
313 thresholdValue.setEnabled(false);
314 thresholdIsMin.setEnabled(false);
319 * Graduated colour, by score or attribute value range
321 graduatedColour.setSelected(true);
322 updateColourMinMax(); // ensure min, max are set
323 colourByRangeCombo.setEnabled(colourByRangeCombo.getItemCount() > 1);
324 minColour.setEnabled(true);
325 maxColour.setEnabled(true);
326 noValueCombo.setEnabled(true);
327 threshold.setEnabled(true);
328 minColour.setBackground(fc.getMinColour());
329 maxColour.setBackground(fc.getMaxColour());
331 if (fc.isColourByAttribute())
333 String[] attributeName = fc.getAttributeName();
334 colourByRangeCombo.setSelectedItem(
335 FeatureMatcher.toAttributeDisplayName(attributeName));
339 colourByRangeCombo.setSelectedItem(SCORE_18N);
341 Color noColour = fc.getNoColour();
342 if (noColour == null)
344 noValueCombo.setSelectedIndex(NO_COLOUR_OPTION);
346 else if (noColour.equals(fc.getMinColour()))
348 noValueCombo.setSelectedIndex(MIN_COLOUR_OPTION);
350 else if (noColour.equals(fc.getMaxColour()))
352 noValueCombo.setSelectedIndex(MAX_COLOUR_OPTION);
356 * update min-max scaling if there is a range to work with,
357 * else disable the widgets (this shouldn't happen if only
358 * valid options are offered in the combo box)
359 * offset slider to have only non-negative values if necessary (JAL-2983)
361 sliderScaleFactor = (max == min) ? 1f : 100f / (max - min);
362 float range = (max - min) * sliderScaleFactor;
363 int minimum = (int) (min * sliderScaleFactor);
364 int maximum = (int) (max * sliderScaleFactor);
365 sliderOffset = minimum < 0f ? -minimum : 0;
366 slider.setMinimum(minimum + sliderOffset);
367 slider.setMaximum(maximum + sliderOffset);
368 slider.setMajorTickSpacing((int) (range / 10f));
370 threshline = new GraphLine((max - min) / 2f, "Threshold",
372 threshline.value = fc.getThreshold();
374 if (fc.hasThreshold())
376 threshold.setSelectedIndex(
377 fc.isAboveThreshold() ? ABOVE_THRESHOLD_OPTION
378 : BELOW_THRESHOLD_OPTION);
379 slider.setEnabled(true);
380 setSliderValue(fc.getThreshold());
381 thresholdValue.setText(String.valueOf(fc.getThreshold()));
382 thresholdValue.setEnabled(true);
383 thresholdIsMin.setEnabled(true);
387 slider.setEnabled(false);
388 thresholdValue.setEnabled(false);
389 thresholdIsMin.setEnabled(false);
391 thresholdIsMin.setSelected(!fc.isAutoScaled());
399 * Configures the initial layout
401 private void initialise()
403 this.setLayout(new BorderLayout());
406 * an ActionListener that applies colour changes
408 changeColourAction = new ActionListener()
411 public void actionPerformed(ActionEvent e)
418 * first panel/tab: colour options
420 JPanel coloursPanel = initialiseColoursPanel();
421 this.add(coloursPanel, BorderLayout.NORTH);
424 * second panel/tab: filter options
426 JPanel filtersPanel = initialiseFiltersPanel();
427 this.add(filtersPanel, BorderLayout.CENTER);
429 JPanel okCancelPanel = initialiseOkCancelPanel();
431 this.add(okCancelPanel, BorderLayout.SOUTH);
435 * Updates the min-max range if Colour By selected item is Score, or an
436 * attribute, with a min-max range
438 protected void updateColourMinMax()
440 if (!graduatedColour.isSelected())
445 String colourBy = (String) colourByRangeCombo.getSelectedItem();
446 float[] minMax = getMinMax(colourBy);
456 * Retrieves the min-max range:
458 * <li>of feature score, if colour or filter is by Score</li>
459 * <li>else of the selected attribute</li>
465 private float[] getMinMax(String attName)
467 float[] minMax = null;
468 if (SCORE_18N.equals(attName))
470 minMax = fr.getMinMax().get(featureType)[0];
474 // colour by attribute range
475 minMax = FeatureAttributes.getInstance().getMinMax(featureType,
476 FeatureMatcher.fromAttributeDisplayName(attName));
482 * Lay out fields for graduated colour (by score or attribute value)
486 private JPanel initialiseGraduatedColourPanel()
488 JPanel graduatedColourPanel = new JPanel();
489 graduatedColourPanel.setLayout(
490 new BoxLayout(graduatedColourPanel, BoxLayout.Y_AXIS));
491 JvSwingUtils.createTitledBorder(graduatedColourPanel,
492 MessageManager.getString("label.graduated_colour"), true);
493 graduatedColourPanel.setBackground(Color.white);
496 * first row: graduated colour radio button, score/attribute drop-down
498 JPanel graduatedChoicePanel = new JPanel(
499 new FlowLayout(FlowLayout.LEFT));
500 graduatedChoicePanel.setBackground(Color.white);
501 graduatedColour = new JRadioButton(
502 MessageManager.getString("label.by_range_of") + COLON);
503 graduatedColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
504 graduatedColour.addItemListener(new ItemListener()
507 public void itemStateChanged(ItemEvent e)
509 if (graduatedColour.isSelected())
515 graduatedChoicePanel.add(graduatedColour);
517 List<String[]> attNames = FeatureAttributes.getInstance()
518 .getAttributes(featureType);
519 colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
520 colourByRangeCombo.addItemListener(new ItemListener()
523 public void itemStateChanged(ItemEvent e)
530 * disable graduated colour option if no range found
532 graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
534 graduatedChoicePanel.add(colourByRangeCombo);
535 graduatedColourPanel.add(graduatedChoicePanel);
538 * second row - min/max/no colours
540 JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
541 colourRangePanel.setBackground(Color.white);
542 graduatedColourPanel.add(colourRangePanel);
544 minColour.setFont(JvSwingUtils.getLabelFont());
545 minColour.setBorder(BorderFactory.createLineBorder(Color.black));
546 minColour.setPreferredSize(new Dimension(40, 20));
547 minColour.setToolTipText(MessageManager.getString("label.min_colour"));
548 minColour.addMouseListener(new MouseAdapter()
551 public void mousePressed(MouseEvent e)
553 if (minColour.isEnabled())
555 showColourChooser(minColour, "label.select_colour_minimum_value");
560 maxColour.setFont(JvSwingUtils.getLabelFont());
561 maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
562 maxColour.setPreferredSize(new Dimension(40, 20));
563 maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
564 maxColour.addMouseListener(new MouseAdapter()
567 public void mousePressed(MouseEvent e)
569 if (maxColour.isEnabled())
571 showColourChooser(maxColour, "label.select_colour_maximum_value");
575 maxColour.setBorder(new LineBorder(Color.black));
578 * if not set, default max colour to last plain colour,
579 * and make min colour a pale version of max colour
581 Color max = originalColour.getMaxColour();
584 max = originalColour.getColour();
585 minColour.setBackground(ColorUtils.bleachColour(max, 0.9f));
589 maxColour.setBackground(max);
590 minColour.setBackground(originalColour.getMinColour());
593 noValueCombo = new JComboBox<>();
594 noValueCombo.addItem(MessageManager.getString("label.no_colour"));
595 noValueCombo.addItem(MessageManager.getString("label.min_colour"));
596 noValueCombo.addItem(MessageManager.getString("label.max_colour"));
597 noValueCombo.addItemListener(new ItemListener()
600 public void itemStateChanged(ItemEvent e)
606 JLabel minText = new JLabel(
607 MessageManager.getString("label.min_value") + COLON);
608 minText.setFont(JvSwingUtils.getLabelFont());
609 JLabel maxText = new JLabel(
610 MessageManager.getString("label.max_value") + COLON);
611 maxText.setFont(JvSwingUtils.getLabelFont());
612 JLabel noText = new JLabel(
613 MessageManager.getString("label.no_value") + COLON);
614 noText.setFont(JvSwingUtils.getLabelFont());
616 colourRangePanel.add(minText);
617 colourRangePanel.add(minColour);
618 colourRangePanel.add(maxText);
619 colourRangePanel.add(maxColour);
620 colourRangePanel.add(noText);
621 colourRangePanel.add(noValueCombo);
624 * third row - threshold options and value
626 JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
627 thresholdPanel.setBackground(Color.white);
628 graduatedColourPanel.add(thresholdPanel);
630 threshold.addActionListener(changeColourAction);
631 threshold.setToolTipText(MessageManager
632 .getString("label.threshold_feature_display_by_score"));
633 threshold.addItem(MessageManager
634 .getString("label.threshold_feature_no_threshold")); // index 0
635 threshold.addItem(MessageManager
636 .getString("label.threshold_feature_above_threshold")); // index 1
637 threshold.addItem(MessageManager
638 .getString("label.threshold_feature_below_threshold")); // index 2
640 thresholdValue.addActionListener(new ActionListener()
643 public void actionPerformed(ActionEvent e)
645 thresholdValue_actionPerformed();
648 thresholdValue.addFocusListener(new FocusAdapter()
651 public void focusLost(FocusEvent e)
653 thresholdValue_actionPerformed();
656 slider.setPaintLabels(false);
657 slider.setPaintTicks(true);
658 slider.setBackground(Color.white);
659 slider.setEnabled(false);
660 slider.setOpaque(false);
661 slider.setPreferredSize(new Dimension(100, 32));
662 slider.setToolTipText(
663 MessageManager.getString("label.adjust_threshold"));
665 slider.addChangeListener(new ChangeListener()
668 public void stateChanged(ChangeEvent evt)
673 .setText(String.format("%.3f", getSliderValue()));
674 thresholdValue.setBackground(Color.white); // to reset red for invalid
675 sliderValueChanged();
679 slider.addMouseListener(new MouseAdapter()
682 public void mouseReleased(MouseEvent evt)
685 * only update Overview and/or structure colouring
686 * when threshold slider drag ends (mouse up)
690 ap.paintAlignment(true, true);
695 thresholdValue.setEnabled(false);
696 thresholdValue.setColumns(7);
698 thresholdPanel.add(threshold);
699 thresholdPanel.add(slider);
700 thresholdPanel.add(thresholdValue);
702 thresholdIsMin.setBackground(Color.white);
704 .setText(MessageManager.getString("label.threshold_minmax"));
705 thresholdIsMin.setToolTipText(MessageManager
706 .getString("label.toggle_absolute_relative_display_threshold"));
707 thresholdIsMin.addActionListener(changeColourAction);
708 thresholdPanel.add(thresholdIsMin);
710 return graduatedColourPanel;
714 * Lay out OK and Cancel buttons
718 private JPanel initialiseOkCancelPanel()
720 JPanel okCancelPanel = new JPanel();
721 // okCancelPanel.setBackground(Color.white);
722 okCancelPanel.add(ok);
723 okCancelPanel.add(cancel);
724 return okCancelPanel;
728 * Lay out Colour options panel, containing
730 * <li>plain colour, with colour picker</li>
731 * <li>colour by text, with choice of Label or other attribute</li>
732 * <li>colour by range, of score or other attribute, when available</li>
737 private JPanel initialiseColoursPanel()
739 JPanel colourByPanel = new JPanel();
740 colourByPanel.setBackground(Color.white);
741 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
742 JvSwingUtils.createTitledBorder(colourByPanel,
743 MessageManager.getString("action.colour"), true);
746 * simple colour radio button and colour picker
748 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
749 simpleColourPanel.setBackground(Color.white);
750 colourByPanel.add(simpleColourPanel);
752 simpleColour = new JRadioButton(
753 MessageManager.getString("label.simple_colour"));
754 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
755 simpleColour.addItemListener(new ItemListener()
758 public void itemStateChanged(ItemEvent e)
760 if (simpleColour.isSelected() && !adjusting)
767 singleColour.setFont(JvSwingUtils.getLabelFont());
768 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
769 singleColour.setPreferredSize(new Dimension(40, 20));
770 // if (originalColour.isGraduatedColour())
772 // singleColour.setBackground(originalColour.getMaxColour());
773 // singleColour.setForeground(originalColour.getMaxColour());
777 singleColour.setBackground(originalColour.getColour());
778 singleColour.setForeground(originalColour.getColour());
780 singleColour.addMouseListener(new MouseAdapter()
783 public void mousePressed(MouseEvent e)
785 if (simpleColour.isSelected())
787 showColourChooser(singleColour, "label.select_colour");
791 simpleColourPanel.add(simpleColour); // radio button
792 simpleColourPanel.add(singleColour); // colour picker button
795 * colour by text (category) radio button and drop-down choice list
797 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
798 byTextPanel.setBackground(Color.white);
799 JvSwingUtils.createTitledBorder(byTextPanel,
800 MessageManager.getString("label.colour_by_text"), true);
801 colourByPanel.add(byTextPanel);
802 byCategory = new JRadioButton(
803 MessageManager.getString("label.by_text_of") + COLON);
804 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
805 byCategory.addItemListener(new ItemListener()
808 public void itemStateChanged(ItemEvent e)
810 if (byCategory.isSelected())
816 byTextPanel.add(byCategory);
818 List<String[]> attNames = FeatureAttributes.getInstance()
819 .getAttributes(featureType);
820 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
821 colourByTextCombo.addItemListener(new ItemListener()
824 public void itemStateChanged(ItemEvent e)
829 byTextPanel.add(colourByTextCombo);
832 * graduated colour panel
834 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
835 colourByPanel.add(graduatedColourPanel);
838 * 3 radio buttons select between simple colour,
839 * by category (text), or graduated
841 ButtonGroup bg = new ButtonGroup();
842 bg.add(simpleColour);
844 bg.add(graduatedColour);
846 return colourByPanel;
849 private void showColourChooser(JPanel colourPanel, String key)
851 Color col = JColorChooser.showDialog(this,
852 MessageManager.getString(key), colourPanel.getBackground());
855 colourPanel.setBackground(col);
856 colourPanel.setForeground(col);
858 colourPanel.repaint();
863 * Constructs and sets the selected colour options as the colour for the
864 * feature type, and repaints the alignment, and optionally the Overview
865 * and/or structure viewer if open
867 * @param updateStructsAndOverview
869 void colourChanged(boolean updateStructsAndOverview)
874 * ignore action handlers while setting values programmatically
880 * ensure min-max range is for the latest choice of
881 * 'graduated colour by'
883 updateColourMinMax();
885 FeatureColourI acg = makeColourFromInputs();
888 * save the colour, and repaint stuff
890 fr.setColour(featureType, acg);
891 ap.paintAlignment(updateStructsAndOverview, updateStructsAndOverview);
897 * Converts the input values into an instance of FeatureColour
901 private FeatureColourI makeColourFromInputs()
904 * min-max range is to (or from) threshold value if
905 * 'threshold is min/max' is selected
911 thresh = Float.valueOf(thresholdValue.getText());
912 } catch (NumberFormatException e)
914 // invalid inputs are already handled on entry
916 float minValue = min;
917 float maxValue = max;
918 final int thresholdOption = threshold.getSelectedIndex();
919 if (thresholdIsMin.isSelected()
920 && thresholdOption == ABOVE_THRESHOLD_OPTION)
924 if (thresholdIsMin.isSelected()
925 && thresholdOption == BELOW_THRESHOLD_OPTION)
929 Color noColour = null;
930 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
932 noColour = minColour.getBackground();
934 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
936 noColour = maxColour.getBackground();
940 * construct a colour that 'remembers' all the options, including
941 * those not currently selected
943 FeatureColourI fc = new FeatureColour(singleColour.getBackground(),
944 minColour.getBackground(), maxColour.getBackground(), noColour,
948 * easiest case - a single colour
950 if (simpleColour.isSelected())
952 ((FeatureColour) fc).setGraduatedColour(false);
957 * next easiest case - colour by Label, or attribute text
959 if (byCategory.isSelected())
961 fc.setColourByLabel(true);
962 String byWhat = (String) colourByTextCombo.getSelectedItem();
963 if (!LABEL_18N.equals(byWhat))
966 FeatureMatcher.fromAttributeDisplayName(byWhat));
972 * remaining case - graduated colour by score, or attribute value;
973 * set attribute to colour by if selected
975 String byWhat = (String) colourByRangeCombo.getSelectedItem();
976 if (!SCORE_18N.equals(byWhat))
978 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
982 * set threshold options and 'autoscaled' which is
983 * false if 'threshold is min/max' is selected
984 * else true (colour range is on actual range of values)
986 fc.setThreshold(thresh);
987 fc.setAutoScaled(!thresholdIsMin.isSelected());
988 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
989 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
991 if (threshline == null)
994 * todo not yet implemented: visual indication of feature threshold
996 threshline = new GraphLine((max - min) / 2f, "Threshold",
1004 protected void raiseClosed()
1006 if (this.featureSettings != null)
1008 featureSettings.actionPerformed(new ActionEvent(this, 0, "CLOSED"));
1013 * Action on OK is just to dismiss the dialog - any changes have already been
1017 public void okPressed()
1022 * Action on Cancel is to restore colour scheme and filters as they were when
1023 * the dialog was opened
1026 public void cancelPressed()
1028 fr.setColour(featureType, originalColour);
1029 fr.setFeatureFilter(featureType, originalFilter);
1030 ap.paintAlignment(true, true);
1034 * Action on text entry of a threshold value
1036 protected void thresholdValue_actionPerformed()
1041 * set 'adjusting' flag while moving the slider, so it
1042 * doesn't then in turn change the value (with rounding)
1045 float f = Float.parseFloat(thresholdValue.getText());
1046 f = Float.max(f, this.min);
1047 f = Float.min(f, this.max);
1048 thresholdValue.setText(String.valueOf(f));
1049 setSliderValue(f * sliderScaleFactor);
1050 threshline.value = f;
1051 thresholdValue.setBackground(Color.white); // ok
1053 colourChanged(true);
1054 } catch (NumberFormatException ex)
1056 thresholdValue.setBackground(Color.red); // not ok
1062 * Action on change of threshold slider value. This may be done interactively
1063 * (by moving the slider), or programmatically (to update the slider after
1064 * manual input of a threshold value).
1066 protected void sliderValueChanged()
1068 threshline.value = getSliderValue();
1071 * repaint alignment, but not Overview or structure,
1072 * to avoid overload while dragging the slider
1074 colourChanged(false);
1077 void addActionListener(ActionListener listener)
1079 if (featureSettings != null)
1082 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1084 featureSettings = listener;
1088 * A helper method to build the drop-down choice of attributes for a feature.
1089 * If 'withRange' is true, then Score, and any attributes with a min-max
1090 * range, are added. If 'withText' is true, Label and any known attributes are
1091 * added. This allows 'categorical numerical' attributes e.g. codon position
1092 * to be coloured by text.
1094 * Where metadata is available with a description for an attribute, that is
1095 * added as a tooltip.
1097 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1098 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1100 * This method does not add any ActionListener to the JComboBox.
1106 protected JComboBox<Object> populateAttributesDropdown(
1107 List<String[]> attNames, boolean withRange, boolean withText)
1109 List<String> displayAtts = new ArrayList<>();
1110 List<String> tooltips = new ArrayList<>();
1114 displayAtts.add(LABEL_18N);
1115 tooltips.add(MessageManager.getString("label.description"));
1119 float[][] minMax = fr.getMinMax().get(featureType);
1120 if (minMax != null && minMax[0][0] != minMax[0][1])
1122 displayAtts.add(SCORE_18N);
1123 tooltips.add(SCORE_18N);
1127 FeatureAttributes fa = FeatureAttributes.getInstance();
1128 for (String[] attName : attNames)
1130 float[] minMax = fa.getMinMax(featureType, attName);
1131 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1132 if (!withText && !hasRange)
1136 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1137 String desc = fa.getDescription(featureType, attName);
1138 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1140 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1142 tooltips.add(desc == null ? "" : desc);
1145 // now convert String List to Object List for buildComboWithTooltips
1146 List<Object> displayAttsObjects = new ArrayList<>(displayAtts);
1147 JComboBox<Object> attCombo = JvSwingUtils
1148 .buildComboWithTooltips(displayAttsObjects, tooltips);
1154 * Populates initial layout of the feature attribute filters panel
1156 private JPanel initialiseFiltersPanel()
1158 filters = new ArrayList<>();
1160 JPanel filtersPanel = new JPanel();
1161 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1162 filtersPanel.setBackground(Color.white);
1163 JvSwingUtils.createTitledBorder(filtersPanel,
1164 MessageManager.getString("label.filters"), true);
1166 JPanel andOrPanel = initialiseAndOrPanel();
1167 filtersPanel.add(andOrPanel);
1170 * panel with filters - populated by refreshFiltersDisplay,
1171 * which also sets the layout manager
1173 chooseFiltersPanel = new JPanel();
1174 chooseFiltersPanel.setBackground(Color.white);
1175 filtersPanel.add(chooseFiltersPanel);
1177 return filtersPanel;
1181 * Lays out the panel with radio buttons to AND or OR filter conditions
1185 private JPanel initialiseAndOrPanel()
1187 JPanel andOrPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
1188 andOrPanel.setBackground(Color.white);
1189 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1190 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1191 ActionListener actionListener = new ActionListener()
1194 public void actionPerformed(ActionEvent e)
1199 andFilters.addActionListener(actionListener);
1200 orFilters.addActionListener(actionListener);
1201 ButtonGroup andOr = new ButtonGroup();
1202 andOr.add(andFilters);
1203 andOr.add(orFilters);
1204 andFilters.setSelected(true);
1206 new JLabel(MessageManager.getString("label.join_conditions")));
1207 andOrPanel.add(andFilters);
1208 andOrPanel.add(orFilters);
1213 * Refreshes the display to show any filters currently configured for the
1214 * selected feature type (editable, with 'remove' option), plus one extra row
1215 * for adding a condition. This should be called after a filter has been
1216 * removed, added or amended.
1218 private void updateFiltersTab()
1221 * clear the panel and list of filter conditions
1223 chooseFiltersPanel.removeAll();
1227 * look up attributes known for feature type
1229 List<String[]> attNames = FeatureAttributes.getInstance()
1230 .getAttributes(featureType);
1233 * if this feature type has filters set, load them first
1235 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1236 if (featureFilters != null)
1238 if (!featureFilters.isAnded())
1240 orFilters.setSelected(true);
1242 featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1246 * and an empty filter for the user to populate (add)
1248 filters.add(FeatureMatcher.NULL_MATCHER);
1251 * use GridLayout to 'justify' rows to the top of the panel, until
1252 * there are too many to fit in, then fall back on BoxLayout
1254 if (filters.size() <= 5)
1256 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1260 chooseFiltersPanel.setLayout(
1261 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1265 * render the conditions in rows, each in its own JPanel
1267 int filterIndex = 0;
1268 for (FeatureMatcherI filter : filters)
1270 JPanel row = addFilter(filter, attNames, filterIndex);
1271 chooseFiltersPanel.add(row);
1280 * A helper method that constructs a row (panel) with one filter condition:
1282 * <li>a drop-down list of Label, Score and attribute names to choose
1284 * <li>a drop-down list of conditions to choose from</li>
1285 * <li>a text field for input of a match pattern</li>
1286 * <li>optionally, a 'remove' button</li>
1288 * The filter values are set as defaults for the input fields. The 'remove'
1289 * button is added unless the pattern is empty (incomplete filter condition).
1291 * Action handlers on these fields provide for
1293 * <li>validate pattern field - should be numeric if condition is numeric</li>
1294 * <li>save filters and refresh display on any (valid) change</li>
1295 * <li>remove filter and refresh on 'Remove'</li>
1296 * <li>update conditions list on change of Label/Score/Attribute</li>
1297 * <li>refresh value field tooltip with min-max range on change of
1303 * @param filterIndex
1306 protected JPanel addFilter(FeatureMatcherI filter,
1307 List<String[]> attNames, int filterIndex)
1309 String[] attName = filter.getAttribute();
1310 Condition cond = filter.getMatcher().getCondition();
1311 String pattern = filter.getMatcher().getPattern();
1313 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1314 filterRow.setBackground(Color.white);
1317 * drop-down choice of attribute, with description as a tooltip
1318 * if we can obtain it
1320 final JComboBox<Object> attCombo = populateAttributesDropdown(attNames,
1322 String filterBy = setSelectedAttribute(attCombo, filter);
1324 JComboBox<Condition> condCombo = new JComboBox<>();
1326 JTextField patternField = new JTextField(8);
1327 patternField.setText(pattern);
1330 * action handlers that validate and (if valid) apply changes
1332 ActionListener actionListener = new ActionListener()
1335 public void actionPerformed(ActionEvent e)
1337 if (validateFilter(patternField, condCombo))
1339 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1346 ItemListener itemListener = new ItemListener()
1349 public void itemStateChanged(ItemEvent e)
1351 actionListener.actionPerformed(null);
1355 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1357 attCombo.setSelectedIndex(0);
1361 attCombo.setSelectedItem(
1362 FeatureMatcher.toAttributeDisplayName(attName));
1364 attCombo.addItemListener(new ItemListener()
1367 public void itemStateChanged(ItemEvent e)
1370 * on change of attribute, refresh the conditions list to
1371 * ensure it is appropriate for the attribute datatype
1373 populateConditions((String) attCombo.getSelectedItem(),
1374 (Condition) condCombo.getSelectedItem(), condCombo,
1376 actionListener.actionPerformed(null);
1380 filterRow.add(attCombo);
1383 * drop-down choice of test condition
1385 populateConditions(filterBy, cond, condCombo, patternField);
1386 condCombo.setPreferredSize(new Dimension(150, 20));
1387 condCombo.addItemListener(itemListener);
1388 filterRow.add(condCombo);
1391 * pattern to match against
1393 patternField.addActionListener(actionListener);
1394 patternField.addFocusListener(new FocusAdapter()
1397 public void focusLost(FocusEvent e)
1399 actionListener.actionPerformed(null);
1402 filterRow.add(patternField);
1405 * disable pattern field for condition 'Present / NotPresent'
1407 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1408 patternField.setEnabled(selectedCondition.needsAPattern());
1411 * if a numeric condition is selected, show the value range
1412 * as a tooltip on the value input field
1414 setNumericHints(filterBy, selectedCondition, patternField);
1417 * add remove button if filter is populated (non-empty pattern)
1419 if (!patternField.isEnabled()
1420 || (pattern != null && pattern.trim().length() > 0))
1422 JButton removeCondition = new JButton("\u2717"); // Dingbats cursive x
1423 removeCondition.setToolTipText(
1424 MessageManager.getString("label.delete_condition"));
1425 removeCondition.setBorder(new EmptyBorder(0, 0, 0, 0));
1426 removeCondition.addActionListener(new ActionListener()
1429 public void actionPerformed(ActionEvent e)
1431 filters.remove(filterIndex);
1435 filterRow.add(removeCondition);
1442 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1448 private String setSelectedAttribute(JComboBox<Object> attCombo,
1449 FeatureMatcherI filter)
1452 if (filter.isByScore())
1456 else if (filter.isByLabel())
1462 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1464 attCombo.setSelectedItem(item);
1469 * If a numeric comparison condition is selected, retrieves the min-max range
1470 * for the value (score or attribute), and sets it as a tooltip on the value
1471 * field. If the field is currently empty, then pre-populates it with
1473 * <li>the minimum value, if condition is > or >=</li>
1474 * <li>the maximum value, if condition is < or <=</li>
1478 * @param selectedCondition
1479 * @param patternField
1481 private void setNumericHints(String attName, Condition selectedCondition,
1482 JTextField patternField)
1484 patternField.setToolTipText("");
1486 if (selectedCondition.isNumeric())
1488 float[] minMax = getMinMax(attName);
1491 String minFormatted = DECFMT_2_2.format(minMax[0]);
1492 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1493 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1494 patternField.setToolTipText(tip);
1495 if (patternField.getText().isEmpty())
1497 if (selectedCondition == Condition.GE
1498 || selectedCondition == Condition.GT)
1500 patternField.setText(minFormatted);
1504 if (selectedCondition == Condition.LE
1505 || selectedCondition == Condition.LT)
1507 patternField.setText(maxFormatted);
1516 * Populates the drop-down list of comparison conditions for the given
1517 * attribute name. The conditions added depend on the datatype of the
1518 * attribute values. The supplied condition is set as the selected item in the
1519 * list, provided it is in the list. If the pattern is now invalid
1520 * (non-numeric pattern for a numeric condition), it is cleared.
1525 * @param patternField
1527 private void populateConditions(String attName, Condition cond,
1528 JComboBox<Condition> condCombo, JTextField patternField)
1530 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1531 FeatureMatcher.fromAttributeDisplayName(attName));
1532 if (LABEL_18N.equals(attName))
1534 type = Datatype.Character;
1536 else if (SCORE_18N.equals(attName))
1538 type = Datatype.Number;
1542 * remove itemListener before starting
1544 ItemListener listener = condCombo.getItemListeners()[0];
1545 condCombo.removeItemListener(listener);
1546 boolean condIsValid = false;
1548 condCombo.removeAllItems();
1549 for (Condition c : Condition.values())
1551 if ((c.isNumeric() && type == Datatype.Number)
1552 || (!c.isNumeric() && type != Datatype.Number))
1554 condCombo.addItem(c);
1563 * set the selected condition (does nothing if not in the list)
1567 condCombo.setSelectedItem(cond);
1571 condCombo.setSelectedIndex(0);
1575 * clear pattern if it is now invalid for condition
1577 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1581 String pattern = patternField.getText().trim();
1582 if (pattern.length() > 0)
1584 Float.valueOf(pattern);
1586 } catch (NumberFormatException e)
1588 patternField.setText("");
1593 * restore the listener
1595 condCombo.addItemListener(listener);
1599 * Answers true unless a numeric condition has been selected with a
1600 * non-numeric value. Sets the value field to RED with a tooltip if in error.
1602 * If the pattern is expected but is empty, this method returns false, but
1603 * does not mark the field as invalid. This supports selecting an attribute
1604 * for a new condition before a match pattern has been entered.
1609 protected boolean validateFilter(JTextField value,
1610 JComboBox<Condition> condCombo)
1612 if (value == null || condCombo == null)
1614 return true; // fields not populated
1617 Condition cond = (Condition) condCombo.getSelectedItem();
1618 if (!cond.needsAPattern())
1623 value.setBackground(Color.white);
1624 value.setToolTipText("");
1625 String v1 = value.getText().trim();
1626 if (v1.length() == 0)
1631 if (cond.isNumeric() && v1.length() > 0)
1636 } catch (NumberFormatException e)
1638 value.setBackground(Color.red);
1639 value.setToolTipText(
1640 MessageManager.getString("label.numeric_required"));
1649 * Constructs a filter condition from the given input fields, and replaces the
1650 * condition at filterIndex with the new one. Does nothing if the pattern
1651 * field is blank (unless the match condition is one that doesn't require a
1652 * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1655 * This method may update the tooltip on the filter value field to show the
1656 * value range, if a numeric condition is selected. This ensures the tooltip
1657 * is updated when a numeric valued attribute is chosen on the last 'add a
1663 * @param filterIndex
1665 protected boolean updateFilter(JComboBox<Object> attCombo,
1666 JComboBox<Condition> condCombo, JTextField valueField,
1672 attName = (String) attCombo.getSelectedItem();
1673 } catch (Exception e)
1675 Cache.log.error("Problem casting Combo box entry to String");
1676 attName = attCombo.getSelectedItem().toString();
1678 Condition cond = (Condition) condCombo.getSelectedItem();
1679 String pattern = valueField.getText().trim();
1681 setNumericHints(attName, cond, valueField);
1683 if (pattern.length() == 0 && cond.needsAPattern())
1685 valueField.setEnabled(true); // ensure pattern field is enabled!
1690 * Construct a matcher that operates on Label, Score,
1691 * or named attribute
1693 FeatureMatcherI km = null;
1694 if (LABEL_18N.equals(attName))
1696 km = FeatureMatcher.byLabel(cond, pattern);
1698 else if (SCORE_18N.equals(attName))
1700 km = FeatureMatcher.byScore(cond, pattern);
1704 km = FeatureMatcher.byAttribute(cond, pattern,
1705 FeatureMatcher.fromAttributeDisplayName(attName));
1708 filters.set(filterIndex, km);
1714 * Action on any change to feature filtering, namely
1716 * <li>change of selected attribute</li>
1717 * <li>change of selected condition</li>
1718 * <li>change of match pattern</li>
1719 * <li>removal of a condition</li>
1721 * The inputs are parsed into a combined filter and this is set for the
1722 * feature type, and the alignment redrawn.
1724 protected void filtersChanged()
1727 * update the filter conditions for the feature type
1729 boolean anded = andFilters.isSelected();
1730 FeatureMatcherSetI combined = new FeatureMatcherSet();
1732 for (FeatureMatcherI filter : filters)
1734 String pattern = filter.getMatcher().getPattern();
1735 Condition condition = filter.getMatcher().getCondition();
1736 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1740 combined.and(filter);
1744 combined.or(filter);
1750 * save the filter conditions in the FeatureRenderer
1751 * (note this might now be an empty filter with no conditions)
1753 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1754 ap.paintAlignment(true, true);
1760 * Answers the slider value, converted to the corresponding 'true' value by
1765 float getSliderValue()
1767 int value = slider.getValue();
1768 float f = (value - sliderOffset) / sliderScaleFactor;
1771 * avoid rounding errors at min/max of range
1773 if (value == slider.getMaximum())
1777 else if (value == slider.getMinimum())
1785 * Sets the slider value, converted from the corresponding 'true' value by
1790 void setSliderValue(float f)
1792 float v = f * sliderScaleFactor + sliderOffset;
1793 slider.setValue((int) v);