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 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)
237 this(frender, false, theType);
241 * Constructor, with option to make a blocking dialog (has to complete in the
242 * AWT event queue thread). Currently this option is always set to false.
248 FeatureTypeSettings(FeatureRenderer frender, boolean blocking,
252 this.featureType = theType;
256 * determine sub-types (if any) of this feature type
258 List<String> types = fr.getRenderOrder();
259 subTypes = SequenceOntologyFactory.getInstance()
260 .getChildTerms(this.featureType, types);
261 Collections.sort(subTypes); // sort for ease of reading in tooltip
264 * save original colours and filters for this feature type
265 * and any sub-types, to restore on Cancel
267 originalFilters = new HashMap<>();
268 originalFilters.put(theType, fr.getFeatureFilter(theType));
269 originalColours = new HashMap<>();
270 originalColours.put(theType, fr.getFeatureColours().get(theType));
271 for (String child : subTypes)
273 originalFilters.put(child, fr.getFeatureFilter(child));
274 originalColours.put(child, fr.getFeatureColours().get(child));
282 } catch (Exception ex)
284 ex.printStackTrace();
294 colourChanged(false);
296 String title = MessageManager
297 .formatMessage("label.display_settings_for", new String[]
299 initDialogFrame(this, true, blocking, title, 600, 360);
305 * Configures the widgets on the Colours tab according to the current feature
308 private void updateColoursTab()
310 FeatureColourI fc = fr.getFeatureColours().get(featureType);
313 * suppress action handling while updating values programmatically
321 if (fc.isSimpleColour())
323 simpleColour.setSelected(true);
324 singleColour.setBackground(fc.getColour());
325 singleColour.setForeground(fc.getColour());
329 * colour by text (Label or attribute text)
331 if (fc.isColourByLabel())
333 byCategory.setSelected(true);
334 colourByTextCombo.setEnabled(colourByTextCombo.getItemCount() > 1);
335 if (fc.isColourByAttribute())
337 String[] attributeName = fc.getAttributeName();
338 colourByTextCombo.setSelectedItem(
339 FeatureMatcher.toAttributeDisplayName(attributeName));
343 colourByTextCombo.setSelectedItem(LABEL_18N);
348 colourByTextCombo.setEnabled(false);
351 if (!fc.isGraduatedColour())
353 colourByRangeCombo.setEnabled(false);
354 minColour.setEnabled(false);
355 maxColour.setEnabled(false);
356 noValueCombo.setEnabled(false);
357 threshold.setEnabled(false);
358 slider.setEnabled(false);
359 thresholdValue.setEnabled(false);
360 thresholdIsMin.setEnabled(false);
365 * Graduated colour, by score or attribute value range
367 graduatedColour.setSelected(true);
368 updateColourMinMax(); // ensure min, max are set
369 colourByRangeCombo.setEnabled(colourByRangeCombo.getItemCount() > 1);
370 minColour.setEnabled(true);
371 maxColour.setEnabled(true);
372 noValueCombo.setEnabled(true);
373 threshold.setEnabled(true);
374 minColour.setBackground(fc.getMinColour());
375 maxColour.setBackground(fc.getMaxColour());
377 if (fc.isColourByAttribute())
379 String[] attributeName = fc.getAttributeName();
380 colourByRangeCombo.setSelectedItem(
381 FeatureMatcher.toAttributeDisplayName(attributeName));
385 colourByRangeCombo.setSelectedItem(SCORE_18N);
387 Color noColour = fc.getNoColour();
388 if (noColour == null)
390 noValueCombo.setSelectedIndex(NO_COLOUR_OPTION);
392 else if (noColour.equals(fc.getMinColour()))
394 noValueCombo.setSelectedIndex(MIN_COLOUR_OPTION);
396 else if (noColour.equals(fc.getMaxColour()))
398 noValueCombo.setSelectedIndex(MAX_COLOUR_OPTION);
402 * update min-max scaling if there is a range to work with,
403 * else disable the widgets (this shouldn't happen if only
404 * valid options are offered in the combo box)
406 scaleFactor = (max == min) ? 1f : 100f / (max - min);
407 float range = (max - min) * scaleFactor;
408 slider.setMinimum((int) (min * scaleFactor));
409 slider.setMaximum((int) (max * scaleFactor));
410 slider.setMajorTickSpacing((int) (range / 10f));
412 threshline = new GraphLine((max - min) / 2f, "Threshold",
414 threshline.value = fc.getThreshold();
416 if (fc.hasThreshold())
418 threshold.setSelectedIndex(
419 fc.isAboveThreshold() ? ABOVE_THRESHOLD_OPTION
420 : BELOW_THRESHOLD_OPTION);
421 slider.setEnabled(true);
422 slider.setValue((int) (fc.getThreshold() * scaleFactor));
423 thresholdValue.setText(String.valueOf(getRoundedSliderValue()));
424 thresholdValue.setEnabled(true);
425 thresholdIsMin.setEnabled(true);
429 slider.setEnabled(false);
430 thresholdValue.setEnabled(false);
431 thresholdIsMin.setEnabled(false);
433 thresholdIsMin.setSelected(!fc.isAutoScaled());
441 * Configures the initial layout
443 private void initialise()
445 this.setLayout(new BorderLayout());
446 tabbedPane = new JTabbedPane();
447 this.add(tabbedPane, BorderLayout.CENTER);
450 * an ActionListener that applies colour changes
452 changeColourAction = new ActionListener()
455 public void actionPerformed(ActionEvent e)
462 * first tab: colour options
464 JPanel coloursPanel = initialiseColoursPanel();
465 tabbedPane.addTab(MessageManager.getString("action.colour"),
469 * second tab: filter options
471 JPanel filtersPanel = initialiseFiltersPanel();
472 tabbedPane.addTab(MessageManager.getString("label.filters"),
475 JPanel okCancelPanel = initialiseOkCancelPanel();
477 this.add(okCancelPanel, BorderLayout.SOUTH);
481 * Updates the min-max range if Colour By selected item is Score, or an
482 * attribute, with a min-max range
484 protected void updateColourMinMax()
486 if (!graduatedColour.isSelected())
491 String colourBy = (String) colourByRangeCombo.getSelectedItem();
492 float[] minMax = getMinMax(colourBy);
502 * Retrieves the min-max range:
504 * <li>of feature score, if colour or filter is by Score</li>
505 * <li>else of the selected attribute</li>
511 private float[] getMinMax(String attName)
513 float[] minMax = null;
514 if (SCORE_18N.equals(attName))
516 minMax = fr.getMinMax().get(featureType)[0];
520 // colour by attribute range
521 minMax = FeatureAttributes.getInstance().getMinMax(featureType,
522 FeatureMatcher.fromAttributeDisplayName(attName));
528 * Lay out fields for graduated colour (by score or attribute value)
532 private JPanel initialiseGraduatedColourPanel()
534 JPanel graduatedColourPanel = new JPanel();
535 graduatedColourPanel.setLayout(
536 new BoxLayout(graduatedColourPanel, BoxLayout.Y_AXIS));
537 JvSwingUtils.createTitledBorder(graduatedColourPanel,
538 MessageManager.getString("label.graduated_colour"), true);
539 graduatedColourPanel.setBackground(Color.white);
542 * first row: graduated colour radio button, score/attribute drop-down
544 JPanel graduatedChoicePanel = new JPanel(
545 new FlowLayout(FlowLayout.LEFT));
546 graduatedChoicePanel.setBackground(Color.white);
547 graduatedColour = new JRadioButton(
548 MessageManager.getString("label.by_range_of") + COLON);
549 graduatedColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
550 graduatedColour.addItemListener(new ItemListener()
553 public void itemStateChanged(ItemEvent e)
555 if (graduatedColour.isSelected())
561 graduatedChoicePanel.add(graduatedColour);
563 List<String[]> attNames = FeatureAttributes.getInstance()
564 .getAttributes(featureType);
565 colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
566 colourByRangeCombo.addItemListener(new ItemListener()
569 public void itemStateChanged(ItemEvent e)
576 * disable graduated colour option if no range found
578 graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
580 graduatedChoicePanel.add(colourByRangeCombo);
581 graduatedColourPanel.add(graduatedChoicePanel);
584 * second row - min/max/no colours
586 JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
587 colourRangePanel.setBackground(Color.white);
588 graduatedColourPanel.add(colourRangePanel);
590 minColour.setFont(JvSwingUtils.getLabelFont());
591 minColour.setBorder(BorderFactory.createLineBorder(Color.black));
592 minColour.setPreferredSize(new Dimension(40, 20));
593 minColour.setToolTipText(MessageManager.getString("label.min_colour"));
594 minColour.addMouseListener(new MouseAdapter()
597 public void mousePressed(MouseEvent e)
599 if (minColour.isEnabled())
601 showColourChooser(minColour, "label.select_colour_minimum_value");
606 maxColour.setFont(JvSwingUtils.getLabelFont());
607 maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
608 maxColour.setPreferredSize(new Dimension(40, 20));
609 maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
610 maxColour.addMouseListener(new MouseAdapter()
613 public void mousePressed(MouseEvent e)
615 if (maxColour.isEnabled())
617 showColourChooser(maxColour, "label.select_colour_maximum_value");
621 maxColour.setBorder(new LineBorder(Color.black));
624 * default max colour to current colour (if a plain colour),
625 * or to Black if colour by label; make min colour a pale
626 * version of max colour
628 FeatureColourI fc = fr.getFeatureColours().get(featureType);
629 Color bg = fc.isSimpleColour() ? fc.getColour() : Color.BLACK;
630 maxColour.setBackground(bg);
631 minColour.setBackground(ColorUtils.bleachColour(bg, 0.9f));
633 noValueCombo = new JComboBox<>();
634 noValueCombo.addItem(MessageManager.getString("label.no_colour"));
635 noValueCombo.addItem(MessageManager.getString("label.min_colour"));
636 noValueCombo.addItem(MessageManager.getString("label.max_colour"));
637 noValueCombo.addItemListener(new ItemListener()
640 public void itemStateChanged(ItemEvent e)
646 JLabel minText = new JLabel(
647 MessageManager.getString("label.min_value") + COLON);
648 minText.setFont(JvSwingUtils.getLabelFont());
649 JLabel maxText = new JLabel(
650 MessageManager.getString("label.max_value") + COLON);
651 maxText.setFont(JvSwingUtils.getLabelFont());
652 JLabel noText = new JLabel(
653 MessageManager.getString("label.no_value") + COLON);
654 noText.setFont(JvSwingUtils.getLabelFont());
656 colourRangePanel.add(minText);
657 colourRangePanel.add(minColour);
658 colourRangePanel.add(maxText);
659 colourRangePanel.add(maxColour);
660 colourRangePanel.add(noText);
661 colourRangePanel.add(noValueCombo);
664 * third row - threshold options and value
666 JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
667 thresholdPanel.setBackground(Color.white);
668 graduatedColourPanel.add(thresholdPanel);
670 threshold.addActionListener(changeColourAction);
671 threshold.setToolTipText(MessageManager
672 .getString("label.threshold_feature_display_by_score"));
673 threshold.addItem(MessageManager
674 .getString("label.threshold_feature_no_threshold")); // index 0
675 threshold.addItem(MessageManager
676 .getString("label.threshold_feature_above_threshold")); // index 1
677 threshold.addItem(MessageManager
678 .getString("label.threshold_feature_below_threshold")); // index 2
680 thresholdValue.addActionListener(new ActionListener()
683 public void actionPerformed(ActionEvent e)
685 thresholdValue_actionPerformed();
688 thresholdValue.addFocusListener(new FocusAdapter()
691 public void focusLost(FocusEvent e)
693 thresholdValue_actionPerformed();
696 slider.setPaintLabels(false);
697 slider.setPaintTicks(true);
698 slider.setBackground(Color.white);
699 slider.setEnabled(false);
700 slider.setOpaque(false);
701 slider.setPreferredSize(new Dimension(100, 32));
702 slider.setToolTipText(
703 MessageManager.getString("label.adjust_threshold"));
705 slider.addChangeListener(new ChangeListener()
708 public void stateChanged(ChangeEvent evt)
713 .setText(String.valueOf(slider.getValue() / scaleFactor));
714 sliderValueChanged();
718 slider.addMouseListener(new MouseAdapter()
721 public void mouseReleased(MouseEvent evt)
724 * only update Overview and/or structure colouring
725 * when threshold slider drag ends (mouse up)
729 ap.paintAlignment(true, true);
734 thresholdValue.setEnabled(false);
735 thresholdValue.setColumns(7);
737 thresholdPanel.add(threshold);
738 thresholdPanel.add(slider);
739 thresholdPanel.add(thresholdValue);
741 thresholdIsMin.setBackground(Color.white);
743 .setText(MessageManager.getString("label.threshold_minmax"));
744 thresholdIsMin.setToolTipText(MessageManager
745 .getString("label.toggle_absolute_relative_display_threshold"));
746 thresholdIsMin.addActionListener(changeColourAction);
747 thresholdPanel.add(thresholdIsMin);
749 return graduatedColourPanel;
753 * Lay out OK and Cancel buttons
757 private JPanel initialiseOkCancelPanel()
759 JPanel okCancelPanel = new JPanel();
760 // okCancelPanel.setBackground(Color.white);
761 okCancelPanel.add(ok);
762 okCancelPanel.add(cancel);
763 return okCancelPanel;
767 * Lay out Colour options panel, containing
769 * <li>plain colour, with colour picker</li>
770 * <li>colour by text, with choice of Label or other attribute</li>
771 * <li>colour by range, of score or other attribute, when available</li>
776 private JPanel initialiseColoursPanel()
778 JPanel colourByPanel = new JPanel();
779 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
782 * option to apply colour to sub-types as well (if there are any)
784 if (!subTypes.isEmpty())
786 applyColourToSubtypes = false;
787 colourByPanel.add(initSubtypesPanel(false));
791 * simple colour radio button and colour picker
793 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
794 simpleColourPanel.setBackground(Color.white);
795 JvSwingUtils.createTitledBorder(simpleColourPanel,
796 MessageManager.getString("label.simple"), true);
797 colourByPanel.add(simpleColourPanel);
799 simpleColour = new JRadioButton(
800 MessageManager.getString("label.simple_colour"));
801 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
802 simpleColour.addItemListener(new ItemListener()
805 public void itemStateChanged(ItemEvent e)
807 if (simpleColour.isSelected() && !adjusting)
809 showColourChooser(singleColour, "label.select_colour");
815 singleColour.setFont(JvSwingUtils.getLabelFont());
816 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
817 singleColour.setPreferredSize(new Dimension(40, 20));
818 singleColour.addMouseListener(new MouseAdapter()
821 public void mousePressed(MouseEvent e)
823 if (simpleColour.isSelected())
825 showColourChooser(singleColour, "label.select_colour");
829 simpleColourPanel.add(simpleColour); // radio button
830 simpleColourPanel.add(singleColour); // colour picker button
833 * colour by text (category) radio button and drop-down choice list
835 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
836 byTextPanel.setBackground(Color.white);
837 JvSwingUtils.createTitledBorder(byTextPanel,
838 MessageManager.getString("label.colour_by_text"), true);
839 colourByPanel.add(byTextPanel);
840 byCategory = new JRadioButton(
841 MessageManager.getString("label.by_text_of") + COLON);
842 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
843 byCategory.addItemListener(new ItemListener()
846 public void itemStateChanged(ItemEvent e)
848 if (byCategory.isSelected())
854 byTextPanel.add(byCategory);
856 List<String[]> attNames = FeatureAttributes.getInstance()
857 .getAttributes(featureType);
858 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
859 colourByTextCombo.addItemListener(new ItemListener()
862 public void itemStateChanged(ItemEvent e)
867 byTextPanel.add(colourByTextCombo);
870 * graduated colour panel
872 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
873 colourByPanel.add(graduatedColourPanel);
876 * 3 radio buttons select between simple colour,
877 * by category (text), or graduated
879 ButtonGroup bg = new ButtonGroup();
880 bg.add(simpleColour);
882 bg.add(graduatedColour);
884 return colourByPanel;
888 * Constructs and returns a panel with a checkbox for the option to apply any
889 * changes also to sub-types of the feature type
893 protected JPanel initSubtypesPanel(final boolean forFilters)
895 JPanel toSubtypes = new JPanel(new FlowLayout(FlowLayout.LEFT));
896 toSubtypes.setBackground(Color.WHITE);
897 JCheckBox applyToSubtypesCB = new JCheckBox(MessageManager
898 .formatMessage("label.apply_to_subtypes", featureType));
899 applyToSubtypesCB.setToolTipText(getSubtypesTooltip());
900 applyToSubtypesCB.addActionListener(new ActionListener()
903 * reset and reapply settings on toggle of checkbox
906 public void actionPerformed(ActionEvent e)
910 applyFiltersToSubtypes = applyToSubtypesCB.isSelected();
911 restoreOriginalFilters();
916 applyColourToSubtypes = applyToSubtypesCB.isSelected();
917 restoreOriginalColours();
922 toSubtypes.add(applyToSubtypesCB);
927 private void showColourChooser(JPanel colourPanel, String key)
929 Color col = JColorChooser.showDialog(this,
930 MessageManager.getString(key), colourPanel.getBackground());
933 colourPanel.setBackground(col);
934 colourPanel.setForeground(col);
936 colourPanel.repaint();
941 * Constructs and sets the selected colour options as the colour for the feature
942 * type, and repaints the alignment, and optionally the Overview and/or
943 * structure viewer if open
945 * @param updateStructsAndOverview
947 void colourChanged(boolean updateStructsAndOverview)
952 * ignore action handlers while setting values programmatically
958 * ensure min-max range is for the latest choice of
959 * 'graduated colour by'
961 updateColourMinMax();
963 FeatureColourI acg = makeColourFromInputs();
966 * save the colour, and set on subtypes if selected
968 fr.setColour(featureType, acg);
969 if (applyColourToSubtypes)
971 for (String child : subTypes)
973 fr.setColour(child, acg);
976 refreshFeatureSettings();
977 ap.paintAlignment(updateStructsAndOverview, updateStructsAndOverview);
983 * Converts the input values into an instance of FeatureColour
987 private FeatureColourI makeColourFromInputs()
990 * easiest case - a single colour
992 if (simpleColour.isSelected())
994 return new FeatureColour(singleColour.getBackground());
998 * next easiest case - colour by Label, or attribute text
1000 if (byCategory.isSelected())
1002 Color c = this.getBackground();
1003 FeatureColourI fc = new FeatureColour(c, c, null, 0f, 0f);
1004 fc.setColourByLabel(true);
1005 String byWhat = (String) colourByTextCombo.getSelectedItem();
1006 if (!LABEL_18N.equals(byWhat))
1008 fc.setAttributeName(
1009 FeatureMatcher.fromAttributeDisplayName(byWhat));
1015 * remaining case - graduated colour by score, or attribute value
1017 Color noColour = null;
1018 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
1020 noColour = minColour.getBackground();
1022 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
1024 noColour = maxColour.getBackground();
1030 thresh = Float.valueOf(thresholdValue.getText());
1031 } catch (NumberFormatException e)
1033 // invalid inputs are already handled on entry
1037 * min-max range is to (or from) threshold value if
1038 * 'threshold is min/max' is selected
1040 float minValue = min;
1041 float maxValue = max;
1042 final int thresholdOption = threshold.getSelectedIndex();
1043 if (thresholdIsMin.isSelected()
1044 && thresholdOption == ABOVE_THRESHOLD_OPTION)
1048 if (thresholdIsMin.isSelected()
1049 && thresholdOption == BELOW_THRESHOLD_OPTION)
1055 * make the graduated colour
1057 FeatureColourI fc = new FeatureColour(minColour.getBackground(),
1058 maxColour.getBackground(), noColour, minValue, maxValue);
1061 * set attribute to colour by if selected
1063 String byWhat = (String) colourByRangeCombo.getSelectedItem();
1064 if (!SCORE_18N.equals(byWhat))
1066 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
1070 * set threshold options and 'autoscaled' which is
1071 * false if 'threshold is min/max' is selected
1072 * else true (colour range is on actual range of values)
1074 fc.setThreshold(thresh);
1075 fc.setAutoScaled(!thresholdIsMin.isSelected());
1076 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
1077 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
1079 if (threshline == null)
1082 * todo not yet implemented: visual indication of feature threshold
1084 threshline = new GraphLine((max - min) / 2f, "Threshold",
1092 protected void raiseClosed()
1094 refreshFeatureSettings();
1097 protected void refreshFeatureSettings()
1099 if (this.featureSettings != null)
1101 featureSettings.actionPerformed(new ActionEvent(this, 0, "REFRESH"));
1106 * Action on OK is just to dismiss the dialog - any changes have already been
1110 public void okPressed()
1115 * Action on Cancel is to restore colour scheme and filters as they were when
1116 * the dialog was opened (including any feature sub-types that may have been
1120 public void cancelPressed()
1122 restoreOriginalColours();
1123 restoreOriginalFilters();
1124 ap.paintAlignment(true, true);
1127 protected void restoreOriginalFilters()
1129 for (Entry<String, FeatureMatcherSetI> entry : originalFilters
1132 fr.setFeatureFilter(entry.getKey(), entry.getValue());
1136 protected void restoreOriginalColours()
1138 for (Entry<String, FeatureColourI> entry : originalColours.entrySet())
1140 fr.setColour(entry.getKey(), entry.getValue());
1145 * Action on text entry of a threshold value
1147 protected void thresholdValue_actionPerformed()
1152 float f = Float.parseFloat(thresholdValue.getText());
1153 slider.setValue((int) (f * scaleFactor));
1154 threshline.value = f;
1155 thresholdValue.setBackground(Color.white); // ok
1158 * force repaint of any Overview window or structure
1160 ap.paintAlignment(true, true);
1161 } catch (NumberFormatException ex)
1163 thresholdValue.setBackground(Color.red); // not ok
1171 * Action on change of threshold slider value. This may be done interactively
1172 * (by moving the slider), or programmatically (to update the slider after
1173 * manual input of a threshold value).
1175 protected void sliderValueChanged()
1177 threshline.value = getRoundedSliderValue();
1180 * repaint alignment, but not Overview or structure,
1181 * to avoid overload while dragging the slider
1183 colourChanged(false);
1187 * Converts the slider value to its absolute value by dividing by the
1188 * scaleFactor. Rounding errors are squashed by forcing min/max of slider range
1189 * to the actual min/max of feature score range
1193 private float getRoundedSliderValue()
1195 int value = slider.getValue();
1196 float f = value == slider.getMaximum() ? max
1197 : (value == slider.getMinimum() ? min : value / scaleFactor);
1201 void addActionListener(ActionListener listener)
1203 if (featureSettings != null)
1206 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1208 featureSettings = listener;
1212 * A helper method to build the drop-down choice of attributes for a feature. If
1213 * 'withRange' is true, then Score, and any attributes with a min-max range, are
1214 * added. If 'withText' is true, Label and any known attributes are added. This
1215 * allows 'categorical numerical' attributes e.g. codon position to be coloured
1218 * Where metadata is available with a description for an attribute, that is
1219 * added as a tooltip.
1221 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1222 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1224 * This method does not add any ActionListener to the JComboBox.
1230 protected JComboBox<String> populateAttributesDropdown(
1231 List<String[]> attNames, boolean withRange, boolean withText)
1233 List<String> displayAtts = new ArrayList<>();
1234 List<String> tooltips = new ArrayList<>();
1238 displayAtts.add(LABEL_18N);
1239 tooltips.add(MessageManager.getString("label.description"));
1243 float[][] minMax = fr.getMinMax().get(featureType);
1244 if (minMax != null && minMax[0][0] != minMax[0][1])
1246 displayAtts.add(SCORE_18N);
1247 tooltips.add(SCORE_18N);
1251 FeatureAttributes fa = FeatureAttributes.getInstance();
1252 for (String[] attName : attNames)
1254 float[] minMax = fa.getMinMax(featureType, attName);
1255 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1256 if (!withText && !hasRange)
1260 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1261 String desc = fa.getDescription(featureType, attName);
1262 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1264 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1266 tooltips.add(desc == null ? "" : desc);
1269 JComboBox<String> attCombo = JvSwingUtils
1270 .buildComboWithTooltips(displayAtts, tooltips);
1276 * Populates initial layout of the feature attribute filters panel
1278 private JPanel initialiseFiltersPanel()
1280 filters = new ArrayList<>();
1282 JPanel outerPanel = new JPanel();
1283 outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
1284 outerPanel.setBackground(Color.white);
1287 * option to apply colour to sub-types as well (if there are any)
1289 if (!subTypes.isEmpty())
1291 applyFiltersToSubtypes = false;
1292 outerPanel.add(initSubtypesPanel(true));
1295 JPanel filtersPanel = new JPanel();
1296 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1297 filtersPanel.setBackground(Color.white);
1298 JvSwingUtils.createTitledBorder(filtersPanel,
1299 MessageManager.getString("label.filters"), true);
1300 outerPanel.add(filtersPanel);
1302 JPanel andOrPanel = initialiseAndOrPanel();
1303 filtersPanel.add(andOrPanel);
1306 * panel with filters - populated by refreshFiltersDisplay,
1307 * which also sets the layout manager
1309 chooseFiltersPanel = new JPanel();
1310 chooseFiltersPanel.setBackground(Color.white);
1311 filtersPanel.add(chooseFiltersPanel);
1317 * Lays out the panel with radio buttons to AND or OR filter conditions
1321 private JPanel initialiseAndOrPanel()
1323 JPanel andOrPanel = new JPanel(new BorderLayout());
1324 andOrPanel.setBackground(Color.white);
1325 JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
1326 andOrPanel.add(panel1, BorderLayout.WEST);
1327 panel1.setBackground(Color.white);
1328 panel1.setBorder(BorderFactory.createLineBorder(debugBorderColour));
1329 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1330 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1331 ActionListener actionListener = new ActionListener()
1334 public void actionPerformed(ActionEvent e)
1339 andFilters.addActionListener(actionListener);
1340 orFilters.addActionListener(actionListener);
1341 ButtonGroup andOr = new ButtonGroup();
1342 andOr.add(andFilters);
1343 andOr.add(orFilters);
1344 andFilters.setSelected(true);
1346 new JLabel(MessageManager.getString("label.join_conditions")));
1347 panel1.add(andFilters);
1348 panel1.add(orFilters);
1354 * Builds a tooltip for the 'Apply to subtypes' checkbox with a list of
1355 * subtypes of this feature type
1359 protected String getSubtypesTooltip()
1361 StringBuilder sb = new StringBuilder(20 * subTypes.size());
1362 sb.append(MessageManager.getString("label.apply_also_to"));
1363 for (String child : subTypes)
1365 sb.append("<br>").append(child);
1367 String tooltip = JvSwingUtils.wrapTooltip(true, sb.toString());
1372 * Refreshes the display to show any filters currently configured for the
1373 * selected feature type (editable, with 'remove' option), plus one extra row
1374 * for adding a condition. This should be called after a filter has been
1375 * removed, added or amended.
1377 private void updateFiltersTab()
1380 * clear the panel and list of filter conditions
1382 chooseFiltersPanel.removeAll();
1386 * look up attributes known for feature type
1388 List<String[]> attNames = FeatureAttributes.getInstance()
1389 .getAttributes(featureType);
1392 * if this feature type has filters set, load them first
1394 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1395 if (featureFilters != null)
1397 if (!featureFilters.isAnded())
1399 orFilters.setSelected(true);
1401 featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1405 * and an empty filter for the user to populate (add)
1407 filters.add(FeatureMatcher.NULL_MATCHER);
1410 * use GridLayout to 'justify' rows to the top of the panel, until
1411 * there are too many to fit in, then fall back on BoxLayout
1413 if (filters.size() <= 5)
1415 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1419 chooseFiltersPanel.setLayout(
1420 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1424 * render the conditions in rows, each in its own JPanel
1426 int filterIndex = 0;
1427 for (FeatureMatcherI filter : filters)
1429 JPanel row = addFilter(filter, attNames, filterIndex);
1430 row.setBorder(BorderFactory.createLineBorder(debugBorderColour));
1431 chooseFiltersPanel.add(row);
1440 * A helper method that constructs a row (panel) with one filter condition:
1442 * <li>a drop-down list of Label, Score and attribute names to choose from</li>
1443 * <li>a drop-down list of conditions to choose from</li>
1444 * <li>a text field for input of a match pattern</li>
1445 * <li>optionally, a 'remove' button</li>
1447 * The filter values are set as defaults for the input fields. The 'remove'
1448 * button is added unless the pattern is empty (incomplete filter condition).
1450 * Action handlers on these fields provide for
1452 * <li>validate pattern field - should be numeric if condition is numeric</li>
1453 * <li>save filters and refresh display on any (valid) change</li>
1454 * <li>remove filter and refresh on 'Remove'</li>
1455 * <li>update conditions list on change of Label/Score/Attribute</li>
1456 * <li>refresh value field tooltip with min-max range on change of
1462 * @param filterIndex
1465 protected JPanel addFilter(FeatureMatcherI filter,
1466 List<String[]> attNames, int filterIndex)
1468 String[] attName = filter.getAttribute();
1469 Condition cond = filter.getMatcher().getCondition();
1470 String pattern = filter.getMatcher().getPattern();
1472 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1473 filterRow.setBackground(Color.white);
1476 * drop-down choice of attribute, with description as a tooltip
1477 * if we can obtain it
1479 final JComboBox<String> attCombo = populateAttributesDropdown(attNames,
1481 String filterBy = setSelectedAttribute(attCombo, filter);
1483 JComboBox<Condition> condCombo = new JComboBox<>();
1485 JTextField patternField = new JTextField(8);
1486 patternField.setText(pattern);
1489 * action handlers that validate and (if valid) apply changes
1491 ActionListener actionListener = new ActionListener()
1494 public void actionPerformed(ActionEvent e)
1496 if (validateFilter(patternField, condCombo))
1498 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1505 ItemListener itemListener = new ItemListener()
1508 public void itemStateChanged(ItemEvent e)
1510 actionListener.actionPerformed(null);
1514 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1516 attCombo.setSelectedIndex(0);
1520 attCombo.setSelectedItem(
1521 FeatureMatcher.toAttributeDisplayName(attName));
1523 attCombo.addItemListener(new ItemListener()
1526 public void itemStateChanged(ItemEvent e)
1529 * on change of attribute, refresh the conditions list to
1530 * ensure it is appropriate for the attribute datatype
1532 populateConditions((String) attCombo.getSelectedItem(),
1533 (Condition) condCombo.getSelectedItem(), condCombo,
1535 actionListener.actionPerformed(null);
1539 filterRow.add(attCombo);
1542 * drop-down choice of test condition
1544 populateConditions(filterBy, cond, condCombo, patternField);
1545 condCombo.setPreferredSize(new Dimension(150, 20));
1546 condCombo.addItemListener(itemListener);
1547 filterRow.add(condCombo);
1550 * pattern to match against
1552 patternField.addActionListener(actionListener);
1553 patternField.addFocusListener(new FocusAdapter()
1556 public void focusLost(FocusEvent e)
1558 actionListener.actionPerformed(null);
1561 filterRow.add(patternField);
1564 * disable pattern field for condition 'Present / NotPresent'
1566 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1567 patternField.setEnabled(selectedCondition.needsAPattern());
1570 * if a numeric condition is selected, show the value range
1571 * as a tooltip on the value input field
1573 setNumericHints(filterBy, selectedCondition, patternField);
1576 * add remove button if filter is populated (non-empty pattern)
1578 if (!patternField.isEnabled()
1579 || (pattern != null && pattern.trim().length() > 0))
1581 // todo: gif for button drawing '-' or 'x'
1582 JButton removeCondition = new BasicArrowButton(SwingConstants.WEST);
1584 .setToolTipText(MessageManager.getString("label.delete_row"));
1585 removeCondition.addActionListener(new ActionListener()
1588 public void actionPerformed(ActionEvent e)
1590 filters.remove(filterIndex);
1594 filterRow.add(removeCondition);
1601 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1607 private String setSelectedAttribute(JComboBox<String> attCombo,
1608 FeatureMatcherI filter)
1611 if (filter.isByScore())
1615 else if (filter.isByLabel())
1621 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1623 attCombo.setSelectedItem(item);
1628 * If a numeric comparison condition is selected, retrieves the min-max range
1629 * for the value (score or attribute), and sets it as a tooltip on the value
1630 * field. If the field is currently empty, then pre-populates it with
1632 * <li>the minimum value, if condition is > or >=</li>
1633 * <li>the maximum value, if condition is < or <=</li>
1637 * @param selectedCondition
1638 * @param patternField
1640 private void setNumericHints(String attName,
1641 Condition selectedCondition, JTextField patternField)
1643 patternField.setToolTipText("");
1645 if (selectedCondition.isNumeric())
1647 float[] minMax = getMinMax(attName);
1650 String minFormatted = DECFMT_2_2.format(minMax[0]);
1651 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1652 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1653 patternField.setToolTipText(tip);
1654 if (patternField.getText().isEmpty())
1656 if (selectedCondition == Condition.GE
1657 || selectedCondition == Condition.GT)
1659 patternField.setText(minFormatted);
1663 if (selectedCondition == Condition.LE
1664 || selectedCondition == Condition.LT)
1666 patternField.setText(maxFormatted);
1675 * Populates the drop-down list of comparison conditions for the given attribute
1676 * name. The conditions added depend on the datatype of the attribute values.
1677 * The supplied condition is set as the selected item in the list, provided it
1678 * is in the list. If the pattern is now invalid (non-numeric pattern for a
1679 * numeric condition), it is cleared.
1684 * @param patternField
1686 private void populateConditions(String attName, Condition cond,
1687 JComboBox<Condition> condCombo, JTextField patternField)
1689 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1690 FeatureMatcher.fromAttributeDisplayName(attName));
1691 if (LABEL_18N.equals(attName))
1693 type = Datatype.Character;
1695 else if (SCORE_18N.equals(attName))
1697 type = Datatype.Number;
1701 * remove itemListener before starting
1703 ItemListener listener = condCombo.getItemListeners()[0];
1704 condCombo.removeItemListener(listener);
1705 boolean condIsValid = false;
1707 condCombo.removeAllItems();
1708 for (Condition c : Condition.values())
1710 if ((c.isNumeric() && type == Datatype.Number)
1711 || (!c.isNumeric() && type != Datatype.Number))
1713 condCombo.addItem(c);
1722 * set the selected condition (does nothing if not in the list)
1726 condCombo.setSelectedItem(cond);
1730 condCombo.setSelectedIndex(0);
1734 * clear pattern if it is now invalid for condition
1736 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1740 String pattern = patternField.getText().trim();
1741 if (pattern.length() > 0)
1743 Float.valueOf(pattern);
1745 } catch (NumberFormatException e)
1747 patternField.setText("");
1752 * restore the listener
1754 condCombo.addItemListener(listener);
1758 * Answers true unless a numeric condition has been selected with a non-numeric
1759 * value. Sets the value field to RED with a tooltip if in error.
1761 * If the pattern is expected but is empty, this method returns false, but does
1762 * not mark the field as invalid. This supports selecting an attribute for a new
1763 * condition before a match pattern has been entered.
1768 protected boolean validateFilter(JTextField value,
1769 JComboBox<Condition> condCombo)
1771 if (value == null || condCombo == null)
1773 return true; // fields not populated
1776 Condition cond = (Condition) condCombo.getSelectedItem();
1777 if (!cond.needsAPattern())
1782 value.setBackground(Color.white);
1783 value.setToolTipText("");
1784 String v1 = value.getText().trim();
1785 if (v1.length() == 0)
1790 if (cond.isNumeric() && v1.length() > 0)
1795 } catch (NumberFormatException e)
1797 value.setBackground(Color.red);
1798 value.setToolTipText(
1799 MessageManager.getString("label.numeric_required"));
1808 * Constructs a filter condition from the given input fields, and replaces the
1809 * condition at filterIndex with the new one. Does nothing if the pattern field
1810 * is blank (unless the match condition is one that doesn't require a pattern,
1811 * e.g. 'Is present'). Answers true if the filter was updated, else false.
1813 * This method may update the tooltip on the filter value field to show the
1814 * value range, if a numeric condition is selected. This ensures the tooltip is
1815 * updated when a numeric valued attribute is chosen on the last 'add a filter'
1821 * @param filterIndex
1823 protected boolean updateFilter(JComboBox<String> attCombo,
1824 JComboBox<Condition> condCombo, JTextField valueField,
1827 String attName = (String) attCombo.getSelectedItem();
1828 Condition cond = (Condition) condCombo.getSelectedItem();
1829 String pattern = valueField.getText().trim();
1831 setNumericHints(attName, cond, valueField);
1833 if (pattern.length() == 0 && cond.needsAPattern())
1835 valueField.setEnabled(true); // ensure pattern field is enabled!
1840 * Construct a matcher that operates on Label, Score,
1841 * or named attribute
1843 FeatureMatcherI km = null;
1844 if (LABEL_18N.equals(attName))
1846 km = FeatureMatcher.byLabel(cond, pattern);
1848 else if (SCORE_18N.equals(attName))
1850 km = FeatureMatcher.byScore(cond, pattern);
1854 km = FeatureMatcher.byAttribute(cond, pattern,
1855 FeatureMatcher.fromAttributeDisplayName(attName));
1858 filters.set(filterIndex, km);
1864 * Makes the dialog visible, at the Feature Colour tab or at the Filters tab
1868 public void showTab(boolean coloursTab)
1871 tabbedPane.setSelectedIndex(coloursTab ? 0 : 1);
1875 * Action on any change to feature filtering, namely
1877 * <li>change of selected attribute</li>
1878 * <li>change of selected condition</li>
1879 * <li>change of match pattern</li>
1880 * <li>removal of a condition</li>
1882 * The inputs are parsed into a combined filter and this is set for the feature
1883 * type, and the alignment redrawn.
1885 protected void filtersChanged()
1888 * update the filter conditions for the feature type
1890 boolean anded = andFilters.isSelected();
1891 FeatureMatcherSetI combined = new FeatureMatcherSet();
1893 for (FeatureMatcherI filter : filters)
1895 String pattern = filter.getMatcher().getPattern();
1896 Condition condition = filter.getMatcher().getCondition();
1897 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1901 combined.and(filter);
1905 combined.or(filter);
1911 * save the filter conditions in the FeatureRenderer
1912 * (note this might now be an empty filter with no conditions)
1914 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1915 if (applyFiltersToSubtypes)
1917 for (String child : subTypes)
1919 fr.setFeatureFilter(child, combined.isEmpty() ? null : combined);
1923 refreshFeatureSettings();
1924 ap.paintAlignment(true, true);