2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.api.AlignViewportI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.api.FeatureColourI;
26 import jalview.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.io.gff.SequenceOntologyFactory;
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.Collections;
55 import java.util.HashMap;
56 import java.util.List;
58 import java.util.Map.Entry;
60 import javax.swing.BorderFactory;
61 import javax.swing.BoxLayout;
62 import javax.swing.ButtonGroup;
63 import javax.swing.JButton;
64 import javax.swing.JCheckBox;
65 import javax.swing.JColorChooser;
66 import javax.swing.JComboBox;
67 import javax.swing.JLabel;
68 import javax.swing.JPanel;
69 import javax.swing.JRadioButton;
70 import javax.swing.JSlider;
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
119 * the view panel to update when settings change
121 private final AlignmentViewPanel ap;
123 private final String featureType;
126 * the colour and filters to reset to on Cancel
127 * (including feature sub-types if modified)
129 private Map<String, FeatureColourI> originalColours;
131 private Map<String, FeatureMatcherSetI> originalFilters;
134 * set flag to true when setting values programmatically,
135 * to avoid invocation of action handlers
137 private boolean adjusting = false;
140 * minimum of the value range for graduated colour
141 * (may be for feature score or for a numeric attribute)
146 * maximum of the value range for graduated colour
151 * scale factor for conversion between absolute min-max and slider
153 private float scaleFactor;
156 * radio button group, to select what to colour by:
157 * simple colour, by category (text), or graduated
159 private JRadioButton simpleColour = new JRadioButton();
161 private JRadioButton byCategory = new JRadioButton();
163 private JRadioButton graduatedColour = new JRadioButton();
166 * colours and filters are shown in tabbed view or single content pane
168 JPanel coloursPanel, filtersPanel;
170 JPanel singleColour = new JPanel();
172 private JPanel minColour = new JPanel();
174 private JPanel maxColour = new JPanel();
176 private JComboBox<String> threshold = new JComboBox<>();
178 private JSlider slider = new JSlider();
180 private JTextField thresholdValue = new JTextField(20);
182 private JCheckBox thresholdIsMin = new JCheckBox();
184 private GraphLine threshline;
186 private ActionListener featureSettings = null;
188 private ActionListener changeColourAction;
191 * choice of option for 'colour for no value'
193 private JComboBox<String> noValueCombo;
196 * choice of what to colour by text (Label or attribute)
198 private JComboBox<String> colourByTextCombo;
201 * choice of what to colour by range (Score or attribute)
203 private JComboBox<String> colourByRangeCombo;
205 private JRadioButton andFilters;
207 private JRadioButton orFilters;
210 * filters for the currently selected feature type
212 private List<FeatureMatcherI> filters;
214 private JPanel chooseFiltersPanel;
217 * feature types present in Feature Renderer which are
218 * sub-types of the one this editor is acting on
220 private final List<String> subTypes;
223 * if true, filter or colour settings are also applied to
224 * any feature sub-types in the Sequence Ontology
226 private boolean applyFiltersToSubtypes;
228 private boolean applyColourToSubtypes;
236 public FeatureTypeSettings(FeatureRenderer frender, String theType)
239 this.featureType = theType;
243 * determine sub-types (if any) of this feature type
245 List<String> types = fr.getRenderOrder();
246 subTypes = SequenceOntologyFactory.getInstance()
247 .getChildTerms(this.featureType, types);
248 Collections.sort(subTypes); // sort for ease of reading in tooltip
251 * save original colours and filters for this feature type
252 * and any sub-types, to restore on Cancel
254 originalFilters = new HashMap<>();
255 originalFilters.put(theType, fr.getFeatureFilter(theType));
256 originalColours = new HashMap<>();
257 originalColours.put(theType, fr.getFeatureColours().get(theType));
258 for (String child : subTypes)
260 originalFilters.put(child, fr.getFeatureFilter(child));
261 originalColours.put(child, fr.getFeatureColours().get(child));
269 } catch (Exception ex)
271 ex.printStackTrace();
281 colourChanged(false);
283 String title = MessageManager
284 .formatMessage("label.display_settings_for", new String[]
286 initDialogFrame(this, true, false, title, 580, 500);
291 * Configures the widgets on the Colours tab according to the current feature
294 private void updateColoursTab()
296 FeatureColourI fc = fr.getFeatureColours().get(featureType);
299 * suppress action handling while updating values programmatically
307 if (fc.isSimpleColour())
309 singleColour.setBackground(fc.getColour());
310 singleColour.setForeground(fc.getColour());
311 simpleColour.setSelected(true);
315 * colour by text (Label or attribute text)
317 if (fc.isColourByLabel())
319 byCategory.setSelected(true);
320 colourByTextCombo.setEnabled(colourByTextCombo.getItemCount() > 1);
321 if (fc.isColourByAttribute())
323 String[] attributeName = fc.getAttributeName();
324 colourByTextCombo.setSelectedItem(
325 FeatureMatcher.toAttributeDisplayName(attributeName));
329 colourByTextCombo.setSelectedItem(LABEL_18N);
334 colourByTextCombo.setEnabled(false);
337 if (!fc.isGraduatedColour())
339 colourByRangeCombo.setEnabled(false);
340 minColour.setEnabled(false);
341 maxColour.setEnabled(false);
342 noValueCombo.setEnabled(false);
343 threshold.setEnabled(false);
344 slider.setEnabled(false);
345 thresholdValue.setEnabled(false);
346 thresholdIsMin.setEnabled(false);
351 * Graduated colour, by score or attribute value range
353 graduatedColour.setSelected(true);
354 updateColourMinMax(); // ensure min, max are set
355 colourByRangeCombo.setEnabled(colourByRangeCombo.getItemCount() > 1);
356 minColour.setEnabled(true);
357 maxColour.setEnabled(true);
358 noValueCombo.setEnabled(true);
359 threshold.setEnabled(true);
360 minColour.setBackground(fc.getMinColour());
361 maxColour.setBackground(fc.getMaxColour());
363 if (fc.isColourByAttribute())
365 String[] attributeName = fc.getAttributeName();
366 colourByRangeCombo.setSelectedItem(
367 FeatureMatcher.toAttributeDisplayName(attributeName));
371 colourByRangeCombo.setSelectedItem(SCORE_18N);
373 Color noColour = fc.getNoColour();
374 if (noColour == null)
376 noValueCombo.setSelectedIndex(NO_COLOUR_OPTION);
378 else if (noColour.equals(fc.getMinColour()))
380 noValueCombo.setSelectedIndex(MIN_COLOUR_OPTION);
382 else if (noColour.equals(fc.getMaxColour()))
384 noValueCombo.setSelectedIndex(MAX_COLOUR_OPTION);
388 * update min-max scaling if there is a range to work with,
389 * else disable the widgets (this shouldn't happen if only
390 * valid options are offered in the combo box)
392 scaleFactor = (max == min) ? 1f : 100f / (max - min);
393 float range = (max - min) * scaleFactor;
394 slider.setMinimum((int) (min * scaleFactor));
395 slider.setMaximum((int) (max * scaleFactor));
396 slider.setMajorTickSpacing((int) (range / 10f));
398 threshline = new GraphLine((max - min) / 2f, "Threshold",
400 threshline.value = fc.getThreshold();
402 if (fc.hasThreshold())
404 threshold.setSelectedIndex(
405 fc.isAboveThreshold() ? ABOVE_THRESHOLD_OPTION
406 : BELOW_THRESHOLD_OPTION);
407 slider.setEnabled(true);
408 slider.setValue((int) (fc.getThreshold() * scaleFactor));
409 thresholdValue.setText(String.valueOf(fc.getThreshold()));
410 thresholdValue.setEnabled(true);
411 thresholdIsMin.setEnabled(true);
415 slider.setEnabled(false);
416 thresholdValue.setEnabled(false);
417 thresholdIsMin.setEnabled(false);
419 thresholdIsMin.setSelected(!fc.isAutoScaled());
427 * Configures the initial layout
429 private void initialise()
431 this.setLayout(new BorderLayout());
434 * an ActionListener that applies colour changes
436 changeColourAction = new ActionListener()
439 public void actionPerformed(ActionEvent e)
446 * first panel/tab: colour options
448 JPanel coloursPanel = initialiseColoursPanel();
449 this.add(coloursPanel, BorderLayout.NORTH);
452 * second panel/tab: filter options
454 JPanel filtersPanel = initialiseFiltersPanel();
455 this.add(filtersPanel, BorderLayout.CENTER);
457 JPanel okCancelPanel = initialiseOkCancelPanel();
459 this.add(okCancelPanel, BorderLayout.SOUTH);
463 * Updates the min-max range if Colour By selected item is Score, or an
464 * attribute, with a min-max range
466 protected void updateColourMinMax()
468 if (!graduatedColour.isSelected())
473 String colourBy = (String) colourByRangeCombo.getSelectedItem();
474 float[] minMax = getMinMax(colourBy);
484 * Retrieves the min-max range:
486 * <li>of feature score, if colour or filter is by Score</li>
487 * <li>else of the selected attribute</li>
493 private float[] getMinMax(String attName)
495 float[] minMax = null;
496 if (SCORE_18N.equals(attName))
498 minMax = fr.getMinMax().get(featureType)[0];
502 // colour by attribute range
503 minMax = FeatureAttributes.getInstance().getMinMax(featureType,
504 FeatureMatcher.fromAttributeDisplayName(attName));
510 * Lay out fields for graduated colour (by score or attribute value)
514 private JPanel initialiseGraduatedColourPanel()
516 JPanel graduatedColourPanel = new JPanel();
517 graduatedColourPanel.setLayout(
518 new BoxLayout(graduatedColourPanel, BoxLayout.Y_AXIS));
519 JvSwingUtils.createTitledBorder(graduatedColourPanel,
520 MessageManager.getString("label.graduated_colour"), true);
521 graduatedColourPanel.setBackground(Color.white);
524 * first row: graduated colour radio button, score/attribute drop-down
526 JPanel graduatedChoicePanel = new JPanel(
527 new FlowLayout(FlowLayout.LEFT));
528 graduatedChoicePanel.setBackground(Color.white);
529 graduatedColour = new JRadioButton(
530 MessageManager.getString("label.by_range_of") + COLON);
531 graduatedColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
532 graduatedColour.addItemListener(new ItemListener()
535 public void itemStateChanged(ItemEvent e)
537 if (graduatedColour.isSelected())
543 graduatedChoicePanel.add(graduatedColour);
545 List<String[]> attNames = FeatureAttributes.getInstance()
546 .getAttributes(featureType);
547 colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
548 colourByRangeCombo.addItemListener(new ItemListener()
551 public void itemStateChanged(ItemEvent e)
558 * disable graduated colour option if no range found
560 graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
562 graduatedChoicePanel.add(colourByRangeCombo);
563 graduatedColourPanel.add(graduatedChoicePanel);
566 * second row - min/max/no colours
568 JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
569 colourRangePanel.setBackground(Color.white);
570 graduatedColourPanel.add(colourRangePanel);
572 minColour.setFont(JvSwingUtils.getLabelFont());
573 minColour.setBorder(BorderFactory.createLineBorder(Color.black));
574 minColour.setPreferredSize(new Dimension(40, 20));
575 minColour.setToolTipText(MessageManager.getString("label.min_colour"));
576 minColour.addMouseListener(new MouseAdapter()
579 public void mousePressed(MouseEvent e)
581 if (minColour.isEnabled())
583 showColourChooser(minColour, "label.select_colour_minimum_value");
588 maxColour.setFont(JvSwingUtils.getLabelFont());
589 maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
590 maxColour.setPreferredSize(new Dimension(40, 20));
591 maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
592 maxColour.addMouseListener(new MouseAdapter()
595 public void mousePressed(MouseEvent e)
597 if (maxColour.isEnabled())
599 showColourChooser(maxColour, "label.select_colour_maximum_value");
603 maxColour.setBorder(new LineBorder(Color.black));
606 * default max colour to last plain colour;
607 * make min colour a pale version of max colour
609 FeatureColourI fc = fr.getFeatureColours().get(featureType);
610 Color bg = fc.getColour() == null ? Color.BLACK : fc.getColour();
611 maxColour.setBackground(bg);
612 minColour.setBackground(ColorUtils.bleachColour(bg, 0.9f));
614 noValueCombo = new JComboBox<>();
615 noValueCombo.addItem(MessageManager.getString("label.no_colour"));
616 noValueCombo.addItem(MessageManager.getString("label.min_colour"));
617 noValueCombo.addItem(MessageManager.getString("label.max_colour"));
618 noValueCombo.addItemListener(new ItemListener()
621 public void itemStateChanged(ItemEvent e)
627 JLabel minText = new JLabel(
628 MessageManager.getString("label.min_value") + COLON);
629 minText.setFont(JvSwingUtils.getLabelFont());
630 JLabel maxText = new JLabel(
631 MessageManager.getString("label.max_value") + COLON);
632 maxText.setFont(JvSwingUtils.getLabelFont());
633 JLabel noText = new JLabel(
634 MessageManager.getString("label.no_value") + COLON);
635 noText.setFont(JvSwingUtils.getLabelFont());
637 colourRangePanel.add(minText);
638 colourRangePanel.add(minColour);
639 colourRangePanel.add(maxText);
640 colourRangePanel.add(maxColour);
641 colourRangePanel.add(noText);
642 colourRangePanel.add(noValueCombo);
645 * third row - threshold options and value
647 JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
648 thresholdPanel.setBackground(Color.white);
649 graduatedColourPanel.add(thresholdPanel);
651 threshold.addActionListener(changeColourAction);
652 threshold.setToolTipText(MessageManager
653 .getString("label.threshold_feature_display_by_score"));
654 threshold.addItem(MessageManager
655 .getString("label.threshold_feature_no_threshold")); // index 0
656 threshold.addItem(MessageManager
657 .getString("label.threshold_feature_above_threshold")); // index 1
658 threshold.addItem(MessageManager
659 .getString("label.threshold_feature_below_threshold")); // index 2
661 thresholdValue.addActionListener(new ActionListener()
664 public void actionPerformed(ActionEvent e)
666 thresholdValue_actionPerformed();
669 thresholdValue.addFocusListener(new FocusAdapter()
672 public void focusLost(FocusEvent e)
674 thresholdValue_actionPerformed();
677 slider.setPaintLabels(false);
678 slider.setPaintTicks(true);
679 slider.setBackground(Color.white);
680 slider.setEnabled(false);
681 slider.setOpaque(false);
682 slider.setPreferredSize(new Dimension(100, 32));
683 slider.setToolTipText(
684 MessageManager.getString("label.adjust_threshold"));
686 slider.addChangeListener(new ChangeListener()
689 public void stateChanged(ChangeEvent evt)
694 .setText(String.valueOf(slider.getValue() / scaleFactor));
695 thresholdValue.setBackground(Color.white); // to reset red for invalid
696 sliderValueChanged();
700 slider.addMouseListener(new MouseAdapter()
703 public void mouseReleased(MouseEvent evt)
706 * only update Overview and/or structure colouring
707 * when threshold slider drag ends (mouse up)
711 refreshDisplay(true);
716 thresholdValue.setEnabled(false);
717 thresholdValue.setColumns(7);
719 thresholdPanel.add(threshold);
720 thresholdPanel.add(slider);
721 thresholdPanel.add(thresholdValue);
723 thresholdIsMin.setBackground(Color.white);
725 .setText(MessageManager.getString("label.threshold_minmax"));
726 thresholdIsMin.setToolTipText(MessageManager
727 .getString("label.toggle_absolute_relative_display_threshold"));
728 thresholdIsMin.addActionListener(changeColourAction);
729 thresholdPanel.add(thresholdIsMin);
731 return graduatedColourPanel;
735 * Lay out OK and Cancel buttons
739 private JPanel initialiseOkCancelPanel()
741 JPanel okCancelPanel = new JPanel();
742 // okCancelPanel.setBackground(Color.white);
743 okCancelPanel.add(ok);
744 okCancelPanel.add(cancel);
745 return okCancelPanel;
749 * Lay out Colour options panel, containing
751 * <li>plain colour, with colour picker</li>
752 * <li>colour by text, with choice of Label or other attribute</li>
753 * <li>colour by range, of score or other attribute, when available</li>
758 private JPanel initialiseColoursPanel()
760 JPanel colourByPanel = new JPanel();
761 colourByPanel.setBackground(Color.white);
762 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
763 JvSwingUtils.createTitledBorder(colourByPanel,
764 MessageManager.getString("action.colour"), true);
767 * option to apply colour to sub-types as well (if there are any)
769 if (!subTypes.isEmpty())
771 applyColourToSubtypes = false;
772 colourByPanel.add(initSubtypesPanel(false));
776 * simple colour radio button and colour picker
778 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
779 simpleColourPanel.setBackground(Color.white);
780 colourByPanel.add(simpleColourPanel);
782 simpleColour = new JRadioButton(
783 MessageManager.getString("label.simple_colour"));
784 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
785 simpleColour.addItemListener(new ItemListener()
788 public void itemStateChanged(ItemEvent e)
790 if (simpleColour.isSelected() && !adjusting)
797 singleColour.setFont(JvSwingUtils.getLabelFont());
798 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
799 singleColour.setPreferredSize(new Dimension(40, 20));
800 singleColour.addMouseListener(new MouseAdapter()
803 public void mousePressed(MouseEvent e)
805 if (simpleColour.isSelected())
807 showColourChooser(singleColour, "label.select_colour");
811 simpleColourPanel.add(simpleColour); // radio button
812 simpleColourPanel.add(singleColour); // colour picker button
815 * colour by text (category) radio button and drop-down choice list
817 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
818 byTextPanel.setBackground(Color.white);
819 JvSwingUtils.createTitledBorder(byTextPanel,
820 MessageManager.getString("label.colour_by_text"), true);
821 colourByPanel.add(byTextPanel);
822 byCategory = new JRadioButton(
823 MessageManager.getString("label.by_text_of") + COLON);
824 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
825 byCategory.addItemListener(new ItemListener()
828 public void itemStateChanged(ItemEvent e)
830 if (byCategory.isSelected())
836 byTextPanel.add(byCategory);
838 List<String[]> attNames = FeatureAttributes.getInstance()
839 .getAttributes(featureType);
840 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
841 colourByTextCombo.addItemListener(new ItemListener()
844 public void itemStateChanged(ItemEvent e)
849 byTextPanel.add(colourByTextCombo);
852 * graduated colour panel
854 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
855 colourByPanel.add(graduatedColourPanel);
858 * 3 radio buttons select between simple colour,
859 * by category (text), or graduated
861 ButtonGroup bg = new ButtonGroup();
862 bg.add(simpleColour);
864 bg.add(graduatedColour);
866 return colourByPanel;
870 * Constructs and returns a panel with a checkbox for the option to apply any
871 * changes also to sub-types of the feature type
875 protected JPanel initSubtypesPanel(final boolean forFilters)
877 JPanel toSubtypes = new JPanel(new FlowLayout(FlowLayout.LEFT));
878 toSubtypes.setBackground(Color.WHITE);
879 JCheckBox applyToSubtypesCB = new JCheckBox(MessageManager
880 .formatMessage("label.apply_to_subtypes", featureType));
881 applyToSubtypesCB.setToolTipText(getSubtypesTooltip());
882 applyToSubtypesCB.addActionListener(new ActionListener()
885 * reset and reapply settings on toggle of checkbox
888 public void actionPerformed(ActionEvent e)
892 applyFiltersToSubtypes = applyToSubtypesCB.isSelected();
893 restoreOriginalFilters();
898 applyColourToSubtypes = applyToSubtypesCB.isSelected();
899 restoreOriginalColours();
904 toSubtypes.add(applyToSubtypesCB);
909 private void showColourChooser(JPanel colourPanel, String key)
911 Color col = JColorChooser.showDialog(this,
912 MessageManager.getString(key), colourPanel.getBackground());
915 colourPanel.setBackground(col);
916 colourPanel.setForeground(col);
918 colourPanel.repaint();
923 * Constructs and sets the selected colour options as the colour for the
924 * feature type, and repaints the alignment, and optionally the Overview
925 * and/or structure viewer if open
927 * @param updateStructsAndOverview
929 void colourChanged(boolean updateStructsAndOverview)
934 * ignore action handlers while setting values programmatically
940 * ensure min-max range is for the latest choice of
941 * 'graduated colour by'
943 updateColourMinMax();
945 FeatureColourI acg = makeColourFromInputs();
948 * save the colour, and set on subtypes if selected
950 fr.setColour(featureType, acg);
951 if (applyColourToSubtypes)
953 for (String child : subTypes)
955 fr.setColour(child, acg);
958 refreshFeatureSettings();
959 refreshDisplay(updateStructsAndOverview);
965 * Converts the input values into an instance of FeatureColour
969 private FeatureColourI makeColourFromInputs()
972 * easiest case - a single colour
974 if (simpleColour.isSelected())
976 return new FeatureColour(singleColour.getBackground());
980 * next easiest case - colour by Label, or attribute text
982 if (byCategory.isSelected())
984 Color c = singleColour.getBackground();
985 FeatureColourI fc = new FeatureColour(c);
986 fc.setColourByLabel(true);
987 String byWhat = (String) colourByTextCombo.getSelectedItem();
988 if (!LABEL_18N.equals(byWhat))
991 FeatureMatcher.fromAttributeDisplayName(byWhat));
997 * remaining case - graduated colour by score, or attribute value
999 Color noColour = null;
1000 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
1002 noColour = minColour.getBackground();
1004 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
1006 noColour = maxColour.getBackground();
1012 thresh = Float.valueOf(thresholdValue.getText());
1013 } catch (NumberFormatException e)
1015 // invalid inputs are already handled on entry
1019 * min-max range is to (or from) threshold value if
1020 * 'threshold is min/max' is selected
1022 float minValue = min;
1023 float maxValue = max;
1024 final int thresholdOption = threshold.getSelectedIndex();
1025 if (thresholdIsMin.isSelected()
1026 && thresholdOption == ABOVE_THRESHOLD_OPTION)
1030 if (thresholdIsMin.isSelected()
1031 && thresholdOption == BELOW_THRESHOLD_OPTION)
1037 * make the graduated colour
1039 FeatureColourI fc = new FeatureColour(minColour.getBackground(),
1040 maxColour.getBackground(), noColour, minValue, maxValue);
1043 * set attribute to colour by if selected
1045 String byWhat = (String) colourByRangeCombo.getSelectedItem();
1046 if (!SCORE_18N.equals(byWhat))
1048 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
1052 * set threshold options and 'autoscaled' which is
1053 * false if 'threshold is min/max' is selected
1054 * else true (colour range is on actual range of values)
1056 fc.setThreshold(thresh);
1057 fc.setAutoScaled(!thresholdIsMin.isSelected());
1058 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
1059 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
1061 if (threshline == null)
1064 * todo not yet implemented: visual indication of feature threshold
1066 threshline = new GraphLine((max - min) / 2f, "Threshold",
1074 protected void raiseClosed()
1076 refreshFeatureSettings();
1079 protected void refreshFeatureSettings()
1081 if (this.featureSettings != null)
1083 featureSettings.actionPerformed(new ActionEvent(this, 0, "REFRESH"));
1088 * Action on OK is just to dismiss the dialog - any changes have already been
1092 public void okPressed()
1097 * Action on Cancel is to restore colour scheme and filters as they were when
1098 * the dialog was opened (including any feature sub-types that may have been
1102 public void cancelPressed()
1104 restoreOriginalColours();
1105 restoreOriginalFilters();
1106 refreshDisplay(true);
1109 protected void restoreOriginalFilters()
1111 for (Entry<String, FeatureMatcherSetI> entry : originalFilters
1114 fr.setFeatureFilter(entry.getKey(), entry.getValue());
1118 protected void restoreOriginalColours()
1120 for (Entry<String, FeatureColourI> entry : originalColours.entrySet())
1122 fr.setColour(entry.getKey(), entry.getValue());
1127 * Action on text entry of a threshold value
1129 protected void thresholdValue_actionPerformed()
1134 * set 'adjusting' flag while moving the slider, so it
1135 * doesn't then in turn change the value (with rounding)
1138 float f = Float.parseFloat(thresholdValue.getText());
1139 f = Float.max(f, this.min);
1140 f = Float.min(f, this.max);
1141 thresholdValue.setText(String.valueOf(f));
1142 slider.setValue((int) (f * scaleFactor));
1143 threshline.value = f;
1144 thresholdValue.setBackground(Color.white); // ok
1146 colourChanged(true);
1147 } catch (NumberFormatException ex)
1149 thresholdValue.setBackground(Color.red); // not ok
1155 * Action on change of threshold slider value. This may be done interactively
1156 * (by moving the slider), or programmatically (to update the slider after
1157 * manual input of a threshold value).
1159 protected void sliderValueChanged()
1161 threshline.value = getRoundedSliderValue();
1164 * repaint alignment, but not Overview or structure,
1165 * to avoid overload while dragging the slider
1167 colourChanged(false);
1171 * Converts the slider value to its absolute value by dividing by the
1172 * scaleFactor. Rounding errors are squashed by forcing min/max of slider
1173 * range to the actual min/max of feature score range
1177 private float getRoundedSliderValue()
1179 int value = slider.getValue();
1180 float f = value == slider.getMaximum() ? max
1181 : (value == slider.getMinimum() ? min : value / scaleFactor);
1185 void addActionListener(ActionListener listener)
1187 if (featureSettings != null)
1190 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1192 featureSettings = listener;
1196 * A helper method to build the drop-down choice of attributes for a feature.
1197 * If 'withRange' is true, then Score, and any attributes with a min-max
1198 * range, are added. If 'withText' is true, Label and any known attributes are
1199 * added. This allows 'categorical numerical' attributes e.g. codon position
1200 * to be coloured by text.
1202 * Where metadata is available with a description for an attribute, that is
1203 * added as a tooltip.
1205 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1206 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1208 * This method does not add any ActionListener to the JComboBox.
1214 protected JComboBox<String> populateAttributesDropdown(
1215 List<String[]> attNames, boolean withRange, boolean withText)
1217 List<String> displayAtts = new ArrayList<>();
1218 List<String> tooltips = new ArrayList<>();
1222 displayAtts.add(LABEL_18N);
1223 tooltips.add(MessageManager.getString("label.description"));
1227 float[][] minMax = fr.getMinMax().get(featureType);
1228 if (minMax != null && minMax[0][0] != minMax[0][1])
1230 displayAtts.add(SCORE_18N);
1231 tooltips.add(SCORE_18N);
1235 FeatureAttributes fa = FeatureAttributes.getInstance();
1236 for (String[] attName : attNames)
1238 float[] minMax = fa.getMinMax(featureType, attName);
1239 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1240 if (!withText && !hasRange)
1244 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1245 String desc = fa.getDescription(featureType, attName);
1246 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1248 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1250 tooltips.add(desc == null ? "" : desc);
1253 JComboBox<String> attCombo = JvSwingUtils
1254 .buildComboWithTooltips(displayAtts, tooltips);
1260 * Populates initial layout of the feature attribute filters panel
1262 private JPanel initialiseFiltersPanel()
1264 filters = new ArrayList<>();
1266 JPanel outerPanel = new JPanel();
1267 outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
1268 outerPanel.setBackground(Color.white);
1271 * option to apply colour to sub-types as well (if there are any)
1273 if (!subTypes.isEmpty())
1275 applyFiltersToSubtypes = false;
1276 outerPanel.add(initSubtypesPanel(true));
1279 JPanel filtersPanel = new JPanel();
1280 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1281 filtersPanel.setBackground(Color.white);
1282 JvSwingUtils.createTitledBorder(filtersPanel,
1283 MessageManager.getString("label.filters"), true);
1284 outerPanel.add(filtersPanel);
1286 JPanel andOrPanel = initialiseAndOrPanel();
1287 filtersPanel.add(andOrPanel);
1290 * panel with filters - populated by refreshFiltersDisplay,
1291 * which also sets the layout manager
1293 chooseFiltersPanel = new JPanel();
1294 chooseFiltersPanel.setBackground(Color.white);
1295 filtersPanel.add(chooseFiltersPanel);
1301 * Lays out the panel with radio buttons to AND or OR filter conditions
1305 private JPanel initialiseAndOrPanel()
1307 JPanel andOrPanel = new JPanel(new BorderLayout());
1308 andOrPanel.setBackground(Color.white);
1310 // JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
1311 // andOrPanel.add(panel1, BorderLayout.WEST);
1312 // panel1.setBackground(Color.white);
1313 // panel1.setBorder(BorderFactory.createLineBorder(debugBorderColour));
1314 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1315 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1316 ActionListener actionListener = new ActionListener()
1319 public void actionPerformed(ActionEvent e)
1324 andFilters.addActionListener(actionListener);
1325 orFilters.addActionListener(actionListener);
1326 ButtonGroup andOr = new ButtonGroup();
1327 andOr.add(andFilters);
1328 andOr.add(orFilters);
1329 andFilters.setSelected(true);
1331 new JLabel(MessageManager.getString("label.join_conditions")));
1332 andOrPanel.add(andFilters);
1333 andOrPanel.add(orFilters);
1339 * Builds a tooltip for the 'Apply to subtypes' checkbox with a list of
1340 * subtypes of this feature type
1344 protected String getSubtypesTooltip()
1346 StringBuilder sb = new StringBuilder(20 * subTypes.size());
1347 sb.append(MessageManager.getString("label.apply_also_to"));
1348 for (String child : subTypes)
1350 sb.append("<br>").append(child);
1352 String tooltip = JvSwingUtils.wrapTooltip(true, sb.toString());
1357 * Refreshes the display to show any filters currently configured for the
1358 * selected feature type (editable, with 'remove' option), plus one extra row
1359 * for adding a condition. This should be called after a filter has been
1360 * removed, added or amended.
1362 private void updateFiltersTab()
1365 * clear the panel and list of filter conditions
1367 chooseFiltersPanel.removeAll();
1371 * look up attributes known for feature type
1373 List<String[]> attNames = FeatureAttributes.getInstance()
1374 .getAttributes(featureType);
1377 * if this feature type has filters set, load them first
1379 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1380 if (featureFilters != null)
1382 if (!featureFilters.isAnded())
1384 orFilters.setSelected(true);
1386 featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1390 * and an empty filter for the user to populate (add)
1392 filters.add(FeatureMatcher.NULL_MATCHER);
1395 * use GridLayout to 'justify' rows to the top of the panel, until
1396 * there are too many to fit in, then fall back on BoxLayout
1398 if (filters.size() <= 5)
1400 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1404 chooseFiltersPanel.setLayout(
1405 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1409 * render the conditions in rows, each in its own JPanel
1411 int filterIndex = 0;
1412 for (FeatureMatcherI filter : filters)
1414 JPanel row = addFilter(filter, attNames, filterIndex);
1415 chooseFiltersPanel.add(row);
1424 * A helper method that constructs a row (panel) with one filter condition:
1426 * <li>a drop-down list of Label, Score and attribute names to choose
1428 * <li>a drop-down list of conditions to choose from</li>
1429 * <li>a text field for input of a match pattern</li>
1430 * <li>optionally, a 'remove' button</li>
1432 * The filter values are set as defaults for the input fields. The 'remove'
1433 * button is added unless the pattern is empty (incomplete filter condition).
1435 * Action handlers on these fields provide for
1437 * <li>validate pattern field - should be numeric if condition is numeric</li>
1438 * <li>save filters and refresh display on any (valid) change</li>
1439 * <li>remove filter and refresh on 'Remove'</li>
1440 * <li>update conditions list on change of Label/Score/Attribute</li>
1441 * <li>refresh value field tooltip with min-max range on change of
1447 * @param filterIndex
1450 protected JPanel addFilter(FeatureMatcherI filter,
1451 List<String[]> attNames, int filterIndex)
1453 String[] attName = filter.getAttribute();
1454 Condition cond = filter.getMatcher().getCondition();
1455 String pattern = filter.getMatcher().getPattern();
1457 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1458 filterRow.setBackground(Color.white);
1461 * drop-down choice of attribute, with description as a tooltip
1462 * if we can obtain it
1464 final JComboBox<String> attCombo = populateAttributesDropdown(attNames,
1466 String filterBy = setSelectedAttribute(attCombo, filter);
1468 JComboBox<Condition> condCombo = new JComboBox<>();
1470 JTextField patternField = new JTextField(8);
1471 patternField.setText(pattern);
1474 * action handlers that validate and (if valid) apply changes
1476 ActionListener actionListener = new ActionListener()
1479 public void actionPerformed(ActionEvent e)
1481 if (validateFilter(patternField, condCombo))
1483 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1490 ItemListener itemListener = new ItemListener()
1493 public void itemStateChanged(ItemEvent e)
1495 actionListener.actionPerformed(null);
1499 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1501 attCombo.setSelectedIndex(0);
1505 attCombo.setSelectedItem(
1506 FeatureMatcher.toAttributeDisplayName(attName));
1508 attCombo.addItemListener(new ItemListener()
1511 public void itemStateChanged(ItemEvent e)
1514 * on change of attribute, refresh the conditions list to
1515 * ensure it is appropriate for the attribute datatype
1517 populateConditions((String) attCombo.getSelectedItem(),
1518 (Condition) condCombo.getSelectedItem(), condCombo,
1520 actionListener.actionPerformed(null);
1524 filterRow.add(attCombo);
1527 * drop-down choice of test condition
1529 populateConditions(filterBy, cond, condCombo, patternField);
1530 condCombo.setPreferredSize(new Dimension(150, 20));
1531 condCombo.addItemListener(itemListener);
1532 filterRow.add(condCombo);
1535 * pattern to match against
1537 patternField.addActionListener(actionListener);
1538 patternField.addFocusListener(new FocusAdapter()
1541 public void focusLost(FocusEvent e)
1543 actionListener.actionPerformed(null);
1546 filterRow.add(patternField);
1549 * disable pattern field for condition 'Present / NotPresent'
1551 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1552 patternField.setEnabled(selectedCondition.needsAPattern());
1555 * if a numeric condition is selected, show the value range
1556 * as a tooltip on the value input field
1558 setNumericHints(filterBy, selectedCondition, patternField);
1561 * add remove button if filter is populated (non-empty pattern)
1563 if (!patternField.isEnabled()
1564 || (pattern != null && pattern.trim().length() > 0))
1566 // todo: gif for button drawing '-' or 'x'
1567 JButton removeCondition = new BasicArrowButton(SwingConstants.WEST);
1569 .setToolTipText(MessageManager.getString("label.delete_row"));
1570 removeCondition.addActionListener(new ActionListener()
1573 public void actionPerformed(ActionEvent e)
1575 filters.remove(filterIndex);
1579 filterRow.add(removeCondition);
1586 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1592 private String setSelectedAttribute(JComboBox<String> attCombo,
1593 FeatureMatcherI filter)
1596 if (filter.isByScore())
1600 else if (filter.isByLabel())
1606 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1608 attCombo.setSelectedItem(item);
1613 * If a numeric comparison condition is selected, retrieves the min-max range
1614 * for the value (score or attribute), and sets it as a tooltip on the value
1615 * field. If the field is currently empty, then pre-populates it with
1617 * <li>the minimum value, if condition is > or >=</li>
1618 * <li>the maximum value, if condition is < or <=</li>
1622 * @param selectedCondition
1623 * @param patternField
1625 private void setNumericHints(String attName, Condition selectedCondition,
1626 JTextField patternField)
1628 patternField.setToolTipText("");
1630 if (selectedCondition.isNumeric())
1632 float[] minMax = getMinMax(attName);
1635 String minFormatted = DECFMT_2_2.format(minMax[0]);
1636 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1637 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1638 patternField.setToolTipText(tip);
1639 if (patternField.getText().isEmpty())
1641 if (selectedCondition == Condition.GE
1642 || selectedCondition == Condition.GT)
1644 patternField.setText(minFormatted);
1648 if (selectedCondition == Condition.LE
1649 || selectedCondition == Condition.LT)
1651 patternField.setText(maxFormatted);
1660 * Populates the drop-down list of comparison conditions for the given
1661 * attribute name. The conditions added depend on the datatype of the
1662 * attribute values. The supplied condition is set as the selected item in the
1663 * list, provided it is in the list. If the pattern is now invalid
1664 * (non-numeric pattern for a numeric condition), it is cleared.
1669 * @param patternField
1671 private void populateConditions(String attName, Condition cond,
1672 JComboBox<Condition> condCombo, JTextField patternField)
1674 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1675 FeatureMatcher.fromAttributeDisplayName(attName));
1676 if (LABEL_18N.equals(attName))
1678 type = Datatype.Character;
1680 else if (SCORE_18N.equals(attName))
1682 type = Datatype.Number;
1686 * remove itemListener before starting
1688 ItemListener listener = condCombo.getItemListeners()[0];
1689 condCombo.removeItemListener(listener);
1690 boolean condIsValid = false;
1692 condCombo.removeAllItems();
1693 for (Condition c : Condition.values())
1695 if ((c.isNumeric() && type == Datatype.Number)
1696 || (!c.isNumeric() && type != Datatype.Number))
1698 condCombo.addItem(c);
1707 * set the selected condition (does nothing if not in the list)
1711 condCombo.setSelectedItem(cond);
1715 condCombo.setSelectedIndex(0);
1719 * clear pattern if it is now invalid for condition
1721 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1725 String pattern = patternField.getText().trim();
1726 if (pattern.length() > 0)
1728 Float.valueOf(pattern);
1730 } catch (NumberFormatException e)
1732 patternField.setText("");
1737 * restore the listener
1739 condCombo.addItemListener(listener);
1743 * Answers true unless a numeric condition has been selected with a
1744 * non-numeric value. Sets the value field to RED with a tooltip if in error.
1746 * If the pattern is expected but is empty, this method returns false, but
1747 * does not mark the field as invalid. This supports selecting an attribute
1748 * for a new condition before a match pattern has been entered.
1753 protected boolean validateFilter(JTextField value,
1754 JComboBox<Condition> condCombo)
1756 if (value == null || condCombo == null)
1758 return true; // fields not populated
1761 Condition cond = (Condition) condCombo.getSelectedItem();
1762 if (!cond.needsAPattern())
1767 value.setBackground(Color.white);
1768 value.setToolTipText("");
1769 String v1 = value.getText().trim();
1770 if (v1.length() == 0)
1775 if (cond.isNumeric() && v1.length() > 0)
1780 } catch (NumberFormatException e)
1782 value.setBackground(Color.red);
1783 value.setToolTipText(
1784 MessageManager.getString("label.numeric_required"));
1793 * Constructs a filter condition from the given input fields, and replaces the
1794 * condition at filterIndex with the new one. Does nothing if the pattern
1795 * field is blank (unless the match condition is one that doesn't require a
1796 * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1799 * This method may update the tooltip on the filter value field to show the
1800 * value range, if a numeric condition is selected. This ensures the tooltip
1801 * is updated when a numeric valued attribute is chosen on the last 'add a
1807 * @param filterIndex
1809 protected boolean updateFilter(JComboBox<String> attCombo,
1810 JComboBox<Condition> condCombo, JTextField valueField,
1813 String attName = (String) attCombo.getSelectedItem();
1814 Condition cond = (Condition) condCombo.getSelectedItem();
1815 String pattern = valueField.getText().trim();
1817 setNumericHints(attName, cond, valueField);
1819 if (pattern.length() == 0 && cond.needsAPattern())
1821 valueField.setEnabled(true); // ensure pattern field is enabled!
1826 * Construct a matcher that operates on Label, Score,
1827 * or named attribute
1829 FeatureMatcherI km = null;
1830 if (LABEL_18N.equals(attName))
1832 km = FeatureMatcher.byLabel(cond, pattern);
1834 else if (SCORE_18N.equals(attName))
1836 km = FeatureMatcher.byScore(cond, pattern);
1840 km = FeatureMatcher.byAttribute(cond, pattern,
1841 FeatureMatcher.fromAttributeDisplayName(attName));
1844 filters.set(filterIndex, km);
1850 * Action on any change to feature filtering, namely
1852 * <li>change of selected attribute</li>
1853 * <li>change of selected condition</li>
1854 * <li>change of match pattern</li>
1855 * <li>removal of a condition</li>
1857 * The inputs are parsed into a combined filter and this is set for the
1858 * feature type, and the alignment redrawn.
1860 protected void filtersChanged()
1863 * update the filter conditions for the feature type
1865 boolean anded = andFilters.isSelected();
1866 FeatureMatcherSetI combined = new FeatureMatcherSet();
1868 for (FeatureMatcherI filter : filters)
1870 String pattern = filter.getMatcher().getPattern();
1871 Condition condition = filter.getMatcher().getCondition();
1872 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1876 combined.and(filter);
1880 combined.or(filter);
1886 * save the filter conditions in the FeatureRenderer
1887 * (note this might now be an empty filter with no conditions)
1889 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1891 if (applyFiltersToSubtypes)
1893 for (String child : subTypes)
1895 fr.setFeatureFilter(child, combined.isEmpty() ? null : combined);
1899 refreshFeatureSettings();
1900 refreshDisplay(true);
1906 * Repaints alignment, structure and overview (if shown). If there is a
1907 * complementary view which is showing this view's features, then also
1910 * @param updateStructsAndOverview
1912 void refreshDisplay(boolean updateStructsAndOverview)
1914 ap.paintAlignment(true, updateStructsAndOverview);
1915 AlignViewportI complement = ap.getAlignViewport().getCodingComplement();
1916 if (complement != null && complement.isShowComplementFeatures())
1918 AlignFrame af2 = Desktop.getAlignFrameFor(complement);
1919 af2.alignPanel.paintAlignment(true, updateStructsAndOverview);