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.JTextField;
71 import javax.swing.SwingConstants;
72 import javax.swing.border.LineBorder;
73 import javax.swing.event.ChangeEvent;
74 import javax.swing.event.ChangeListener;
75 import javax.swing.plaf.basic.BasicArrowButton;
78 * A dialog where the user can configure colour scheme, and any filters, for one
81 * (Was FeatureColourChooser prior to Jalview 1.11, renamed with the addition of
84 public class FeatureTypeSettings extends JalviewDialog
86 private final static String LABEL_18N = MessageManager
87 .getString("label.label");
89 private final static String SCORE_18N = MessageManager
90 .getString("label.score");
92 private static final int RADIO_WIDTH = 130;
94 private static final String COLON = ":";
96 private static final int MAX_TOOLTIP_LENGTH = 50;
98 private static final int NO_COLOUR_OPTION = 0;
100 private static final int MIN_COLOUR_OPTION = 1;
102 private static final int MAX_COLOUR_OPTION = 2;
104 private static final int ABOVE_THRESHOLD_OPTION = 1;
106 private static final int BELOW_THRESHOLD_OPTION = 2;
108 private static final DecimalFormat DECFMT_2_2 = new DecimalFormat(
112 * FeatureRenderer holds colour scheme and filters for feature types
114 private final FeatureRenderer fr; // todo refactor to allow interface type
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();
165 * colours and filters are shown in tabbed view or single content pane
167 JPanel coloursPanel, filtersPanel;
169 JPanel singleColour = new JPanel();
171 private JPanel minColour = new JPanel();
173 private JPanel maxColour = new JPanel();
175 private JComboBox<String> threshold = new JComboBox<>();
177 private JSlider slider = new JSlider();
179 private JTextField thresholdValue = new JTextField(20);
181 private JCheckBox thresholdIsMin = new JCheckBox();
183 private GraphLine threshline;
185 private ActionListener featureSettings = null;
187 private ActionListener changeColourAction;
190 * choice of option for 'colour for no value'
192 private JComboBox<String> noValueCombo;
195 * choice of what to colour by text (Label or attribute)
197 private JComboBox<String> colourByTextCombo;
200 * choice of what to colour by range (Score or attribute)
202 private JComboBox<String> colourByRangeCombo;
204 private JRadioButton andFilters;
206 private JRadioButton orFilters;
209 * filters for the currently selected feature type
211 private List<FeatureMatcherI> filters;
213 private JPanel chooseFiltersPanel;
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 true, filter or colour settings are also applied to
223 * any feature sub-types in the Sequence Ontology
225 private boolean applyFiltersToSubtypes;
227 private boolean applyColourToSubtypes;
235 public FeatureTypeSettings(FeatureRenderer frender, String theType)
238 this.featureType = theType;
242 * determine sub-types (if any) of this feature type
244 List<String> types = fr.getRenderOrder();
245 subTypes = SequenceOntologyFactory.getInstance()
246 .getChildTerms(this.featureType, types);
247 Collections.sort(subTypes); // sort for ease of reading in tooltip
250 * save original colours and filters for this feature type
251 * and any sub-types, to restore on Cancel
253 originalFilters = new HashMap<>();
254 originalFilters.put(theType, fr.getFeatureFilter(theType));
255 originalColours = new HashMap<>();
256 originalColours.put(theType, fr.getFeatureColours().get(theType));
257 for (String child : subTypes)
259 originalFilters.put(child, fr.getFeatureFilter(child));
260 originalColours.put(child, fr.getFeatureColours().get(child));
268 } catch (Exception ex)
270 ex.printStackTrace();
280 colourChanged(false);
282 String title = MessageManager
283 .formatMessage("label.display_settings_for", new String[]
285 initDialogFrame(this, true, false, title, 500, 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(getRoundedSliderValue()));
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 sliderValueChanged();
699 slider.addMouseListener(new MouseAdapter()
702 public void mouseReleased(MouseEvent evt)
705 * only update Overview and/or structure colouring
706 * when threshold slider drag ends (mouse up)
710 ap.paintAlignment(true, true);
715 thresholdValue.setEnabled(false);
716 thresholdValue.setColumns(7);
718 thresholdPanel.add(threshold);
719 thresholdPanel.add(slider);
720 thresholdPanel.add(thresholdValue);
722 thresholdIsMin.setBackground(Color.white);
724 .setText(MessageManager.getString("label.threshold_minmax"));
725 thresholdIsMin.setToolTipText(MessageManager
726 .getString("label.toggle_absolute_relative_display_threshold"));
727 thresholdIsMin.addActionListener(changeColourAction);
728 thresholdPanel.add(thresholdIsMin);
730 return graduatedColourPanel;
734 * Lay out OK and Cancel buttons
738 private JPanel initialiseOkCancelPanel()
740 JPanel okCancelPanel = new JPanel();
741 // okCancelPanel.setBackground(Color.white);
742 okCancelPanel.add(ok);
743 okCancelPanel.add(cancel);
744 return okCancelPanel;
748 * Lay out Colour options panel, containing
750 * <li>plain colour, with colour picker</li>
751 * <li>colour by text, with choice of Label or other attribute</li>
752 * <li>colour by range, of score or other attribute, when available</li>
757 private JPanel initialiseColoursPanel()
759 JPanel colourByPanel = new JPanel();
760 colourByPanel.setBackground(Color.white);
761 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
762 JvSwingUtils.createTitledBorder(colourByPanel,
763 MessageManager.getString("action.colour"), true);
766 * option to apply colour to sub-types as well (if there are any)
768 if (!subTypes.isEmpty())
770 applyColourToSubtypes = false;
771 colourByPanel.add(initSubtypesPanel(false));
775 * simple colour radio button and colour picker
777 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
778 simpleColourPanel.setBackground(Color.white);
779 colourByPanel.add(simpleColourPanel);
781 simpleColour = new JRadioButton(
782 MessageManager.getString("label.simple_colour"));
783 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
784 simpleColour.addItemListener(new ItemListener()
787 public void itemStateChanged(ItemEvent e)
789 if (simpleColour.isSelected() && !adjusting)
796 singleColour.setFont(JvSwingUtils.getLabelFont());
797 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
798 singleColour.setPreferredSize(new Dimension(40, 20));
799 singleColour.addMouseListener(new MouseAdapter()
802 public void mousePressed(MouseEvent e)
804 if (simpleColour.isSelected())
806 showColourChooser(singleColour, "label.select_colour");
810 simpleColourPanel.add(simpleColour); // radio button
811 simpleColourPanel.add(singleColour); // colour picker button
814 * colour by text (category) radio button and drop-down choice list
816 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
817 byTextPanel.setBackground(Color.white);
818 JvSwingUtils.createTitledBorder(byTextPanel,
819 MessageManager.getString("label.colour_by_text"), true);
820 colourByPanel.add(byTextPanel);
821 byCategory = new JRadioButton(
822 MessageManager.getString("label.by_text_of") + COLON);
823 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
824 byCategory.addItemListener(new ItemListener()
827 public void itemStateChanged(ItemEvent e)
829 if (byCategory.isSelected())
835 byTextPanel.add(byCategory);
837 List<String[]> attNames = FeatureAttributes.getInstance()
838 .getAttributes(featureType);
839 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
840 colourByTextCombo.addItemListener(new ItemListener()
843 public void itemStateChanged(ItemEvent e)
848 byTextPanel.add(colourByTextCombo);
851 * graduated colour panel
853 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
854 colourByPanel.add(graduatedColourPanel);
857 * 3 radio buttons select between simple colour,
858 * by category (text), or graduated
860 ButtonGroup bg = new ButtonGroup();
861 bg.add(simpleColour);
863 bg.add(graduatedColour);
865 return colourByPanel;
869 * Constructs and returns a panel with a checkbox for the option to apply any
870 * changes also to sub-types of the feature type
874 protected JPanel initSubtypesPanel(final boolean forFilters)
876 JPanel toSubtypes = new JPanel(new FlowLayout(FlowLayout.LEFT));
877 toSubtypes.setBackground(Color.WHITE);
878 JCheckBox applyToSubtypesCB = new JCheckBox(MessageManager
879 .formatMessage("label.apply_to_subtypes", featureType));
880 applyToSubtypesCB.setToolTipText(getSubtypesTooltip());
881 applyToSubtypesCB.addActionListener(new ActionListener()
884 * reset and reapply settings on toggle of checkbox
887 public void actionPerformed(ActionEvent e)
891 applyFiltersToSubtypes = applyToSubtypesCB.isSelected();
892 restoreOriginalFilters();
897 applyColourToSubtypes = applyToSubtypesCB.isSelected();
898 restoreOriginalColours();
903 toSubtypes.add(applyToSubtypesCB);
908 private void showColourChooser(JPanel colourPanel, String key)
910 Color col = JColorChooser.showDialog(this,
911 MessageManager.getString(key), colourPanel.getBackground());
914 colourPanel.setBackground(col);
915 colourPanel.setForeground(col);
917 colourPanel.repaint();
922 * Constructs and sets the selected colour options as the colour for the
923 * feature type, and repaints the alignment, and optionally the Overview
924 * and/or structure viewer if open
926 * @param updateStructsAndOverview
928 void colourChanged(boolean updateStructsAndOverview)
933 * ignore action handlers while setting values programmatically
939 * ensure min-max range is for the latest choice of
940 * 'graduated colour by'
942 updateColourMinMax();
944 FeatureColourI acg = makeColourFromInputs();
947 * save the colour, and set on subtypes if selected
949 fr.setColour(featureType, acg);
950 if (applyColourToSubtypes)
952 for (String child : subTypes)
954 fr.setColour(child, acg);
957 refreshFeatureSettings();
958 ap.paintAlignment(updateStructsAndOverview, updateStructsAndOverview);
964 * Converts the input values into an instance of FeatureColour
968 private FeatureColourI makeColourFromInputs()
971 * easiest case - a single colour
973 if (simpleColour.isSelected())
975 return new FeatureColour(singleColour.getBackground());
979 * next easiest case - colour by Label, or attribute text
981 if (byCategory.isSelected())
983 Color c = singleColour.getBackground();
984 FeatureColourI fc = new FeatureColour(c);
985 fc.setColourByLabel(true);
986 String byWhat = (String) colourByTextCombo.getSelectedItem();
987 if (!LABEL_18N.equals(byWhat))
990 FeatureMatcher.fromAttributeDisplayName(byWhat));
996 * remaining case - graduated colour by score, or attribute value
998 Color noColour = null;
999 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
1001 noColour = minColour.getBackground();
1003 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
1005 noColour = maxColour.getBackground();
1011 thresh = Float.valueOf(thresholdValue.getText());
1012 } catch (NumberFormatException e)
1014 // invalid inputs are already handled on entry
1018 * min-max range is to (or from) threshold value if
1019 * 'threshold is min/max' is selected
1021 float minValue = min;
1022 float maxValue = max;
1023 final int thresholdOption = threshold.getSelectedIndex();
1024 if (thresholdIsMin.isSelected()
1025 && thresholdOption == ABOVE_THRESHOLD_OPTION)
1029 if (thresholdIsMin.isSelected()
1030 && thresholdOption == BELOW_THRESHOLD_OPTION)
1036 * make the graduated colour
1038 FeatureColourI fc = new FeatureColour(minColour.getBackground(),
1039 maxColour.getBackground(), noColour, minValue, maxValue);
1042 * set attribute to colour by if selected
1044 String byWhat = (String) colourByRangeCombo.getSelectedItem();
1045 if (!SCORE_18N.equals(byWhat))
1047 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
1051 * set threshold options and 'autoscaled' which is
1052 * false if 'threshold is min/max' is selected
1053 * else true (colour range is on actual range of values)
1055 fc.setThreshold(thresh);
1056 fc.setAutoScaled(!thresholdIsMin.isSelected());
1057 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
1058 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
1060 if (threshline == null)
1063 * todo not yet implemented: visual indication of feature threshold
1065 threshline = new GraphLine((max - min) / 2f, "Threshold",
1073 protected void raiseClosed()
1075 refreshFeatureSettings();
1078 protected void refreshFeatureSettings()
1080 if (this.featureSettings != null)
1082 featureSettings.actionPerformed(new ActionEvent(this, 0, "REFRESH"));
1087 * Action on OK is just to dismiss the dialog - any changes have already been
1091 public void okPressed()
1096 * Action on Cancel is to restore colour scheme and filters as they were when
1097 * the dialog was opened (including any feature sub-types that may have been
1101 public void cancelPressed()
1103 restoreOriginalColours();
1104 restoreOriginalFilters();
1105 ap.paintAlignment(true, true);
1108 protected void restoreOriginalFilters()
1110 for (Entry<String, FeatureMatcherSetI> entry : originalFilters
1113 fr.setFeatureFilter(entry.getKey(), entry.getValue());
1117 protected void restoreOriginalColours()
1119 for (Entry<String, FeatureColourI> entry : originalColours.entrySet())
1121 fr.setColour(entry.getKey(), entry.getValue());
1126 * Action on text entry of a threshold value
1128 protected void thresholdValue_actionPerformed()
1133 float f = Float.parseFloat(thresholdValue.getText());
1134 slider.setValue((int) (f * scaleFactor));
1135 threshline.value = f;
1136 thresholdValue.setBackground(Color.white); // ok
1139 * force repaint of any Overview window or structure
1141 ap.paintAlignment(true, true);
1142 } catch (NumberFormatException ex)
1144 thresholdValue.setBackground(Color.red); // not ok
1152 * Action on change of threshold slider value. This may be done interactively
1153 * (by moving the slider), or programmatically (to update the slider after
1154 * manual input of a threshold value).
1156 protected void sliderValueChanged()
1158 threshline.value = getRoundedSliderValue();
1161 * repaint alignment, but not Overview or structure,
1162 * to avoid overload while dragging the slider
1164 colourChanged(false);
1168 * Converts the slider value to its absolute value by dividing by the
1169 * scaleFactor. Rounding errors are squashed by forcing min/max of slider
1170 * range to the actual min/max of feature score range
1174 private float getRoundedSliderValue()
1176 int value = slider.getValue();
1177 float f = value == slider.getMaximum() ? max
1178 : (value == slider.getMinimum() ? min : value / scaleFactor);
1182 void addActionListener(ActionListener listener)
1184 if (featureSettings != null)
1187 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1189 featureSettings = listener;
1193 * A helper method to build the drop-down choice of attributes for a feature.
1194 * If 'withRange' is true, then Score, and any attributes with a min-max
1195 * range, are added. If 'withText' is true, Label and any known attributes are
1196 * added. This allows 'categorical numerical' attributes e.g. codon position
1197 * to be coloured by text.
1199 * Where metadata is available with a description for an attribute, that is
1200 * added as a tooltip.
1202 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1203 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1205 * This method does not add any ActionListener to the JComboBox.
1211 protected JComboBox<String> populateAttributesDropdown(
1212 List<String[]> attNames, boolean withRange, boolean withText)
1214 List<String> displayAtts = new ArrayList<>();
1215 List<String> tooltips = new ArrayList<>();
1219 displayAtts.add(LABEL_18N);
1220 tooltips.add(MessageManager.getString("label.description"));
1224 float[][] minMax = fr.getMinMax().get(featureType);
1225 if (minMax != null && minMax[0][0] != minMax[0][1])
1227 displayAtts.add(SCORE_18N);
1228 tooltips.add(SCORE_18N);
1232 FeatureAttributes fa = FeatureAttributes.getInstance();
1233 for (String[] attName : attNames)
1235 float[] minMax = fa.getMinMax(featureType, attName);
1236 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1237 if (!withText && !hasRange)
1241 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1242 String desc = fa.getDescription(featureType, attName);
1243 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1245 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1247 tooltips.add(desc == null ? "" : desc);
1250 JComboBox<String> attCombo = JvSwingUtils
1251 .buildComboWithTooltips(displayAtts, tooltips);
1257 * Populates initial layout of the feature attribute filters panel
1259 private JPanel initialiseFiltersPanel()
1261 filters = new ArrayList<>();
1263 JPanel outerPanel = new JPanel();
1264 outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
1265 outerPanel.setBackground(Color.white);
1268 * option to apply colour to sub-types as well (if there are any)
1270 if (!subTypes.isEmpty())
1272 applyFiltersToSubtypes = false;
1273 outerPanel.add(initSubtypesPanel(true));
1276 JPanel filtersPanel = new JPanel();
1277 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1278 filtersPanel.setBackground(Color.white);
1279 JvSwingUtils.createTitledBorder(filtersPanel,
1280 MessageManager.getString("label.filters"), true);
1281 outerPanel.add(filtersPanel);
1283 JPanel andOrPanel = initialiseAndOrPanel();
1284 filtersPanel.add(andOrPanel);
1287 * panel with filters - populated by refreshFiltersDisplay,
1288 * which also sets the layout manager
1290 chooseFiltersPanel = new JPanel();
1291 chooseFiltersPanel.setBackground(Color.white);
1292 filtersPanel.add(chooseFiltersPanel);
1298 * Lays out the panel with radio buttons to AND or OR filter conditions
1302 private JPanel initialiseAndOrPanel()
1304 JPanel andOrPanel = new JPanel(new BorderLayout());
1305 andOrPanel.setBackground(Color.white);
1307 // JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
1308 // andOrPanel.add(panel1, BorderLayout.WEST);
1309 // panel1.setBackground(Color.white);
1310 // panel1.setBorder(BorderFactory.createLineBorder(debugBorderColour));
1311 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1312 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1313 ActionListener actionListener = new ActionListener()
1316 public void actionPerformed(ActionEvent e)
1321 andFilters.addActionListener(actionListener);
1322 orFilters.addActionListener(actionListener);
1323 ButtonGroup andOr = new ButtonGroup();
1324 andOr.add(andFilters);
1325 andOr.add(orFilters);
1326 andFilters.setSelected(true);
1328 new JLabel(MessageManager.getString("label.join_conditions")));
1329 andOrPanel.add(andFilters);
1330 andOrPanel.add(orFilters);
1336 * Builds a tooltip for the 'Apply to subtypes' checkbox with a list of
1337 * subtypes of this feature type
1341 protected String getSubtypesTooltip()
1343 StringBuilder sb = new StringBuilder(20 * subTypes.size());
1344 sb.append(MessageManager.getString("label.apply_also_to"));
1345 for (String child : subTypes)
1347 sb.append("<br>").append(child);
1349 String tooltip = JvSwingUtils.wrapTooltip(true, sb.toString());
1354 * Refreshes the display to show any filters currently configured for the
1355 * selected feature type (editable, with 'remove' option), plus one extra row
1356 * for adding a condition. This should be called after a filter has been
1357 * removed, added or amended.
1359 private void updateFiltersTab()
1362 * clear the panel and list of filter conditions
1364 chooseFiltersPanel.removeAll();
1368 * look up attributes known for feature type
1370 List<String[]> attNames = FeatureAttributes.getInstance()
1371 .getAttributes(featureType);
1374 * if this feature type has filters set, load them first
1376 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1377 if (featureFilters != null)
1379 if (!featureFilters.isAnded())
1381 orFilters.setSelected(true);
1383 featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1387 * and an empty filter for the user to populate (add)
1389 filters.add(FeatureMatcher.NULL_MATCHER);
1392 * use GridLayout to 'justify' rows to the top of the panel, until
1393 * there are too many to fit in, then fall back on BoxLayout
1395 if (filters.size() <= 5)
1397 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1401 chooseFiltersPanel.setLayout(
1402 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1406 * render the conditions in rows, each in its own JPanel
1408 int filterIndex = 0;
1409 for (FeatureMatcherI filter : filters)
1411 JPanel row = addFilter(filter, attNames, filterIndex);
1412 chooseFiltersPanel.add(row);
1421 * A helper method that constructs a row (panel) with one filter condition:
1423 * <li>a drop-down list of Label, Score and attribute names to choose
1425 * <li>a drop-down list of conditions to choose from</li>
1426 * <li>a text field for input of a match pattern</li>
1427 * <li>optionally, a 'remove' button</li>
1429 * The filter values are set as defaults for the input fields. The 'remove'
1430 * button is added unless the pattern is empty (incomplete filter condition).
1432 * Action handlers on these fields provide for
1434 * <li>validate pattern field - should be numeric if condition is numeric</li>
1435 * <li>save filters and refresh display on any (valid) change</li>
1436 * <li>remove filter and refresh on 'Remove'</li>
1437 * <li>update conditions list on change of Label/Score/Attribute</li>
1438 * <li>refresh value field tooltip with min-max range on change of
1444 * @param filterIndex
1447 protected JPanel addFilter(FeatureMatcherI filter,
1448 List<String[]> attNames, int filterIndex)
1450 String[] attName = filter.getAttribute();
1451 Condition cond = filter.getMatcher().getCondition();
1452 String pattern = filter.getMatcher().getPattern();
1454 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1455 filterRow.setBackground(Color.white);
1458 * drop-down choice of attribute, with description as a tooltip
1459 * if we can obtain it
1461 final JComboBox<String> attCombo = populateAttributesDropdown(attNames,
1463 String filterBy = setSelectedAttribute(attCombo, filter);
1465 JComboBox<Condition> condCombo = new JComboBox<>();
1467 JTextField patternField = new JTextField(8);
1468 patternField.setText(pattern);
1471 * action handlers that validate and (if valid) apply changes
1473 ActionListener actionListener = new ActionListener()
1476 public void actionPerformed(ActionEvent e)
1478 if (validateFilter(patternField, condCombo))
1480 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1487 ItemListener itemListener = new ItemListener()
1490 public void itemStateChanged(ItemEvent e)
1492 actionListener.actionPerformed(null);
1496 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1498 attCombo.setSelectedIndex(0);
1502 attCombo.setSelectedItem(
1503 FeatureMatcher.toAttributeDisplayName(attName));
1505 attCombo.addItemListener(new ItemListener()
1508 public void itemStateChanged(ItemEvent e)
1511 * on change of attribute, refresh the conditions list to
1512 * ensure it is appropriate for the attribute datatype
1514 populateConditions((String) attCombo.getSelectedItem(),
1515 (Condition) condCombo.getSelectedItem(), condCombo,
1517 actionListener.actionPerformed(null);
1521 filterRow.add(attCombo);
1524 * drop-down choice of test condition
1526 populateConditions(filterBy, cond, condCombo, patternField);
1527 condCombo.setPreferredSize(new Dimension(150, 20));
1528 condCombo.addItemListener(itemListener);
1529 filterRow.add(condCombo);
1532 * pattern to match against
1534 patternField.addActionListener(actionListener);
1535 patternField.addFocusListener(new FocusAdapter()
1538 public void focusLost(FocusEvent e)
1540 actionListener.actionPerformed(null);
1543 filterRow.add(patternField);
1546 * disable pattern field for condition 'Present / NotPresent'
1548 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1549 patternField.setEnabled(selectedCondition.needsAPattern());
1552 * if a numeric condition is selected, show the value range
1553 * as a tooltip on the value input field
1555 setNumericHints(filterBy, selectedCondition, patternField);
1558 * add remove button if filter is populated (non-empty pattern)
1560 if (!patternField.isEnabled()
1561 || (pattern != null && pattern.trim().length() > 0))
1563 // todo: gif for button drawing '-' or 'x'
1564 JButton removeCondition = new BasicArrowButton(SwingConstants.WEST);
1566 .setToolTipText(MessageManager.getString("label.delete_row"));
1567 removeCondition.addActionListener(new ActionListener()
1570 public void actionPerformed(ActionEvent e)
1572 filters.remove(filterIndex);
1576 filterRow.add(removeCondition);
1583 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1589 private String setSelectedAttribute(JComboBox<String> attCombo,
1590 FeatureMatcherI filter)
1593 if (filter.isByScore())
1597 else if (filter.isByLabel())
1603 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1605 attCombo.setSelectedItem(item);
1610 * If a numeric comparison condition is selected, retrieves the min-max range
1611 * for the value (score or attribute), and sets it as a tooltip on the value
1612 * field. If the field is currently empty, then pre-populates it with
1614 * <li>the minimum value, if condition is > or >=</li>
1615 * <li>the maximum value, if condition is < or <=</li>
1619 * @param selectedCondition
1620 * @param patternField
1622 private void setNumericHints(String attName, Condition selectedCondition,
1623 JTextField patternField)
1625 patternField.setToolTipText("");
1627 if (selectedCondition.isNumeric())
1629 float[] minMax = getMinMax(attName);
1632 String minFormatted = DECFMT_2_2.format(minMax[0]);
1633 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1634 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1635 patternField.setToolTipText(tip);
1636 if (patternField.getText().isEmpty())
1638 if (selectedCondition == Condition.GE
1639 || selectedCondition == Condition.GT)
1641 patternField.setText(minFormatted);
1645 if (selectedCondition == Condition.LE
1646 || selectedCondition == Condition.LT)
1648 patternField.setText(maxFormatted);
1657 * Populates the drop-down list of comparison conditions for the given
1658 * attribute name. The conditions added depend on the datatype of the
1659 * attribute values. The supplied condition is set as the selected item in the
1660 * list, provided it is in the list. If the pattern is now invalid
1661 * (non-numeric pattern for a numeric condition), it is cleared.
1666 * @param patternField
1668 private void populateConditions(String attName, Condition cond,
1669 JComboBox<Condition> condCombo, JTextField patternField)
1671 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1672 FeatureMatcher.fromAttributeDisplayName(attName));
1673 if (LABEL_18N.equals(attName))
1675 type = Datatype.Character;
1677 else if (SCORE_18N.equals(attName))
1679 type = Datatype.Number;
1683 * remove itemListener before starting
1685 ItemListener listener = condCombo.getItemListeners()[0];
1686 condCombo.removeItemListener(listener);
1687 boolean condIsValid = false;
1689 condCombo.removeAllItems();
1690 for (Condition c : Condition.values())
1692 if ((c.isNumeric() && type == Datatype.Number)
1693 || (!c.isNumeric() && type != Datatype.Number))
1695 condCombo.addItem(c);
1704 * set the selected condition (does nothing if not in the list)
1708 condCombo.setSelectedItem(cond);
1712 condCombo.setSelectedIndex(0);
1716 * clear pattern if it is now invalid for condition
1718 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1722 String pattern = patternField.getText().trim();
1723 if (pattern.length() > 0)
1725 Float.valueOf(pattern);
1727 } catch (NumberFormatException e)
1729 patternField.setText("");
1734 * restore the listener
1736 condCombo.addItemListener(listener);
1740 * Answers true unless a numeric condition has been selected with a
1741 * non-numeric value. Sets the value field to RED with a tooltip if in error.
1743 * If the pattern is expected but is empty, this method returns false, but
1744 * does not mark the field as invalid. This supports selecting an attribute
1745 * for a new condition before a match pattern has been entered.
1750 protected boolean validateFilter(JTextField value,
1751 JComboBox<Condition> condCombo)
1753 if (value == null || condCombo == null)
1755 return true; // fields not populated
1758 Condition cond = (Condition) condCombo.getSelectedItem();
1759 if (!cond.needsAPattern())
1764 value.setBackground(Color.white);
1765 value.setToolTipText("");
1766 String v1 = value.getText().trim();
1767 if (v1.length() == 0)
1772 if (cond.isNumeric() && v1.length() > 0)
1777 } catch (NumberFormatException e)
1779 value.setBackground(Color.red);
1780 value.setToolTipText(
1781 MessageManager.getString("label.numeric_required"));
1790 * Constructs a filter condition from the given input fields, and replaces the
1791 * condition at filterIndex with the new one. Does nothing if the pattern
1792 * field is blank (unless the match condition is one that doesn't require a
1793 * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1796 * This method may update the tooltip on the filter value field to show the
1797 * value range, if a numeric condition is selected. This ensures the tooltip
1798 * is updated when a numeric valued attribute is chosen on the last 'add a
1804 * @param filterIndex
1806 protected boolean updateFilter(JComboBox<String> attCombo,
1807 JComboBox<Condition> condCombo, JTextField valueField,
1810 String attName = (String) attCombo.getSelectedItem();
1811 Condition cond = (Condition) condCombo.getSelectedItem();
1812 String pattern = valueField.getText().trim();
1814 setNumericHints(attName, cond, valueField);
1816 if (pattern.length() == 0 && cond.needsAPattern())
1818 valueField.setEnabled(true); // ensure pattern field is enabled!
1823 * Construct a matcher that operates on Label, Score,
1824 * or named attribute
1826 FeatureMatcherI km = null;
1827 if (LABEL_18N.equals(attName))
1829 km = FeatureMatcher.byLabel(cond, pattern);
1831 else if (SCORE_18N.equals(attName))
1833 km = FeatureMatcher.byScore(cond, pattern);
1837 km = FeatureMatcher.byAttribute(cond, pattern,
1838 FeatureMatcher.fromAttributeDisplayName(attName));
1841 filters.set(filterIndex, km);
1847 * Action on any change to feature filtering, namely
1849 * <li>change of selected attribute</li>
1850 * <li>change of selected condition</li>
1851 * <li>change of match pattern</li>
1852 * <li>removal of a condition</li>
1854 * The inputs are parsed into a combined filter and this is set for the
1855 * feature type, and the alignment redrawn.
1857 protected void filtersChanged()
1860 * update the filter conditions for the feature type
1862 boolean anded = andFilters.isSelected();
1863 FeatureMatcherSetI combined = new FeatureMatcherSet();
1865 for (FeatureMatcherI filter : filters)
1867 String pattern = filter.getMatcher().getPattern();
1868 Condition condition = filter.getMatcher().getCondition();
1869 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1873 combined.and(filter);
1877 combined.or(filter);
1883 * save the filter conditions in the FeatureRenderer
1884 * (note this might now be an empty filter with no conditions)
1886 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1887 if (applyFiltersToSubtypes)
1889 for (String child : subTypes)
1891 fr.setFeatureFilter(child, combined.isEmpty() ? null : combined);
1895 refreshFeatureSettings();
1896 ap.paintAlignment(true, true);