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.datamodel.GraphLine;
26 import jalview.datamodel.features.FeatureAttributes;
27 import jalview.datamodel.features.FeatureAttributes.Datatype;
28 import jalview.datamodel.features.FeatureMatcher;
29 import jalview.datamodel.features.FeatureMatcherI;
30 import jalview.datamodel.features.FeatureMatcherSet;
31 import jalview.datamodel.features.FeatureMatcherSetI;
32 import jalview.schemes.FeatureColour;
33 import jalview.util.ColorUtils;
34 import jalview.util.MessageManager;
35 import jalview.util.matcher.Condition;
37 import java.awt.BorderLayout;
38 import java.awt.Color;
39 import java.awt.Dimension;
40 import java.awt.FlowLayout;
41 import java.awt.GridLayout;
42 import java.awt.event.ActionEvent;
43 import java.awt.event.ActionListener;
44 import java.awt.event.FocusAdapter;
45 import java.awt.event.FocusEvent;
46 import java.awt.event.ItemEvent;
47 import java.awt.event.ItemListener;
48 import java.awt.event.MouseAdapter;
49 import java.awt.event.MouseEvent;
50 import java.text.DecimalFormat;
51 import java.util.ArrayList;
52 import java.util.List;
54 import javax.swing.BorderFactory;
55 import javax.swing.BoxLayout;
56 import javax.swing.ButtonGroup;
57 import javax.swing.JButton;
58 import javax.swing.JCheckBox;
59 import javax.swing.JColorChooser;
60 import javax.swing.JComboBox;
61 import javax.swing.JLabel;
62 import javax.swing.JPanel;
63 import javax.swing.JRadioButton;
64 import javax.swing.JSlider;
65 import javax.swing.JTextField;
66 import javax.swing.border.EmptyBorder;
67 import javax.swing.border.LineBorder;
68 import javax.swing.event.ChangeEvent;
69 import javax.swing.event.ChangeListener;
72 * A dialog where the user can configure colour scheme, and any filters, for one
75 * (Was FeatureColourChooser prior to Jalview 1.11, renamed with the addition of
78 public class FeatureTypeSettings extends JalviewDialog
80 private final static String LABEL_18N = MessageManager
81 .getString("label.label");
83 private final static String SCORE_18N = MessageManager
84 .getString("label.score");
86 private static final int RADIO_WIDTH = 130;
88 private static final String COLON = ":";
90 private static final int MAX_TOOLTIP_LENGTH = 50;
92 private static final int NO_COLOUR_OPTION = 0;
94 private static final int MIN_COLOUR_OPTION = 1;
96 private static final int MAX_COLOUR_OPTION = 2;
98 private static final int ABOVE_THRESHOLD_OPTION = 1;
100 private static final int BELOW_THRESHOLD_OPTION = 2;
102 private static final DecimalFormat DECFMT_2_2 = new DecimalFormat(
106 * FeatureRenderer holds colour scheme and filters for feature types
108 private final FeatureRenderer fr; // todo refactor to allow interface type
112 * the view panel to update when settings change
114 private final AlignmentViewPanel ap;
116 private final String featureType;
119 * the colour and filters to reset to on Cancel
121 private final FeatureColourI originalColour;
123 private final FeatureMatcherSetI originalFilter;
126 * set flag to true when setting values programmatically,
127 * to avoid invocation of action handlers
129 private boolean adjusting = false;
132 * minimum of the value range for graduated colour
133 * (may be for feature score or for a numeric attribute)
138 * maximum of the value range for graduated colour
143 * scale factor for conversion between absolute min-max and slider
145 private float scaleFactor;
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<String> threshold = new JComboBox<>();
170 private JSlider slider = new JSlider();
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<String> noValueCombo;
188 * choice of what to colour by text (Label or attribute)
190 private JComboBox<String> colourByTextCombo;
193 * choice of what to colour by range (Score or attribute)
195 private JComboBox<String> 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)
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/tab: colour options
406 JPanel coloursPanel = initialiseColoursPanel();
407 this.add(coloursPanel, BorderLayout.NORTH);
410 * second panel/tab: 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.addItemListener(new ItemListener()
493 public void itemStateChanged(ItemEvent e)
495 if (graduatedColour.isSelected())
501 graduatedChoicePanel.add(graduatedColour);
503 List<String[]> attNames = FeatureAttributes.getInstance()
504 .getAttributes(featureType);
505 colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
506 colourByRangeCombo.addItemListener(new ItemListener()
509 public void itemStateChanged(ItemEvent e)
516 * disable graduated colour option if no range found
518 graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
520 graduatedChoicePanel.add(colourByRangeCombo);
521 graduatedColourPanel.add(graduatedChoicePanel);
524 * second row - min/max/no colours
526 JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
527 colourRangePanel.setBackground(Color.white);
528 graduatedColourPanel.add(colourRangePanel);
530 minColour.setFont(JvSwingUtils.getLabelFont());
531 minColour.setBorder(BorderFactory.createLineBorder(Color.black));
532 minColour.setPreferredSize(new Dimension(40, 20));
533 minColour.setToolTipText(MessageManager.getString("label.min_colour"));
534 minColour.addMouseListener(new MouseAdapter()
537 public void mousePressed(MouseEvent e)
539 if (minColour.isEnabled())
541 showColourChooser(minColour, "label.select_colour_minimum_value");
546 maxColour.setFont(JvSwingUtils.getLabelFont());
547 maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
548 maxColour.setPreferredSize(new Dimension(40, 20));
549 maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
550 maxColour.addMouseListener(new MouseAdapter()
553 public void mousePressed(MouseEvent e)
555 if (maxColour.isEnabled())
557 showColourChooser(maxColour, "label.select_colour_maximum_value");
561 maxColour.setBorder(new LineBorder(Color.black));
564 * if not set, default max colour to last plain colour,
565 * and make min colour a pale version of max colour
567 Color max = originalColour.getMaxColour();
570 max = originalColour.getColour();
571 minColour.setBackground(ColorUtils.bleachColour(max, 0.9f));
575 maxColour.setBackground(max);
576 minColour.setBackground(originalColour.getMinColour());
579 noValueCombo = new JComboBox<>();
580 noValueCombo.addItem(MessageManager.getString("label.no_colour"));
581 noValueCombo.addItem(MessageManager.getString("label.min_colour"));
582 noValueCombo.addItem(MessageManager.getString("label.max_colour"));
583 noValueCombo.addItemListener(new ItemListener()
586 public void itemStateChanged(ItemEvent e)
592 JLabel minText = new JLabel(
593 MessageManager.getString("label.min_value") + COLON);
594 minText.setFont(JvSwingUtils.getLabelFont());
595 JLabel maxText = new JLabel(
596 MessageManager.getString("label.max_value") + COLON);
597 maxText.setFont(JvSwingUtils.getLabelFont());
598 JLabel noText = new JLabel(
599 MessageManager.getString("label.no_value") + COLON);
600 noText.setFont(JvSwingUtils.getLabelFont());
602 colourRangePanel.add(minText);
603 colourRangePanel.add(minColour);
604 colourRangePanel.add(maxText);
605 colourRangePanel.add(maxColour);
606 colourRangePanel.add(noText);
607 colourRangePanel.add(noValueCombo);
610 * third row - threshold options and value
612 JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
613 thresholdPanel.setBackground(Color.white);
614 graduatedColourPanel.add(thresholdPanel);
616 threshold.addActionListener(changeColourAction);
617 threshold.setToolTipText(MessageManager
618 .getString("label.threshold_feature_display_by_score"));
619 threshold.addItem(MessageManager
620 .getString("label.threshold_feature_no_threshold")); // index 0
621 threshold.addItem(MessageManager
622 .getString("label.threshold_feature_above_threshold")); // index 1
623 threshold.addItem(MessageManager
624 .getString("label.threshold_feature_below_threshold")); // index 2
626 thresholdValue.addActionListener(new ActionListener()
629 public void actionPerformed(ActionEvent e)
631 thresholdValue_actionPerformed();
634 thresholdValue.addFocusListener(new FocusAdapter()
637 public void focusLost(FocusEvent e)
639 thresholdValue_actionPerformed();
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)
659 .setText(String.valueOf(slider.getValue() / scaleFactor));
660 thresholdValue.setBackground(Color.white); // to reset red for invalid
661 sliderValueChanged();
665 slider.addMouseListener(new MouseAdapter()
668 public void mouseReleased(MouseEvent evt)
671 * only update Overview and/or structure colouring
672 * when threshold slider drag ends (mouse up)
676 ap.paintAlignment(true, true);
681 thresholdValue.setEnabled(false);
682 thresholdValue.setColumns(7);
684 thresholdPanel.add(threshold);
685 thresholdPanel.add(slider);
686 thresholdPanel.add(thresholdValue);
688 thresholdIsMin.setBackground(Color.white);
690 .setText(MessageManager.getString("label.threshold_minmax"));
691 thresholdIsMin.setToolTipText(MessageManager
692 .getString("label.toggle_absolute_relative_display_threshold"));
693 thresholdIsMin.addActionListener(changeColourAction);
694 thresholdPanel.add(thresholdIsMin);
696 return graduatedColourPanel;
700 * Lay out OK and Cancel buttons
704 private JPanel initialiseOkCancelPanel()
706 JPanel okCancelPanel = new JPanel();
707 // okCancelPanel.setBackground(Color.white);
708 okCancelPanel.add(ok);
709 okCancelPanel.add(cancel);
710 return okCancelPanel;
714 * Lay out Colour options panel, containing
716 * <li>plain colour, with colour picker</li>
717 * <li>colour by text, with choice of Label or other attribute</li>
718 * <li>colour by range, of score or other attribute, when available</li>
723 private JPanel initialiseColoursPanel()
725 JPanel colourByPanel = new JPanel();
726 colourByPanel.setBackground(Color.white);
727 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
728 JvSwingUtils.createTitledBorder(colourByPanel,
729 MessageManager.getString("action.colour"), true);
732 * simple colour radio button and colour picker
734 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
735 simpleColourPanel.setBackground(Color.white);
736 colourByPanel.add(simpleColourPanel);
738 simpleColour = new JRadioButton(
739 MessageManager.getString("label.simple_colour"));
740 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
741 simpleColour.addItemListener(new ItemListener()
744 public void itemStateChanged(ItemEvent e)
746 if (simpleColour.isSelected() && !adjusting)
753 singleColour.setFont(JvSwingUtils.getLabelFont());
754 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
755 singleColour.setPreferredSize(new Dimension(40, 20));
756 // if (originalColour.isGraduatedColour())
758 // singleColour.setBackground(originalColour.getMaxColour());
759 // singleColour.setForeground(originalColour.getMaxColour());
763 singleColour.setBackground(originalColour.getColour());
764 singleColour.setForeground(originalColour.getColour());
766 singleColour.addMouseListener(new MouseAdapter()
769 public void mousePressed(MouseEvent e)
771 if (simpleColour.isSelected())
773 showColourChooser(singleColour, "label.select_colour");
777 simpleColourPanel.add(simpleColour); // radio button
778 simpleColourPanel.add(singleColour); // colour picker button
781 * colour by text (category) radio button and drop-down choice list
783 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
784 byTextPanel.setBackground(Color.white);
785 JvSwingUtils.createTitledBorder(byTextPanel,
786 MessageManager.getString("label.colour_by_text"), true);
787 colourByPanel.add(byTextPanel);
788 byCategory = new JRadioButton(
789 MessageManager.getString("label.by_text_of") + COLON);
790 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
791 byCategory.addItemListener(new ItemListener()
794 public void itemStateChanged(ItemEvent e)
796 if (byCategory.isSelected())
802 byTextPanel.add(byCategory);
804 List<String[]> attNames = FeatureAttributes.getInstance()
805 .getAttributes(featureType);
806 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
807 colourByTextCombo.addItemListener(new ItemListener()
810 public void itemStateChanged(ItemEvent e)
815 byTextPanel.add(colourByTextCombo);
818 * graduated colour panel
820 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
821 colourByPanel.add(graduatedColourPanel);
824 * 3 radio buttons select between simple colour,
825 * by category (text), or graduated
827 ButtonGroup bg = new ButtonGroup();
828 bg.add(simpleColour);
830 bg.add(graduatedColour);
832 return colourByPanel;
835 private void showColourChooser(JPanel colourPanel, String key)
837 Color col = JColorChooser.showDialog(this,
838 MessageManager.getString(key), colourPanel.getBackground());
841 colourPanel.setBackground(col);
842 colourPanel.setForeground(col);
844 colourPanel.repaint();
849 * Constructs and sets the selected colour options as the colour for the
850 * feature type, and repaints the alignment, and optionally the Overview
851 * and/or structure viewer if open
853 * @param updateStructsAndOverview
855 void colourChanged(boolean updateStructsAndOverview)
860 * ignore action handlers while setting values programmatically
866 * ensure min-max range is for the latest choice of
867 * 'graduated colour by'
869 updateColourMinMax();
871 FeatureColourI acg = makeColourFromInputs();
874 * save the colour, and repaint stuff
876 fr.setColour(featureType, acg);
877 ap.paintAlignment(updateStructsAndOverview, updateStructsAndOverview);
883 * Converts the input values into an instance of FeatureColour
887 private FeatureColourI makeColourFromInputs()
890 * min-max range is to (or from) threshold value if
891 * 'threshold is min/max' is selected
897 thresh = Float.valueOf(thresholdValue.getText());
898 } catch (NumberFormatException e)
900 // invalid inputs are already handled on entry
902 float minValue = min;
903 float maxValue = max;
904 final int thresholdOption = threshold.getSelectedIndex();
905 if (thresholdIsMin.isSelected()
906 && thresholdOption == ABOVE_THRESHOLD_OPTION)
910 if (thresholdIsMin.isSelected()
911 && thresholdOption == BELOW_THRESHOLD_OPTION)
915 Color noColour = null;
916 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
918 noColour = minColour.getBackground();
920 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
922 noColour = maxColour.getBackground();
926 * construct a colour that 'remembers' all the options, including
927 * those not currently selected
929 FeatureColourI fc = new FeatureColour(singleColour.getBackground(),
930 minColour.getBackground(), maxColour.getBackground(), noColour,
934 * easiest case - a single colour
936 if (simpleColour.isSelected())
938 ((FeatureColour) fc).setGraduatedColour(false);
943 * next easiest case - colour by Label, or attribute text
945 if (byCategory.isSelected())
947 fc.setColourByLabel(true);
948 String byWhat = (String) colourByTextCombo.getSelectedItem();
949 if (!LABEL_18N.equals(byWhat))
952 FeatureMatcher.fromAttributeDisplayName(byWhat));
958 * remaining case - graduated colour by score, or attribute value;
959 * set attribute to colour by if selected
961 String byWhat = (String) colourByRangeCombo.getSelectedItem();
962 if (!SCORE_18N.equals(byWhat))
964 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
968 * set threshold options and 'autoscaled' which is
969 * false if 'threshold is min/max' is selected
970 * else true (colour range is on actual range of values)
972 fc.setThreshold(thresh);
973 fc.setAutoScaled(!thresholdIsMin.isSelected());
974 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
975 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
977 if (threshline == null)
980 * todo not yet implemented: visual indication of feature threshold
982 threshline = new GraphLine((max - min) / 2f, "Threshold",
990 protected void raiseClosed()
992 if (this.featureSettings != null)
994 featureSettings.actionPerformed(new ActionEvent(this, 0, "CLOSED"));
999 * Action on OK is just to dismiss the dialog - any changes have already been
1003 public void okPressed()
1008 * Action on Cancel is to restore colour scheme and filters as they were when
1009 * the dialog was opened
1012 public void cancelPressed()
1014 fr.setColour(featureType, originalColour);
1015 fr.setFeatureFilter(featureType, originalFilter);
1016 ap.paintAlignment(true, true);
1020 * Action on text entry of a threshold value
1022 protected void thresholdValue_actionPerformed()
1027 * set 'adjusting' flag while moving the slider, so it
1028 * doesn't then in turn change the value (with rounding)
1031 float f = Float.parseFloat(thresholdValue.getText());
1032 f = Float.max(f, this.min);
1033 f = Float.min(f, this.max);
1034 thresholdValue.setText(String.valueOf(f));
1035 slider.setValue((int) (f * scaleFactor));
1036 threshline.value = f;
1037 thresholdValue.setBackground(Color.white); // ok
1039 colourChanged(true);
1040 } catch (NumberFormatException ex)
1042 thresholdValue.setBackground(Color.red); // not ok
1048 * Action on change of threshold slider value. This may be done interactively
1049 * (by moving the slider), or programmatically (to update the slider after
1050 * manual input of a threshold value).
1052 protected void sliderValueChanged()
1054 threshline.value = getRoundedSliderValue();
1057 * repaint alignment, but not Overview or structure,
1058 * to avoid overload while dragging the slider
1060 colourChanged(false);
1064 * Converts the slider value to its absolute value by dividing by the
1065 * scaleFactor. Rounding errors are squashed by forcing min/max of slider
1066 * range to the actual min/max of feature score range
1070 private float getRoundedSliderValue()
1072 int value = slider.getValue();
1073 float f = value == slider.getMaximum() ? max
1074 : (value == slider.getMinimum() ? min : value / scaleFactor);
1078 void addActionListener(ActionListener listener)
1080 if (featureSettings != null)
1083 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1085 featureSettings = listener;
1089 * A helper method to build the drop-down choice of attributes for a feature.
1090 * If 'withRange' is true, then Score, and any attributes with a min-max
1091 * range, are added. If 'withText' is true, Label and any known attributes are
1092 * added. This allows 'categorical numerical' attributes e.g. codon position
1093 * to be coloured by text.
1095 * Where metadata is available with a description for an attribute, that is
1096 * added as a tooltip.
1098 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1099 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1101 * This method does not add any ActionListener to the JComboBox.
1107 protected JComboBox<String> populateAttributesDropdown(
1108 List<String[]> attNames, boolean withRange, boolean withText)
1110 List<String> displayAtts = new ArrayList<>();
1111 List<String> tooltips = new ArrayList<>();
1115 displayAtts.add(LABEL_18N);
1116 tooltips.add(MessageManager.getString("label.description"));
1120 float[][] minMax = fr.getMinMax().get(featureType);
1121 if (minMax != null && minMax[0][0] != minMax[0][1])
1123 displayAtts.add(SCORE_18N);
1124 tooltips.add(SCORE_18N);
1128 FeatureAttributes fa = FeatureAttributes.getInstance();
1129 for (String[] attName : attNames)
1131 float[] minMax = fa.getMinMax(featureType, attName);
1132 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1133 if (!withText && !hasRange)
1137 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1138 String desc = fa.getDescription(featureType, attName);
1139 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1141 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1143 tooltips.add(desc == null ? "" : desc);
1146 JComboBox<String> attCombo = JvSwingUtils
1147 .buildComboWithTooltips(displayAtts, tooltips);
1153 * Populates initial layout of the feature attribute filters panel
1155 private JPanel initialiseFiltersPanel()
1157 filters = new ArrayList<>();
1159 JPanel filtersPanel = new JPanel();
1160 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1161 filtersPanel.setBackground(Color.white);
1162 JvSwingUtils.createTitledBorder(filtersPanel,
1163 MessageManager.getString("label.filters"), true);
1165 JPanel andOrPanel = initialiseAndOrPanel();
1166 filtersPanel.add(andOrPanel);
1169 * panel with filters - populated by refreshFiltersDisplay,
1170 * which also sets the layout manager
1172 chooseFiltersPanel = new JPanel();
1173 chooseFiltersPanel.setBackground(Color.white);
1174 filtersPanel.add(chooseFiltersPanel);
1176 return filtersPanel;
1180 * Lays out the panel with radio buttons to AND or OR filter conditions
1184 private JPanel initialiseAndOrPanel()
1186 JPanel andOrPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
1187 andOrPanel.setBackground(Color.white);
1188 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1189 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1190 ActionListener actionListener = new ActionListener()
1193 public void actionPerformed(ActionEvent e)
1198 andFilters.addActionListener(actionListener);
1199 orFilters.addActionListener(actionListener);
1200 ButtonGroup andOr = new ButtonGroup();
1201 andOr.add(andFilters);
1202 andOr.add(orFilters);
1203 andFilters.setSelected(true);
1205 new JLabel(MessageManager.getString("label.join_conditions")));
1206 andOrPanel.add(andFilters);
1207 andOrPanel.add(orFilters);
1212 * Refreshes the display to show any filters currently configured for the
1213 * selected feature type (editable, with 'remove' option), plus one extra row
1214 * for adding a condition. This should be called after a filter has been
1215 * removed, added or amended.
1217 private void updateFiltersTab()
1220 * clear the panel and list of filter conditions
1222 chooseFiltersPanel.removeAll();
1226 * look up attributes known for feature type
1228 List<String[]> attNames = FeatureAttributes.getInstance()
1229 .getAttributes(featureType);
1232 * if this feature type has filters set, load them first
1234 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1235 if (featureFilters != null)
1237 if (!featureFilters.isAnded())
1239 orFilters.setSelected(true);
1241 featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1245 * and an empty filter for the user to populate (add)
1247 filters.add(FeatureMatcher.NULL_MATCHER);
1250 * use GridLayout to 'justify' rows to the top of the panel, until
1251 * there are too many to fit in, then fall back on BoxLayout
1253 if (filters.size() <= 5)
1255 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1259 chooseFiltersPanel.setLayout(
1260 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1264 * render the conditions in rows, each in its own JPanel
1266 int filterIndex = 0;
1267 for (FeatureMatcherI filter : filters)
1269 JPanel row = addFilter(filter, attNames, filterIndex);
1270 chooseFiltersPanel.add(row);
1279 * A helper method that constructs a row (panel) with one filter condition:
1281 * <li>a drop-down list of Label, Score and attribute names to choose
1283 * <li>a drop-down list of conditions to choose from</li>
1284 * <li>a text field for input of a match pattern</li>
1285 * <li>optionally, a 'remove' button</li>
1287 * The filter values are set as defaults for the input fields. The 'remove'
1288 * button is added unless the pattern is empty (incomplete filter condition).
1290 * Action handlers on these fields provide for
1292 * <li>validate pattern field - should be numeric if condition is numeric</li>
1293 * <li>save filters and refresh display on any (valid) change</li>
1294 * <li>remove filter and refresh on 'Remove'</li>
1295 * <li>update conditions list on change of Label/Score/Attribute</li>
1296 * <li>refresh value field tooltip with min-max range on change of
1302 * @param filterIndex
1305 protected JPanel addFilter(FeatureMatcherI filter,
1306 List<String[]> attNames, int filterIndex)
1308 String[] attName = filter.getAttribute();
1309 Condition cond = filter.getMatcher().getCondition();
1310 String pattern = filter.getMatcher().getPattern();
1312 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1313 filterRow.setBackground(Color.white);
1316 * drop-down choice of attribute, with description as a tooltip
1317 * if we can obtain it
1319 final JComboBox<String> attCombo = populateAttributesDropdown(attNames,
1321 String filterBy = setSelectedAttribute(attCombo, filter);
1323 JComboBox<Condition> condCombo = new JComboBox<>();
1325 JTextField patternField = new JTextField(8);
1326 patternField.setText(pattern);
1329 * action handlers that validate and (if valid) apply changes
1331 ActionListener actionListener = new ActionListener()
1334 public void actionPerformed(ActionEvent e)
1336 if (validateFilter(patternField, condCombo))
1338 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1345 ItemListener itemListener = new ItemListener()
1348 public void itemStateChanged(ItemEvent e)
1350 actionListener.actionPerformed(null);
1354 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1356 attCombo.setSelectedIndex(0);
1360 attCombo.setSelectedItem(
1361 FeatureMatcher.toAttributeDisplayName(attName));
1363 attCombo.addItemListener(new ItemListener()
1366 public void itemStateChanged(ItemEvent e)
1369 * on change of attribute, refresh the conditions list to
1370 * ensure it is appropriate for the attribute datatype
1372 populateConditions((String) attCombo.getSelectedItem(),
1373 (Condition) condCombo.getSelectedItem(), condCombo,
1375 actionListener.actionPerformed(null);
1379 filterRow.add(attCombo);
1382 * drop-down choice of test condition
1384 populateConditions(filterBy, cond, condCombo, patternField);
1385 condCombo.setPreferredSize(new Dimension(150, 20));
1386 condCombo.addItemListener(itemListener);
1387 filterRow.add(condCombo);
1390 * pattern to match against
1392 patternField.addActionListener(actionListener);
1393 patternField.addFocusListener(new FocusAdapter()
1396 public void focusLost(FocusEvent e)
1398 actionListener.actionPerformed(null);
1401 filterRow.add(patternField);
1404 * disable pattern field for condition 'Present / NotPresent'
1406 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1407 patternField.setEnabled(selectedCondition.needsAPattern());
1410 * if a numeric condition is selected, show the value range
1411 * as a tooltip on the value input field
1413 setNumericHints(filterBy, selectedCondition, patternField);
1416 * add remove button if filter is populated (non-empty pattern)
1418 if (!patternField.isEnabled()
1419 || (pattern != null && pattern.trim().length() > 0))
1421 JButton removeCondition = new JButton("\u2717"); // Dingbats cursive x
1422 removeCondition.setToolTipText(
1423 MessageManager.getString("label.delete_condition"));
1424 removeCondition.setBorder(new EmptyBorder(0, 0, 0, 0));
1425 removeCondition.addActionListener(new ActionListener()
1428 public void actionPerformed(ActionEvent e)
1430 filters.remove(filterIndex);
1434 filterRow.add(removeCondition);
1441 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1447 private String setSelectedAttribute(JComboBox<String> attCombo,
1448 FeatureMatcherI filter)
1451 if (filter.isByScore())
1455 else if (filter.isByLabel())
1461 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1463 attCombo.setSelectedItem(item);
1468 * If a numeric comparison condition is selected, retrieves the min-max range
1469 * for the value (score or attribute), and sets it as a tooltip on the value
1470 * field. If the field is currently empty, then pre-populates it with
1472 * <li>the minimum value, if condition is > or >=</li>
1473 * <li>the maximum value, if condition is < or <=</li>
1477 * @param selectedCondition
1478 * @param patternField
1480 private void setNumericHints(String attName, Condition selectedCondition,
1481 JTextField patternField)
1483 patternField.setToolTipText("");
1485 if (selectedCondition.isNumeric())
1487 float[] minMax = getMinMax(attName);
1490 String minFormatted = DECFMT_2_2.format(minMax[0]);
1491 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1492 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1493 patternField.setToolTipText(tip);
1494 if (patternField.getText().isEmpty())
1496 if (selectedCondition == Condition.GE
1497 || selectedCondition == Condition.GT)
1499 patternField.setText(minFormatted);
1503 if (selectedCondition == Condition.LE
1504 || selectedCondition == Condition.LT)
1506 patternField.setText(maxFormatted);
1515 * Populates the drop-down list of comparison conditions for the given
1516 * attribute name. The conditions added depend on the datatype of the
1517 * attribute values. The supplied condition is set as the selected item in the
1518 * list, provided it is in the list. If the pattern is now invalid
1519 * (non-numeric pattern for a numeric condition), it is cleared.
1524 * @param patternField
1526 private void populateConditions(String attName, Condition cond,
1527 JComboBox<Condition> condCombo, JTextField patternField)
1529 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1530 FeatureMatcher.fromAttributeDisplayName(attName));
1531 if (LABEL_18N.equals(attName))
1533 type = Datatype.Character;
1535 else if (SCORE_18N.equals(attName))
1537 type = Datatype.Number;
1541 * remove itemListener before starting
1543 ItemListener listener = condCombo.getItemListeners()[0];
1544 condCombo.removeItemListener(listener);
1545 boolean condIsValid = false;
1547 condCombo.removeAllItems();
1548 for (Condition c : Condition.values())
1550 if ((c.isNumeric() && type == Datatype.Number)
1551 || (!c.isNumeric() && type != Datatype.Number))
1553 condCombo.addItem(c);
1562 * set the selected condition (does nothing if not in the list)
1566 condCombo.setSelectedItem(cond);
1570 condCombo.setSelectedIndex(0);
1574 * clear pattern if it is now invalid for condition
1576 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1580 String pattern = patternField.getText().trim();
1581 if (pattern.length() > 0)
1583 Float.valueOf(pattern);
1585 } catch (NumberFormatException e)
1587 patternField.setText("");
1592 * restore the listener
1594 condCombo.addItemListener(listener);
1598 * Answers true unless a numeric condition has been selected with a
1599 * non-numeric value. Sets the value field to RED with a tooltip if in error.
1601 * If the pattern is expected but is empty, this method returns false, but
1602 * does not mark the field as invalid. This supports selecting an attribute
1603 * for a new condition before a match pattern has been entered.
1608 protected boolean validateFilter(JTextField value,
1609 JComboBox<Condition> condCombo)
1611 if (value == null || condCombo == null)
1613 return true; // fields not populated
1616 Condition cond = (Condition) condCombo.getSelectedItem();
1617 if (!cond.needsAPattern())
1622 value.setBackground(Color.white);
1623 value.setToolTipText("");
1624 String v1 = value.getText().trim();
1625 if (v1.length() == 0)
1630 if (cond.isNumeric() && v1.length() > 0)
1635 } catch (NumberFormatException e)
1637 value.setBackground(Color.red);
1638 value.setToolTipText(
1639 MessageManager.getString("label.numeric_required"));
1648 * Constructs a filter condition from the given input fields, and replaces the
1649 * condition at filterIndex with the new one. Does nothing if the pattern
1650 * field is blank (unless the match condition is one that doesn't require a
1651 * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1654 * This method may update the tooltip on the filter value field to show the
1655 * value range, if a numeric condition is selected. This ensures the tooltip
1656 * is updated when a numeric valued attribute is chosen on the last 'add a
1662 * @param filterIndex
1664 protected boolean updateFilter(JComboBox<String> attCombo,
1665 JComboBox<Condition> condCombo, JTextField valueField,
1668 String attName = (String) attCombo.getSelectedItem();
1669 Condition cond = (Condition) condCombo.getSelectedItem();
1670 String pattern = valueField.getText().trim();
1672 setNumericHints(attName, cond, valueField);
1674 if (pattern.length() == 0 && cond.needsAPattern())
1676 valueField.setEnabled(true); // ensure pattern field is enabled!
1681 * Construct a matcher that operates on Label, Score,
1682 * or named attribute
1684 FeatureMatcherI km = null;
1685 if (LABEL_18N.equals(attName))
1687 km = FeatureMatcher.byLabel(cond, pattern);
1689 else if (SCORE_18N.equals(attName))
1691 km = FeatureMatcher.byScore(cond, pattern);
1695 km = FeatureMatcher.byAttribute(cond, pattern,
1696 FeatureMatcher.fromAttributeDisplayName(attName));
1699 filters.set(filterIndex, km);
1705 * Action on any change to feature filtering, namely
1707 * <li>change of selected attribute</li>
1708 * <li>change of selected condition</li>
1709 * <li>change of match pattern</li>
1710 * <li>removal of a condition</li>
1712 * The inputs are parsed into a combined filter and this is set for the
1713 * feature type, and the alignment redrawn.
1715 protected void filtersChanged()
1718 * update the filter conditions for the feature type
1720 boolean anded = andFilters.isSelected();
1721 FeatureMatcherSetI combined = new FeatureMatcherSet();
1723 for (FeatureMatcherI filter : filters)
1725 String pattern = filter.getMatcher().getPattern();
1726 Condition condition = filter.getMatcher().getCondition();
1727 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1731 combined.and(filter);
1735 combined.or(filter);
1741 * save the filter conditions in the FeatureRenderer
1742 * (note this might now be an empty filter with no conditions)
1744 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1745 ap.paintAlignment(true, true);