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)
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, 500, 500);
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());
448 * an ActionListener that applies colour changes
450 changeColourAction = new ActionListener()
453 public void actionPerformed(ActionEvent e)
460 * first panel/tab: colour options
462 JPanel coloursPanel = initialiseColoursPanel();
463 this.add(coloursPanel, BorderLayout.NORTH);
466 * second panel/tab: filter options
468 JPanel filtersPanel = initialiseFiltersPanel();
469 this.add(filtersPanel, BorderLayout.CENTER);
471 JPanel okCancelPanel = initialiseOkCancelPanel();
473 this.add(okCancelPanel, BorderLayout.SOUTH);
477 * Updates the min-max range if Colour By selected item is Score, or an
478 * attribute, with a min-max range
480 protected void updateColourMinMax()
482 if (!graduatedColour.isSelected())
487 String colourBy = (String) colourByRangeCombo.getSelectedItem();
488 float[] minMax = getMinMax(colourBy);
498 * Retrieves the min-max range:
500 * <li>of feature score, if colour or filter is by Score</li>
501 * <li>else of the selected attribute</li>
507 private float[] getMinMax(String attName)
509 float[] minMax = null;
510 if (SCORE_18N.equals(attName))
512 minMax = fr.getMinMax().get(featureType)[0];
516 // colour by attribute range
517 minMax = FeatureAttributes.getInstance().getMinMax(featureType,
518 FeatureMatcher.fromAttributeDisplayName(attName));
524 * Lay out fields for graduated colour (by score or attribute value)
528 private JPanel initialiseGraduatedColourPanel()
530 JPanel graduatedColourPanel = new JPanel();
531 graduatedColourPanel.setLayout(
532 new BoxLayout(graduatedColourPanel, BoxLayout.Y_AXIS));
533 JvSwingUtils.createTitledBorder(graduatedColourPanel,
534 MessageManager.getString("label.graduated_colour"), true);
535 graduatedColourPanel.setBackground(Color.white);
538 * first row: graduated colour radio button, score/attribute drop-down
540 JPanel graduatedChoicePanel = new JPanel(
541 new FlowLayout(FlowLayout.LEFT));
542 graduatedChoicePanel.setBackground(Color.white);
543 graduatedColour = new JRadioButton(
544 MessageManager.getString("label.by_range_of") + COLON);
545 graduatedColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
546 graduatedColour.addItemListener(new ItemListener()
549 public void itemStateChanged(ItemEvent e)
551 if (graduatedColour.isSelected())
557 graduatedChoicePanel.add(graduatedColour);
559 List<String[]> attNames = FeatureAttributes.getInstance()
560 .getAttributes(featureType);
561 colourByRangeCombo = populateAttributesDropdown(attNames, true, false);
562 colourByRangeCombo.addItemListener(new ItemListener()
565 public void itemStateChanged(ItemEvent e)
572 * disable graduated colour option if no range found
574 graduatedColour.setEnabled(colourByRangeCombo.getItemCount() > 0);
576 graduatedChoicePanel.add(colourByRangeCombo);
577 graduatedColourPanel.add(graduatedChoicePanel);
580 * second row - min/max/no colours
582 JPanel colourRangePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
583 colourRangePanel.setBackground(Color.white);
584 graduatedColourPanel.add(colourRangePanel);
586 minColour.setFont(JvSwingUtils.getLabelFont());
587 minColour.setBorder(BorderFactory.createLineBorder(Color.black));
588 minColour.setPreferredSize(new Dimension(40, 20));
589 minColour.setToolTipText(MessageManager.getString("label.min_colour"));
590 minColour.addMouseListener(new MouseAdapter()
593 public void mousePressed(MouseEvent e)
595 if (minColour.isEnabled())
597 showColourChooser(minColour, "label.select_colour_minimum_value");
602 maxColour.setFont(JvSwingUtils.getLabelFont());
603 maxColour.setBorder(BorderFactory.createLineBorder(Color.black));
604 maxColour.setPreferredSize(new Dimension(40, 20));
605 maxColour.setToolTipText(MessageManager.getString("label.max_colour"));
606 maxColour.addMouseListener(new MouseAdapter()
609 public void mousePressed(MouseEvent e)
611 if (maxColour.isEnabled())
613 showColourChooser(maxColour, "label.select_colour_maximum_value");
617 maxColour.setBorder(new LineBorder(Color.black));
620 * default max colour to current colour (if a plain colour),
621 * or to Black if colour by label; make min colour a pale
622 * version of max colour
624 FeatureColourI fc = fr.getFeatureColours().get(featureType);
625 Color bg = fc.isSimpleColour() ? fc.getColour() : Color.BLACK;
626 maxColour.setBackground(bg);
627 minColour.setBackground(ColorUtils.bleachColour(bg, 0.9f));
629 noValueCombo = new JComboBox<>();
630 noValueCombo.addItem(MessageManager.getString("label.no_colour"));
631 noValueCombo.addItem(MessageManager.getString("label.min_colour"));
632 noValueCombo.addItem(MessageManager.getString("label.max_colour"));
633 noValueCombo.addItemListener(new ItemListener()
636 public void itemStateChanged(ItemEvent e)
642 JLabel minText = new JLabel(
643 MessageManager.getString("label.min_value") + COLON);
644 minText.setFont(JvSwingUtils.getLabelFont());
645 JLabel maxText = new JLabel(
646 MessageManager.getString("label.max_value") + COLON);
647 maxText.setFont(JvSwingUtils.getLabelFont());
648 JLabel noText = new JLabel(
649 MessageManager.getString("label.no_value") + COLON);
650 noText.setFont(JvSwingUtils.getLabelFont());
652 colourRangePanel.add(minText);
653 colourRangePanel.add(minColour);
654 colourRangePanel.add(maxText);
655 colourRangePanel.add(maxColour);
656 colourRangePanel.add(noText);
657 colourRangePanel.add(noValueCombo);
660 * third row - threshold options and value
662 JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
663 thresholdPanel.setBackground(Color.white);
664 graduatedColourPanel.add(thresholdPanel);
666 threshold.addActionListener(changeColourAction);
667 threshold.setToolTipText(MessageManager
668 .getString("label.threshold_feature_display_by_score"));
669 threshold.addItem(MessageManager
670 .getString("label.threshold_feature_no_threshold")); // index 0
671 threshold.addItem(MessageManager
672 .getString("label.threshold_feature_above_threshold")); // index 1
673 threshold.addItem(MessageManager
674 .getString("label.threshold_feature_below_threshold")); // index 2
676 thresholdValue.addActionListener(new ActionListener()
679 public void actionPerformed(ActionEvent e)
681 thresholdValue_actionPerformed();
684 thresholdValue.addFocusListener(new FocusAdapter()
687 public void focusLost(FocusEvent e)
689 thresholdValue_actionPerformed();
692 slider.setPaintLabels(false);
693 slider.setPaintTicks(true);
694 slider.setBackground(Color.white);
695 slider.setEnabled(false);
696 slider.setOpaque(false);
697 slider.setPreferredSize(new Dimension(100, 32));
698 slider.setToolTipText(
699 MessageManager.getString("label.adjust_threshold"));
701 slider.addChangeListener(new ChangeListener()
704 public void stateChanged(ChangeEvent evt)
709 .setText(String.valueOf(slider.getValue() / scaleFactor));
710 sliderValueChanged();
714 slider.addMouseListener(new MouseAdapter()
717 public void mouseReleased(MouseEvent evt)
720 * only update Overview and/or structure colouring
721 * when threshold slider drag ends (mouse up)
725 ap.paintAlignment(true, true);
730 thresholdValue.setEnabled(false);
731 thresholdValue.setColumns(7);
733 thresholdPanel.add(threshold);
734 thresholdPanel.add(slider);
735 thresholdPanel.add(thresholdValue);
737 thresholdIsMin.setBackground(Color.white);
739 .setText(MessageManager.getString("label.threshold_minmax"));
740 thresholdIsMin.setToolTipText(MessageManager
741 .getString("label.toggle_absolute_relative_display_threshold"));
742 thresholdIsMin.addActionListener(changeColourAction);
743 thresholdPanel.add(thresholdIsMin);
745 return graduatedColourPanel;
749 * Lay out OK and Cancel buttons
753 private JPanel initialiseOkCancelPanel()
755 JPanel okCancelPanel = new JPanel();
756 // okCancelPanel.setBackground(Color.white);
757 okCancelPanel.add(ok);
758 okCancelPanel.add(cancel);
759 return okCancelPanel;
763 * Lay out Colour options panel, containing
765 * <li>plain colour, with colour picker</li>
766 * <li>colour by text, with choice of Label or other attribute</li>
767 * <li>colour by range, of score or other attribute, when available</li>
772 private JPanel initialiseColoursPanel()
774 JPanel colourByPanel = new JPanel();
775 colourByPanel.setBackground(Color.white);
776 colourByPanel.setLayout(new BoxLayout(colourByPanel, BoxLayout.Y_AXIS));
777 JvSwingUtils.createTitledBorder(colourByPanel,
778 MessageManager.getString("action.colour"), true);
781 * option to apply colour to sub-types as well (if there are any)
783 if (!subTypes.isEmpty())
785 applyColourToSubtypes = false;
786 colourByPanel.add(initSubtypesPanel(false));
790 * simple colour radio button and colour picker
792 JPanel simpleColourPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
793 simpleColourPanel.setBackground(Color.white);
794 // JvSwingUtils.createTitledBorder(simpleColourPanel,
795 // MessageManager.getString("label.simple"), true);
796 colourByPanel.add(simpleColourPanel);
798 simpleColour = new JRadioButton(
799 MessageManager.getString("label.simple_colour"));
800 simpleColour.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
801 simpleColour.addItemListener(new ItemListener()
804 public void itemStateChanged(ItemEvent e)
806 if (simpleColour.isSelected() && !adjusting)
808 showColourChooser(singleColour, "label.select_colour");
814 singleColour.setFont(JvSwingUtils.getLabelFont());
815 singleColour.setBorder(BorderFactory.createLineBorder(Color.black));
816 singleColour.setPreferredSize(new Dimension(40, 20));
817 singleColour.addMouseListener(new MouseAdapter()
820 public void mousePressed(MouseEvent e)
822 if (simpleColour.isSelected())
824 showColourChooser(singleColour, "label.select_colour");
828 simpleColourPanel.add(simpleColour); // radio button
829 simpleColourPanel.add(singleColour); // colour picker button
832 * colour by text (category) radio button and drop-down choice list
834 JPanel byTextPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
835 byTextPanel.setBackground(Color.white);
836 JvSwingUtils.createTitledBorder(byTextPanel,
837 MessageManager.getString("label.colour_by_text"), true);
838 colourByPanel.add(byTextPanel);
839 byCategory = new JRadioButton(
840 MessageManager.getString("label.by_text_of") + COLON);
841 byCategory.setPreferredSize(new Dimension(RADIO_WIDTH, 20));
842 byCategory.addItemListener(new ItemListener()
845 public void itemStateChanged(ItemEvent e)
847 if (byCategory.isSelected())
853 byTextPanel.add(byCategory);
855 List<String[]> attNames = FeatureAttributes.getInstance()
856 .getAttributes(featureType);
857 colourByTextCombo = populateAttributesDropdown(attNames, false, true);
858 colourByTextCombo.addItemListener(new ItemListener()
861 public void itemStateChanged(ItemEvent e)
866 byTextPanel.add(colourByTextCombo);
869 * graduated colour panel
871 JPanel graduatedColourPanel = initialiseGraduatedColourPanel();
872 colourByPanel.add(graduatedColourPanel);
875 * 3 radio buttons select between simple colour,
876 * by category (text), or graduated
878 ButtonGroup bg = new ButtonGroup();
879 bg.add(simpleColour);
881 bg.add(graduatedColour);
883 return colourByPanel;
887 * Constructs and returns a panel with a checkbox for the option to apply any
888 * changes also to sub-types of the feature type
892 protected JPanel initSubtypesPanel(final boolean forFilters)
894 JPanel toSubtypes = new JPanel(new FlowLayout(FlowLayout.LEFT));
895 toSubtypes.setBackground(Color.WHITE);
896 JCheckBox applyToSubtypesCB = new JCheckBox(MessageManager
897 .formatMessage("label.apply_to_subtypes", featureType));
898 applyToSubtypesCB.setToolTipText(getSubtypesTooltip());
899 applyToSubtypesCB.addActionListener(new ActionListener()
902 * reset and reapply settings on toggle of checkbox
905 public void actionPerformed(ActionEvent e)
909 applyFiltersToSubtypes = applyToSubtypesCB.isSelected();
910 restoreOriginalFilters();
915 applyColourToSubtypes = applyToSubtypesCB.isSelected();
916 restoreOriginalColours();
921 toSubtypes.add(applyToSubtypesCB);
926 private void showColourChooser(JPanel colourPanel, String key)
928 Color col = JColorChooser.showDialog(this,
929 MessageManager.getString(key), colourPanel.getBackground());
932 colourPanel.setBackground(col);
933 colourPanel.setForeground(col);
935 colourPanel.repaint();
940 * Constructs and sets the selected colour options as the colour for the
941 * feature type, and repaints the alignment, and optionally the Overview
942 * and/or structure viewer if open
944 * @param updateStructsAndOverview
946 void colourChanged(boolean updateStructsAndOverview)
951 * ignore action handlers while setting values programmatically
957 * ensure min-max range is for the latest choice of
958 * 'graduated colour by'
960 updateColourMinMax();
962 FeatureColourI acg = makeColourFromInputs();
965 * save the colour, and set on subtypes if selected
967 fr.setColour(featureType, acg);
968 if (applyColourToSubtypes)
970 for (String child : subTypes)
972 fr.setColour(child, acg);
975 refreshFeatureSettings();
976 ap.paintAlignment(updateStructsAndOverview, updateStructsAndOverview);
982 * Converts the input values into an instance of FeatureColour
986 private FeatureColourI makeColourFromInputs()
989 * easiest case - a single colour
991 if (simpleColour.isSelected())
993 return new FeatureColour(singleColour.getBackground());
997 * next easiest case - colour by Label, or attribute text
999 if (byCategory.isSelected())
1001 Color c = this.getBackground();
1002 FeatureColourI fc = new FeatureColour(c, c, null, 0f, 0f);
1003 fc.setColourByLabel(true);
1004 String byWhat = (String) colourByTextCombo.getSelectedItem();
1005 if (!LABEL_18N.equals(byWhat))
1007 fc.setAttributeName(
1008 FeatureMatcher.fromAttributeDisplayName(byWhat));
1014 * remaining case - graduated colour by score, or attribute value
1016 Color noColour = null;
1017 if (noValueCombo.getSelectedIndex() == MIN_COLOUR_OPTION)
1019 noColour = minColour.getBackground();
1021 else if (noValueCombo.getSelectedIndex() == MAX_COLOUR_OPTION)
1023 noColour = maxColour.getBackground();
1029 thresh = Float.valueOf(thresholdValue.getText());
1030 } catch (NumberFormatException e)
1032 // invalid inputs are already handled on entry
1036 * min-max range is to (or from) threshold value if
1037 * 'threshold is min/max' is selected
1039 float minValue = min;
1040 float maxValue = max;
1041 final int thresholdOption = threshold.getSelectedIndex();
1042 if (thresholdIsMin.isSelected()
1043 && thresholdOption == ABOVE_THRESHOLD_OPTION)
1047 if (thresholdIsMin.isSelected()
1048 && thresholdOption == BELOW_THRESHOLD_OPTION)
1054 * make the graduated colour
1056 FeatureColourI fc = new FeatureColour(minColour.getBackground(),
1057 maxColour.getBackground(), noColour, minValue, maxValue);
1060 * set attribute to colour by if selected
1062 String byWhat = (String) colourByRangeCombo.getSelectedItem();
1063 if (!SCORE_18N.equals(byWhat))
1065 fc.setAttributeName(FeatureMatcher.fromAttributeDisplayName(byWhat));
1069 * set threshold options and 'autoscaled' which is
1070 * false if 'threshold is min/max' is selected
1071 * else true (colour range is on actual range of values)
1073 fc.setThreshold(thresh);
1074 fc.setAutoScaled(!thresholdIsMin.isSelected());
1075 fc.setAboveThreshold(thresholdOption == ABOVE_THRESHOLD_OPTION);
1076 fc.setBelowThreshold(thresholdOption == BELOW_THRESHOLD_OPTION);
1078 if (threshline == null)
1081 * todo not yet implemented: visual indication of feature threshold
1083 threshline = new GraphLine((max - min) / 2f, "Threshold",
1091 protected void raiseClosed()
1093 refreshFeatureSettings();
1096 protected void refreshFeatureSettings()
1098 if (this.featureSettings != null)
1100 featureSettings.actionPerformed(new ActionEvent(this, 0, "REFRESH"));
1105 * Action on OK is just to dismiss the dialog - any changes have already been
1109 public void okPressed()
1114 * Action on Cancel is to restore colour scheme and filters as they were when
1115 * the dialog was opened (including any feature sub-types that may have been
1119 public void cancelPressed()
1121 restoreOriginalColours();
1122 restoreOriginalFilters();
1123 ap.paintAlignment(true, true);
1126 protected void restoreOriginalFilters()
1128 for (Entry<String, FeatureMatcherSetI> entry : originalFilters
1131 fr.setFeatureFilter(entry.getKey(), entry.getValue());
1135 protected void restoreOriginalColours()
1137 for (Entry<String, FeatureColourI> entry : originalColours.entrySet())
1139 fr.setColour(entry.getKey(), entry.getValue());
1144 * Action on text entry of a threshold value
1146 protected void thresholdValue_actionPerformed()
1151 float f = Float.parseFloat(thresholdValue.getText());
1152 slider.setValue((int) (f * scaleFactor));
1153 threshline.value = f;
1154 thresholdValue.setBackground(Color.white); // ok
1157 * force repaint of any Overview window or structure
1159 ap.paintAlignment(true, true);
1160 } catch (NumberFormatException ex)
1162 thresholdValue.setBackground(Color.red); // not ok
1170 * Action on change of threshold slider value. This may be done interactively
1171 * (by moving the slider), or programmatically (to update the slider after
1172 * manual input of a threshold value).
1174 protected void sliderValueChanged()
1176 threshline.value = getRoundedSliderValue();
1179 * repaint alignment, but not Overview or structure,
1180 * to avoid overload while dragging the slider
1182 colourChanged(false);
1186 * Converts the slider value to its absolute value by dividing by the
1187 * scaleFactor. Rounding errors are squashed by forcing min/max of slider
1188 * range to the actual min/max of feature score range
1192 private float getRoundedSliderValue()
1194 int value = slider.getValue();
1195 float f = value == slider.getMaximum() ? max
1196 : (value == slider.getMinimum() ? min : value / scaleFactor);
1200 void addActionListener(ActionListener listener)
1202 if (featureSettings != null)
1205 "IMPLEMENTATION ISSUE: overwriting action listener for FeatureColourChooser");
1207 featureSettings = listener;
1211 * A helper method to build the drop-down choice of attributes for a feature.
1212 * If 'withRange' is true, then Score, and any attributes with a min-max
1213 * range, are added. If 'withText' is true, Label and any known attributes are
1214 * added. This allows 'categorical numerical' attributes e.g. codon position
1215 * to be coloured by text.
1217 * Where metadata is available with a description for an attribute, that is
1218 * added as a tooltip.
1220 * Attribute names may be 'simple' e.g. "AC" or 'compound' e.g. {"CSQ",
1221 * "Allele"}. Compound names are rendered for display as (e.g.) CSQ:Allele.
1223 * This method does not add any ActionListener to the JComboBox.
1229 protected JComboBox<String> populateAttributesDropdown(
1230 List<String[]> attNames, boolean withRange, boolean withText)
1232 List<String> displayAtts = new ArrayList<>();
1233 List<String> tooltips = new ArrayList<>();
1237 displayAtts.add(LABEL_18N);
1238 tooltips.add(MessageManager.getString("label.description"));
1242 float[][] minMax = fr.getMinMax().get(featureType);
1243 if (minMax != null && minMax[0][0] != minMax[0][1])
1245 displayAtts.add(SCORE_18N);
1246 tooltips.add(SCORE_18N);
1250 FeatureAttributes fa = FeatureAttributes.getInstance();
1251 for (String[] attName : attNames)
1253 float[] minMax = fa.getMinMax(featureType, attName);
1254 boolean hasRange = minMax != null && minMax[0] != minMax[1];
1255 if (!withText && !hasRange)
1259 displayAtts.add(FeatureMatcher.toAttributeDisplayName(attName));
1260 String desc = fa.getDescription(featureType, attName);
1261 if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1263 desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1265 tooltips.add(desc == null ? "" : desc);
1268 JComboBox<String> attCombo = JvSwingUtils
1269 .buildComboWithTooltips(displayAtts, tooltips);
1275 * Populates initial layout of the feature attribute filters panel
1277 private JPanel initialiseFiltersPanel()
1279 filters = new ArrayList<>();
1281 JPanel outerPanel = new JPanel();
1282 outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
1283 outerPanel.setBackground(Color.white);
1286 * option to apply colour to sub-types as well (if there are any)
1288 if (!subTypes.isEmpty())
1290 applyFiltersToSubtypes = false;
1291 outerPanel.add(initSubtypesPanel(true));
1294 JPanel filtersPanel = new JPanel();
1295 filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1296 filtersPanel.setBackground(Color.white);
1297 JvSwingUtils.createTitledBorder(filtersPanel,
1298 MessageManager.getString("label.filters"), true);
1299 outerPanel.add(filtersPanel);
1301 JPanel andOrPanel = initialiseAndOrPanel();
1302 filtersPanel.add(andOrPanel);
1305 * panel with filters - populated by refreshFiltersDisplay,
1306 * which also sets the layout manager
1308 chooseFiltersPanel = new JPanel();
1309 chooseFiltersPanel.setBackground(Color.white);
1310 filtersPanel.add(chooseFiltersPanel);
1316 * Lays out the panel with radio buttons to AND or OR filter conditions
1320 private JPanel initialiseAndOrPanel()
1322 JPanel andOrPanel = new JPanel(new BorderLayout());
1323 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));
1330 //>>>>>>> refs/heads/develop
1331 andFilters = new JRadioButton(MessageManager.getString("label.and"));
1332 orFilters = new JRadioButton(MessageManager.getString("label.or"));
1333 ActionListener actionListener = new ActionListener()
1336 public void actionPerformed(ActionEvent e)
1341 andFilters.addActionListener(actionListener);
1342 orFilters.addActionListener(actionListener);
1343 ButtonGroup andOr = new ButtonGroup();
1344 andOr.add(andFilters);
1345 andOr.add(orFilters);
1346 andFilters.setSelected(true);
1348 new JLabel(MessageManager.getString("label.join_conditions")));
1349 andOrPanel.add(andFilters);
1350 andOrPanel.add(orFilters);
1356 * Builds a tooltip for the 'Apply to subtypes' checkbox with a list of
1357 * subtypes of this feature type
1361 protected String getSubtypesTooltip()
1363 StringBuilder sb = new StringBuilder(20 * subTypes.size());
1364 sb.append(MessageManager.getString("label.apply_also_to"));
1365 for (String child : subTypes)
1367 sb.append("<br>").append(child);
1369 String tooltip = JvSwingUtils.wrapTooltip(true, sb.toString());
1374 * Refreshes the display to show any filters currently configured for the
1375 * selected feature type (editable, with 'remove' option), plus one extra row
1376 * for adding a condition. This should be called after a filter has been
1377 * removed, added or amended.
1379 private void updateFiltersTab()
1382 * clear the panel and list of filter conditions
1384 chooseFiltersPanel.removeAll();
1388 * look up attributes known for feature type
1390 List<String[]> attNames = FeatureAttributes.getInstance()
1391 .getAttributes(featureType);
1394 * if this feature type has filters set, load them first
1396 FeatureMatcherSetI featureFilters = fr.getFeatureFilter(featureType);
1397 if (featureFilters != null)
1399 if (!featureFilters.isAnded())
1401 orFilters.setSelected(true);
1403 featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1407 * and an empty filter for the user to populate (add)
1409 filters.add(FeatureMatcher.NULL_MATCHER);
1412 * use GridLayout to 'justify' rows to the top of the panel, until
1413 * there are too many to fit in, then fall back on BoxLayout
1415 if (filters.size() <= 5)
1417 chooseFiltersPanel.setLayout(new GridLayout(5, 1));
1421 chooseFiltersPanel.setLayout(
1422 new BoxLayout(chooseFiltersPanel, BoxLayout.Y_AXIS));
1426 * render the conditions in rows, each in its own JPanel
1428 int filterIndex = 0;
1429 for (FeatureMatcherI filter : filters)
1431 JPanel row = addFilter(filter, attNames, filterIndex);
1432 chooseFiltersPanel.add(row);
1441 * A helper method that constructs a row (panel) with one filter condition:
1443 * <li>a drop-down list of Label, Score and attribute names to choose
1445 * <li>a drop-down list of conditions to choose from</li>
1446 * <li>a text field for input of a match pattern</li>
1447 * <li>optionally, a 'remove' button</li>
1449 * The filter values are set as defaults for the input fields. The 'remove'
1450 * button is added unless the pattern is empty (incomplete filter condition).
1452 * Action handlers on these fields provide for
1454 * <li>validate pattern field - should be numeric if condition is numeric</li>
1455 * <li>save filters and refresh display on any (valid) change</li>
1456 * <li>remove filter and refresh on 'Remove'</li>
1457 * <li>update conditions list on change of Label/Score/Attribute</li>
1458 * <li>refresh value field tooltip with min-max range on change of
1464 * @param filterIndex
1467 protected JPanel addFilter(FeatureMatcherI filter,
1468 List<String[]> attNames, int filterIndex)
1470 String[] attName = filter.getAttribute();
1471 Condition cond = filter.getMatcher().getCondition();
1472 String pattern = filter.getMatcher().getPattern();
1474 JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1475 filterRow.setBackground(Color.white);
1478 * drop-down choice of attribute, with description as a tooltip
1479 * if we can obtain it
1481 final JComboBox<String> attCombo = populateAttributesDropdown(attNames,
1483 String filterBy = setSelectedAttribute(attCombo, filter);
1485 JComboBox<Condition> condCombo = new JComboBox<>();
1487 JTextField patternField = new JTextField(8);
1488 patternField.setText(pattern);
1491 * action handlers that validate and (if valid) apply changes
1493 ActionListener actionListener = new ActionListener()
1496 public void actionPerformed(ActionEvent e)
1498 if (validateFilter(patternField, condCombo))
1500 if (updateFilter(attCombo, condCombo, patternField, filterIndex))
1507 ItemListener itemListener = new ItemListener()
1510 public void itemStateChanged(ItemEvent e)
1512 actionListener.actionPerformed(null);
1516 if (filter == FeatureMatcher.NULL_MATCHER) // the 'add a condition' row
1518 attCombo.setSelectedIndex(0);
1522 attCombo.setSelectedItem(
1523 FeatureMatcher.toAttributeDisplayName(attName));
1525 attCombo.addItemListener(new ItemListener()
1528 public void itemStateChanged(ItemEvent e)
1531 * on change of attribute, refresh the conditions list to
1532 * ensure it is appropriate for the attribute datatype
1534 populateConditions((String) attCombo.getSelectedItem(),
1535 (Condition) condCombo.getSelectedItem(), condCombo,
1537 actionListener.actionPerformed(null);
1541 filterRow.add(attCombo);
1544 * drop-down choice of test condition
1546 populateConditions(filterBy, cond, condCombo, patternField);
1547 condCombo.setPreferredSize(new Dimension(150, 20));
1548 condCombo.addItemListener(itemListener);
1549 filterRow.add(condCombo);
1552 * pattern to match against
1554 patternField.addActionListener(actionListener);
1555 patternField.addFocusListener(new FocusAdapter()
1558 public void focusLost(FocusEvent e)
1560 actionListener.actionPerformed(null);
1563 filterRow.add(patternField);
1566 * disable pattern field for condition 'Present / NotPresent'
1568 Condition selectedCondition = (Condition) condCombo.getSelectedItem();
1569 patternField.setEnabled(selectedCondition.needsAPattern());
1572 * if a numeric condition is selected, show the value range
1573 * as a tooltip on the value input field
1575 setNumericHints(filterBy, selectedCondition, patternField);
1578 * add remove button if filter is populated (non-empty pattern)
1580 if (!patternField.isEnabled()
1581 || (pattern != null && pattern.trim().length() > 0))
1583 // todo: gif for button drawing '-' or 'x'
1584 JButton removeCondition = new BasicArrowButton(SwingConstants.WEST);
1586 .setToolTipText(MessageManager.getString("label.delete_row"));
1587 removeCondition.addActionListener(new ActionListener()
1590 public void actionPerformed(ActionEvent e)
1592 filters.remove(filterIndex);
1596 filterRow.add(removeCondition);
1603 * Sets the selected item in the Label/Score/Attribute drop-down to match the
1609 private String setSelectedAttribute(JComboBox<String> attCombo,
1610 FeatureMatcherI filter)
1613 if (filter.isByScore())
1617 else if (filter.isByLabel())
1623 item = FeatureMatcher.toAttributeDisplayName(filter.getAttribute());
1625 attCombo.setSelectedItem(item);
1630 * If a numeric comparison condition is selected, retrieves the min-max range
1631 * for the value (score or attribute), and sets it as a tooltip on the value
1632 * field. If the field is currently empty, then pre-populates it with
1634 * <li>the minimum value, if condition is > or >=</li>
1635 * <li>the maximum value, if condition is < or <=</li>
1639 * @param selectedCondition
1640 * @param patternField
1642 private void setNumericHints(String attName, Condition selectedCondition,
1643 JTextField patternField)
1645 patternField.setToolTipText("");
1647 if (selectedCondition.isNumeric())
1649 float[] minMax = getMinMax(attName);
1652 String minFormatted = DECFMT_2_2.format(minMax[0]);
1653 String maxFormatted = DECFMT_2_2.format(minMax[1]);
1654 String tip = String.format("(%s - %s)", minFormatted, maxFormatted);
1655 patternField.setToolTipText(tip);
1656 if (patternField.getText().isEmpty())
1658 if (selectedCondition == Condition.GE
1659 || selectedCondition == Condition.GT)
1661 patternField.setText(minFormatted);
1665 if (selectedCondition == Condition.LE
1666 || selectedCondition == Condition.LT)
1668 patternField.setText(maxFormatted);
1677 * Populates the drop-down list of comparison conditions for the given
1678 * attribute name. The conditions added depend on the datatype of the
1679 * attribute values. The supplied condition is set as the selected item in the
1680 * list, provided it is in the list. If the pattern is now invalid
1681 * (non-numeric pattern for a numeric condition), it is cleared.
1686 * @param patternField
1688 private void populateConditions(String attName, Condition cond,
1689 JComboBox<Condition> condCombo, JTextField patternField)
1691 Datatype type = FeatureAttributes.getInstance().getDatatype(featureType,
1692 FeatureMatcher.fromAttributeDisplayName(attName));
1693 if (LABEL_18N.equals(attName))
1695 type = Datatype.Character;
1697 else if (SCORE_18N.equals(attName))
1699 type = Datatype.Number;
1703 * remove itemListener before starting
1705 ItemListener listener = condCombo.getItemListeners()[0];
1706 condCombo.removeItemListener(listener);
1707 boolean condIsValid = false;
1709 condCombo.removeAllItems();
1710 for (Condition c : Condition.values())
1712 if ((c.isNumeric() && type == Datatype.Number)
1713 || (!c.isNumeric() && type != Datatype.Number))
1715 condCombo.addItem(c);
1724 * set the selected condition (does nothing if not in the list)
1728 condCombo.setSelectedItem(cond);
1732 condCombo.setSelectedIndex(0);
1736 * clear pattern if it is now invalid for condition
1738 if (((Condition) condCombo.getSelectedItem()).isNumeric())
1742 String pattern = patternField.getText().trim();
1743 if (pattern.length() > 0)
1745 Float.valueOf(pattern);
1747 } catch (NumberFormatException e)
1749 patternField.setText("");
1754 * restore the listener
1756 condCombo.addItemListener(listener);
1760 * Answers true unless a numeric condition has been selected with a
1761 * non-numeric value. Sets the value field to RED with a tooltip if in error.
1763 * If the pattern is expected but is empty, this method returns false, but
1764 * does not mark the field as invalid. This supports selecting an attribute
1765 * for a new condition before a match pattern has been entered.
1770 protected boolean validateFilter(JTextField value,
1771 JComboBox<Condition> condCombo)
1773 if (value == null || condCombo == null)
1775 return true; // fields not populated
1778 Condition cond = (Condition) condCombo.getSelectedItem();
1779 if (!cond.needsAPattern())
1784 value.setBackground(Color.white);
1785 value.setToolTipText("");
1786 String v1 = value.getText().trim();
1787 if (v1.length() == 0)
1792 if (cond.isNumeric() && v1.length() > 0)
1797 } catch (NumberFormatException e)
1799 value.setBackground(Color.red);
1800 value.setToolTipText(
1801 MessageManager.getString("label.numeric_required"));
1810 * Constructs a filter condition from the given input fields, and replaces the
1811 * condition at filterIndex with the new one. Does nothing if the pattern
1812 * field is blank (unless the match condition is one that doesn't require a
1813 * pattern, e.g. 'Is present'). Answers true if the filter was updated, else
1816 * This method may update the tooltip on the filter value field to show the
1817 * value range, if a numeric condition is selected. This ensures the tooltip
1818 * is updated when a numeric valued attribute is chosen on the last 'add a
1824 * @param filterIndex
1826 protected boolean updateFilter(JComboBox<String> attCombo,
1827 JComboBox<Condition> condCombo, JTextField valueField,
1830 String attName = (String) attCombo.getSelectedItem();
1831 Condition cond = (Condition) condCombo.getSelectedItem();
1832 String pattern = valueField.getText().trim();
1834 setNumericHints(attName, cond, valueField);
1836 if (pattern.length() == 0 && cond.needsAPattern())
1838 valueField.setEnabled(true); // ensure pattern field is enabled!
1843 * Construct a matcher that operates on Label, Score,
1844 * or named attribute
1846 FeatureMatcherI km = null;
1847 if (LABEL_18N.equals(attName))
1849 km = FeatureMatcher.byLabel(cond, pattern);
1851 else if (SCORE_18N.equals(attName))
1853 km = FeatureMatcher.byScore(cond, pattern);
1857 km = FeatureMatcher.byAttribute(cond, pattern,
1858 FeatureMatcher.fromAttributeDisplayName(attName));
1861 filters.set(filterIndex, km);
1867 * Action on any change to feature filtering, namely
1869 * <li>change of selected attribute</li>
1870 * <li>change of selected condition</li>
1871 * <li>change of match pattern</li>
1872 * <li>removal of a condition</li>
1874 * The inputs are parsed into a combined filter and this is set for the
1875 * feature type, and the alignment redrawn.
1877 protected void filtersChanged()
1880 * update the filter conditions for the feature type
1882 boolean anded = andFilters.isSelected();
1883 FeatureMatcherSetI combined = new FeatureMatcherSet();
1885 for (FeatureMatcherI filter : filters)
1887 String pattern = filter.getMatcher().getPattern();
1888 Condition condition = filter.getMatcher().getCondition();
1889 if (pattern.trim().length() > 0 || !condition.needsAPattern())
1893 combined.and(filter);
1897 combined.or(filter);
1903 * save the filter conditions in the FeatureRenderer
1904 * (note this might now be an empty filter with no conditions)
1906 fr.setFeatureFilter(featureType, combined.isEmpty() ? null : combined);
1907 if (applyFiltersToSubtypes)
1909 for (String child : subTypes)
1911 fr.setFeatureFilter(child, combined.isEmpty() ? null : combined);
1915 refreshFeatureSettings();
1916 ap.paintAlignment(true, true);