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.gui.JalviewColourChooser.ColourChooserListener;
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.text.DecimalFormat;
53 import java.util.ArrayList;
54 import java.util.List;
56 import javax.swing.BorderFactory;
57 import javax.swing.BoxLayout;
58 import javax.swing.ButtonGroup;
59 import javax.swing.JButton;
60 import javax.swing.JCheckBox;
61 import javax.swing.JComboBox;
62 import javax.swing.JLabel;
63 import javax.swing.JPanel;
64 import javax.swing.JRadioButton;
65 import javax.swing.JSlider;
66 import javax.swing.JTextField;
67 import javax.swing.border.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 final AlignmentViewPanel ap;
117 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 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
149 * radio button group, to select what to colour by:
150 * simple colour, by category (text), or graduated
152 JRadioButton simpleColour = new JRadioButton();
154 JRadioButton byCategory = new JRadioButton();
156 JRadioButton graduatedColour = new JRadioButton();
162 JPanel singleColour = new JPanel();
164 JPanel minColour = new JPanel();
166 JPanel maxColour = new JPanel();
168 private JComboBox<Object> threshold = new JComboBox<>();
170 JSlider slider = new JSlider();
172 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 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();
233 updateColoursPanel();
235 updateFiltersPanel();
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 panel according to the current feature
252 private void updateColoursPanel()
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)
350 scaleFactor = (max == min) ? 1f : 100f / (max - min);
351 float range = (max - min) * scaleFactor;
352 slider.setMinimum((int) (min * scaleFactor));
353 slider.setMaximum((int) (max * scaleFactor));
354 slider.setMajorTickSpacing((int) (range / 10f));
356 threshline = new GraphLine((max - min) / 2f, "Threshold",
358 threshline.value = fc.getThreshold();
360 if (fc.hasThreshold())
362 threshold.setSelectedIndex(
363 fc.isAboveThreshold() ? ABOVE_THRESHOLD_OPTION
364 : BELOW_THRESHOLD_OPTION);
365 slider.setEnabled(true);
366 slider.setValue((int) (fc.getThreshold() * scaleFactor));
367 thresholdValue.setText(String.valueOf(fc.getThreshold()));
368 thresholdValue.setEnabled(true);
369 thresholdIsMin.setEnabled(true);
373 slider.setEnabled(false);
374 thresholdValue.setEnabled(false);
375 thresholdIsMin.setEnabled(false);
377 thresholdIsMin.setSelected(!fc.isAutoScaled());
385 * Configures the initial layout
387 private void initialise()
389 this.setLayout(new BorderLayout());
392 * an ActionListener that applies colour changes
394 changeColourAction = new ActionListener()
397 public void actionPerformed(ActionEvent e)
404 * first panel: colour options
406 JPanel coloursPanel = initialiseColoursPanel();
407 this.add(coloursPanel, BorderLayout.NORTH);
410 * second panel: filter options
412 JPanel filtersPanel = initialiseFiltersPanel();
413 this.add(filtersPanel, BorderLayout.CENTER);
415 JPanel okCancelPanel = initialiseOkCancelPanel();
417 this.add(okCancelPanel, BorderLayout.SOUTH);
421 * Updates the min-max range if Colour By selected item is Score, or an
422 * attribute, with a min-max range
424 protected void updateColourMinMax()
426 if (!graduatedColour.isSelected())
431 String colourBy = (String) colourByRangeCombo.getSelectedItem();
432 float[] minMax = getMinMax(colourBy);
442 * Retrieves the min-max range:
444 * <li>of feature score, if colour or filter is by Score</li>
445 * <li>else of the selected attribute</li>
451 private float[] getMinMax(String attName)
453 float[] minMax = null;
454 if (SCORE_18N.equals(attName))
456 minMax = fr.getMinMax().get(featureType)[0];
460 // colour by attribute range
461 minMax = FeatureAttributes.getInstance().getMinMax(featureType,
462 FeatureMatcher.fromAttributeDisplayName(attName));
468 * Lay out fields for graduated colour (by score or attribute value)
472 private JPanel initialiseGraduatedColourPanel()
474 JPanel graduatedColourPanel = new JPanel();
475 graduatedColourPanel.setLayout(
476 new BoxLayout(graduatedColourPanel, BoxLayout.Y_AXIS));
477 JvSwingUtils.createTitledBorder(graduatedColourPanel,
478 MessageManager.getString("label.graduated_colour"), true);
479 graduatedColourPanel.setBackground(Color.white);
482 * first row: graduated colour radio button, score/attribute drop-down
484 JPanel graduatedChoicePanel = new JPanel(
485 new FlowLayout(FlowLayout.LEFT));
486 graduatedChoicePanel.setBackground(Color.white);
487 graduatedColour = new JRadioButton(
488 MessageManager.getString("label.by_range_of") + COLON);
489 graduatedColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
490 graduatedColour.setOpaque(false);
491 graduatedColour.addItemListener(new ItemListener()
494 public void itemStateChanged(ItemEvent e)
496 if (graduatedColour.isSelected())
502 graduatedChoicePanel.add(graduatedColour);
504 List<String[]> attNames = FeatureAttributes.getInstance()
505 .getAttributes(featureType);
506 colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
507 colourByRangeCombo.addItemListener(new ItemListener()
510 public void itemStateChanged(ItemEvent e)
517 * disable graduated colour option if no range found
519 graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
521 graduatedChoicePanel.add(colourByRangeCombo);
522 graduatedColourPanel.add(graduatedChoicePanel);
525 * second row - min/max/no colours
527 JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
528 colourRangePanel.setBackground(Color.white);
529 graduatedColourPanel.add(colourRangePanel);
531 minColour.setFont(JvSwingUtils.getLabelFont());
532 minColour.setBorder(BorderFactory.createLineBorder(Color.black));
533 minColour.setPreferredSize(new Dimension(40, 20));
534 minColour.setToolTipText(MessageManager.getString("label.min_colour"));
535 minColour.addMouseListener(new MouseAdapter()
538 public void mousePressed(MouseEvent e)
540 if (minColour.isEnabled())
542 String ttl = MessageManager.getString("label.select_colour_minimum_value");
543 showColourChooser(minColour, ttl);
548 maxColour.setFont(JvSwingUtils.getLabelFont());
549 maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
550 maxColour.setPreferredSize(new Dimension(40, 20));
551 maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
552 maxColour.addMouseListener(new MouseAdapter()
555 public void mousePressed(MouseEvent e)
557 if (maxColour.isEnabled())
559 String ttl = MessageManager.getString("label.select_colour_maximum_value");
560 showColourChooser(maxColour, ttl);
564 maxColour.setBorder(new LineBorder(Color.black));
567 * if not set, default max colour to last plain colour,
568 * and make min colour a pale version of max colour
570 Color max = originalColour.getMaxColour();
573 max = originalColour.getColour();
574 minColour.setBackground(ColorUtils.bleachColour(max, 0.9f));
578 maxColour.setBackground(max);
579 minColour.setBackground(originalColour.getMinColour());
582 noValueCombo = new JComboBox<>();
583 noValueCombo.addItem(MessageManager.getString("label.no_colour"));
584 noValueCombo.addItem(MessageManager.getString("label.min_colour"));
585 noValueCombo.addItem(MessageManager.getString("label.max_colour"));
586 noValueCombo.addItemListener(new ItemListener()
589 public void itemStateChanged(ItemEvent e)
595 JLabel minText = new JLabel(
596 MessageManager.getString("label.min_value") + COLON);
597 minText.setFont(JvSwingUtils.getLabelFont());
598 JLabel maxText = new JLabel(
599 MessageManager.getString("label.max_value") + COLON);
600 maxText.setFont(JvSwingUtils.getLabelFont());
601 JLabel noText = new JLabel(
602 MessageManager.getString("label.no_value") + COLON);
603 noText.setFont(JvSwingUtils.getLabelFont());
605 colourRangePanel.add(minText);
606 colourRangePanel.add(minColour);
607 colourRangePanel.add(maxText);
608 colourRangePanel.add(maxColour);
609 colourRangePanel.add(noText);
610 colourRangePanel.add(noValueCombo);
613 * third row - threshold options and value
615 JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
616 thresholdPanel.setBackground(Color.white);
617 graduatedColourPanel.add(thresholdPanel);
619 threshold.addActionListener(changeColourAction);
620 threshold.setToolTipText(MessageManager
621 .getString("label.threshold_feature_display_by_score"));
622 threshold.addItem(MessageManager
623 .getString("label.threshold_feature_no_threshold")); // index 0
624 threshold.addItem(MessageManager
625 .getString("label.threshold_feature_above_threshold")); // index 1
626 threshold.addItem(MessageManager
627 .getString("label.threshold_feature_below_threshold")); // index 2
629 thresholdValue.addActionListener(new ActionListener()
632 public void actionPerformed(ActionEvent e)
634 thresholdValue_actionPerformed();
637 thresholdValue.addFocusListener(new FocusAdapter()
640 public void focusLost(FocusEvent e)
642 thresholdValue_actionPerformed();
645 slider.setPaintLabels(false);
646 slider.setPaintTicks(true);
647 slider.setBackground(Color.white);
648 slider.setEnabled(false);
649 slider.setOpaque(false);
650 slider.setPreferredSize(new Dimension(100, 32));
651 slider.setToolTipText(
652 MessageManager.getString("label.adjust_threshold"));
654 slider.addChangeListener(new ChangeListener()
657 public void stateChanged(ChangeEvent evt)
662 .setText(String.valueOf(slider.getValue() / scaleFactor));
663 thresholdValue.setBackground(Color.white); // to reset red for invalid
664 sliderValueChanged();
668 slider.addMouseListener(new MouseAdapter()
671 public void mouseReleased(MouseEvent evt)
674 * only update Overview and/or structure colouring
675 * when threshold slider drag ends (mouse up)
679 ap.paintAlignment(true, true);
684 thresholdValue.setEnabled(false);
685 thresholdValue.setColumns(7);
687 thresholdPanel.add(threshold);
688 thresholdPanel.add(slider);
689 thresholdPanel.add(thresholdValue);
691 thresholdIsMin.setBackground(Color.white);
693 .setText(MessageManager.getString("label.threshold_minmax"));
694 thresholdIsMin.setToolTipText(MessageManager
695 .getString("label.toggle_absolute_relative_display_threshold"));
696 thresholdIsMin.addActionListener(changeColourAction);
697 thresholdPanel.add(thresholdIsMin);
699 return graduatedColourPanel;
703 * Lay out OK and Cancel buttons
707 private JPanel initialiseOkCancelPanel()
709 JPanel okCancelPanel = new JPanel();
710 // okCancelPanel.setBackground(Color.white);
711 okCancelPanel.add(ok);
712 okCancelPanel.add(cancel);
713 return okCancelPanel;
717 * Lay out Colour options panel, containing
719 * <li>plain colour, with colour picker</li>
720 * <li>colour by text, with choice of Label or other attribute</li>
721 * <li>colour by range, of score or other attribute, when available</li>
726 private JPanel initialiseColoursPanel()
728 JPanel colourByPanel = new JPanel();
729 colourByPanel.setBackground(Color.white);
730 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
731 JvSwingUtils.createTitledBorder(colourByPanel,
732 MessageManager.getString("action.colour"), true);
735 * simple colour radio button and colour picker
737 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
738 simpleColourPanel.setBackground(Color.white);
739 colourByPanel.add(simpleColourPanel);
741 simpleColour = new JRadioButton(
742 MessageManager.getString("label.simple_colour"));
743 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
744 simpleColour.setOpaque(false);
745 simpleColour.addItemListener(new ItemListener()
748 public void itemStateChanged(ItemEvent e)
750 if (simpleColour.isSelected() && !adjusting)
757 singleColour.setFont(JvSwingUtils.getLabelFont());
758 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
759 singleColour.setPreferredSize(new Dimension(40, 20));
760 // if (originalColour.isGraduatedColour())
762 // singleColour.setBackground(originalColour.getMaxColour());
763 // singleColour.setForeground(originalColour.getMaxColour());
767 singleColour.setBackground(originalColour.getColour());
768 singleColour.setForeground(originalColour.getColour());
770 singleColour.addMouseListener(new MouseAdapter()
773 public void mousePressed(MouseEvent e)
775 if (simpleColour.isSelected())
777 String ttl = MessageManager.formatMessage("label.select_colour_for", featureType);
778 showColourChooser(singleColour, ttl);
782 simpleColourPanel.add(simpleColour); // radio button
783 simpleColourPanel.add(singleColour); // colour picker button
786 * colour by text (category) radio button and drop-down choice list
788 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
789 byTextPanel.setBackground(Color.white);
790 JvSwingUtils.createTitledBorder(byTextPanel,
791 MessageManager.getString("label.colour_by_text"), true);
792 colourByPanel.add(byTextPanel);
793 byCategory = new JRadioButton(
794 MessageManager.getString("label.by_text_of") + COLON);
795 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
796 byCategory.setOpaque(false);
797 byCategory.addItemListener(new ItemListener()
800 public void itemStateChanged(ItemEvent e)
802 if (byCategory.isSelected())
808 byTextPanel.add(byCategory);
810 List<String[]> attNames = FeatureAttributes.getInstance()
811 .getAttributes(featureType);
812 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
813 colourByTextCombo.addItemListener(new ItemListener()
816 public void itemStateChanged(ItemEvent e)
821 byTextPanel.add(colourByTextCombo);
824 * graduated colour panel
826 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
827 colourByPanel.add(graduatedColourPanel);
830 * 3 radio buttons select between simple colour,
831 * by category (text), or graduated
833 ButtonGroup bg = new ButtonGroup();
834 bg.add(simpleColour);
836 bg.add(graduatedColour);
838 return colourByPanel;
842 * Shows a colour chooser dialog, and if a selection is made, updates the
843 * colour of the given panel
846 * the panel whose background colour is being picked
849 void showColourChooser(JPanel colourPanel, String title)
851 ColourChooserListener listener = new ColourChooserListener()
854 public void colourSelected(Color col)
856 colourPanel.setBackground(col);
857 colourPanel.setForeground(col);
858 colourPanel.repaint();
862 JalviewColourChooser.showColourChooser(this, title,
863 colourPanel.getBackground(), listener);
867 * Constructs and sets the selected colour options as the colour for the
868 * feature type, and repaints the alignment, and optionally the Overview
869 * and/or structure viewer if open
871 * @param updateStructsAndOverview
873 void colourChanged(boolean updateStructsAndOverview)
878 * ignore action handlers while setting values programmatically
884 * ensure min-max range is for the latest choice of
885 * 'graduated colour by'
887 updateColourMinMax();
889 FeatureColourI acg = makeColourFromInputs();
892 * save the colour, and repaint stuff
894 fr.setColour(featureType, acg);
895 ap.paintAlignment(updateStructsAndOverview, updateStructsAndOverview);
897 updateColoursPanel();
901 * Converts the input values into an instance of FeatureColour
905 private FeatureColourI makeColourFromInputs()
908 * min-max range is to (or from) threshold value if
909 * 'threshold is min/max' is selected
915 thresh = Float.valueOf(thresholdValue.getText());
916 } catch (NumberFormatException e)
918 // invalid inputs are already handled on entry
920 float minValue = min;
921 float maxValue = max;
922 int thresholdOption = threshold.getSelectedIndex();
923 if (thresholdIsMin.isSelected()
924 && thresholdOption == ABOVE_THRESHOLD_OPTION)
928 if (thresholdIsMin.isSelected()
929 && thresholdOption == BELOW_THRESHOLD_OPTION)
933 Color noColour = null;
934 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
936 noColour = minColour.getBackground();
938 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
940 noColour = maxColour.getBackground();
944 * construct a colour that 'remembers' all the options, including
945 * those not currently selected
947 FeatureColourI fc = new FeatureColour(singleColour.getBackground(),
948 minColour.getBackground(), maxColour.getBackground(), noColour,
952 * easiest case - a single colour
954 if (simpleColour.isSelected())
956 ((FeatureColour) fc).setGraduatedColour(false);
961 * next easiest case - colour by Label, or attribute text
963 if (byCategory.isSelected())
965 fc.setColourByLabel(true);
966 String byWhat = (String) colourByTextCombo.getSelectedItem();
967 if (!LABEL_18N.equals(byWhat))
970 FeatureMatcher.fromAttributeDisplayName(byWhat));
976 * remaining case - graduated colour by score, or attribute value;
977 * set attribute to colour by if selected
979 String byWhat = (String) colourByRangeCombo.getSelectedItem();
980 if (!SCORE_18N.equals(byWhat))
982 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
986 * set threshold options and 'autoscaled' which is
987 * false if 'threshold is min/max' is selected
988 * else true (colour range is on actual range of values)
990 fc.setThreshold(thresh);
991 fc.setAutoScaled(!thresholdIsMin.isSelected());
992 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
993 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
995 if (threshline == null)
998 * todo not yet implemented: visual indication of feature threshold
1000 threshline = new GraphLine((max - min) / 2f, "Threshold",
1008 protected void raiseClosed()
1010 if (this.featureSettings != null)
1012 featureSettings.actionPerformed(new ActionEvent(this, 0, "CLOSED"));
1017 * Action on OK is just to dismiss the dialog - any changes have already been
1021 public void okPressed()
1026 * Action on Cancel is to restore colour scheme and filters as they were when
1027 * the dialog was opened
1030 public void cancelPressed()
1032 fr.setColour(featureType, originalColour);
1033 fr.setFeatureFilter(featureType, originalFilter);
1034 ap.paintAlignment(true, true);
1038 * Action on text entry of a threshold value
1040 protected void thresholdValue_actionPerformed()
1045 * set 'adjusting' flag while moving the slider, so it
1046 * doesn't then in turn change the value (with rounding)
1049 float f = Float.parseFloat(thresholdValue.getText());
1050 f = Float.max(f, this.min);
1051 f = Float.min(f, this.max);
1052 thresholdValue.setText(String.valueOf(f));
1053 slider.setValue((int) (f * scaleFactor));
1054 threshline.value = f;
1055 thresholdValue.setBackground(Color.white); // ok
1057 colourChanged(true);
1058 } catch (NumberFormatException ex)
1060 thresholdValue.setBackground(Color.red); // not ok
1066 * Action on change of threshold slider value. This may be done interactively
1067 * (by moving the slider), or programmatically (to update the slider after
1068 * manual input of a threshold value).
1070 protected void sliderValueChanged()
1072 threshline.value = getRoundedSliderValue();
1075 * repaint alignment, but not Overview or structure,
1076 * to avoid overload while dragging the slider
1078 colourChanged(false);
1082 * Converts the slider value to its absolute value by dividing by the
1083 * scaleFactor. Rounding errors are squashed by forcing min/max of slider
1084 * range to the actual min/max of feature score range
1088 private float getRoundedSliderValue()
1090 int value = slider.getValue();
1091 float f = value == slider.getMaximum() ? max
1092 : (value == slider.getMinimum() ? min : value / scaleFactor);
1096 void addActionListener(ActionListener listener)
1098 if (featureSettings != null)
1101 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1103 featureSettings = listener;
1107 * A helper method to build the drop-down choice of attributes for a feature.
1108 * If 'withRange' is true, then Score, and any attributes with a min-max
1109 * range, are added. If 'withText' is true, Label and any known attributes are
1110 * added. This allows 'categorical numerical' attributes e.g. codon position
1111 * to be coloured by text.
1113 * Where metadata is available with a description for an attribute, that is
1114 * added as a tooltip.
1116 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1117 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1119 * This method does not add any ActionListener to the JComboBox.
1125 protected JComboBox<Object> populateAttributesDropdown(
1126 List<String[]> attNames, boolean withRange, boolean withText)
1128 List<String> displayAtts = new ArrayList<>();
1129 List<String> tooltips = new ArrayList<>();
1133 displayAtts.add(LABEL_18N);
1134 tooltips.add(MessageManager.getString("label.description"));
1138 float[][] minMax = fr.getMinMax().get(featureType);
1139 if (minMax != null && minMax[0][0] != minMax[0][1])
1141 displayAtts.add(SCORE_18N);
1142 tooltips.add(SCORE_18N);
1146 FeatureAttributes fa = FeatureAttributes.getInstance();
1147 for (String[] attName : attNames)
1149 float[] minMax = fa.getMinMax(featureType, attName);
1150 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1151 if (!withText && !hasRange)
1155 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1156 String desc = fa.getDescription(featureType, attName);
1157 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1159 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1161 tooltips.add(desc == null ? "" : desc);
1164 // now convert String List to Object List for buildComboWithTooltips
1165 List<Object> displayAttsObjects = new ArrayList<>(displayAtts);
1166 JComboBox<Object> attCombo = JvSwingUtils
1167 .buildComboWithTooltips(displayAttsObjects, tooltips);
1173 * Populates initial layout of the feature attribute filters panel
1175 private JPanel initialiseFiltersPanel()
1177 filters = new ArrayList<>();
1179 JPanel filtersPanel = new JPanel();
1180 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1181 filtersPanel.setBackground(Color.white);
1182 JvSwingUtils.createTitledBorder(filtersPanel,
1183 MessageManager.getString("label.filters"), true);
1185 JPanel andOrPanel = initialiseAndOrPanel();
1186 filtersPanel.add(andOrPanel);
1189 * panel with filters - populated by refreshFiltersDisplay,
1190 * which also sets the layout manager
1192 chooseFiltersPanel = new JPanel();
1193 chooseFiltersPanel.setBackground(Color.white);
1194 filtersPanel.add(chooseFiltersPanel);
1196 return filtersPanel;
1200 * Lays out the panel with radio buttons to AND or OR filter conditions
1204 private JPanel initialiseAndOrPanel()
1206 JPanel andOrPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
1207 andOrPanel.setBackground(Color.white);
1208 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1209 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1210 andFilters.setOpaque(false);
1211 orFilters.setOpaque(false);
1212 ActionListener actionListener = new ActionListener()
1215 public void actionPerformed(ActionEvent e)
1220 andFilters.addActionListener(actionListener);
1221 orFilters.addActionListener(actionListener);
1222 ButtonGroup andOr = new ButtonGroup();
1223 andOr.add(andFilters);
1224 andOr.add(orFilters);
1225 andFilters.setSelected(true);
1227 new JLabel(MessageManager.getString("label.join_conditions")));
1228 andOrPanel.add(andFilters);
1229 andOrPanel.add(orFilters);
1234 * Refreshes the display to show any filters currently configured for the
1235 * selected feature type (editable, with 'remove' option), plus one extra row
1236 * for adding a condition. This should be called after a filter has been
1237 * removed, added or amended.
1239 private void updateFiltersPanel()
1242 * clear the panel and list of filter conditions
1244 chooseFiltersPanel.removeAll();
1248 * look up attributes known for feature type
1250 List<String[]> attNames = FeatureAttributes.getInstance()
1251 .getAttributes(featureType);
1254 * if this feature type has filters set, load them first
1256 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1257 if (featureFilters != null)
1259 if (!featureFilters.isAnded())
1261 orFilters.setSelected(true);
1263 // avoid use of lambda expression to keep SwingJS happy
1264 // featureFilters.getMatchers().forEach(item -> filters.add(item));
1265 for (FeatureMatcherI matcher : featureFilters.getMatchers())
1267 filters.add(matcher);
1272 * and an empty filter for the user to populate (add)
1274 filters.add(FeatureMatcher.NULL_MATCHER);
1277 * use GridLayout to 'justify' rows to the top of the panel, until
1278 * there are too many to fit in, then fall back on BoxLayout
1280 if (filters.size() <= 5)
1282 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1286 chooseFiltersPanel.setLayout(
1287 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1291 * render the conditions in rows, each in its own JPanel
1293 int filterIndex = 0;
1294 for (FeatureMatcherI filter : filters)
1296 JPanel row = addFilter(filter, attNames, filterIndex);
1297 chooseFiltersPanel.add(row);
1306 * A helper method that constructs a row (panel) with one filter condition:
1308 * <li>a drop-down list of Label, Score and attribute names to choose
1310 * <li>a drop-down list of conditions to choose from</li>
1311 * <li>a text field for input of a match pattern</li>
1312 * <li>optionally, a 'remove' button</li>
1314 * The filter values are set as defaults for the input fields. The 'remove'
1315 * button is added unless the pattern is empty (incomplete filter condition).
1317 * Action handlers on these fields provide for
1319 * <li>validate pattern field - should be numeric if condition is numeric</li>
1320 * <li>save filters and refresh display on any (valid) change</li>
1321 * <li>remove filter and refresh on 'Remove'</li>
1322 * <li>update conditions list on change of Label/Score/Attribute</li>
1323 * <li>refresh value field tooltip with min-max range on change of
1329 * @param filterIndex
1332 protected JPanel addFilter(FeatureMatcherI filter,
1333 List<String[]> attNames, int filterIndex)
1335 String[] attName = filter.getAttribute();
1336 Condition cond = filter.getMatcher().getCondition();
1337 String pattern = filter.getMatcher().getPattern();
1339 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1340 filterRow.setBackground(Color.white);
1343 * drop-down choice of attribute, with description as a tooltip
1344 * if we can obtain it
1346 final JComboBox<Object> attCombo = populateAttributesDropdown(attNames,
1348 String filterBy = setSelectedAttribute(attCombo, filter);
1350 JComboBox<Condition> condCombo = new JComboBox<>();
1352 JTextField patternField = new JTextField(8);
1353 patternField.setText(pattern);
1356 * action handlers that validate and (if valid) apply changes
1358 ActionListener actionListener = new ActionListener()
1361 public void actionPerformed(ActionEvent e)
1363 if (validateFilter(patternField, condCombo))
1365 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1372 ItemListener itemListener = new ItemListener()
1375 public void itemStateChanged(ItemEvent e)
1377 actionListener.actionPerformed(null);
1381 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1383 attCombo.setSelectedIndex(0);
1387 attCombo.setSelectedItem(
1388 FeatureMatcher.toAttributeDisplayName(attName));
1390 attCombo.addItemListener(new ItemListener()
1393 public void itemStateChanged(ItemEvent e)
1396 * on change of attribute, refresh the conditions list to
1397 * ensure it is appropriate for the attribute datatype
1399 populateConditions((String) attCombo.getSelectedItem(),
1400 (Condition) condCombo.getSelectedItem(), condCombo,
1402 actionListener.actionPerformed(null);
1406 filterRow.add(attCombo);
1409 * drop-down choice of test condition
1411 populateConditions(filterBy, cond, condCombo, patternField);
1412 condCombo.setPreferredSize(new Dimension(150, 20));
1413 condCombo.addItemListener(itemListener);
1414 filterRow.add(condCombo);
1417 * pattern to match against
1419 patternField.addActionListener(actionListener);
1420 patternField.addFocusListener(new FocusAdapter()
1423 public void focusLost(FocusEvent e)
1425 actionListener.actionPerformed(null);
1428 filterRow.add(patternField);
1431 * disable pattern field for condition 'Present / NotPresent'
1433 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1434 patternField.setEnabled(selectedCondition.needsAPattern());
1437 * if a numeric condition is selected, show the value range
1438 * as a tooltip on the value input field
1440 setNumericHints(filterBy, selectedCondition, patternField);
1443 * add remove button if filter is populated (non-empty pattern)
1445 if (!patternField.isEnabled()
1446 || (pattern != null && pattern.trim().length() > 0))
1448 JButton removeCondition = new JButton("\u2717");
1449 // Dingbats cursive x
1450 removeCondition.setBorder(new EmptyBorder(0, 0, 0, 0));
1451 removeCondition.setBackground(Color.WHITE);
1452 removeCondition.setPreferredSize(new Dimension(23, 17));
1453 removeCondition.setToolTipText(
1454 MessageManager.getString("label.delete_condition"));
1455 removeCondition.addActionListener(new ActionListener()
1458 public void actionPerformed(ActionEvent e)
1460 filters.remove(filterIndex);
1464 filterRow.add(removeCondition);
1471 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1477 private String setSelectedAttribute(JComboBox<Object> attCombo,
1478 FeatureMatcherI filter)
1481 if (filter.isByScore())
1485 else if (filter.isByLabel())
1491 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1493 attCombo.setSelectedItem(item);
1498 * If a numeric comparison condition is selected, retrieves the min-max range
1499 * for the value (score or attribute), and sets it as a tooltip on the value
1500 * field. If the field is currently empty, then pre-populates it with
1502 * <li>the minimum value, if condition is > or >=</li>
1503 * <li>the maximum value, if condition is < or <=</li>
1507 * @param selectedCondition
1508 * @param patternField
1510 private void setNumericHints(String attName, Condition selectedCondition,
1511 JTextField patternField)
1513 patternField.setToolTipText("");
1515 if (selectedCondition.isNumeric())
1517 float[] minMax = getMinMax(attName);
1520 String minFormatted = DECFMT_2_2.format(minMax[0]);
1521 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1522 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1523 patternField.setToolTipText(tip);
1524 if (patternField.getText().isEmpty())
1526 if (selectedCondition == Condition.GE
1527 || selectedCondition == Condition.GT)
1529 patternField.setText(minFormatted);
1533 if (selectedCondition == Condition.LE
1534 || selectedCondition == Condition.LT)
1536 patternField.setText(maxFormatted);
1545 * Populates the drop-down list of comparison conditions for the given
1546 * attribute name. The conditions added depend on the datatype of the
1547 * attribute values. The supplied condition is set as the selected item in the
1548 * list, provided it is in the list. If the pattern is now invalid
1549 * (non-numeric pattern for a numeric condition), it is cleared.
1554 * @param patternField
1556 void populateConditions(String attName, Condition cond,
1557 JComboBox<Condition> condCombo, JTextField patternField)
1559 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1560 FeatureMatcher.fromAttributeDisplayName(attName));
1561 if (LABEL_18N.equals(attName))
1563 type = Datatype.Character;
1565 else if (SCORE_18N.equals(attName))
1567 type = Datatype.Number;
1571 * remove itemListener before starting
1573 ItemListener listener = condCombo.getItemListeners()[0];
1574 condCombo.removeItemListener(listener);
1575 boolean condIsValid = false;
1577 condCombo.removeAllItems();
1578 for (Condition c : Condition.values())
1580 if ((c.isNumeric() && type == Datatype.Number)
1581 || (!c.isNumeric() && type != Datatype.Number))
1583 condCombo.addItem(c);
1592 * set the selected condition (does nothing if not in the list)
1596 condCombo.setSelectedItem(cond);
1600 condCombo.setSelectedIndex(0);
1604 * clear pattern if it is now invalid for condition
1606 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1610 String pattern = patternField.getText().trim();
1611 if (pattern.length() > 0)
1613 Float.valueOf(pattern);
1615 } catch (NumberFormatException e)
1617 patternField.setText("");
1622 * restore the listener
1624 condCombo.addItemListener(listener);
1628 * Answers true unless a numeric condition has been selected with a
1629 * non-numeric value. Sets the value field to RED with a tooltip if in error.
1631 * If the pattern is expected but is empty, this method returns false, but
1632 * does not mark the field as invalid. This supports selecting an attribute
1633 * for a new condition before a match pattern has been entered.
1638 protected boolean validateFilter(JTextField value,
1639 JComboBox<Condition> condCombo)
1641 if (value == null || condCombo == null)
1643 return true; // fields not populated
1646 Condition cond = (Condition) condCombo.getSelectedItem();
1647 if (!cond.needsAPattern())
1652 value.setBackground(Color.white);
1653 value.setToolTipText("");
1654 String v1 = value.getText().trim();
1655 if (v1.length() == 0)
1660 if (cond.isNumeric() && v1.length() > 0)
1665 } catch (NumberFormatException e)
1667 value.setBackground(Color.red);
1668 value.setToolTipText(
1669 MessageManager.getString("label.numeric_required"));
1678 * Constructs a filter condition from the given input fields, and replaces the
1679 * condition at filterIndex with the new one. Does nothing if the pattern
1680 * field is blank (unless the match condition is one that doesn't require a
1681 * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1684 * This method may update the tooltip on the filter value field to show the
1685 * value range, if a numeric condition is selected. This ensures the tooltip
1686 * is updated when a numeric valued attribute is chosen on the last 'add a
1692 * @param filterIndex
1694 protected boolean updateFilter(JComboBox<Object> attCombo,
1695 JComboBox<Condition> condCombo, JTextField valueField,
1701 attName = (String) attCombo.getSelectedItem();
1702 } catch (Exception e)
1704 Cache.log.error("Problem casting Combo box entry to String");
1705 attName = attCombo.getSelectedItem().toString();
1707 Condition cond = (Condition) condCombo.getSelectedItem();
1708 String pattern = valueField.getText().trim();
1710 setNumericHints(attName, cond, valueField);
1712 if (pattern.length() == 0 && cond.needsAPattern())
1714 valueField.setEnabled(true); // ensure pattern field is enabled!
1719 * Construct a matcher that operates on Label, Score,
1720 * or named attribute
1722 FeatureMatcherI km = null;
1723 if (LABEL_18N.equals(attName))
1725 km = FeatureMatcher.byLabel(cond, pattern);
1727 else if (SCORE_18N.equals(attName))
1729 km = FeatureMatcher.byScore(cond, pattern);
1733 km = FeatureMatcher.byAttribute(cond, pattern,
1734 FeatureMatcher.fromAttributeDisplayName(attName));
1737 filters.set(filterIndex, km);
1743 * Action on any change to feature filtering, namely
1745 * <li>change of selected attribute</li>
1746 * <li>change of selected condition</li>
1747 * <li>change of match pattern</li>
1748 * <li>removal of a condition</li>
1750 * The inputs are parsed into a combined filter and this is set for the
1751 * feature type, and the alignment redrawn.
1753 protected void filtersChanged()
1756 * update the filter conditions for the feature type
1758 boolean anded = andFilters.isSelected();
1759 FeatureMatcherSetI combined = new FeatureMatcherSet();
1761 for (FeatureMatcherI filter : filters)
1763 String pattern = filter.getMatcher().getPattern();
1764 Condition condition = filter.getMatcher().getCondition();
1765 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1769 combined.and(filter);
1773 combined.or(filter);
1779 * save the filter conditions in the FeatureRenderer
1780 * (note this might now be an empty filter with no conditions)
1782 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1783 ap.paintAlignment(true, true);
1785 updateFiltersPanel();