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.io.gff.SequenceOntologyFactory;
33 import jalview.schemes.FeatureColour;
34 import jalview.util.ColorUtils;
35 import jalview.util.MessageManager;
36 import jalview.util.matcher.Condition;
38 import java.awt.BorderLayout;
39 import java.awt.Color;
40 import java.awt.Dimension;
41 import java.awt.FlowLayout;
42 import java.awt.GridLayout;
43 import java.awt.event.ActionEvent;
44 import java.awt.event.ActionListener;
45 import java.awt.event.FocusAdapter;
46 import java.awt.event.FocusEvent;
47 import java.awt.event.ItemEvent;
48 import java.awt.event.ItemListener;
49 import java.awt.event.MouseAdapter;
50 import java.awt.event.MouseEvent;
51 import java.text.DecimalFormat;
52 import java.util.ArrayList;
53 import java.util.Collections;
54 import java.util.HashMap;
55 import java.util.List;
57 import java.util.Map.Entry;
59 import javax.swing.BorderFactory;
60 import javax.swing.BoxLayout;
61 import javax.swing.ButtonGroup;
62 import javax.swing.JButton;
63 import javax.swing.JCheckBox;
64 import javax.swing.JColorChooser;
65 import javax.swing.JComboBox;
66 import javax.swing.JLabel;
67 import javax.swing.JPanel;
68 import javax.swing.JRadioButton;
69 import javax.swing.JSlider;
70 import javax.swing.JTabbedPane;
71 import javax.swing.JTextField;
72 import javax.swing.SwingConstants;
73 import javax.swing.border.LineBorder;
74 import javax.swing.event.ChangeEvent;
75 import javax.swing.event.ChangeListener;
76 import javax.swing.plaf.basic.BasicArrowButton;
79 * A dialog where the user can configure colour scheme, and any filters, for one
82 * (Was FeatureColourChooser prior to Jalview 1.11, renamed with the addition of
85 public class FeatureTypeSettings extends JalviewDialog
87 private final static String LABEL_18N = MessageManager
88 .getString("label.label");
90 private final static String SCORE_18N = MessageManager
91 .getString("label.score");
93 private static final int RADIO_WIDTH = 130;
95 private static final String COLON = ":";
97 private static final int MAX_TOOLTIP_LENGTH = 50;
99 private static final int NO_COLOUR_OPTION = 0;
101 private static final int MIN_COLOUR_OPTION = 1;
103 private static final int MAX_COLOUR_OPTION = 2;
105 private static final int ABOVE_THRESHOLD_OPTION = 1;
107 private static final int BELOW_THRESHOLD_OPTION = 2;
109 private static final DecimalFormat DECFMT_2_2 = new DecimalFormat(
113 * FeatureRenderer holds colour scheme and filters for feature types
115 private final FeatureRenderer fr; // todo refactor to allow interface type here
118 * the view panel to update when settings change
120 private final AlignmentViewPanel ap;
122 private final String featureType;
125 * the colour and filters to reset to on Cancel
126 * (including feature sub-types if modified)
128 private Map<String, FeatureColourI> originalColours;
130 private Map<String, FeatureMatcherSetI> originalFilters;
133 * set flag to true when setting values programmatically,
134 * to avoid invocation of action handlers
136 private boolean adjusting = false;
139 * minimum of the value range for graduated colour
140 * (may be for feature score or for a numeric attribute)
145 * maximum of the value range for graduated colour
150 * scale factor for conversion between absolute min-max and slider
152 private float scaleFactor;
155 * radio button group, to select what to colour by:
156 * simple colour, by category (text), or graduated
158 private JRadioButton simpleColour = new JRadioButton();
160 private JRadioButton byCategory = new JRadioButton();
162 private JRadioButton graduatedColour = new JRadioButton();
164 private JPanel singleColour = new JPanel();
166 private JPanel minColour = new JPanel();
168 private JPanel maxColour = new JPanel();
170 private JComboBox<String> threshold = new JComboBox<>();
172 private JSlider slider = new JSlider();
174 private JTextField thresholdValue = new JTextField(20);
176 private JCheckBox thresholdIsMin = new JCheckBox();
178 private GraphLine threshline;
180 private ActionListener featureSettings = null;
182 private ActionListener changeColourAction;
185 * choice of option for 'colour for no value'
187 private JComboBox<String> noValueCombo;
190 * choice of what to colour by text (Label or attribute)
192 private JComboBox<String> colourByTextCombo;
195 * choice of what to colour by range (Score or attribute)
197 private JComboBox<String> colourByRangeCombo;
199 private JRadioButton andFilters;
201 private JRadioButton orFilters;
204 * filters for the currently selected feature type
206 private List<FeatureMatcherI> filters;
208 // set white normally, black to debug layout
209 private Color debugBorderColour = Color.white;
211 private JPanel chooseFiltersPanel;
213 private JTabbedPane tabbedPane;
216 * feature types present in Feature Renderer which are
217 * sub-types of the one this editor is acting on
219 private final List<String> subTypes;
222 * if selected, filter settings are also applied to any
223 * feature sub-types in the Sequence Ontology
225 private JCheckBox applyFiltersToSubtypes;
228 * if selected, colour settings are also applied to any
229 * feature sub-types in the Sequence Ontology
231 private JCheckBox applyColourToChildren;
239 public FeatureTypeSettings(FeatureRenderer frender, String theType)
241 this(frender, false, theType);
245 * Constructor, with option to make a blocking dialog (has to complete in the
246 * AWT event queue thread). Currently this option is always set to false.
252 FeatureTypeSettings(FeatureRenderer frender, boolean blocking,
256 this.featureType = theType;
260 * determine sub-types (if any) of this feature type
262 List<String> types = fr.getRenderOrder();
263 subTypes = SequenceOntologyFactory.getInstance()
264 .getChildTerms(this.featureType, types);
265 Collections.sort(subTypes); // sort for ease of reading in tooltip
268 * save original colours and filters for this feature type
269 * and any sub-types, to restore on Cancel
271 originalFilters = new HashMap<>();
272 originalFilters.put(theType, fr.getFeatureFilter(theType));
273 originalColours = new HashMap<>();
274 originalColours.put(theType, fr.getFeatureColours().get(theType));
275 for (String child : subTypes)
277 originalFilters.put(child, fr.getFeatureFilter(child));
278 originalColours.put(child, fr.getFeatureColours().get(child));
286 } catch (Exception ex)
288 ex.printStackTrace();
298 colourChanged(false);
300 String title = MessageManager
301 .formatMessage("label.display_settings_for", new String[]
303 initDialogFrame(this, true, blocking, title, 600, 360);
309 * Configures the widgets on the Colours tab according to the current feature
312 private void updateColoursTab()
314 FeatureColourI fc = fr.getFeatureColours().get(featureType);
317 * suppress action handling while updating values programmatically
325 if (fc.isSimpleColour())
327 simpleColour.setSelected(true);
328 singleColour.setBackground(fc.getColour());
329 singleColour.setForeground(fc.getColour());
333 * colour by text (Label or attribute text)
335 if (fc.isColourByLabel())
337 byCategory.setSelected(true);
338 colourByTextCombo.setEnabled(colourByTextCombo.getItemCount() > 1);
339 if (fc.isColourByAttribute())
341 String[] attributeName = fc.getAttributeName();
342 colourByTextCombo.setSelectedItem(
343 FeatureMatcher.toAttributeDisplayName(attributeName));
347 colourByTextCombo.setSelectedItem(LABEL_18N);
352 colourByTextCombo.setEnabled(false);
355 if (!fc.isGraduatedColour())
357 colourByRangeCombo.setEnabled(false);
358 minColour.setEnabled(false);
359 maxColour.setEnabled(false);
360 noValueCombo.setEnabled(false);
361 threshold.setEnabled(false);
362 slider.setEnabled(false);
363 thresholdValue.setEnabled(false);
364 thresholdIsMin.setEnabled(false);
369 * Graduated colour, by score or attribute value range
371 graduatedColour.setSelected(true);
372 updateColourMinMax(); // ensure min, max are set
373 colourByRangeCombo.setEnabled(colourByRangeCombo.getItemCount() > 1);
374 minColour.setEnabled(true);
375 maxColour.setEnabled(true);
376 noValueCombo.setEnabled(true);
377 threshold.setEnabled(true);
378 minColour.setBackground(fc.getMinColour());
379 maxColour.setBackground(fc.getMaxColour());
381 if (fc.isColourByAttribute())
383 String[] attributeName = fc.getAttributeName();
384 colourByRangeCombo.setSelectedItem(
385 FeatureMatcher.toAttributeDisplayName(attributeName));
389 colourByRangeCombo.setSelectedItem(SCORE_18N);
391 Color noColour = fc.getNoColour();
392 if (noColour == null)
394 noValueCombo.setSelectedIndex(NO_COLOUR_OPTION);
396 else if (noColour.equals(fc.getMinColour()))
398 noValueCombo.setSelectedIndex(MIN_COLOUR_OPTION);
400 else if (noColour.equals(fc.getMaxColour()))
402 noValueCombo.setSelectedIndex(MAX_COLOUR_OPTION);
406 * update min-max scaling if there is a range to work with,
407 * else disable the widgets (this shouldn't happen if only
408 * valid options are offered in the combo box)
410 scaleFactor = (max == min) ? 1f : 100f / (max - min);
411 float range = (max - min) * scaleFactor;
412 slider.setMinimum((int) (min * scaleFactor));
413 slider.setMaximum((int) (max * scaleFactor));
414 slider.setMajorTickSpacing((int) (range / 10f));
416 threshline = new GraphLine((max - min) / 2f, "Threshold",
418 threshline.value = fc.getThreshold();
420 if (fc.hasThreshold())
422 threshold.setSelectedIndex(
423 fc.isAboveThreshold() ? ABOVE_THRESHOLD_OPTION
424 : BELOW_THRESHOLD_OPTION);
425 slider.setEnabled(true);
426 slider.setValue((int) (fc.getThreshold() * scaleFactor));
427 thresholdValue.setText(String.valueOf(getRoundedSliderValue()));
428 thresholdValue.setEnabled(true);
429 thresholdIsMin.setEnabled(true);
433 slider.setEnabled(false);
434 thresholdValue.setEnabled(false);
435 thresholdIsMin.setEnabled(false);
437 thresholdIsMin.setSelected(!fc.isAutoScaled());
445 * Configures the initial layout
447 private void initialise()
449 this.setLayout(new BorderLayout());
450 tabbedPane = new JTabbedPane();
451 this.add(tabbedPane, BorderLayout.CENTER);
454 * an ActionListener that applies colour changes
456 changeColourAction = new ActionListener()
459 public void actionPerformed(ActionEvent e)
466 * first tab: colour options
468 JPanel coloursPanel = initialiseColoursPanel();
469 tabbedPane.addTab(MessageManager.getString("action.colour"),
473 * second tab: filter options
475 JPanel filtersPanel = initialiseFiltersPanel();
476 tabbedPane.addTab(MessageManager.getString("label.filters"),
479 JPanel okCancelPanel = initialiseOkCancelPanel();
481 this.add(okCancelPanel, BorderLayout.SOUTH);
485 * Updates the min-max range if Colour By selected item is Score, or an
486 * attribute, with a min-max range
488 protected void updateColourMinMax()
490 if (!graduatedColour.isSelected())
495 String colourBy = (String) colourByRangeCombo.getSelectedItem();
496 float[] minMax = getMinMax(colourBy);
506 * Retrieves the min-max range:
508 * <li>of feature score, if colour or filter is by Score</li>
509 * <li>else of the selected attribute</li>
515 private float[] getMinMax(String attName)
517 float[] minMax = null;
518 if (SCORE_18N.equals(attName))
520 minMax = fr.getMinMax().get(featureType)[0];
524 // colour by attribute range
525 minMax = FeatureAttributes.getInstance().getMinMax(featureType,
526 FeatureMatcher.fromAttributeDisplayName(attName));
532 * Lay out fields for graduated colour (by score or attribute value)
536 private JPanel initialiseGraduatedColourPanel()
538 JPanel graduatedColourPanel = new JPanel();
539 graduatedColourPanel.setLayout(
540 new BoxLayout(graduatedColourPanel, BoxLayout.Y_AXIS));
541 JvSwingUtils.createTitledBorder(graduatedColourPanel,
542 MessageManager.getString("label.graduated_colour"), true);
543 graduatedColourPanel.setBackground(Color.white);
546 * first row: graduated colour radio button, score/attribute drop-down
548 JPanel graduatedChoicePanel = new JPanel(
549 new FlowLayout(FlowLayout.LEFT));
550 graduatedChoicePanel.setBackground(Color.white);
551 graduatedColour = new JRadioButton(
552 MessageManager.getString("label.by_range_of") + COLON);
553 graduatedColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
554 graduatedColour.addItemListener(new ItemListener()
557 public void itemStateChanged(ItemEvent e)
559 if (graduatedColour.isSelected())
565 graduatedChoicePanel.add(graduatedColour);
567 List<String[]> attNames = FeatureAttributes.getInstance()
568 .getAttributes(featureType);
569 colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
570 colourByRangeCombo.addItemListener(new ItemListener()
573 public void itemStateChanged(ItemEvent e)
580 * disable graduated colour option if no range found
582 graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
584 graduatedChoicePanel.add(colourByRangeCombo);
585 graduatedColourPanel.add(graduatedChoicePanel);
588 * second row - min/max/no colours
590 JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
591 colourRangePanel.setBackground(Color.white);
592 graduatedColourPanel.add(colourRangePanel);
594 minColour.setFont(JvSwingUtils.getLabelFont());
595 minColour.setBorder(BorderFactory.createLineBorder(Color.black));
596 minColour.setPreferredSize(new Dimension(40, 20));
597 minColour.setToolTipText(MessageManager.getString("label.min_colour"));
598 minColour.addMouseListener(new MouseAdapter()
601 public void mousePressed(MouseEvent e)
603 if (minColour.isEnabled())
605 showColourChooser(minColour, "label.select_colour_minimum_value");
610 maxColour.setFont(JvSwingUtils.getLabelFont());
611 maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
612 maxColour.setPreferredSize(new Dimension(40, 20));
613 maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
614 maxColour.addMouseListener(new MouseAdapter()
617 public void mousePressed(MouseEvent e)
619 if (maxColour.isEnabled())
621 showColourChooser(maxColour, "label.select_colour_maximum_value");
625 maxColour.setBorder(new LineBorder(Color.black));
628 * default max colour to current colour (if a plain colour),
629 * or to Black if colour by label; make min colour a pale
630 * version of max colour
632 FeatureColourI fc = fr.getFeatureColours().get(featureType);
633 Color bg = fc.isSimpleColour() ? fc.getColour() : Color.BLACK;
634 maxColour.setBackground(bg);
635 minColour.setBackground(ColorUtils.bleachColour(bg, 0.9f));
637 noValueCombo = new JComboBox<>();
638 noValueCombo.addItem(MessageManager.getString("label.no_colour"));
639 noValueCombo.addItem(MessageManager.getString("label.min_colour"));
640 noValueCombo.addItem(MessageManager.getString("label.max_colour"));
641 noValueCombo.addItemListener(new ItemListener()
644 public void itemStateChanged(ItemEvent e)
650 JLabel minText = new JLabel(
651 MessageManager.getString("label.min_value") + COLON);
652 minText.setFont(JvSwingUtils.getLabelFont());
653 JLabel maxText = new JLabel(
654 MessageManager.getString("label.max_value") + COLON);
655 maxText.setFont(JvSwingUtils.getLabelFont());
656 JLabel noText = new JLabel(
657 MessageManager.getString("label.no_value") + COLON);
658 noText.setFont(JvSwingUtils.getLabelFont());
660 colourRangePanel.add(minText);
661 colourRangePanel.add(minColour);
662 colourRangePanel.add(maxText);
663 colourRangePanel.add(maxColour);
664 colourRangePanel.add(noText);
665 colourRangePanel.add(noValueCombo);
668 * third row - threshold options and value
670 JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
671 thresholdPanel.setBackground(Color.white);
672 graduatedColourPanel.add(thresholdPanel);
674 threshold.addActionListener(changeColourAction);
675 threshold.setToolTipText(MessageManager
676 .getString("label.threshold_feature_display_by_score"));
677 threshold.addItem(MessageManager
678 .getString("label.threshold_feature_no_threshold")); // index 0
679 threshold.addItem(MessageManager
680 .getString("label.threshold_feature_above_threshold")); // index 1
681 threshold.addItem(MessageManager
682 .getString("label.threshold_feature_below_threshold")); // index 2
684 thresholdValue.addActionListener(new ActionListener()
687 public void actionPerformed(ActionEvent e)
689 thresholdValue_actionPerformed();
692 thresholdValue.addFocusListener(new FocusAdapter()
695 public void focusLost(FocusEvent e)
697 thresholdValue_actionPerformed();
700 slider.setPaintLabels(false);
701 slider.setPaintTicks(true);
702 slider.setBackground(Color.white);
703 slider.setEnabled(false);
704 slider.setOpaque(false);
705 slider.setPreferredSize(new Dimension(100, 32));
706 slider.setToolTipText(
707 MessageManager.getString("label.adjust_threshold"));
709 slider.addChangeListener(new ChangeListener()
712 public void stateChanged(ChangeEvent evt)
717 .setText(String.valueOf(slider.getValue() / scaleFactor));
718 sliderValueChanged();
722 slider.addMouseListener(new MouseAdapter()
725 public void mouseReleased(MouseEvent evt)
728 * only update Overview and/or structure colouring
729 * when threshold slider drag ends (mouse up)
733 ap.paintAlignment(true, true);
738 thresholdValue.setEnabled(false);
739 thresholdValue.setColumns(7);
741 thresholdPanel.add(threshold);
742 thresholdPanel.add(slider);
743 thresholdPanel.add(thresholdValue);
745 thresholdIsMin.setBackground(Color.white);
747 .setText(MessageManager.getString("label.threshold_minmax"));
748 thresholdIsMin.setToolTipText(MessageManager
749 .getString("label.toggle_absolute_relative_display_threshold"));
750 thresholdIsMin.addActionListener(changeColourAction);
751 thresholdPanel.add(thresholdIsMin);
753 return graduatedColourPanel;
757 * Lay out OK and Cancel buttons
761 private JPanel initialiseOkCancelPanel()
763 JPanel okCancelPanel = new JPanel();
764 // okCancelPanel.setBackground(Color.white);
765 okCancelPanel.add(ok);
766 okCancelPanel.add(cancel);
767 return okCancelPanel;
771 * Lay out Colour options panel, containing
773 * <li>plain colour, with colour picker</li>
774 * <li>colour by text, with choice of Label or other attribute</li>
775 * <li>colour by range, of score or other attribute, when available</li>
780 private JPanel initialiseColoursPanel()
782 JPanel colourByPanel = new JPanel();
783 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
786 * simple colour radio button and colour picker
788 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
789 simpleColourPanel.setBackground(Color.white);
790 JvSwingUtils.createTitledBorder(simpleColourPanel,
791 MessageManager.getString("label.simple"), true);
792 colourByPanel.add(simpleColourPanel);
794 simpleColour = new JRadioButton(
795 MessageManager.getString("label.simple_colour"));
796 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
797 simpleColour.addItemListener(new ItemListener()
800 public void itemStateChanged(ItemEvent e)
802 if (simpleColour.isSelected() && !adjusting)
804 showColourChooser(singleColour, "label.select_colour");
810 singleColour.setFont(JvSwingUtils.getLabelFont());
811 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
812 singleColour.setPreferredSize(new Dimension(40, 20));
813 singleColour.addMouseListener(new MouseAdapter()
816 public void mousePressed(MouseEvent e)
818 if (simpleColour.isSelected())
820 showColourChooser(singleColour, "label.select_colour");
824 simpleColourPanel.add(simpleColour); // radio button
825 simpleColourPanel.add(singleColour); // colour picker button
828 * colour by text (category) radio button and drop-down choice list
830 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
831 byTextPanel.setBackground(Color.white);
832 JvSwingUtils.createTitledBorder(byTextPanel,
833 MessageManager.getString("label.colour_by_text"), true);
834 colourByPanel.add(byTextPanel);
835 byCategory = new JRadioButton(
836 MessageManager.getString("label.by_text_of") + COLON);
837 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
838 byCategory.addItemListener(new ItemListener()
841 public void itemStateChanged(ItemEvent e)
843 if (byCategory.isSelected())
849 byTextPanel.add(byCategory);
851 List<String[]> attNames = FeatureAttributes.getInstance()
852 .getAttributes(featureType);
853 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
854 colourByTextCombo.addItemListener(new ItemListener()
857 public void itemStateChanged(ItemEvent e)
862 byTextPanel.add(colourByTextCombo);
865 * graduated colour panel
867 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
868 colourByPanel.add(graduatedColourPanel);
871 * 3 radio buttons select between simple colour,
872 * by category (text), or graduated
874 ButtonGroup bg = new ButtonGroup();
875 bg.add(simpleColour);
877 bg.add(graduatedColour);
879 return colourByPanel;
882 private void showColourChooser(JPanel colourPanel, String key)
884 Color col = JColorChooser.showDialog(this,
885 MessageManager.getString(key), colourPanel.getBackground());
888 colourPanel.setBackground(col);
889 colourPanel.setForeground(col);
891 colourPanel.repaint();
896 * Constructs and sets the selected colour options as the colour for the feature
897 * type, and repaints the alignment, and optionally the Overview and/or
898 * structure viewer if open
900 * @param updateStructsAndOverview
902 void colourChanged(boolean updateStructsAndOverview)
907 * ignore action handlers while setting values programmatically
913 * ensure min-max range is for the latest choice of
914 * 'graduated colour by'
916 updateColourMinMax();
918 FeatureColourI acg = makeColourFromInputs();
921 * save the colour, and repaint stuff
923 fr.setColour(featureType, acg);
924 refreshFeatureSettings();
925 ap.paintAlignment(updateStructsAndOverview, updateStructsAndOverview);
931 * Converts the input values into an instance of FeatureColour
935 private FeatureColourI makeColourFromInputs()
938 * easiest case - a single colour
940 if (simpleColour.isSelected())
942 return new FeatureColour(singleColour.getBackground());
946 * next easiest case - colour by Label, or attribute text
948 if (byCategory.isSelected())
950 Color c = this.getBackground();
951 FeatureColourI fc = new FeatureColour(c, c, null, 0f, 0f);
952 fc.setColourByLabel(true);
953 String byWhat = (String) colourByTextCombo.getSelectedItem();
954 if (!LABEL_18N.equals(byWhat))
957 FeatureMatcher.fromAttributeDisplayName(byWhat));
963 * remaining case - graduated colour by score, or attribute value
965 Color noColour = null;
966 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
968 noColour = minColour.getBackground();
970 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
972 noColour = maxColour.getBackground();
978 thresh = Float.valueOf(thresholdValue.getText());
979 } catch (NumberFormatException e)
981 // invalid inputs are already handled on entry
985 * min-max range is to (or from) threshold value if
986 * 'threshold is min/max' is selected
988 float minValue = min;
989 float maxValue = max;
990 final int thresholdOption = threshold.getSelectedIndex();
991 if (thresholdIsMin.isSelected()
992 && thresholdOption == ABOVE_THRESHOLD_OPTION)
996 if (thresholdIsMin.isSelected()
997 && thresholdOption == BELOW_THRESHOLD_OPTION)
1003 * make the graduated colour
1005 FeatureColourI fc = new FeatureColour(minColour.getBackground(),
1006 maxColour.getBackground(), noColour, minValue, maxValue);
1009 * set attribute to colour by if selected
1011 String byWhat = (String) colourByRangeCombo.getSelectedItem();
1012 if (!SCORE_18N.equals(byWhat))
1014 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
1018 * set threshold options and 'autoscaled' which is
1019 * false if 'threshold is min/max' is selected
1020 * else true (colour range is on actual range of values)
1022 fc.setThreshold(thresh);
1023 fc.setAutoScaled(!thresholdIsMin.isSelected());
1024 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
1025 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
1027 if (threshline == null)
1030 * todo not yet implemented: visual indication of feature threshold
1032 threshline = new GraphLine((max - min) / 2f, "Threshold",
1040 protected void raiseClosed()
1042 refreshFeatureSettings();
1045 protected void refreshFeatureSettings()
1047 if (this.featureSettings != null)
1049 featureSettings.actionPerformed(new ActionEvent(this, 0, "REFRESH"));
1054 * Action on OK is just to dismiss the dialog - any changes have already been
1058 public void okPressed()
1063 * Action on Cancel is to restore colour scheme and filters as they were when
1064 * the dialog was opened (including any feature sub-types that may have been
1068 public void cancelPressed()
1070 for (Entry<String, FeatureColourI> entry : originalColours.entrySet())
1072 fr.setColour(entry.getKey(), entry.getValue());
1074 for (Entry<String, FeatureMatcherSetI> entry : originalFilters
1077 fr.setFeatureFilter(entry.getKey(), entry.getValue());
1080 ap.paintAlignment(true, true);
1084 * Action on text entry of a threshold value
1086 protected void thresholdValue_actionPerformed()
1091 float f = Float.parseFloat(thresholdValue.getText());
1092 slider.setValue((int) (f * scaleFactor));
1093 threshline.value = f;
1094 thresholdValue.setBackground(Color.white); // ok
1097 * force repaint of any Overview window or structure
1099 ap.paintAlignment(true, true);
1100 } catch (NumberFormatException ex)
1102 thresholdValue.setBackground(Color.red); // not ok
1110 * Action on change of threshold slider value. This may be done interactively
1111 * (by moving the slider), or programmatically (to update the slider after
1112 * manual input of a threshold value).
1114 protected void sliderValueChanged()
1116 threshline.value = getRoundedSliderValue();
1119 * repaint alignment, but not Overview or structure,
1120 * to avoid overload while dragging the slider
1122 colourChanged(false);
1126 * Converts the slider value to its absolute value by dividing by the
1127 * scaleFactor. Rounding errors are squashed by forcing min/max of slider range
1128 * to the actual min/max of feature score range
1132 private float getRoundedSliderValue()
1134 int value = slider.getValue();
1135 float f = value == slider.getMaximum() ? max
1136 : (value == slider.getMinimum() ? min : value / scaleFactor);
1140 void addActionListener(ActionListener listener)
1142 if (featureSettings != null)
1145 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1147 featureSettings = listener;
1151 * A helper method to build the drop-down choice of attributes for a feature. If
1152 * 'withRange' is true, then Score, and any attributes with a min-max range, are
1153 * added. If 'withText' is true, Label and any known attributes are added. This
1154 * allows 'categorical numerical' attributes e.g. codon position to be coloured
1157 * Where metadata is available with a description for an attribute, that is
1158 * added as a tooltip.
1160 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1161 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1163 * This method does not add any ActionListener to the JComboBox.
1169 protected JComboBox<String> populateAttributesDropdown(
1170 List<String[]> attNames, boolean withRange, boolean withText)
1172 List<String> displayAtts = new ArrayList<>();
1173 List<String> tooltips = new ArrayList<>();
1177 displayAtts.add(LABEL_18N);
1178 tooltips.add(MessageManager.getString("label.description"));
1182 float[][] minMax = fr.getMinMax().get(featureType);
1183 if (minMax != null && minMax[0][0] != minMax[0][1])
1185 displayAtts.add(SCORE_18N);
1186 tooltips.add(SCORE_18N);
1190 FeatureAttributes fa = FeatureAttributes.getInstance();
1191 for (String[] attName : attNames)
1193 float[] minMax = fa.getMinMax(featureType, attName);
1194 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1195 if (!withText && !hasRange)
1199 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1200 String desc = fa.getDescription(featureType, attName);
1201 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1203 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1205 tooltips.add(desc == null ? "" : desc);
1208 JComboBox<String> attCombo = JvSwingUtils
1209 .buildComboWithTooltips(displayAtts, tooltips);
1215 * Populates initial layout of the feature attribute filters panel
1217 private JPanel initialiseFiltersPanel()
1219 filters = new ArrayList<>();
1221 JPanel filtersPanel = new JPanel();
1222 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1223 filtersPanel.setBackground(Color.white);
1224 JvSwingUtils.createTitledBorder(filtersPanel,
1225 MessageManager.getString("label.filters"), true);
1227 JPanel andOrPanel = initialiseAndOrPanel();
1228 filtersPanel.add(andOrPanel);
1231 * panel with filters - populated by refreshFiltersDisplay,
1232 * which also sets the layout manager
1234 chooseFiltersPanel = new JPanel();
1235 chooseFiltersPanel.setBackground(Color.white);
1236 filtersPanel.add(chooseFiltersPanel);
1238 return filtersPanel;
1242 * Lays out the panel with radio buttons to AND or OR filter conditions
1246 private JPanel initialiseAndOrPanel()
1248 JPanel andOrPanel = new JPanel(new BorderLayout());
1249 andOrPanel.setBackground(Color.white);
1250 JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
1251 andOrPanel.add(panel1, BorderLayout.WEST);
1252 panel1.setBackground(Color.white);
1253 panel1.setBorder(BorderFactory.createLineBorder(debugBorderColour));
1254 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1255 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1256 ActionListener actionListener = new ActionListener()
1259 public void actionPerformed(ActionEvent e)
1264 andFilters.addActionListener(actionListener);
1265 orFilters.addActionListener(actionListener);
1266 ButtonGroup andOr = new ButtonGroup();
1267 andOr.add(andFilters);
1268 andOr.add(orFilters);
1269 andFilters.setSelected(true);
1271 new JLabel(MessageManager.getString("label.join_conditions")));
1272 panel1.add(andFilters);
1273 panel1.add(orFilters);
1276 * add an 'Apply to child terms' checkbox if there are any child terms
1278 applyFiltersToSubtypes = new JCheckBox("Apply also to child terms");
1279 if (!subTypes.isEmpty())
1281 JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
1282 panel2.setBackground(Color.white);
1283 andOrPanel.add(panel2, BorderLayout.EAST);
1284 StringBuilder sb = new StringBuilder(20 * subTypes.size());
1285 sb.append("Apply filters also to child terms" + ":"); // todo i18n
1286 for (String child : subTypes)
1288 sb.append("<br>").append(child);
1290 String tooltip = JvSwingUtils.wrapTooltip(true, sb.toString());
1291 applyFiltersToSubtypes.setToolTipText(tooltip);
1292 panel2.add(applyFiltersToSubtypes);
1299 * Refreshes the display to show any filters currently configured for the
1300 * selected feature type (editable, with 'remove' option), plus one extra row
1301 * for adding a condition. This should be called after a filter has been
1302 * removed, added or amended.
1304 private void updateFiltersTab()
1307 * clear the panel and list of filter conditions
1309 chooseFiltersPanel.removeAll();
1313 * look up attributes known for feature type
1315 List<String[]> attNames = FeatureAttributes.getInstance()
1316 .getAttributes(featureType);
1319 * if this feature type has filters set, load them first
1321 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1322 if (featureFilters != null)
1324 if (!featureFilters.isAnded())
1326 orFilters.setSelected(true);
1328 featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1332 * and an empty filter for the user to populate (add)
1334 filters.add(FeatureMatcher.NULL_MATCHER);
1337 * use GridLayout to 'justify' rows to the top of the panel, until
1338 * there are too many to fit in, then fall back on BoxLayout
1340 if (filters.size() <= 5)
1342 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1346 chooseFiltersPanel.setLayout(
1347 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1351 * render the conditions in rows, each in its own JPanel
1353 int filterIndex = 0;
1354 for (FeatureMatcherI filter : filters)
1356 JPanel row = addFilter(filter, attNames, filterIndex);
1357 row.setBorder(BorderFactory.createLineBorder(debugBorderColour));
1358 chooseFiltersPanel.add(row);
1367 * A helper method that constructs a row (panel) with one filter condition:
1369 * <li>a drop-down list of Label, Score and attribute names to choose from</li>
1370 * <li>a drop-down list of conditions to choose from</li>
1371 * <li>a text field for input of a match pattern</li>
1372 * <li>optionally, a 'remove' button</li>
1374 * The filter values are set as defaults for the input fields. The 'remove'
1375 * button is added unless the pattern is empty (incomplete filter condition).
1377 * Action handlers on these fields provide for
1379 * <li>validate pattern field - should be numeric if condition is numeric</li>
1380 * <li>save filters and refresh display on any (valid) change</li>
1381 * <li>remove filter and refresh on 'Remove'</li>
1382 * <li>update conditions list on change of Label/Score/Attribute</li>
1383 * <li>refresh value field tooltip with min-max range on change of
1389 * @param filterIndex
1392 protected JPanel addFilter(FeatureMatcherI filter,
1393 List<String[]> attNames, int filterIndex)
1395 String[] attName = filter.getAttribute();
1396 Condition cond = filter.getMatcher().getCondition();
1397 String pattern = filter.getMatcher().getPattern();
1399 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1400 filterRow.setBackground(Color.white);
1403 * drop-down choice of attribute, with description as a tooltip
1404 * if we can obtain it
1406 final JComboBox<String> attCombo = populateAttributesDropdown(attNames,
1408 String filterBy = setSelectedAttribute(attCombo, filter);
1410 JComboBox<Condition> condCombo = new JComboBox<>();
1412 JTextField patternField = new JTextField(8);
1413 patternField.setText(pattern);
1416 * action handlers that validate and (if valid) apply changes
1418 ActionListener actionListener = new ActionListener()
1421 public void actionPerformed(ActionEvent e)
1423 if (validateFilter(patternField, condCombo))
1425 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1432 ItemListener itemListener = new ItemListener()
1435 public void itemStateChanged(ItemEvent e)
1437 actionListener.actionPerformed(null);
1441 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1443 attCombo.setSelectedIndex(0);
1447 attCombo.setSelectedItem(
1448 FeatureMatcher.toAttributeDisplayName(attName));
1450 attCombo.addItemListener(new ItemListener()
1453 public void itemStateChanged(ItemEvent e)
1456 * on change of attribute, refresh the conditions list to
1457 * ensure it is appropriate for the attribute datatype
1459 populateConditions((String) attCombo.getSelectedItem(),
1460 (Condition) condCombo.getSelectedItem(), condCombo,
1462 actionListener.actionPerformed(null);
1466 filterRow.add(attCombo);
1469 * drop-down choice of test condition
1471 populateConditions(filterBy, cond, condCombo, patternField);
1472 condCombo.setPreferredSize(new Dimension(150, 20));
1473 condCombo.addItemListener(itemListener);
1474 filterRow.add(condCombo);
1477 * pattern to match against
1479 patternField.addActionListener(actionListener);
1480 patternField.addFocusListener(new FocusAdapter()
1483 public void focusLost(FocusEvent e)
1485 actionListener.actionPerformed(null);
1488 filterRow.add(patternField);
1491 * disable pattern field for condition 'Present / NotPresent'
1493 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1494 patternField.setEnabled(selectedCondition.needsAPattern());
1497 * if a numeric condition is selected, show the value range
1498 * as a tooltip on the value input field
1500 setNumericHints(filterBy, selectedCondition, patternField);
1503 * add remove button if filter is populated (non-empty pattern)
1505 if (!patternField.isEnabled()
1506 || (pattern != null && pattern.trim().length() > 0))
1508 // todo: gif for button drawing '-' or 'x'
1509 JButton removeCondition = new BasicArrowButton(SwingConstants.WEST);
1511 .setToolTipText(MessageManager.getString("label.delete_row"));
1512 removeCondition.addActionListener(new ActionListener()
1515 public void actionPerformed(ActionEvent e)
1517 filters.remove(filterIndex);
1521 filterRow.add(removeCondition);
1528 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1534 private String setSelectedAttribute(JComboBox<String> attCombo,
1535 FeatureMatcherI filter)
1538 if (filter.isByScore())
1542 else if (filter.isByLabel())
1548 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1550 attCombo.setSelectedItem(item);
1555 * If a numeric comparison condition is selected, retrieves the min-max range
1556 * for the value (score or attribute), and sets it as a tooltip on the value
1557 * field. If the field is currently empty, then pre-populates it with
1559 * <li>the minimum value, if condition is > or >=</li>
1560 * <li>the maximum value, if condition is < or <=</li>
1564 * @param selectedCondition
1565 * @param patternField
1567 private void setNumericHints(String attName,
1568 Condition selectedCondition, JTextField patternField)
1570 patternField.setToolTipText("");
1572 if (selectedCondition.isNumeric())
1574 float[] minMax = getMinMax(attName);
1577 String minFormatted = DECFMT_2_2.format(minMax[0]);
1578 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1579 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1580 patternField.setToolTipText(tip);
1581 if (patternField.getText().isEmpty())
1583 if (selectedCondition == Condition.GE
1584 || selectedCondition == Condition.GT)
1586 patternField.setText(minFormatted);
1590 if (selectedCondition == Condition.LE
1591 || selectedCondition == Condition.LT)
1593 patternField.setText(maxFormatted);
1602 * Populates the drop-down list of comparison conditions for the given attribute
1603 * name. The conditions added depend on the datatype of the attribute values.
1604 * The supplied condition is set as the selected item in the list, provided it
1605 * is in the list. If the pattern is now invalid (non-numeric pattern for a
1606 * numeric condition), it is cleared.
1611 * @param patternField
1613 private void populateConditions(String attName, Condition cond,
1614 JComboBox<Condition> condCombo, JTextField patternField)
1616 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1617 FeatureMatcher.fromAttributeDisplayName(attName));
1618 if (LABEL_18N.equals(attName))
1620 type = Datatype.Character;
1622 else if (SCORE_18N.equals(attName))
1624 type = Datatype.Number;
1628 * remove itemListener before starting
1630 ItemListener listener = condCombo.getItemListeners()[0];
1631 condCombo.removeItemListener(listener);
1632 boolean condIsValid = false;
1634 condCombo.removeAllItems();
1635 for (Condition c : Condition.values())
1637 if ((c.isNumeric() && type == Datatype.Number)
1638 || (!c.isNumeric() && type != Datatype.Number))
1640 condCombo.addItem(c);
1649 * set the selected condition (does nothing if not in the list)
1653 condCombo.setSelectedItem(cond);
1657 condCombo.setSelectedIndex(0);
1661 * clear pattern if it is now invalid for condition
1663 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1667 String pattern = patternField.getText().trim();
1668 if (pattern.length() > 0)
1670 Float.valueOf(pattern);
1672 } catch (NumberFormatException e)
1674 patternField.setText("");
1679 * restore the listener
1681 condCombo.addItemListener(listener);
1685 * Answers true unless a numeric condition has been selected with a non-numeric
1686 * value. Sets the value field to RED with a tooltip if in error.
1688 * If the pattern is expected but is empty, this method returns false, but does
1689 * not mark the field as invalid. This supports selecting an attribute for a new
1690 * condition before a match pattern has been entered.
1695 protected boolean validateFilter(JTextField value,
1696 JComboBox<Condition> condCombo)
1698 if (value == null || condCombo == null)
1700 return true; // fields not populated
1703 Condition cond = (Condition) condCombo.getSelectedItem();
1704 if (!cond.needsAPattern())
1709 value.setBackground(Color.white);
1710 value.setToolTipText("");
1711 String v1 = value.getText().trim();
1712 if (v1.length() == 0)
1717 if (cond.isNumeric() && v1.length() > 0)
1722 } catch (NumberFormatException e)
1724 value.setBackground(Color.red);
1725 value.setToolTipText(
1726 MessageManager.getString("label.numeric_required"));
1735 * Constructs a filter condition from the given input fields, and replaces the
1736 * condition at filterIndex with the new one. Does nothing if the pattern field
1737 * is blank (unless the match condition is one that doesn't require a pattern,
1738 * e.g. 'Is present'). Answers true if the filter was updated, else false.
1740 * This method may update the tooltip on the filter value field to show the
1741 * value range, if a numeric condition is selected. This ensures the tooltip is
1742 * updated when a numeric valued attribute is chosen on the last 'add a filter'
1748 * @param filterIndex
1750 protected boolean updateFilter(JComboBox<String> attCombo,
1751 JComboBox<Condition> condCombo, JTextField valueField,
1754 String attName = (String) attCombo.getSelectedItem();
1755 Condition cond = (Condition) condCombo.getSelectedItem();
1756 String pattern = valueField.getText().trim();
1758 setNumericHints(attName, cond, valueField);
1760 if (pattern.length() == 0 && cond.needsAPattern())
1762 valueField.setEnabled(true); // ensure pattern field is enabled!
1767 * Construct a matcher that operates on Label, Score,
1768 * or named attribute
1770 FeatureMatcherI km = null;
1771 if (LABEL_18N.equals(attName))
1773 km = FeatureMatcher.byLabel(cond, pattern);
1775 else if (SCORE_18N.equals(attName))
1777 km = FeatureMatcher.byScore(cond, pattern);
1781 km = FeatureMatcher.byAttribute(cond, pattern,
1782 FeatureMatcher.fromAttributeDisplayName(attName));
1785 filters.set(filterIndex, km);
1791 * Makes the dialog visible, at the Feature Colour tab or at the Filters tab
1795 public void showTab(boolean coloursTab)
1798 tabbedPane.setSelectedIndex(coloursTab ? 0 : 1);
1802 * Action on any change to feature filtering, namely
1804 * <li>change of selected attribute</li>
1805 * <li>change of selected condition</li>
1806 * <li>change of match pattern</li>
1807 * <li>removal of a condition</li>
1809 * The inputs are parsed into a combined filter and this is set for the feature
1810 * type, and the alignment redrawn.
1812 protected void filtersChanged()
1815 * update the filter conditions for the feature type
1817 boolean anded = andFilters.isSelected();
1818 FeatureMatcherSetI combined = new FeatureMatcherSet();
1820 for (FeatureMatcherI filter : filters)
1822 String pattern = filter.getMatcher().getPattern();
1823 Condition condition = filter.getMatcher().getCondition();
1824 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1828 combined.and(filter);
1832 combined.or(filter);
1838 * save the filter conditions in the FeatureRenderer
1839 * (note this might now be an empty filter with no conditions)
1841 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1842 if (applyFiltersToSubtypes.isSelected())
1844 for (String child : subTypes)
1846 fr.setFeatureFilter(child, combined.isEmpty() ? null : combined);
1850 refreshFeatureSettings();
1851 ap.paintAlignment(true, true);