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.schemes.FeatureColour;
35 import jalview.util.ColorUtils;
36 import jalview.util.MessageManager;
37 import jalview.util.matcher.Condition;
39 import java.awt.BorderLayout;
40 import java.awt.Color;
41 import java.awt.Dimension;
42 import java.awt.FlowLayout;
43 import java.awt.GridLayout;
44 import java.awt.event.ActionEvent;
45 import java.awt.event.ActionListener;
46 import java.awt.event.FocusAdapter;
47 import java.awt.event.FocusEvent;
48 import java.awt.event.ItemEvent;
49 import java.awt.event.ItemListener;
50 import java.awt.event.MouseAdapter;
51 import java.awt.event.MouseEvent;
52 import java.math.BigDecimal;
53 import java.math.MathContext;
54 import java.text.DecimalFormat;
55 import java.util.ArrayList;
56 import java.util.List;
58 import javax.swing.BorderFactory;
59 import javax.swing.BoxLayout;
60 import javax.swing.ButtonGroup;
61 import javax.swing.JButton;
62 import javax.swing.JCheckBox;
63 import javax.swing.JColorChooser;
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 private final AlignmentViewPanel ap;
121 private 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 private 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 private JRadioButton simpleColour = new JRadioButton();
153 private JRadioButton byCategory = new JRadioButton();
155 private JRadioButton graduatedColour = new JRadioButton();
158 * colours and filters are shown in tabbed view or single content pane
160 JPanel coloursPanel, filtersPanel;
162 JPanel singleColour = new JPanel();
164 private JPanel minColour = new JPanel();
166 private JPanel maxColour = new JPanel();
168 private JComboBox<Object> threshold = new JComboBox<>();
170 private Slider slider;
172 private JTextField thresholdValue = new JTextField(20);
174 private JCheckBox thresholdIsMin = new JCheckBox();
176 private GraphLine threshline;
178 private ActionListener featureSettings = null;
180 private ActionListener changeColourAction;
183 * choice of option for 'colour for no value'
185 private JComboBox<Object> noValueCombo;
188 * choice of what to colour by text (Label or attribute)
190 private JComboBox<Object> colourByTextCombo;
193 * choice of what to colour by range (Score or attribute)
195 private JComboBox<Object> colourByRangeCombo;
197 private JRadioButton andFilters;
199 private JRadioButton orFilters;
202 * filters for the currently selected feature type
204 private List<FeatureMatcherI> filters;
206 private JPanel chooseFiltersPanel;
214 public FeatureTypeSettings(FeatureRenderer frender, String theType)
217 this.featureType = theType;
219 originalFilter = fr.getFeatureFilter(theType);
220 originalColour = fr.getFeatureColours().get(theType);
227 } catch (Exception ex)
229 ex.printStackTrace();
239 colourChanged(false);
241 String title = MessageManager
242 .formatMessage("label.display_settings_for", new String[]
244 initDialogFrame(this, true, false, title, 580, 500);
249 * Configures the widgets on the Colours tab according to the current feature
252 private void updateColoursTab()
254 FeatureColourI fc = fr.getFeatureColours().get(featureType);
257 * suppress action handling while updating values programmatically
265 if (fc.isSimpleColour())
267 singleColour.setBackground(fc.getColour());
268 singleColour.setForeground(fc.getColour());
269 simpleColour.setSelected(true);
273 * colour by text (Label or attribute text)
275 if (fc.isColourByLabel())
277 byCategory.setSelected(true);
278 colourByTextCombo.setEnabled(colourByTextCombo.getItemCount() > 1);
279 if (fc.isColourByAttribute())
281 String[] attributeName = fc.getAttributeName();
282 colourByTextCombo.setSelectedItem(
283 FeatureMatcher.toAttributeDisplayName(attributeName));
287 colourByTextCombo.setSelectedItem(LABEL_18N);
292 colourByTextCombo.setEnabled(false);
295 if (!fc.isGraduatedColour())
297 colourByRangeCombo.setEnabled(false);
298 minColour.setEnabled(false);
299 maxColour.setEnabled(false);
300 noValueCombo.setEnabled(false);
301 threshold.setEnabled(false);
302 slider.setEnabled(false);
303 thresholdValue.setEnabled(false);
304 thresholdIsMin.setEnabled(false);
309 * Graduated colour, by score or attribute value range
311 graduatedColour.setSelected(true);
312 updateColourMinMax(); // ensure min, max are set
313 colourByRangeCombo.setEnabled(colourByRangeCombo.getItemCount() > 1);
314 minColour.setEnabled(true);
315 maxColour.setEnabled(true);
316 noValueCombo.setEnabled(true);
317 threshold.setEnabled(true);
318 minColour.setBackground(fc.getMinColour());
319 maxColour.setBackground(fc.getMaxColour());
321 if (fc.isColourByAttribute())
323 String[] attributeName = fc.getAttributeName();
324 colourByRangeCombo.setSelectedItem(
325 FeatureMatcher.toAttributeDisplayName(attributeName));
329 colourByRangeCombo.setSelectedItem(SCORE_18N);
331 Color noColour = fc.getNoColour();
332 if (noColour == null)
334 noValueCombo.setSelectedIndex(NO_COLOUR_OPTION);
336 else if (noColour.equals(fc.getMinColour()))
338 noValueCombo.setSelectedIndex(MIN_COLOUR_OPTION);
340 else if (noColour.equals(fc.getMaxColour()))
342 noValueCombo.setSelectedIndex(MAX_COLOUR_OPTION);
346 * update min-max scaling if there is a range to work with,
347 * else disable the widgets (this shouldn't happen if only
348 * valid options are offered in the combo box)
349 * offset slider to have only non-negative values if necessary (JAL-2983)
351 slider.setSliderModel(min, max, min);
352 slider.setMajorTickSpacing(
353 (int) ((slider.getMaximum() - slider.getMinimum()) / 10f));
355 threshline = new GraphLine((max - min) / 2f, "Threshold",
357 threshline.value = fc.getThreshold();
359 if (fc.hasThreshold())
361 threshold.setSelectedIndex(
362 fc.isAboveThreshold() ? ABOVE_THRESHOLD_OPTION
363 : BELOW_THRESHOLD_OPTION);
364 slider.setEnabled(true);
365 slider.setSliderValue(fc.getThreshold());
366 setThresholdValueText(fc.getThreshold());
367 thresholdValue.setEnabled(true);
368 thresholdIsMin.setEnabled(true);
372 slider.setEnabled(false);
373 thresholdValue.setEnabled(false);
374 thresholdIsMin.setEnabled(false);
376 thresholdIsMin.setSelected(!fc.isAutoScaled());
384 * Configures the initial layout
386 private void initialise()
388 this.setLayout(new BorderLayout());
391 * an ActionListener that applies colour changes
393 changeColourAction = new ActionListener()
396 public void actionPerformed(ActionEvent e)
403 * first panel/tab: colour options
405 JPanel coloursPanel = initialiseColoursPanel();
406 this.add(coloursPanel, BorderLayout.NORTH);
409 * second panel/tab: filter options
411 JPanel filtersPanel = initialiseFiltersPanel();
412 this.add(filtersPanel, BorderLayout.CENTER);
414 JPanel okCancelPanel = initialiseOkCancelPanel();
416 this.add(okCancelPanel, BorderLayout.SOUTH);
420 * Updates the min-max range if Colour By selected item is Score, or an
421 * attribute, with a min-max range
423 protected void updateColourMinMax()
425 if (!graduatedColour.isSelected())
430 String colourBy = (String) colourByRangeCombo.getSelectedItem();
431 float[] minMax = getMinMax(colourBy);
441 * Retrieves the min-max range:
443 * <li>of feature score, if colour or filter is by Score</li>
444 * <li>else of the selected attribute</li>
450 private float[] getMinMax(String attName)
452 float[] minMax = null;
453 if (SCORE_18N.equals(attName))
455 minMax = fr.getMinMax().get(featureType)[0];
459 // colour by attribute range
460 minMax = FeatureAttributes.getInstance().getMinMax(featureType,
461 FeatureMatcher.fromAttributeDisplayName(attName));
467 * Lay out fields for graduated colour (by score or attribute value)
471 private JPanel initialiseGraduatedColourPanel()
473 JPanel graduatedColourPanel = new JPanel();
474 graduatedColourPanel.setLayout(
475 new BoxLayout(graduatedColourPanel, BoxLayout.Y_AXIS));
476 JvSwingUtils.createTitledBorder(graduatedColourPanel,
477 MessageManager.getString("label.graduated_colour"), true);
478 graduatedColourPanel.setBackground(Color.white);
481 * first row: graduated colour radio button, score/attribute drop-down
483 JPanel graduatedChoicePanel = new JPanel(
484 new FlowLayout(FlowLayout.LEFT));
485 graduatedChoicePanel.setBackground(Color.white);
486 graduatedColour = new JRadioButton(
487 MessageManager.getString("label.by_range_of") + COLON);
488 graduatedColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
489 graduatedColour.addItemListener(new ItemListener()
492 public void itemStateChanged(ItemEvent e)
494 if (graduatedColour.isSelected())
500 graduatedChoicePanel.add(graduatedColour);
502 List<String[]> attNames = FeatureAttributes.getInstance()
503 .getAttributes(featureType);
504 colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
505 colourByRangeCombo.addItemListener(new ItemListener()
508 public void itemStateChanged(ItemEvent e)
515 * disable graduated colour option if no range found
517 graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
519 graduatedChoicePanel.add(colourByRangeCombo);
520 graduatedColourPanel.add(graduatedChoicePanel);
523 * second row - min/max/no colours
525 JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
526 colourRangePanel.setBackground(Color.white);
527 graduatedColourPanel.add(colourRangePanel);
529 minColour.setFont(JvSwingUtils.getLabelFont());
530 minColour.setBorder(BorderFactory.createLineBorder(Color.black));
531 minColour.setPreferredSize(new Dimension(40, 20));
532 minColour.setToolTipText(MessageManager.getString("label.min_colour"));
533 minColour.addMouseListener(new MouseAdapter()
536 public void mousePressed(MouseEvent e)
538 if (minColour.isEnabled())
540 showColourChooser(minColour, "label.select_colour_minimum_value");
545 maxColour.setFont(JvSwingUtils.getLabelFont());
546 maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
547 maxColour.setPreferredSize(new Dimension(40, 20));
548 maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
549 maxColour.addMouseListener(new MouseAdapter()
552 public void mousePressed(MouseEvent e)
554 if (maxColour.isEnabled())
556 showColourChooser(maxColour, "label.select_colour_maximum_value");
560 maxColour.setBorder(new LineBorder(Color.black));
563 * if not set, default max colour to last plain colour,
564 * and make min colour a pale version of max colour
566 Color max = originalColour.getMaxColour();
569 max = originalColour.getColour();
570 minColour.setBackground(ColorUtils.bleachColour(max, 0.9f));
574 maxColour.setBackground(max);
575 minColour.setBackground(originalColour.getMinColour());
578 noValueCombo = new JComboBox<>();
579 noValueCombo.addItem(MessageManager.getString("label.no_colour"));
580 noValueCombo.addItem(MessageManager.getString("label.min_colour"));
581 noValueCombo.addItem(MessageManager.getString("label.max_colour"));
582 noValueCombo.addItemListener(new ItemListener()
585 public void itemStateChanged(ItemEvent e)
591 JLabel minText = new JLabel(
592 MessageManager.getString("label.min_value") + COLON);
593 minText.setFont(JvSwingUtils.getLabelFont());
594 JLabel maxText = new JLabel(
595 MessageManager.getString("label.max_value") + COLON);
596 maxText.setFont(JvSwingUtils.getLabelFont());
597 JLabel noText = new JLabel(
598 MessageManager.getString("label.no_value") + COLON);
599 noText.setFont(JvSwingUtils.getLabelFont());
601 colourRangePanel.add(minText);
602 colourRangePanel.add(minColour);
603 colourRangePanel.add(maxText);
604 colourRangePanel.add(maxColour);
605 colourRangePanel.add(noText);
606 colourRangePanel.add(noValueCombo);
609 * third row - threshold options and value
611 JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
612 thresholdPanel.setBackground(Color.white);
613 graduatedColourPanel.add(thresholdPanel);
615 threshold.addActionListener(changeColourAction);
616 threshold.setToolTipText(MessageManager
617 .getString("label.threshold_feature_display_by_score"));
618 threshold.addItem(MessageManager
619 .getString("label.threshold_feature_no_threshold")); // index 0
620 threshold.addItem(MessageManager
621 .getString("label.threshold_feature_above_threshold")); // index 1
622 threshold.addItem(MessageManager
623 .getString("label.threshold_feature_below_threshold")); // index 2
625 thresholdValue.addActionListener(new ActionListener()
628 public void actionPerformed(ActionEvent e)
630 thresholdValue_actionPerformed();
633 thresholdValue.addFocusListener(new FocusAdapter()
636 public void focusLost(FocusEvent e)
638 thresholdValue_actionPerformed();
641 slider = new Slider(0f, 100f, 50f);
642 slider.setPaintLabels(false);
643 slider.setPaintTicks(true);
644 slider.setBackground(Color.white);
645 slider.setEnabled(false);
646 slider.setOpaque(false);
647 slider.setPreferredSize(new Dimension(100, 32));
648 slider.setToolTipText(
649 MessageManager.getString("label.adjust_threshold"));
651 slider.addChangeListener(new ChangeListener()
654 public void stateChanged(ChangeEvent evt)
658 setThresholdValueText(slider.getSliderValue());
659 thresholdValue.setBackground(Color.white); // to reset red for invalid
660 sliderValueChanged();
664 slider.addMouseListener(new MouseAdapter()
667 public void mouseReleased(MouseEvent evt)
670 * only update Overview and/or structure colouring
671 * when threshold slider drag ends (mouse up)
675 refreshDisplay(true);
680 thresholdValue.setEnabled(false);
681 thresholdValue.setColumns(7);
683 thresholdPanel.add(threshold);
684 thresholdPanel.add(slider);
685 thresholdPanel.add(thresholdValue);
687 thresholdIsMin.setBackground(Color.white);
689 .setText(MessageManager.getString("label.threshold_minmax"));
690 thresholdIsMin.setToolTipText(MessageManager
691 .getString("label.toggle_absolute_relative_display_threshold"));
692 thresholdIsMin.addActionListener(changeColourAction);
693 thresholdPanel.add(thresholdIsMin);
695 return graduatedColourPanel;
699 * Lay out OK and Cancel buttons
703 private JPanel initialiseOkCancelPanel()
705 JPanel okCancelPanel = new JPanel();
706 // okCancelPanel.setBackground(Color.white);
707 okCancelPanel.add(ok);
708 okCancelPanel.add(cancel);
709 return okCancelPanel;
713 * Lay out Colour options panel, containing
715 * <li>plain colour, with colour picker</li>
716 * <li>colour by text, with choice of Label or other attribute</li>
717 * <li>colour by range, of score or other attribute, when available</li>
722 private JPanel initialiseColoursPanel()
724 JPanel colourByPanel = new JPanel();
725 colourByPanel.setBackground(Color.white);
726 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
727 JvSwingUtils.createTitledBorder(colourByPanel,
728 MessageManager.getString("action.colour"), true);
731 * simple colour radio button and colour picker
733 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
734 simpleColourPanel.setBackground(Color.white);
735 colourByPanel.add(simpleColourPanel);
737 simpleColour = new JRadioButton(
738 MessageManager.getString("label.simple_colour"));
739 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
740 simpleColour.addItemListener(new ItemListener()
743 public void itemStateChanged(ItemEvent e)
745 if (simpleColour.isSelected() && !adjusting)
752 singleColour.setFont(JvSwingUtils.getLabelFont());
753 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
754 singleColour.setPreferredSize(new Dimension(40, 20));
755 // if (originalColour.isGraduatedColour())
757 // singleColour.setBackground(originalColour.getMaxColour());
758 // singleColour.setForeground(originalColour.getMaxColour());
762 singleColour.setBackground(originalColour.getColour());
763 singleColour.setForeground(originalColour.getColour());
765 singleColour.addMouseListener(new MouseAdapter()
768 public void mousePressed(MouseEvent e)
770 if (simpleColour.isSelected())
772 showColourChooser(singleColour, "label.select_colour");
776 simpleColourPanel.add(simpleColour); // radio button
777 simpleColourPanel.add(singleColour); // colour picker button
780 * colour by text (category) radio button and drop-down choice list
782 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
783 byTextPanel.setBackground(Color.white);
784 JvSwingUtils.createTitledBorder(byTextPanel,
785 MessageManager.getString("label.colour_by_text"), true);
786 colourByPanel.add(byTextPanel);
787 byCategory = new JRadioButton(
788 MessageManager.getString("label.by_text_of") + COLON);
789 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
790 byCategory.addItemListener(new ItemListener()
793 public void itemStateChanged(ItemEvent e)
795 if (byCategory.isSelected())
801 byTextPanel.add(byCategory);
803 List<String[]> attNames = FeatureAttributes.getInstance()
804 .getAttributes(featureType);
805 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
806 colourByTextCombo.addItemListener(new ItemListener()
809 public void itemStateChanged(ItemEvent e)
814 byTextPanel.add(colourByTextCombo);
817 * graduated colour panel
819 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
820 colourByPanel.add(graduatedColourPanel);
823 * 3 radio buttons select between simple colour,
824 * by category (text), or graduated
826 ButtonGroup bg = new ButtonGroup();
827 bg.add(simpleColour);
829 bg.add(graduatedColour);
831 return colourByPanel;
834 private void showColourChooser(JPanel colourPanel, String key)
836 Color col = JColorChooser.showDialog(this,
837 MessageManager.getString(key), colourPanel.getBackground());
840 colourPanel.setBackground(col);
841 colourPanel.setForeground(col);
843 colourPanel.repaint();
848 * Constructs and sets the selected colour options as the colour for the
849 * feature type, and repaints the alignment, and optionally the Overview
850 * and/or structure viewer if open
852 * @param updateStructsAndOverview
854 void colourChanged(boolean updateStructsAndOverview)
859 * ignore action handlers while setting values programmatically
865 * ensure min-max range is for the latest choice of
866 * 'graduated colour by'
868 updateColourMinMax();
870 FeatureColourI acg = makeColourFromInputs();
873 * save the colour, and repaint stuff
875 fr.setColour(featureType, acg);
876 refreshDisplay(updateStructsAndOverview);
882 * Converts the input values into an instance of FeatureColour
886 private FeatureColourI makeColourFromInputs()
889 * min-max range is to (or from) threshold value if
890 * 'threshold is min/max' is selected
896 thresh = Float.valueOf(thresholdValue.getText());
897 } catch (NumberFormatException e)
899 // invalid inputs are already handled on entry
901 float minValue = min;
902 float maxValue = max;
903 final int thresholdOption = threshold.getSelectedIndex();
904 if (thresholdIsMin.isSelected()
905 && thresholdOption == ABOVE_THRESHOLD_OPTION)
909 if (thresholdIsMin.isSelected()
910 && thresholdOption == BELOW_THRESHOLD_OPTION)
914 Color noColour = null;
915 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
917 noColour = minColour.getBackground();
919 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
921 noColour = maxColour.getBackground();
925 * construct a colour that 'remembers' all the options, including
926 * those not currently selected
928 FeatureColourI fc = new FeatureColour(singleColour.getBackground(),
929 minColour.getBackground(), maxColour.getBackground(), noColour,
933 * easiest case - a single colour
935 if (simpleColour.isSelected())
937 ((FeatureColour) fc).setGraduatedColour(false);
942 * next easiest case - colour by Label, or attribute text
944 if (byCategory.isSelected())
946 fc.setColourByLabel(true);
947 String byWhat = (String) colourByTextCombo.getSelectedItem();
948 if (!LABEL_18N.equals(byWhat))
951 FeatureMatcher.fromAttributeDisplayName(byWhat));
957 * remaining case - graduated colour by score, or attribute value;
958 * set attribute to colour by if selected
960 String byWhat = (String) colourByRangeCombo.getSelectedItem();
961 if (!SCORE_18N.equals(byWhat))
963 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
967 * set threshold options and 'autoscaled' which is
968 * false if 'threshold is min/max' is selected
969 * else true (colour range is on actual range of values)
971 fc.setThreshold(thresh);
972 fc.setAutoScaled(!thresholdIsMin.isSelected());
973 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
974 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
976 if (threshline == null)
979 * todo not yet implemented: visual indication of feature threshold
981 threshline = new GraphLine((max - min) / 2f, "Threshold",
989 protected void raiseClosed()
991 if (this.featureSettings != null)
993 featureSettings.actionPerformed(new ActionEvent(this, 0, "CLOSED"));
998 * Action on OK is just to dismiss the dialog - any changes have already been
1002 public void okPressed()
1007 * Action on Cancel is to restore colour scheme and filters as they were when
1008 * the dialog was opened
1011 public void cancelPressed()
1013 fr.setColour(featureType, originalColour);
1014 fr.setFeatureFilter(featureType, originalFilter);
1015 refreshDisplay(true);
1019 * Action on text entry of a threshold value
1021 protected void thresholdValue_actionPerformed()
1026 * set 'adjusting' flag while moving the slider, so it
1027 * doesn't then in turn change the value (with rounding)
1030 float f = Float.parseFloat(thresholdValue.getText());
1031 f = Float.max(f, this.min);
1032 f = Float.min(f, this.max);
1033 setThresholdValueText(f);
1034 slider.setSliderValue(f);
1035 threshline.value = f;
1036 thresholdValue.setBackground(Color.white); // ok
1038 colourChanged(true);
1039 } catch (NumberFormatException ex)
1041 thresholdValue.setBackground(Color.red); // not ok
1047 * Sets the text field for threshold value, rounded to four significant figures
1051 void setThresholdValueText(float f)
1053 BigDecimal formatted = new BigDecimal(f).round(FOUR_SIG_FIG)
1054 .stripTrailingZeros();
1055 thresholdValue.setText(formatted.toPlainString());
1059 * Action on change of threshold slider value. This may be done interactively
1060 * (by moving the slider), or programmatically (to update the slider after
1061 * manual input of a threshold value).
1063 protected void sliderValueChanged()
1065 threshline.value = slider.getSliderValue();
1068 * repaint alignment, but not Overview or structure,
1069 * to avoid overload while dragging the slider
1071 colourChanged(false);
1074 void addActionListener(ActionListener listener)
1076 if (featureSettings != null)
1079 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1081 featureSettings = listener;
1085 * A helper method to build the drop-down choice of attributes for a feature.
1086 * If 'withRange' is true, then Score, and any attributes with a min-max
1087 * range, are added. If 'withText' is true, Label and any known attributes are
1088 * added. This allows 'categorical numerical' attributes e.g. codon position
1089 * to be coloured by text.
1091 * Where metadata is available with a description for an attribute, that is
1092 * added as a tooltip.
1094 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1095 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1097 * This method does not add any ActionListener to the JComboBox.
1103 protected JComboBox<Object> populateAttributesDropdown(
1104 List<String[]> attNames, boolean withRange, boolean withText)
1106 List<String> displayAtts = new ArrayList<>();
1107 List<String> tooltips = new ArrayList<>();
1111 displayAtts.add(LABEL_18N);
1112 tooltips.add(MessageManager.getString("label.description"));
1116 float[][] minMax = fr.getMinMax().get(featureType);
1117 if (minMax != null && minMax[0][0] != minMax[0][1])
1119 displayAtts.add(SCORE_18N);
1120 tooltips.add(SCORE_18N);
1124 FeatureAttributes fa = FeatureAttributes.getInstance();
1125 for (String[] attName : attNames)
1127 float[] minMax = fa.getMinMax(featureType, attName);
1128 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1129 if (!withText && !hasRange)
1133 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1134 String desc = fa.getDescription(featureType, attName);
1135 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1137 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1139 tooltips.add(desc == null ? "" : desc);
1142 // now convert String List to Object List for buildComboWithTooltips
1143 List<Object> displayAttsObjects = new ArrayList<>(displayAtts);
1144 JComboBox<Object> attCombo = JvSwingUtils
1145 .buildComboWithTooltips(displayAttsObjects, tooltips);
1151 * Populates initial layout of the feature attribute filters panel
1153 private JPanel initialiseFiltersPanel()
1155 filters = new ArrayList<>();
1157 JPanel filtersPanel = new JPanel();
1158 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1159 filtersPanel.setBackground(Color.white);
1160 JvSwingUtils.createTitledBorder(filtersPanel,
1161 MessageManager.getString("label.filters"), true);
1163 JPanel andOrPanel = initialiseAndOrPanel();
1164 filtersPanel.add(andOrPanel);
1167 * panel with filters - populated by refreshFiltersDisplay,
1168 * which also sets the layout manager
1170 chooseFiltersPanel = new JPanel();
1171 chooseFiltersPanel.setBackground(Color.white);
1172 filtersPanel.add(chooseFiltersPanel);
1174 return filtersPanel;
1178 * Lays out the panel with radio buttons to AND or OR filter conditions
1182 private JPanel initialiseAndOrPanel()
1184 JPanel andOrPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
1185 andOrPanel.setBackground(Color.white);
1186 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1187 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1188 ActionListener actionListener = new ActionListener()
1191 public void actionPerformed(ActionEvent e)
1196 andFilters.addActionListener(actionListener);
1197 orFilters.addActionListener(actionListener);
1198 ButtonGroup andOr = new ButtonGroup();
1199 andOr.add(andFilters);
1200 andOr.add(orFilters);
1201 andFilters.setSelected(true);
1203 new JLabel(MessageManager.getString("label.join_conditions")));
1204 andOrPanel.add(andFilters);
1205 andOrPanel.add(orFilters);
1210 * Refreshes the display to show any filters currently configured for the
1211 * selected feature type (editable, with 'remove' option), plus one extra row
1212 * for adding a condition. This should be called after a filter has been
1213 * removed, added or amended.
1215 private void updateFiltersTab()
1218 * clear the panel and list of filter conditions
1220 chooseFiltersPanel.removeAll();
1224 * look up attributes known for feature type
1226 List<String[]> attNames = FeatureAttributes.getInstance()
1227 .getAttributes(featureType);
1230 * if this feature type has filters set, load them first
1232 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1233 if (featureFilters != null)
1235 if (!featureFilters.isAnded())
1237 orFilters.setSelected(true);
1239 featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1243 * and an empty filter for the user to populate (add)
1245 filters.add(FeatureMatcher.NULL_MATCHER);
1248 * use GridLayout to 'justify' rows to the top of the panel, until
1249 * there are too many to fit in, then fall back on BoxLayout
1251 if (filters.size() <= 5)
1253 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1257 chooseFiltersPanel.setLayout(
1258 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1262 * render the conditions in rows, each in its own JPanel
1264 int filterIndex = 0;
1265 for (FeatureMatcherI filter : filters)
1267 JPanel row = addFilter(filter, attNames, filterIndex);
1268 chooseFiltersPanel.add(row);
1277 * A helper method that constructs a row (panel) with one filter condition:
1279 * <li>a drop-down list of Label, Score and attribute names to choose
1281 * <li>a drop-down list of conditions to choose from</li>
1282 * <li>a text field for input of a match pattern</li>
1283 * <li>optionally, a 'remove' button</li>
1285 * The filter values are set as defaults for the input fields. The 'remove'
1286 * button is added unless the pattern is empty (incomplete filter condition).
1288 * Action handlers on these fields provide for
1290 * <li>validate pattern field - should be numeric if condition is numeric</li>
1291 * <li>save filters and refresh display on any (valid) change</li>
1292 * <li>remove filter and refresh on 'Remove'</li>
1293 * <li>update conditions list on change of Label/Score/Attribute</li>
1294 * <li>refresh value field tooltip with min-max range on change of
1300 * @param filterIndex
1303 protected JPanel addFilter(FeatureMatcherI filter,
1304 List<String[]> attNames, int filterIndex)
1306 String[] attName = filter.getAttribute();
1307 Condition cond = filter.getMatcher().getCondition();
1308 String pattern = filter.getMatcher().getPattern();
1310 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1311 filterRow.setBackground(Color.white);
1314 * drop-down choice of attribute, with description as a tooltip
1315 * if we can obtain it
1317 final JComboBox<Object> attCombo = populateAttributesDropdown(attNames,
1319 String filterBy = setSelectedAttribute(attCombo, filter);
1321 JComboBox<Condition> condCombo = new JComboBox<>();
1323 JTextField patternField = new JTextField(8);
1324 patternField.setText(pattern);
1327 * action handlers that validate and (if valid) apply changes
1329 ActionListener actionListener = new ActionListener()
1332 public void actionPerformed(ActionEvent e)
1334 if (validateFilter(patternField, condCombo))
1336 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1343 ItemListener itemListener = new ItemListener()
1346 public void itemStateChanged(ItemEvent e)
1348 actionListener.actionPerformed(null);
1352 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1354 attCombo.setSelectedIndex(0);
1358 attCombo.setSelectedItem(
1359 FeatureMatcher.toAttributeDisplayName(attName));
1361 attCombo.addItemListener(new ItemListener()
1364 public void itemStateChanged(ItemEvent e)
1367 * on change of attribute, refresh the conditions list to
1368 * ensure it is appropriate for the attribute datatype
1370 populateConditions((String) attCombo.getSelectedItem(),
1371 (Condition) condCombo.getSelectedItem(), condCombo,
1373 actionListener.actionPerformed(null);
1377 filterRow.add(attCombo);
1380 * drop-down choice of test condition
1382 populateConditions(filterBy, cond, condCombo, patternField);
1383 condCombo.setPreferredSize(new Dimension(150, 20));
1384 condCombo.addItemListener(itemListener);
1385 filterRow.add(condCombo);
1388 * pattern to match against
1390 patternField.addActionListener(actionListener);
1391 patternField.addFocusListener(new FocusAdapter()
1394 public void focusLost(FocusEvent e)
1396 actionListener.actionPerformed(null);
1399 filterRow.add(patternField);
1402 * disable pattern field for condition 'Present / NotPresent'
1404 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1405 patternField.setEnabled(selectedCondition.needsAPattern());
1408 * if a numeric condition is selected, show the value range
1409 * as a tooltip on the value input field
1411 setNumericHints(filterBy, selectedCondition, patternField);
1414 * add remove button if filter is populated (non-empty pattern)
1416 if (!patternField.isEnabled()
1417 || (pattern != null && pattern.trim().length() > 0))
1419 JButton removeCondition = new JButton("\u2717"); // Dingbats cursive x
1420 removeCondition.setToolTipText(
1421 MessageManager.getString("label.delete_condition"));
1422 removeCondition.setBorder(new EmptyBorder(0, 0, 0, 0));
1423 removeCondition.addActionListener(new ActionListener()
1426 public void actionPerformed(ActionEvent e)
1428 filters.remove(filterIndex);
1432 filterRow.add(removeCondition);
1439 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1445 private String setSelectedAttribute(JComboBox<Object> attCombo,
1446 FeatureMatcherI filter)
1449 if (filter.isByScore())
1453 else if (filter.isByLabel())
1459 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1461 attCombo.setSelectedItem(item);
1466 * If a numeric comparison condition is selected, retrieves the min-max range
1467 * for the value (score or attribute), and sets it as a tooltip on the value
1468 * field. If the field is currently empty, then pre-populates it with
1470 * <li>the minimum value, if condition is > or >=</li>
1471 * <li>the maximum value, if condition is < or <=</li>
1475 * @param selectedCondition
1476 * @param patternField
1478 private void setNumericHints(String attName, Condition selectedCondition,
1479 JTextField patternField)
1481 patternField.setToolTipText("");
1483 if (selectedCondition.isNumeric())
1485 float[] minMax = getMinMax(attName);
1488 String minFormatted = DECFMT_2_2.format(minMax[0]);
1489 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1490 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1491 patternField.setToolTipText(tip);
1492 if (patternField.getText().isEmpty())
1494 if (selectedCondition == Condition.GE
1495 || selectedCondition == Condition.GT)
1497 patternField.setText(minFormatted);
1501 if (selectedCondition == Condition.LE
1502 || selectedCondition == Condition.LT)
1504 patternField.setText(maxFormatted);
1513 * Populates the drop-down list of comparison conditions for the given
1514 * attribute name. The conditions added depend on the datatype of the
1515 * attribute values. The supplied condition is set as the selected item in the
1516 * list, provided it is in the list. If the pattern is now invalid
1517 * (non-numeric pattern for a numeric condition), it is cleared.
1522 * @param patternField
1524 private void populateConditions(String attName, Condition cond,
1525 JComboBox<Condition> condCombo, JTextField patternField)
1527 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1528 FeatureMatcher.fromAttributeDisplayName(attName));
1529 if (LABEL_18N.equals(attName))
1531 type = Datatype.Character;
1533 else if (SCORE_18N.equals(attName))
1535 type = Datatype.Number;
1539 * remove itemListener before starting
1541 ItemListener listener = condCombo.getItemListeners()[0];
1542 condCombo.removeItemListener(listener);
1543 boolean condIsValid = false;
1545 condCombo.removeAllItems();
1546 for (Condition c : Condition.values())
1548 if ((c.isNumeric() && type == Datatype.Number)
1549 || (!c.isNumeric() && type != Datatype.Number))
1551 condCombo.addItem(c);
1560 * set the selected condition (does nothing if not in the list)
1564 condCombo.setSelectedItem(cond);
1568 condCombo.setSelectedIndex(0);
1572 * clear pattern if it is now invalid for condition
1574 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1578 String pattern = patternField.getText().trim();
1579 if (pattern.length() > 0)
1581 Float.valueOf(pattern);
1583 } catch (NumberFormatException e)
1585 patternField.setText("");
1590 * restore the listener
1592 condCombo.addItemListener(listener);
1596 * Answers true unless a numeric condition has been selected with a
1597 * non-numeric value. Sets the value field to RED with a tooltip if in error.
1599 * If the pattern is expected but is empty, this method returns false, but
1600 * does not mark the field as invalid. This supports selecting an attribute
1601 * for a new condition before a match pattern has been entered.
1606 protected boolean validateFilter(JTextField value,
1607 JComboBox<Condition> condCombo)
1609 if (value == null || condCombo == null)
1611 return true; // fields not populated
1614 Condition cond = (Condition) condCombo.getSelectedItem();
1615 if (!cond.needsAPattern())
1620 value.setBackground(Color.white);
1621 value.setToolTipText("");
1622 String v1 = value.getText().trim();
1623 if (v1.length() == 0)
1628 if (cond.isNumeric() && v1.length() > 0)
1633 } catch (NumberFormatException e)
1635 value.setBackground(Color.red);
1636 value.setToolTipText(
1637 MessageManager.getString("label.numeric_required"));
1646 * Constructs a filter condition from the given input fields, and replaces the
1647 * condition at filterIndex with the new one. Does nothing if the pattern
1648 * field is blank (unless the match condition is one that doesn't require a
1649 * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1652 * This method may update the tooltip on the filter value field to show the
1653 * value range, if a numeric condition is selected. This ensures the tooltip
1654 * is updated when a numeric valued attribute is chosen on the last 'add a
1660 * @param filterIndex
1662 protected boolean updateFilter(JComboBox<Object> attCombo,
1663 JComboBox<Condition> condCombo, JTextField valueField,
1669 attName = (String) attCombo.getSelectedItem();
1670 } catch (Exception e)
1672 Cache.log.error("Problem casting Combo box entry to String");
1673 attName = attCombo.getSelectedItem().toString();
1675 Condition cond = (Condition) condCombo.getSelectedItem();
1676 String pattern = valueField.getText().trim();
1678 setNumericHints(attName, cond, valueField);
1680 if (pattern.length() == 0 && cond.needsAPattern())
1682 valueField.setEnabled(true); // ensure pattern field is enabled!
1687 * Construct a matcher that operates on Label, Score,
1688 * or named attribute
1690 FeatureMatcherI km = null;
1691 if (LABEL_18N.equals(attName))
1693 km = FeatureMatcher.byLabel(cond, pattern);
1695 else if (SCORE_18N.equals(attName))
1697 km = FeatureMatcher.byScore(cond, pattern);
1701 km = FeatureMatcher.byAttribute(cond, pattern,
1702 FeatureMatcher.fromAttributeDisplayName(attName));
1705 filters.set(filterIndex, km);
1711 * Action on any change to feature filtering, namely
1713 * <li>change of selected attribute</li>
1714 * <li>change of selected condition</li>
1715 * <li>change of match pattern</li>
1716 * <li>removal of a condition</li>
1718 * The inputs are parsed into a combined filter and this is set for the
1719 * feature type, and the alignment redrawn.
1721 protected void filtersChanged()
1724 * update the filter conditions for the feature type
1726 boolean anded = andFilters.isSelected();
1727 FeatureMatcherSetI combined = new FeatureMatcherSet();
1729 for (FeatureMatcherI filter : filters)
1731 String pattern = filter.getMatcher().getPattern();
1732 Condition condition = filter.getMatcher().getCondition();
1733 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1737 combined.and(filter);
1741 combined.or(filter);
1747 * save the filter conditions in the FeatureRenderer
1748 * (note this might now be an empty filter with no conditions)
1750 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1751 refreshDisplay(true);
1757 * Repaints alignment, structure and overview (if shown). If there is a
1758 * complementary view which is showing this view's features, then also
1761 * @param updateStructsAndOverview
1763 void refreshDisplay(boolean updateStructsAndOverview)
1765 ap.paintAlignment(true, updateStructsAndOverview);
1766 AlignViewportI complement = ap.getAlignViewport().getCodingComplement();
1767 if (complement != null && complement.isShowComplementFeatures())
1769 AlignFrame af2 = Desktop.getAlignFrameFor(complement);
1770 af2.alignPanel.paintAlignment(true, updateStructsAndOverview);