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, colour settings are also applied to any
223 * feature sub-types in the Sequence Ontology
225 private JCheckBox applyToSubtypes;
233 public FeatureTypeSettings(FeatureRenderer frender, String theType)
235 this(frender, false, theType);
239 * Constructor, with option to make a blocking dialog (has to complete in the
240 * AWT event queue thread). Currently this option is always set to false.
246 FeatureTypeSettings(FeatureRenderer frender, boolean blocking,
250 this.featureType = theType;
254 * determine sub-types (if any) of this feature type
256 List<String> types = fr.getRenderOrder();
257 subTypes = SequenceOntologyFactory.getInstance()
258 .getChildTerms(this.featureType, types);
259 Collections.sort(subTypes); // sort for ease of reading in tooltip
262 * save original colours and filters for this feature type
263 * and any sub-types, to restore on Cancel
265 originalFilters = new HashMap<>();
266 originalFilters.put(theType, fr.getFeatureFilter(theType));
267 originalColours = new HashMap<>();
268 originalColours.put(theType, fr.getFeatureColours().get(theType));
269 for (String child : subTypes)
271 originalFilters.put(child, fr.getFeatureFilter(child));
272 originalColours.put(child, fr.getFeatureColours().get(child));
280 } catch (Exception ex)
282 ex.printStackTrace();
292 colourChanged(false);
294 String title = MessageManager
295 .formatMessage("label.display_settings_for", new String[]
297 initDialogFrame(this, true, blocking, title, 600, 360);
303 * Configures the widgets on the Colours tab according to the current feature
306 private void updateColoursTab()
308 FeatureColourI fc = fr.getFeatureColours().get(featureType);
311 * suppress action handling while updating values programmatically
319 if (fc.isSimpleColour())
321 simpleColour.setSelected(true);
322 singleColour.setBackground(fc.getColour());
323 singleColour.setForeground(fc.getColour());
327 * colour by text (Label or attribute text)
329 if (fc.isColourByLabel())
331 byCategory.setSelected(true);
332 colourByTextCombo.setEnabled(colourByTextCombo.getItemCount() > 1);
333 if (fc.isColourByAttribute())
335 String[] attributeName = fc.getAttributeName();
336 colourByTextCombo.setSelectedItem(
337 FeatureMatcher.toAttributeDisplayName(attributeName));
341 colourByTextCombo.setSelectedItem(LABEL_18N);
346 colourByTextCombo.setEnabled(false);
349 if (!fc.isGraduatedColour())
351 colourByRangeCombo.setEnabled(false);
352 minColour.setEnabled(false);
353 maxColour.setEnabled(false);
354 noValueCombo.setEnabled(false);
355 threshold.setEnabled(false);
356 slider.setEnabled(false);
357 thresholdValue.setEnabled(false);
358 thresholdIsMin.setEnabled(false);
363 * Graduated colour, by score or attribute value range
365 graduatedColour.setSelected(true);
366 updateColourMinMax(); // ensure min, max are set
367 colourByRangeCombo.setEnabled(colourByRangeCombo.getItemCount() > 1);
368 minColour.setEnabled(true);
369 maxColour.setEnabled(true);
370 noValueCombo.setEnabled(true);
371 threshold.setEnabled(true);
372 minColour.setBackground(fc.getMinColour());
373 maxColour.setBackground(fc.getMaxColour());
375 if (fc.isColourByAttribute())
377 String[] attributeName = fc.getAttributeName();
378 colourByRangeCombo.setSelectedItem(
379 FeatureMatcher.toAttributeDisplayName(attributeName));
383 colourByRangeCombo.setSelectedItem(SCORE_18N);
385 Color noColour = fc.getNoColour();
386 if (noColour == null)
388 noValueCombo.setSelectedIndex(NO_COLOUR_OPTION);
390 else if (noColour.equals(fc.getMinColour()))
392 noValueCombo.setSelectedIndex(MIN_COLOUR_OPTION);
394 else if (noColour.equals(fc.getMaxColour()))
396 noValueCombo.setSelectedIndex(MAX_COLOUR_OPTION);
400 * update min-max scaling if there is a range to work with,
401 * else disable the widgets (this shouldn't happen if only
402 * valid options are offered in the combo box)
404 scaleFactor = (max == min) ? 1f : 100f / (max - min);
405 float range = (max - min) * scaleFactor;
406 slider.setMinimum((int) (min * scaleFactor));
407 slider.setMaximum((int) (max * scaleFactor));
408 slider.setMajorTickSpacing((int) (range / 10f));
410 threshline = new GraphLine((max - min) / 2f, "Threshold",
412 threshline.value = fc.getThreshold();
414 if (fc.hasThreshold())
416 threshold.setSelectedIndex(
417 fc.isAboveThreshold() ? ABOVE_THRESHOLD_OPTION
418 : BELOW_THRESHOLD_OPTION);
419 slider.setEnabled(true);
420 slider.setValue((int) (fc.getThreshold() * scaleFactor));
421 thresholdValue.setText(String.valueOf(getRoundedSliderValue()));
422 thresholdValue.setEnabled(true);
423 thresholdIsMin.setEnabled(true);
427 slider.setEnabled(false);
428 thresholdValue.setEnabled(false);
429 thresholdIsMin.setEnabled(false);
431 thresholdIsMin.setSelected(!fc.isAutoScaled());
439 * Configures the initial layout
441 private void initialise()
443 this.setLayout(new BorderLayout());
444 tabbedPane = new JTabbedPane();
445 this.add(tabbedPane, BorderLayout.CENTER);
448 * an ActionListener that applies colour changes
450 changeColourAction = new ActionListener()
453 public void actionPerformed(ActionEvent e)
460 * first tab: colour options
462 JPanel coloursPanel = initialiseColoursPanel();
463 tabbedPane.addTab(MessageManager.getString("action.colour"),
467 * second tab: filter options
469 JPanel filtersPanel = initialiseFiltersPanel();
470 tabbedPane.addTab(MessageManager.getString("label.filters"),
473 JPanel okCancelPanel = initialiseOkCancelPanel();
475 this.add(okCancelPanel, BorderLayout.SOUTH);
479 * Updates the min-max range if Colour By selected item is Score, or an
480 * attribute, with a min-max range
482 protected void updateColourMinMax()
484 if (!graduatedColour.isSelected())
489 String colourBy = (String) colourByRangeCombo.getSelectedItem();
490 float[] minMax = getMinMax(colourBy);
500 * Retrieves the min-max range:
502 * <li>of feature score, if colour or filter is by Score</li>
503 * <li>else of the selected attribute</li>
509 private float[] getMinMax(String attName)
511 float[] minMax = null;
512 if (SCORE_18N.equals(attName))
514 minMax = fr.getMinMax().get(featureType)[0];
518 // colour by attribute range
519 minMax = FeatureAttributes.getInstance().getMinMax(featureType,
520 FeatureMatcher.fromAttributeDisplayName(attName));
526 * Lay out fields for graduated colour (by score or attribute value)
530 private JPanel initialiseGraduatedColourPanel()
532 JPanel graduatedColourPanel = new JPanel();
533 graduatedColourPanel.setLayout(
534 new BoxLayout(graduatedColourPanel, BoxLayout.Y_AXIS));
535 JvSwingUtils.createTitledBorder(graduatedColourPanel,
536 MessageManager.getString("label.graduated_colour"), true);
537 graduatedColourPanel.setBackground(Color.white);
540 * first row: graduated colour radio button, score/attribute drop-down
542 JPanel graduatedChoicePanel = new JPanel(
543 new FlowLayout(FlowLayout.LEFT));
544 graduatedChoicePanel.setBackground(Color.white);
545 graduatedColour = new JRadioButton(
546 MessageManager.getString("label.by_range_of") + COLON);
547 graduatedColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
548 graduatedColour.addItemListener(new ItemListener()
551 public void itemStateChanged(ItemEvent e)
553 if (graduatedColour.isSelected())
559 graduatedChoicePanel.add(graduatedColour);
561 List<String[]> attNames = FeatureAttributes.getInstance()
562 .getAttributes(featureType);
563 colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
564 colourByRangeCombo.addItemListener(new ItemListener()
567 public void itemStateChanged(ItemEvent e)
574 * disable graduated colour option if no range found
576 graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
578 graduatedChoicePanel.add(colourByRangeCombo);
579 graduatedColourPanel.add(graduatedChoicePanel);
582 * second row - min/max/no colours
584 JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
585 colourRangePanel.setBackground(Color.white);
586 graduatedColourPanel.add(colourRangePanel);
588 minColour.setFont(JvSwingUtils.getLabelFont());
589 minColour.setBorder(BorderFactory.createLineBorder(Color.black));
590 minColour.setPreferredSize(new Dimension(40, 20));
591 minColour.setToolTipText(MessageManager.getString("label.min_colour"));
592 minColour.addMouseListener(new MouseAdapter()
595 public void mousePressed(MouseEvent e)
597 if (minColour.isEnabled())
599 showColourChooser(minColour, "label.select_colour_minimum_value");
604 maxColour.setFont(JvSwingUtils.getLabelFont());
605 maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
606 maxColour.setPreferredSize(new Dimension(40, 20));
607 maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
608 maxColour.addMouseListener(new MouseAdapter()
611 public void mousePressed(MouseEvent e)
613 if (maxColour.isEnabled())
615 showColourChooser(maxColour, "label.select_colour_maximum_value");
619 maxColour.setBorder(new LineBorder(Color.black));
622 * default max colour to current colour (if a plain colour),
623 * or to Black if colour by label; make min colour a pale
624 * version of max colour
626 FeatureColourI fc = fr.getFeatureColours().get(featureType);
627 Color bg = fc.isSimpleColour() ? fc.getColour() : Color.BLACK;
628 maxColour.setBackground(bg);
629 minColour.setBackground(ColorUtils.bleachColour(bg, 0.9f));
631 noValueCombo = new JComboBox<>();
632 noValueCombo.addItem(MessageManager.getString("label.no_colour"));
633 noValueCombo.addItem(MessageManager.getString("label.min_colour"));
634 noValueCombo.addItem(MessageManager.getString("label.max_colour"));
635 noValueCombo.addItemListener(new ItemListener()
638 public void itemStateChanged(ItemEvent e)
644 JLabel minText = new JLabel(
645 MessageManager.getString("label.min_value") + COLON);
646 minText.setFont(JvSwingUtils.getLabelFont());
647 JLabel maxText = new JLabel(
648 MessageManager.getString("label.max_value") + COLON);
649 maxText.setFont(JvSwingUtils.getLabelFont());
650 JLabel noText = new JLabel(
651 MessageManager.getString("label.no_value") + COLON);
652 noText.setFont(JvSwingUtils.getLabelFont());
654 colourRangePanel.add(minText);
655 colourRangePanel.add(minColour);
656 colourRangePanel.add(maxText);
657 colourRangePanel.add(maxColour);
658 colourRangePanel.add(noText);
659 colourRangePanel.add(noValueCombo);
662 * third row - threshold options and value
664 JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
665 thresholdPanel.setBackground(Color.white);
666 graduatedColourPanel.add(thresholdPanel);
668 threshold.addActionListener(changeColourAction);
669 threshold.setToolTipText(MessageManager
670 .getString("label.threshold_feature_display_by_score"));
671 threshold.addItem(MessageManager
672 .getString("label.threshold_feature_no_threshold")); // index 0
673 threshold.addItem(MessageManager
674 .getString("label.threshold_feature_above_threshold")); // index 1
675 threshold.addItem(MessageManager
676 .getString("label.threshold_feature_below_threshold")); // index 2
678 thresholdValue.addActionListener(new ActionListener()
681 public void actionPerformed(ActionEvent e)
683 thresholdValue_actionPerformed();
686 thresholdValue.addFocusListener(new FocusAdapter()
689 public void focusLost(FocusEvent e)
691 thresholdValue_actionPerformed();
694 slider.setPaintLabels(false);
695 slider.setPaintTicks(true);
696 slider.setBackground(Color.white);
697 slider.setEnabled(false);
698 slider.setOpaque(false);
699 slider.setPreferredSize(new Dimension(100, 32));
700 slider.setToolTipText(
701 MessageManager.getString("label.adjust_threshold"));
703 slider.addChangeListener(new ChangeListener()
706 public void stateChanged(ChangeEvent evt)
711 .setText(String.valueOf(slider.getValue() / scaleFactor));
712 sliderValueChanged();
716 slider.addMouseListener(new MouseAdapter()
719 public void mouseReleased(MouseEvent evt)
722 * only update Overview and/or structure colouring
723 * when threshold slider drag ends (mouse up)
727 ap.paintAlignment(true, true);
732 thresholdValue.setEnabled(false);
733 thresholdValue.setColumns(7);
735 thresholdPanel.add(threshold);
736 thresholdPanel.add(slider);
737 thresholdPanel.add(thresholdValue);
739 thresholdIsMin.setBackground(Color.white);
741 .setText(MessageManager.getString("label.threshold_minmax"));
742 thresholdIsMin.setToolTipText(MessageManager
743 .getString("label.toggle_absolute_relative_display_threshold"));
744 thresholdIsMin.addActionListener(changeColourAction);
745 thresholdPanel.add(thresholdIsMin);
747 return graduatedColourPanel;
751 * Lay out OK and Cancel buttons
755 private JPanel initialiseOkCancelPanel()
757 JPanel okCancelPanel = new JPanel();
758 // okCancelPanel.setBackground(Color.white);
759 okCancelPanel.add(ok);
760 okCancelPanel.add(cancel);
761 return okCancelPanel;
765 * Lay out Colour options panel, containing
767 * <li>plain colour, with colour picker</li>
768 * <li>colour by text, with choice of Label or other attribute</li>
769 * <li>colour by range, of score or other attribute, when available</li>
774 private JPanel initialiseColoursPanel()
776 JPanel colourByPanel = new JPanel();
777 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
780 * option to apply colour to sub-types as well (if there are any)
782 if (!subTypes.isEmpty())
784 colourByPanel.add(initSubtypesPanel());
788 * simple colour radio button and colour picker
790 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
791 simpleColourPanel.setBackground(Color.white);
792 JvSwingUtils.createTitledBorder(simpleColourPanel,
793 MessageManager.getString("label.simple"), true);
794 colourByPanel.add(simpleColourPanel);
796 simpleColour = new JRadioButton(
797 MessageManager.getString("label.simple_colour"));
798 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
799 simpleColour.addItemListener(new ItemListener()
802 public void itemStateChanged(ItemEvent e)
804 if (simpleColour.isSelected() && !adjusting)
806 showColourChooser(singleColour, "label.select_colour");
812 singleColour.setFont(JvSwingUtils.getLabelFont());
813 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
814 singleColour.setPreferredSize(new Dimension(40, 20));
815 singleColour.addMouseListener(new MouseAdapter()
818 public void mousePressed(MouseEvent e)
820 if (simpleColour.isSelected())
822 showColourChooser(singleColour, "label.select_colour");
826 simpleColourPanel.add(simpleColour); // radio button
827 simpleColourPanel.add(singleColour); // colour picker button
830 * colour by text (category) radio button and drop-down choice list
832 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
833 byTextPanel.setBackground(Color.white);
834 JvSwingUtils.createTitledBorder(byTextPanel,
835 MessageManager.getString("label.colour_by_text"), true);
836 colourByPanel.add(byTextPanel);
837 byCategory = new JRadioButton(
838 MessageManager.getString("label.by_text_of") + COLON);
839 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
840 byCategory.addItemListener(new ItemListener()
843 public void itemStateChanged(ItemEvent e)
845 if (byCategory.isSelected())
851 byTextPanel.add(byCategory);
853 List<String[]> attNames = FeatureAttributes.getInstance()
854 .getAttributes(featureType);
855 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
856 colourByTextCombo.addItemListener(new ItemListener()
859 public void itemStateChanged(ItemEvent e)
864 byTextPanel.add(colourByTextCombo);
867 * graduated colour panel
869 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
870 colourByPanel.add(graduatedColourPanel);
873 * 3 radio buttons select between simple colour,
874 * by category (text), or graduated
876 ButtonGroup bg = new ButtonGroup();
877 bg.add(simpleColour);
879 bg.add(graduatedColour);
881 return colourByPanel;
885 * Constructs and returns a panel with a checkbox for the option to apply any
886 * changes also to sub-types of the feature type
890 protected JPanel initSubtypesPanel()
892 JPanel toSubtypes = new JPanel(new FlowLayout(FlowLayout.LEFT));
893 toSubtypes.setBackground(Color.WHITE);
894 applyToSubtypes = new JCheckBox(
895 "Apply changes also to sub-types of " + featureType);
896 applyToSubtypes.setToolTipText(getSubtypesTooltip());
897 toSubtypes.add(applyToSubtypes);
901 private void showColourChooser(JPanel colourPanel, String key)
903 Color col = JColorChooser.showDialog(this,
904 MessageManager.getString(key), colourPanel.getBackground());
907 colourPanel.setBackground(col);
908 colourPanel.setForeground(col);
910 colourPanel.repaint();
915 * Constructs and sets the selected colour options as the colour for the feature
916 * type, and repaints the alignment, and optionally the Overview and/or
917 * structure viewer if open
919 * @param updateStructsAndOverview
921 void colourChanged(boolean updateStructsAndOverview)
926 * ignore action handlers while setting values programmatically
932 * ensure min-max range is for the latest choice of
933 * 'graduated colour by'
935 updateColourMinMax();
937 FeatureColourI acg = makeColourFromInputs();
940 * save the colour, and set on subtypes if selected
942 fr.setColour(featureType, acg);
943 if (applyToSubtypes.isSelected())
945 for (String child : subTypes)
947 fr.setColour(child, acg);
950 refreshFeatureSettings();
951 ap.paintAlignment(updateStructsAndOverview, updateStructsAndOverview);
957 * Converts the input values into an instance of FeatureColour
961 private FeatureColourI makeColourFromInputs()
964 * easiest case - a single colour
966 if (simpleColour.isSelected())
968 return new FeatureColour(singleColour.getBackground());
972 * next easiest case - colour by Label, or attribute text
974 if (byCategory.isSelected())
976 Color c = this.getBackground();
977 FeatureColourI fc = new FeatureColour(c, c, null, 0f, 0f);
978 fc.setColourByLabel(true);
979 String byWhat = (String) colourByTextCombo.getSelectedItem();
980 if (!LABEL_18N.equals(byWhat))
983 FeatureMatcher.fromAttributeDisplayName(byWhat));
989 * remaining case - graduated colour by score, or attribute value
991 Color noColour = null;
992 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
994 noColour = minColour.getBackground();
996 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
998 noColour = maxColour.getBackground();
1004 thresh = Float.valueOf(thresholdValue.getText());
1005 } catch (NumberFormatException e)
1007 // invalid inputs are already handled on entry
1011 * min-max range is to (or from) threshold value if
1012 * 'threshold is min/max' is selected
1014 float minValue = min;
1015 float maxValue = max;
1016 final int thresholdOption = threshold.getSelectedIndex();
1017 if (thresholdIsMin.isSelected()
1018 && thresholdOption == ABOVE_THRESHOLD_OPTION)
1022 if (thresholdIsMin.isSelected()
1023 && thresholdOption == BELOW_THRESHOLD_OPTION)
1029 * make the graduated colour
1031 FeatureColourI fc = new FeatureColour(minColour.getBackground(),
1032 maxColour.getBackground(), noColour, minValue, maxValue);
1035 * set attribute to colour by if selected
1037 String byWhat = (String) colourByRangeCombo.getSelectedItem();
1038 if (!SCORE_18N.equals(byWhat))
1040 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
1044 * set threshold options and 'autoscaled' which is
1045 * false if 'threshold is min/max' is selected
1046 * else true (colour range is on actual range of values)
1048 fc.setThreshold(thresh);
1049 fc.setAutoScaled(!thresholdIsMin.isSelected());
1050 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
1051 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
1053 if (threshline == null)
1056 * todo not yet implemented: visual indication of feature threshold
1058 threshline = new GraphLine((max - min) / 2f, "Threshold",
1066 protected void raiseClosed()
1068 refreshFeatureSettings();
1071 protected void refreshFeatureSettings()
1073 if (this.featureSettings != null)
1075 featureSettings.actionPerformed(new ActionEvent(this, 0, "REFRESH"));
1080 * Action on OK is just to dismiss the dialog - any changes have already been
1084 public void okPressed()
1089 * Action on Cancel is to restore colour scheme and filters as they were when
1090 * the dialog was opened (including any feature sub-types that may have been
1094 public void cancelPressed()
1096 for (Entry<String, FeatureColourI> entry : originalColours.entrySet())
1098 fr.setColour(entry.getKey(), entry.getValue());
1100 for (Entry<String, FeatureMatcherSetI> entry : originalFilters
1103 fr.setFeatureFilter(entry.getKey(), entry.getValue());
1106 ap.paintAlignment(true, true);
1110 * Action on text entry of a threshold value
1112 protected void thresholdValue_actionPerformed()
1117 float f = Float.parseFloat(thresholdValue.getText());
1118 slider.setValue((int) (f * scaleFactor));
1119 threshline.value = f;
1120 thresholdValue.setBackground(Color.white); // ok
1123 * force repaint of any Overview window or structure
1125 ap.paintAlignment(true, true);
1126 } catch (NumberFormatException ex)
1128 thresholdValue.setBackground(Color.red); // not ok
1136 * Action on change of threshold slider value. This may be done interactively
1137 * (by moving the slider), or programmatically (to update the slider after
1138 * manual input of a threshold value).
1140 protected void sliderValueChanged()
1142 threshline.value = getRoundedSliderValue();
1145 * repaint alignment, but not Overview or structure,
1146 * to avoid overload while dragging the slider
1148 colourChanged(false);
1152 * Converts the slider value to its absolute value by dividing by the
1153 * scaleFactor. Rounding errors are squashed by forcing min/max of slider range
1154 * to the actual min/max of feature score range
1158 private float getRoundedSliderValue()
1160 int value = slider.getValue();
1161 float f = value == slider.getMaximum() ? max
1162 : (value == slider.getMinimum() ? min : value / scaleFactor);
1166 void addActionListener(ActionListener listener)
1168 if (featureSettings != null)
1171 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1173 featureSettings = listener;
1177 * A helper method to build the drop-down choice of attributes for a feature. If
1178 * 'withRange' is true, then Score, and any attributes with a min-max range, are
1179 * added. If 'withText' is true, Label and any known attributes are added. This
1180 * allows 'categorical numerical' attributes e.g. codon position to be coloured
1183 * Where metadata is available with a description for an attribute, that is
1184 * added as a tooltip.
1186 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1187 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1189 * This method does not add any ActionListener to the JComboBox.
1195 protected JComboBox<String> populateAttributesDropdown(
1196 List<String[]> attNames, boolean withRange, boolean withText)
1198 List<String> displayAtts = new ArrayList<>();
1199 List<String> tooltips = new ArrayList<>();
1203 displayAtts.add(LABEL_18N);
1204 tooltips.add(MessageManager.getString("label.description"));
1208 float[][] minMax = fr.getMinMax().get(featureType);
1209 if (minMax != null && minMax[0][0] != minMax[0][1])
1211 displayAtts.add(SCORE_18N);
1212 tooltips.add(SCORE_18N);
1216 FeatureAttributes fa = FeatureAttributes.getInstance();
1217 for (String[] attName : attNames)
1219 float[] minMax = fa.getMinMax(featureType, attName);
1220 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1221 if (!withText && !hasRange)
1225 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1226 String desc = fa.getDescription(featureType, attName);
1227 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1229 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1231 tooltips.add(desc == null ? "" : desc);
1234 JComboBox<String> attCombo = JvSwingUtils
1235 .buildComboWithTooltips(displayAtts, tooltips);
1241 * Populates initial layout of the feature attribute filters panel
1243 private JPanel initialiseFiltersPanel()
1245 filters = new ArrayList<>();
1247 JPanel outerPanel = new JPanel();
1248 outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
1249 outerPanel.setBackground(Color.white);
1252 * option to apply colour to sub-types as well (if there are any)
1254 if (!subTypes.isEmpty())
1256 outerPanel.add(initSubtypesPanel());
1259 JPanel filtersPanel = new JPanel();
1260 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1261 filtersPanel.setBackground(Color.white);
1262 JvSwingUtils.createTitledBorder(filtersPanel,
1263 MessageManager.getString("label.filters"), true);
1264 outerPanel.add(filtersPanel);
1266 JPanel andOrPanel = initialiseAndOrPanel();
1267 filtersPanel.add(andOrPanel);
1270 * panel with filters - populated by refreshFiltersDisplay,
1271 * which also sets the layout manager
1273 chooseFiltersPanel = new JPanel();
1274 chooseFiltersPanel.setBackground(Color.white);
1275 filtersPanel.add(chooseFiltersPanel);
1281 * Lays out the panel with radio buttons to AND or OR filter conditions
1285 private JPanel initialiseAndOrPanel()
1287 JPanel andOrPanel = new JPanel(new BorderLayout());
1288 andOrPanel.setBackground(Color.white);
1289 JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
1290 andOrPanel.add(panel1, BorderLayout.WEST);
1291 panel1.setBackground(Color.white);
1292 panel1.setBorder(BorderFactory.createLineBorder(debugBorderColour));
1293 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1294 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1295 ActionListener actionListener = new ActionListener()
1298 public void actionPerformed(ActionEvent e)
1303 andFilters.addActionListener(actionListener);
1304 orFilters.addActionListener(actionListener);
1305 ButtonGroup andOr = new ButtonGroup();
1306 andOr.add(andFilters);
1307 andOr.add(orFilters);
1308 andFilters.setSelected(true);
1310 new JLabel(MessageManager.getString("label.join_conditions")));
1311 panel1.add(andFilters);
1312 panel1.add(orFilters);
1318 * Builds a tooltip for the 'Apply to subtypes' checkbox with a list of
1319 * subtypes of this feature type
1323 protected String getSubtypesTooltip()
1325 StringBuilder sb = new StringBuilder(20 * subTypes.size());
1326 sb.append("Apply settings also to" + ":"); // todo i18n
1327 for (String child : subTypes)
1329 sb.append("<br>").append(child);
1331 String tooltip = JvSwingUtils.wrapTooltip(true, sb.toString());
1336 * Refreshes the display to show any filters currently configured for the
1337 * selected feature type (editable, with 'remove' option), plus one extra row
1338 * for adding a condition. This should be called after a filter has been
1339 * removed, added or amended.
1341 private void updateFiltersTab()
1344 * clear the panel and list of filter conditions
1346 chooseFiltersPanel.removeAll();
1350 * look up attributes known for feature type
1352 List<String[]> attNames = FeatureAttributes.getInstance()
1353 .getAttributes(featureType);
1356 * if this feature type has filters set, load them first
1358 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1359 if (featureFilters != null)
1361 if (!featureFilters.isAnded())
1363 orFilters.setSelected(true);
1365 featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1369 * and an empty filter for the user to populate (add)
1371 filters.add(FeatureMatcher.NULL_MATCHER);
1374 * use GridLayout to 'justify' rows to the top of the panel, until
1375 * there are too many to fit in, then fall back on BoxLayout
1377 if (filters.size() <= 5)
1379 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1383 chooseFiltersPanel.setLayout(
1384 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1388 * render the conditions in rows, each in its own JPanel
1390 int filterIndex = 0;
1391 for (FeatureMatcherI filter : filters)
1393 JPanel row = addFilter(filter, attNames, filterIndex);
1394 row.setBorder(BorderFactory.createLineBorder(debugBorderColour));
1395 chooseFiltersPanel.add(row);
1404 * A helper method that constructs a row (panel) with one filter condition:
1406 * <li>a drop-down list of Label, Score and attribute names to choose from</li>
1407 * <li>a drop-down list of conditions to choose from</li>
1408 * <li>a text field for input of a match pattern</li>
1409 * <li>optionally, a 'remove' button</li>
1411 * The filter values are set as defaults for the input fields. The 'remove'
1412 * button is added unless the pattern is empty (incomplete filter condition).
1414 * Action handlers on these fields provide for
1416 * <li>validate pattern field - should be numeric if condition is numeric</li>
1417 * <li>save filters and refresh display on any (valid) change</li>
1418 * <li>remove filter and refresh on 'Remove'</li>
1419 * <li>update conditions list on change of Label/Score/Attribute</li>
1420 * <li>refresh value field tooltip with min-max range on change of
1426 * @param filterIndex
1429 protected JPanel addFilter(FeatureMatcherI filter,
1430 List<String[]> attNames, int filterIndex)
1432 String[] attName = filter.getAttribute();
1433 Condition cond = filter.getMatcher().getCondition();
1434 String pattern = filter.getMatcher().getPattern();
1436 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1437 filterRow.setBackground(Color.white);
1440 * drop-down choice of attribute, with description as a tooltip
1441 * if we can obtain it
1443 final JComboBox<String> attCombo = populateAttributesDropdown(attNames,
1445 String filterBy = setSelectedAttribute(attCombo, filter);
1447 JComboBox<Condition> condCombo = new JComboBox<>();
1449 JTextField patternField = new JTextField(8);
1450 patternField.setText(pattern);
1453 * action handlers that validate and (if valid) apply changes
1455 ActionListener actionListener = new ActionListener()
1458 public void actionPerformed(ActionEvent e)
1460 if (validateFilter(patternField, condCombo))
1462 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1469 ItemListener itemListener = new ItemListener()
1472 public void itemStateChanged(ItemEvent e)
1474 actionListener.actionPerformed(null);
1478 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1480 attCombo.setSelectedIndex(0);
1484 attCombo.setSelectedItem(
1485 FeatureMatcher.toAttributeDisplayName(attName));
1487 attCombo.addItemListener(new ItemListener()
1490 public void itemStateChanged(ItemEvent e)
1493 * on change of attribute, refresh the conditions list to
1494 * ensure it is appropriate for the attribute datatype
1496 populateConditions((String) attCombo.getSelectedItem(),
1497 (Condition) condCombo.getSelectedItem(), condCombo,
1499 actionListener.actionPerformed(null);
1503 filterRow.add(attCombo);
1506 * drop-down choice of test condition
1508 populateConditions(filterBy, cond, condCombo, patternField);
1509 condCombo.setPreferredSize(new Dimension(150, 20));
1510 condCombo.addItemListener(itemListener);
1511 filterRow.add(condCombo);
1514 * pattern to match against
1516 patternField.addActionListener(actionListener);
1517 patternField.addFocusListener(new FocusAdapter()
1520 public void focusLost(FocusEvent e)
1522 actionListener.actionPerformed(null);
1525 filterRow.add(patternField);
1528 * disable pattern field for condition 'Present / NotPresent'
1530 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1531 patternField.setEnabled(selectedCondition.needsAPattern());
1534 * if a numeric condition is selected, show the value range
1535 * as a tooltip on the value input field
1537 setNumericHints(filterBy, selectedCondition, patternField);
1540 * add remove button if filter is populated (non-empty pattern)
1542 if (!patternField.isEnabled()
1543 || (pattern != null && pattern.trim().length() > 0))
1545 // todo: gif for button drawing '-' or 'x'
1546 JButton removeCondition = new BasicArrowButton(SwingConstants.WEST);
1548 .setToolTipText(MessageManager.getString("label.delete_row"));
1549 removeCondition.addActionListener(new ActionListener()
1552 public void actionPerformed(ActionEvent e)
1554 filters.remove(filterIndex);
1558 filterRow.add(removeCondition);
1565 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1571 private String setSelectedAttribute(JComboBox<String> attCombo,
1572 FeatureMatcherI filter)
1575 if (filter.isByScore())
1579 else if (filter.isByLabel())
1585 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1587 attCombo.setSelectedItem(item);
1592 * If a numeric comparison condition is selected, retrieves the min-max range
1593 * for the value (score or attribute), and sets it as a tooltip on the value
1594 * field. If the field is currently empty, then pre-populates it with
1596 * <li>the minimum value, if condition is > or >=</li>
1597 * <li>the maximum value, if condition is < or <=</li>
1601 * @param selectedCondition
1602 * @param patternField
1604 private void setNumericHints(String attName,
1605 Condition selectedCondition, JTextField patternField)
1607 patternField.setToolTipText("");
1609 if (selectedCondition.isNumeric())
1611 float[] minMax = getMinMax(attName);
1614 String minFormatted = DECFMT_2_2.format(minMax[0]);
1615 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1616 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1617 patternField.setToolTipText(tip);
1618 if (patternField.getText().isEmpty())
1620 if (selectedCondition == Condition.GE
1621 || selectedCondition == Condition.GT)
1623 patternField.setText(minFormatted);
1627 if (selectedCondition == Condition.LE
1628 || selectedCondition == Condition.LT)
1630 patternField.setText(maxFormatted);
1639 * Populates the drop-down list of comparison conditions for the given attribute
1640 * name. The conditions added depend on the datatype of the attribute values.
1641 * The supplied condition is set as the selected item in the list, provided it
1642 * is in the list. If the pattern is now invalid (non-numeric pattern for a
1643 * numeric condition), it is cleared.
1648 * @param patternField
1650 private void populateConditions(String attName, Condition cond,
1651 JComboBox<Condition> condCombo, JTextField patternField)
1653 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1654 FeatureMatcher.fromAttributeDisplayName(attName));
1655 if (LABEL_18N.equals(attName))
1657 type = Datatype.Character;
1659 else if (SCORE_18N.equals(attName))
1661 type = Datatype.Number;
1665 * remove itemListener before starting
1667 ItemListener listener = condCombo.getItemListeners()[0];
1668 condCombo.removeItemListener(listener);
1669 boolean condIsValid = false;
1671 condCombo.removeAllItems();
1672 for (Condition c : Condition.values())
1674 if ((c.isNumeric() && type == Datatype.Number)
1675 || (!c.isNumeric() && type != Datatype.Number))
1677 condCombo.addItem(c);
1686 * set the selected condition (does nothing if not in the list)
1690 condCombo.setSelectedItem(cond);
1694 condCombo.setSelectedIndex(0);
1698 * clear pattern if it is now invalid for condition
1700 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1704 String pattern = patternField.getText().trim();
1705 if (pattern.length() > 0)
1707 Float.valueOf(pattern);
1709 } catch (NumberFormatException e)
1711 patternField.setText("");
1716 * restore the listener
1718 condCombo.addItemListener(listener);
1722 * Answers true unless a numeric condition has been selected with a non-numeric
1723 * value. Sets the value field to RED with a tooltip if in error.
1725 * If the pattern is expected but is empty, this method returns false, but does
1726 * not mark the field as invalid. This supports selecting an attribute for a new
1727 * condition before a match pattern has been entered.
1732 protected boolean validateFilter(JTextField value,
1733 JComboBox<Condition> condCombo)
1735 if (value == null || condCombo == null)
1737 return true; // fields not populated
1740 Condition cond = (Condition) condCombo.getSelectedItem();
1741 if (!cond.needsAPattern())
1746 value.setBackground(Color.white);
1747 value.setToolTipText("");
1748 String v1 = value.getText().trim();
1749 if (v1.length() == 0)
1754 if (cond.isNumeric() && v1.length() > 0)
1759 } catch (NumberFormatException e)
1761 value.setBackground(Color.red);
1762 value.setToolTipText(
1763 MessageManager.getString("label.numeric_required"));
1772 * Constructs a filter condition from the given input fields, and replaces the
1773 * condition at filterIndex with the new one. Does nothing if the pattern field
1774 * is blank (unless the match condition is one that doesn't require a pattern,
1775 * e.g. 'Is present'). Answers true if the filter was updated, else false.
1777 * This method may update the tooltip on the filter value field to show the
1778 * value range, if a numeric condition is selected. This ensures the tooltip is
1779 * updated when a numeric valued attribute is chosen on the last 'add a filter'
1785 * @param filterIndex
1787 protected boolean updateFilter(JComboBox<String> attCombo,
1788 JComboBox<Condition> condCombo, JTextField valueField,
1791 String attName = (String) attCombo.getSelectedItem();
1792 Condition cond = (Condition) condCombo.getSelectedItem();
1793 String pattern = valueField.getText().trim();
1795 setNumericHints(attName, cond, valueField);
1797 if (pattern.length() == 0 && cond.needsAPattern())
1799 valueField.setEnabled(true); // ensure pattern field is enabled!
1804 * Construct a matcher that operates on Label, Score,
1805 * or named attribute
1807 FeatureMatcherI km = null;
1808 if (LABEL_18N.equals(attName))
1810 km = FeatureMatcher.byLabel(cond, pattern);
1812 else if (SCORE_18N.equals(attName))
1814 km = FeatureMatcher.byScore(cond, pattern);
1818 km = FeatureMatcher.byAttribute(cond, pattern,
1819 FeatureMatcher.fromAttributeDisplayName(attName));
1822 filters.set(filterIndex, km);
1828 * Makes the dialog visible, at the Feature Colour tab or at the Filters tab
1832 public void showTab(boolean coloursTab)
1835 tabbedPane.setSelectedIndex(coloursTab ? 0 : 1);
1839 * Action on any change to feature filtering, namely
1841 * <li>change of selected attribute</li>
1842 * <li>change of selected condition</li>
1843 * <li>change of match pattern</li>
1844 * <li>removal of a condition</li>
1846 * The inputs are parsed into a combined filter and this is set for the feature
1847 * type, and the alignment redrawn.
1849 protected void filtersChanged()
1852 * update the filter conditions for the feature type
1854 boolean anded = andFilters.isSelected();
1855 FeatureMatcherSetI combined = new FeatureMatcherSet();
1857 for (FeatureMatcherI filter : filters)
1859 String pattern = filter.getMatcher().getPattern();
1860 Condition condition = filter.getMatcher().getCondition();
1861 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1865 combined.and(filter);
1869 combined.or(filter);
1875 * save the filter conditions in the FeatureRenderer
1876 * (note this might now be an empty filter with no conditions)
1878 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1879 if (applyToSubtypes.isSelected())
1881 for (String child : subTypes)
1883 fr.setFeatureFilter(child, combined.isEmpty() ? null : combined);
1887 refreshFeatureSettings();
1888 ap.paintAlignment(true, true);