X-Git-Url: http://source.jalview.org/gitweb/?a=blobdiff_plain;f=src%2Fjalview%2Fgui%2FFeatureSettings.java;h=ea3a6677f475593cca49604dbd4f63bbeda389e8;hb=f20ff42eac30f33cb69635ba3217a6224dbeb555;hp=4e4d2cb901ebf260022966184e42a165424d4d9a;hpb=05d220bbea0e8ce667490219436b96ebdf9826df;p=jalview.git diff --git a/src/jalview/gui/FeatureSettings.java b/src/jalview/gui/FeatureSettings.java index 4e4d2cb..ea3a667 100644 --- a/src/jalview/gui/FeatureSettings.java +++ b/src/jalview/gui/FeatureSettings.java @@ -22,42 +22,36 @@ package jalview.gui; import jalview.api.FeatureColourI; import jalview.api.FeatureSettingsControllerI; -import jalview.bin.Cache; import jalview.datamodel.AlignmentI; import jalview.datamodel.SequenceI; -import jalview.datamodel.features.FeatureAttributes; +import jalview.datamodel.features.FeatureMatcher; +import jalview.datamodel.features.FeatureMatcherI; +import jalview.datamodel.features.FeatureMatcherSet; +import jalview.datamodel.features.FeatureMatcherSetI; import jalview.gui.Help.HelpId; +import jalview.gui.JalviewColourChooser.ColourChooserListener; import jalview.io.JalviewFileChooser; import jalview.io.JalviewFileView; +import jalview.schemabinding.version2.Filter; import jalview.schemabinding.version2.JalviewUserColours; +import jalview.schemabinding.version2.MatcherSet; import jalview.schemes.FeatureColour; -import jalview.util.Format; import jalview.util.MessageManager; import jalview.util.Platform; -import jalview.util.QuickSort; -import jalview.util.ReverseListIterator; -import jalview.util.matcher.Condition; -import jalview.util.matcher.KeyedMatcher; -import jalview.util.matcher.KeyedMatcherI; -import jalview.util.matcher.KeyedMatcherSet; -import jalview.util.matcher.KeyedMatcherSetI; -import jalview.viewmodel.AlignmentViewport; -import jalview.ws.DasSequenceFeatureFetcher; -import jalview.ws.dbsources.das.api.jalviewSourceI; +import jalview.util.dialogrunner.RunResponse; +import jalview.viewmodel.seqfeatures.FeatureRendererModel.FeatureSettingsBean; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; -import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.GridLayout; +import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.awt.event.FocusAdapter; -import java.awt.event.FocusEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; @@ -71,65 +65,67 @@ import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; -import java.util.ArrayList; import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.Vector; import javax.help.HelpSetException; import javax.swing.AbstractCellEditor; import javax.swing.BorderFactory; -import javax.swing.BoxLayout; -import javax.swing.ButtonGroup; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; -import javax.swing.JColorChooser; -import javax.swing.JComboBox; -import javax.swing.JDialog; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; -import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSlider; -import javax.swing.JTabbedPane; import javax.swing.JTable; -import javax.swing.JTextArea; -import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; -import javax.swing.SwingUtilities; +import javax.swing.ToolTipManager; +import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; -import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumn; public class FeatureSettings extends JPanel implements FeatureSettingsControllerI { - private static final int MIN_WIDTH = 400; + private static final String SEQUENCE_FEATURE_COLOURS = MessageManager + .getString("label.sequence_feature_colours"); - private static final int MIN_HEIGHT = 400; + /* + * column indices of fields in Feature Settings table + */ + static final int TYPE_COLUMN = 0; - private static final int MAX_TOOLTIP_LENGTH = 50; + static final int COLOUR_COLUMN = 1; - DasSourceBrowser dassourceBrowser; + static final int FILTER_COLUMN = 2; + + static final int SHOW_COLUMN = 3; + + private static final int COLUMN_COUNT = 4; + + private static final int MIN_WIDTH = 400; - DasSequenceFeatureFetcher dasFeatureFetcher; + private static final int MIN_HEIGHT = 400; - JPanel dasSettingsPane = new JPanel(); + private final static String BASE_TOOLTIP = MessageManager.getString("label.click_to_edit"); final FeatureRenderer fr; @@ -140,9 +136,9 @@ public class FeatureSettings extends JPanel */ Object[][] originalData; - private float originalTransparency; + float originalTransparency; - private Map originalFilters; + Map originalFilters; final JInternalFrame frame; @@ -153,7 +149,7 @@ public class FeatureSettings extends JPanel JPanel groupPanel; JSlider transparency = new JSlider(); - + /* * when true, constructor is still executing - so ignore UI events */ @@ -172,33 +168,13 @@ public class FeatureSettings extends JPanel /* * true when Feature Settings are updating from feature renderer */ - private boolean handlingUpdate = false; + boolean handlingUpdate = false; /* * holds {featureCount, totalExtent} for each feature type */ Map typeWidth = null; - /* - * fields of the feature filters tab - */ - private JPanel filtersPane; - - private JPanel chooseFiltersPanel; - - private JComboBox filteredFeatureChoice; - - private JRadioButton andFilters; - - private JRadioButton orFilters; - - /* - * filters for the currently selected feature type - */ - private List filters; - - private JTextArea filtersAsText; - /** * Constructor * @@ -214,7 +190,7 @@ public class FeatureSettings extends JPanel int originalTransparencyAsPercent = (int) (originalTransparency * 100); transparency.setMaximum(100 - originalTransparencyAsPercent); - originalFilters = fr.getFeatureFilters(); + originalFilters = new HashMap<>(fr.getFeatureFilters()); // shallow copy try { @@ -229,25 +205,67 @@ public class FeatureSettings extends JPanel @Override public String getToolTipText(MouseEvent e) { - if (table.columnAtPoint(e.getPoint()) == 0) + String tip = null; + int column = table.columnAtPoint(e.getPoint()); + int row = table.rowAtPoint(e.getPoint()); + + switch (column) { - /* - * Tooltip for feature name only - */ - return JvSwingUtils.wrapTooltip(true, MessageManager + case TYPE_COLUMN: + tip = JvSwingUtils.wrapTooltip(true, MessageManager .getString("label.feature_settings_click_drag")); + break; + case COLOUR_COLUMN: + FeatureColourI colour = (FeatureColourI) table.getValueAt(row, + column); + tip = getColorTooltip(colour, true); + break; + case FILTER_COLUMN: + FeatureMatcherSet o = (FeatureMatcherSet) table.getValueAt(row, + column); + tip = o.isEmpty() + ? MessageManager.getString("label.filters_tooltip") + : o.toString(); + break; + default: + break; } - return null; + + return tip; + } + + /** + * Position the tooltip near the bottom edge of, and half way across, the + * current cell + */ + @Override + public Point getToolTipLocation(MouseEvent e) + { + Point point = e.getPoint(); + int column = table.columnAtPoint(point); + int row = table.rowAtPoint(point); + Rectangle r = getCellRect(row, column, false); + Point loc = new Point(r.x + r.width / 2, r.y + r.height - 3); + return loc; } }; table.getTableHeader().setFont(new Font("Verdana", Font.PLAIN, 12)); - table.setFont(new Font("Verdana", Font.PLAIN, 12)); - table.setDefaultRenderer(Color.class, new ColorRenderer()); - - table.setDefaultEditor(Color.class, new ColorEditor(this)); + ToolTipManager.sharedInstance().registerComponent(table); table.setDefaultEditor(FeatureColour.class, new ColorEditor(this)); table.setDefaultRenderer(FeatureColour.class, new ColorRenderer()); + + table.setDefaultEditor(FeatureMatcherSet.class, new FilterEditor(this)); + table.setDefaultRenderer(FeatureMatcherSet.class, new FilterRenderer()); + + TableColumn colourColumn = new TableColumn(COLOUR_COLUMN, 75, + new ColorRenderer(), new ColorEditor(this)); + table.addColumn(colourColumn); + + TableColumn filterColumn = new TableColumn(FILTER_COLUMN, 75, + new FilterRenderer(), new FilterEditor(this)); + table.addColumn(filterColumn); + table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.addMouseListener(new MouseAdapter() @@ -256,11 +274,12 @@ public class FeatureSettings extends JPanel public void mousePressed(MouseEvent evt) { selectedRow = table.rowAtPoint(evt.getPoint()); + String type = (String) table.getValueAt(selectedRow, TYPE_COLUMN); if (evt.isPopupTrigger()) { - popupSort(selectedRow, (String) table.getValueAt(selectedRow, 0), - table.getValueAt(selectedRow, 1), fr.getMinMax(), - evt.getX(), evt.getY()); + Object colour = table.getValueAt(selectedRow, COLOUR_COLUMN); + popupSort(selectedRow, type, colour, fr.getMinMax(), evt.getX(), + evt.getY()); } else if (evt.getClickCount() == 2) { @@ -268,8 +287,7 @@ public class FeatureSettings extends JPanel boolean toggleSelection = Platform.isControlDown(evt); boolean extendSelection = evt.isShiftDown(); fr.ap.alignFrame.avc.markColumnsContainingFeatures( - invertSelection, extendSelection, toggleSelection, - (String) table.getValueAt(selectedRow, 0)); + invertSelection, extendSelection, toggleSelection, type); } } @@ -280,9 +298,10 @@ public class FeatureSettings extends JPanel selectedRow = table.rowAtPoint(evt.getPoint()); if (evt.isPopupTrigger()) { - popupSort(selectedRow, (String) table.getValueAt(selectedRow, 0), - table.getValueAt(selectedRow, 1), fr.getMinMax(), - evt.getX(), evt.getY()); + String type = (String) table.getValueAt(selectedRow, TYPE_COLUMN); + Object colour = table.getValueAt(selectedRow, COLOUR_COLUMN); + popupSort(selectedRow, type, colour, fr.getMinMax(), evt.getX(), + evt.getY()); } } }); @@ -319,9 +338,6 @@ public class FeatureSettings extends JPanel // MessageManager.getString("label.feature_settings_click_drag"))); scrollPane.setViewportView(table); - dassourceBrowser = new DasSourceBrowser(this); - dasSettingsPane.add(dassourceBrowser, BorderLayout.CENTER); - if (af.getViewport().isShowSequenceFeatures() || !fr.hasRenderOrder()) { fr.findAllFeatures(true); // display everything! @@ -338,8 +354,8 @@ public class FeatureSettings extends JPanel if (!fs.resettingTable && !fs.handlingUpdate) { fs.handlingUpdate = true; - fs.resetTable(null); // new groups may be added with new seuqence - // feature types only + fs.resetTable(null); + // new groups may be added with new sequence feature types only fs.handlingUpdate = false; } } @@ -370,14 +386,13 @@ public class FeatureSettings extends JPanel javax.swing.event.InternalFrameEvent evt) { fr.removePropertyChangeListener(change); - dassourceBrowser.fs = null; }; }); frame.setLayer(JLayeredPane.PALETTE_LAYER); inConstruction = false; } - protected void popupSort(final int selectedRow, final String type, + protected void popupSort(final int rowSelected, final String type, final Object typeCol, final Map minmax, int x, int y) { @@ -422,52 +437,62 @@ public class FeatureSettings extends JPanel * variable colour options include colour by label, by score, * by selected attribute text, or attribute value */ - final JCheckBoxMenuItem mxcol = new JCheckBoxMenuItem( + final JCheckBoxMenuItem variableColourCB = new JCheckBoxMenuItem( MessageManager.getString("label.variable_colour")); - mxcol.setSelected(!featureColour.isSimpleColour()); - men.add(mxcol); - mxcol.addActionListener(new ActionListener() + variableColourCB.setSelected(!featureColour.isSimpleColour()); + men.add(variableColourCB); + + /* + * checkbox action listener doubles up as listener to OK + * from the variable colour / filters dialog + */ + variableColourCB.addActionListener(new ActionListener() { - JColorChooser colorChooser; - @Override public void actionPerformed(ActionEvent e) { - if (e.getSource() == mxcol) + if (e.getSource() == variableColourCB) { if (featureColour.isSimpleColour()) { - FeatureColourChooser fc = new FeatureColourChooser(me.fr, type); + /* + * toggle simple colour to variable colour - show dialog + */ + FeatureTypeSettings fc = new FeatureTypeSettings(me.fr, type); fc.addActionListener(this); } else { - // bring up simple color chooser - colorChooser = new JColorChooser(); - JDialog dialog = JColorChooser.createDialog(me, - "Select new Colour", true, // modal - colorChooser, this, // OK button handler - null); // no CANCEL button handler - colorChooser.setColor(featureColour.getMaxColour()); - dialog.setVisible(true); + /* + * toggle variable to simple colour - show colour chooser + */ + String title = MessageManager.getString("label.select_colour"); + ColourChooserListener listener = new ColourChooserListener() + { + @Override + public void colourSelected(Color c) + { + table.setValueAt(new FeatureColour(c), rowSelected, + COLOUR_COLUMN); + table.validate(); + me.updateFeatureRenderer( + ((FeatureTableModel) table.getModel()).getData(), + false); + } + }; + JalviewColourChooser.showColourChooser(me, title, featureColour.getMaxColour(), listener); } } - else - { - if (e.getSource() instanceof FeatureColourChooser) - { - FeatureColourChooser fc = (FeatureColourChooser) e.getSource(); - table.setValueAt(fc.getLastColour(), selectedRow, 1); - table.validate(); - } - else + else { + if (e.getSource() instanceof FeatureTypeSettings) { - // probably the color chooser! - table.setValueAt(new FeatureColour(colorChooser.getColor()), - selectedRow, 1); + /* + * update after OK in feature colour dialog; the updated + * colour will have already been set in the FeatureRenderer + */ + FeatureColourI fci = fr.getFeatureColours().get(type); + table.setValueAt(fci, rowSelected, COLOUR_COLUMN); table.validate(); - me.updateFeatureRenderer( - ((FeatureTableModel) table.getModel()).getData(), false); } } } @@ -542,8 +567,6 @@ public class FeatureSettings extends JPanel } } - populateFilterableFeatures(); - resetTable(null); validate(); @@ -648,7 +671,7 @@ public class FeatureSettings extends JPanel } } - Object[][] data = new Object[displayableTypes.size()][3]; + Object[][] data = new Object[displayableTypes.size()][COLUMN_COUNT]; int dataIndex = 0; if (fr.hasRenderOrder()) @@ -671,9 +694,13 @@ public class FeatureSettings extends JPanel continue; } - data[dataIndex][0] = type; - data[dataIndex][1] = fr.getFeatureStyle(type); - data[dataIndex][2] = new Boolean( + data[dataIndex][TYPE_COLUMN] = type; + data[dataIndex][COLOUR_COLUMN] = fr.getFeatureStyle(type); + FeatureMatcherSetI featureFilter = fr.getFeatureFilter(type); + data[dataIndex][FILTER_COLUMN] = featureFilter == null + ? new FeatureMatcherSet() + : featureFilter; + data[dataIndex][SHOW_COLUMN] = new Boolean( af.getViewport().getFeaturesDisplayed().isVisible(type)); dataIndex++; displayableTypes.remove(type); @@ -687,27 +714,30 @@ public class FeatureSettings extends JPanel while (!displayableTypes.isEmpty()) { String type = displayableTypes.iterator().next(); - data[dataIndex][0] = type; + data[dataIndex][TYPE_COLUMN] = type; - data[dataIndex][1] = fr.getFeatureStyle(type); - if (data[dataIndex][1] == null) + data[dataIndex][COLOUR_COLUMN] = fr.getFeatureStyle(type); + if (data[dataIndex][COLOUR_COLUMN] == null) { // "Colour has been updated in another view!!" fr.clearRenderOrder(); return; } - - data[dataIndex][2] = new Boolean(true); + FeatureMatcherSetI featureFilter = fr.getFeatureFilter(type); + data[dataIndex][FILTER_COLUMN] = featureFilter == null + ? new FeatureMatcherSet() + : featureFilter; + data[dataIndex][SHOW_COLUMN] = new Boolean(true); dataIndex++; displayableTypes.remove(type); } if (originalData == null) { - originalData = new Object[data.length][3]; + originalData = new Object[data.length][COLUMN_COUNT]; for (int i = 0; i < data.length; i++) { - System.arraycopy(data[i], 0, originalData[i], 0, 3); + System.arraycopy(data[i], 0, originalData[i], 0, COLUMN_COUNT); } } else @@ -728,8 +758,8 @@ public class FeatureSettings extends JPanel } /** - * Updates 'originalData' (used for restore on Cancel) if we detect that - * changes have been made outwith this dialog + * Updates 'originalData' (used for restore on Cancel) if we detect that changes + * have been made outwith this dialog *
    *
  • a new feature type added (and made visible)
  • *
  • a feature colour changed (in the Amend Features dialog)
  • @@ -745,27 +775,27 @@ public class FeatureSettings extends JPanel .getData(); for (Object[] row : foundData) { - String type = (String) row[0]; + String type = (String) row[TYPE_COLUMN]; boolean found = false; for (Object[] current : currentData) { - if (type.equals(current[0])) + if (type.equals(current[TYPE_COLUMN])) { found = true; /* * currently dependent on object equality here; * really need an equals method on FeatureColour */ - if (!row[1].equals(current[1])) + if (!row[COLOUR_COLUMN].equals(current[COLOUR_COLUMN])) { /* * feature colour has changed externally - update originalData */ for (Object[] original : originalData) { - if (type.equals(original[0])) + if (type.equals(original[TYPE_COLUMN])) { - original[1] = row[1]; + original[COLOUR_COLUMN] = row[COLOUR_COLUMN]; break; } } @@ -778,10 +808,12 @@ public class FeatureSettings extends JPanel /* * new feature detected - add to original data (on top) */ - Object[][] newData = new Object[originalData.length + 1][3]; + Object[][] newData = new Object[originalData.length + + 1][COLUMN_COUNT]; for (int i = 0; i < originalData.length; i++) { - System.arraycopy(originalData[i], 0, newData[i + 1], 0, 3); + System.arraycopy(originalData[i], 0, newData[i + 1], 0, + COLUMN_COUNT); } newData[0] = row; originalData = newData; @@ -791,8 +823,8 @@ public class FeatureSettings extends JPanel /** * Remove from the groups panel any checkboxes for groups that are not in the - * foundGroups set. This enables removing a group from the display when the - * last feature in that group is deleted. + * foundGroups set. This enables removing a group from the display when the last + * feature in that group is deleted. * * @param foundGroups */ @@ -835,173 +867,185 @@ public class FeatureSettings extends JPanel } } + /** + * Offers a file chooser dialog, and then loads the feature colours and + * filters from file in XML format and unmarshals to Jalview feature settings + */ void load() { JalviewFileChooser chooser = new JalviewFileChooser("fc", - "Sequence Feature Colours"); + SEQUENCE_FEATURE_COLOURS); chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle( MessageManager.getString("label.load_feature_colours")); chooser.setToolTipText(MessageManager.getString("action.load")); + chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION){ + + @Override + public void run() { + File file = chooser.getSelectedFile(); + load(file); + }}); + chooser.showOpenDialog(this); + } - int value = chooser.showOpenDialog(this); - - if (value == JalviewFileChooser.APPROVE_OPTION) + /** + * Loads feature colours and filters from XML stored in the given file + * + * @param file + */ + void load(File file) + { + try { - File file = chooser.getSelectedFile(); - - try - { - InputStreamReader in = new InputStreamReader( - new FileInputStream(file), "UTF-8"); + InputStreamReader in = new InputStreamReader( + new FileInputStream(file), "UTF-8"); - JalviewUserColours jucs = JalviewUserColours.unmarshal(in); + JalviewUserColours jucs = JalviewUserColours.unmarshal(in); - for (int i = jucs.getColourCount() - 1; i >= 0; i--) - { - String name; - jalview.schemabinding.version2.Colour newcol = jucs.getColour(i); - if (newcol.hasMax()) - { - Color mincol = null, maxcol = null; - try - { - mincol = new Color(Integer.parseInt(newcol.getMinRGB(), 16)); - maxcol = new Color(Integer.parseInt(newcol.getRGB(), 16)); + /* + * load feature colours + */ + for (int i = jucs.getColourCount() - 1; i >= 0; i--) + { + jalview.schemabinding.version2.Colour newcol = jucs.getColour(i); + FeatureColourI colour = Jalview2XML.unmarshalColour(newcol); + fr.setColour(newcol.getName(), colour); + fr.setOrder(newcol.getName(), i / (float) jucs.getColourCount()); + } - } catch (Exception e) - { - Cache.log.warn("Couldn't parse out graduated feature color.", - e); - } - FeatureColourI gcol = new FeatureColour(mincol, maxcol, - newcol.getMin(), newcol.getMax()); - if (newcol.hasAutoScale()) - { - gcol.setAutoScaled(newcol.getAutoScale()); - } - if (newcol.hasColourByLabel()) - { - gcol.setColourByLabel(newcol.getColourByLabel()); - } - if (newcol.hasThreshold()) - { - gcol.setThreshold(newcol.getThreshold()); - } - if (newcol.getThreshType().length() > 0) - { - String ttyp = newcol.getThreshType(); - if (ttyp.equalsIgnoreCase("ABOVE")) - { - gcol.setAboveThreshold(true); - } - if (ttyp.equalsIgnoreCase("BELOW")) - { - gcol.setBelowThreshold(true); - } - } - fr.setColour(name = newcol.getName(), gcol); - } - else - { - Color color = new Color( - Integer.parseInt(jucs.getColour(i).getRGB(), 16)); - fr.setColour(name = jucs.getColour(i).getName(), - new FeatureColour(color)); - } - fr.setOrder(name, (i == 0) ? 0 : i / jucs.getColourCount()); - } - if (table != null) + /* + * load feature filters; loaded filters will replace any that are + * currently defined, other defined filters are left unchanged + */ + for (int i = 0; i < jucs.getFilterCount(); i++) + { + jalview.schemabinding.version2.Filter filterModel = jucs + .getFilter(i); + String featureType = filterModel.getFeatureType(); + FeatureMatcherSetI filter = Jalview2XML.unmarshalFilter(featureType, + filterModel.getMatcherSet()); + if (!filter.isEmpty()) { - resetTable(null); - Object[][] data = ((FeatureTableModel) table.getModel()) - .getData(); - ensureOrder(data); - updateFeatureRenderer(data, false); - table.repaint(); + fr.setFeatureFilter(featureType, filter); } - } catch (Exception ex) + } + + /* + * update feature settings table + */ + if (table != null) { - System.out.println("Error loading User Colour File\n" + ex); + resetTable(null); + Object[][] data = ((FeatureTableModel) table.getModel()) + .getData(); + ensureOrder(data); + updateFeatureRenderer(data, false); + table.repaint(); } + } catch (Exception ex) + { + System.out.println("Error loading User Colour File\n" + ex); } } + /** + * Offers a file chooser dialog, and then saves the current feature colours + * and any filters to the selected file in XML format + */ void save() { JalviewFileChooser chooser = new JalviewFileChooser("fc", - "Sequence Feature Colours"); + SEQUENCE_FEATURE_COLOURS); chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle( MessageManager.getString("label.save_feature_colours")); chooser.setToolTipText(MessageManager.getString("action.save")); + int option = chooser.showSaveDialog(this); + if (option == JalviewFileChooser.APPROVE_OPTION) + { + File file = chooser.getSelectedFile(); + save(file); + } + } - int value = chooser.showSaveDialog(this); - - if (value == JalviewFileChooser.APPROVE_OPTION) + /** + * Saves feature colours and filters to the given file + * + * @param file + */ + void save(File file) + { + JalviewUserColours ucs = new JalviewUserColours(); + ucs.setSchemeName("Sequence Features"); + try { - String choice = chooser.getSelectedFile().getPath(); - jalview.schemabinding.version2.JalviewUserColours ucs = new jalview.schemabinding.version2.JalviewUserColours(); - ucs.setSchemeName("Sequence Features"); - try - { - PrintWriter out = new PrintWriter(new OutputStreamWriter( - new FileOutputStream(choice), "UTF-8")); + PrintWriter out = new PrintWriter(new OutputStreamWriter( + new FileOutputStream(file), "UTF-8")); - Set fr_colours = fr.getAllFeatureColours(); - Iterator e = fr_colours.iterator(); - float[] sortOrder = new float[fr_colours.size()]; - String[] sortTypes = new String[fr_colours.size()]; - int i = 0; - while (e.hasNext()) + /* + * sort feature types by colour order, from 0 (highest) + * to 1 (lowest) + */ + Set fr_colours = fr.getAllFeatureColours(); + String[] sortedTypes = fr_colours + .toArray(new String[fr_colours.size()]); + Arrays.sort(sortedTypes, new Comparator() + { + @Override + public int compare(String type1, String type2) { - sortTypes[i] = e.next(); - sortOrder[i] = fr.getOrder(sortTypes[i]); - i++; + return Float.compare(fr.getOrder(type1), fr.getOrder(type2)); } - QuickSort.sort(sortOrder, sortTypes); - sortOrder = null; - for (i = 0; i < sortTypes.length; i++) + }); + + /* + * save feature colours + */ + for (String featureType : sortedTypes) + { + FeatureColourI fcol = fr.getFeatureStyle(featureType); + jalview.schemabinding.version2.Colour col = Jalview2XML.marshalColour( + featureType, fcol); + ucs.addColour(col); + } + + /* + * save any feature filters + */ + for (String featureType : sortedTypes) + { + FeatureMatcherSetI filter = fr.getFeatureFilter(featureType); + if (filter != null && !filter.isEmpty()) { - jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour(); - col.setName(sortTypes[i]); - FeatureColourI fcol = fr.getFeatureStyle(sortTypes[i]); - if (fcol.isSimpleColour()) - { - col.setRGB(Format.getHexString(fcol.getColour())); - } - else - { - col.setRGB(Format.getHexString(fcol.getMaxColour())); - col.setMin(fcol.getMin()); - col.setMax(fcol.getMax()); - col.setMinRGB( - jalview.util.Format.getHexString(fcol.getMinColour())); - col.setAutoScale(fcol.isAutoScaled()); - col.setThreshold(fcol.getThreshold()); - col.setColourByLabel(fcol.isColourByLabel()); - col.setThreshType(fcol.isAboveThreshold() ? "ABOVE" - : (fcol.isBelowThreshold() ? "BELOW" : "NONE")); - } - ucs.addColour(col); + Iterator iterator = filter.getMatchers().iterator(); + FeatureMatcherI firstMatcher = iterator.next(); + MatcherSet ms = Jalview2XML.marshalFilter(firstMatcher, iterator, + filter.isAnded()); + Filter filterModel = new Filter(); + filterModel.setFeatureType(featureType); + filterModel.setMatcherSet(ms); + ucs.addFilter(filterModel); } - ucs.marshal(out); - out.close(); - } catch (Exception ex) - { - ex.printStackTrace(); } + + ucs.marshal(out); + out.close(); + } catch (Exception ex) + { + ex.printStackTrace(); } } public void invertSelection() { - for (int i = 0; i < table.getRowCount(); i++) + Object[][] data = ((FeatureTableModel) table.getModel()).getData(); + for (int i = 0; i < data.length; i++) { - Boolean value = (Boolean) table.getValueAt(i, 2); - - table.setValueAt(new Boolean(!value.booleanValue()), i, 2); + data[i][SHOW_COLUMN] = !(Boolean) data[i][SHOW_COLUMN]; } + updateFeatureRenderer(data, true); + table.repaint(); } public void orderByAvWidth() @@ -1014,17 +1058,16 @@ public class FeatureSettings extends JPanel float[] width = new float[data.length]; float[] awidth; float max = 0; - int num = 0; + for (int i = 0; i < data.length; i++) { - awidth = typeWidth.get(data[i][0]); + awidth = typeWidth.get(data[i][TYPE_COLUMN]); if (awidth[0] > 0) { width[i] = awidth[1] / awidth[0];// *awidth[0]*awidth[2]; - better // weight - but have to make per // sequence, too (awidth[2]) // if (width[i]==1) // hack to distinguish single width sequences. - num++; } else { @@ -1041,16 +1084,17 @@ public class FeatureSettings extends JPanel // awidth = (float[]) typeWidth.get(data[i][0]); if (width[i] == 0) { - width[i] = fr.getOrder(data[i][0].toString()); + width[i] = fr.getOrder(data[i][TYPE_COLUMN].toString()); if (width[i] < 0) { - width[i] = fr.setOrder(data[i][0].toString(), i / data.length); + width[i] = fr.setOrder(data[i][TYPE_COLUMN].toString(), + i / data.length); } } else { width[i] /= max; // normalize - fr.setOrder(data[i][0].toString(), width[i]); // store for later + fr.setOrder(data[i][TYPE_COLUMN].toString(), width[i]); // store for later } if (i > 0) { @@ -1084,20 +1128,40 @@ public class FeatureSettings extends JPanel } /** - * Update the priority order of features; only repaint if this changed the - * order of visible features + * Update the priority order of features; only repaint if this changed the order + * of visible features * * @param data * @param visibleNew */ - private void updateFeatureRenderer(Object[][] data, boolean visibleNew) + void updateFeatureRenderer(Object[][] data, boolean visibleNew) { - if (fr.setFeaturePriority(data, visibleNew)) + FeatureSettingsBean[] rowData = getTableAsBeans(data); + + if (fr.setFeaturePriority(rowData, visibleNew)) { af.alignPanel.paintAlignment(true, true); } } + /** + * Converts table data into an array of data beans + */ + private FeatureSettingsBean[] getTableAsBeans(Object[][] data) + { + FeatureSettingsBean[] rowData = new FeatureSettingsBean[data.length]; + for (int i = 0; i < data.length; i++) + { + String type = (String) data[i][TYPE_COLUMN]; + FeatureColourI colour = (FeatureColourI) data[i][COLOUR_COLUMN]; + FeatureMatcherSetI theFilter = (FeatureMatcherSetI) data[i][FILTER_COLUMN]; + Boolean isShown = (Boolean) data[i][SHOW_COLUMN]; + rowData[i] = new FeatureSettingsBean(type, colour, theFilter, + isShown); + } + return rowData; + } + private void jbInit() throws Exception { this.setLayout(new BorderLayout()); @@ -1105,10 +1169,6 @@ public class FeatureSettings extends JPanel JPanel settingsPane = new JPanel(); settingsPane.setLayout(new BorderLayout()); - filtersPane = new JPanel(); - - dasSettingsPane.setLayout(new BorderLayout()); - JPanel bigPanel = new JPanel(); bigPanel.setLayout(new BorderLayout()); @@ -1223,6 +1283,8 @@ public class FeatureSettings extends JPanel JButton loadColours = new JButton( MessageManager.getString("label.load_colours")); loadColours.setFont(JvSwingUtils.getLabelFont()); + loadColours.setToolTipText( + MessageManager.getString("label.load_colours_tooltip")); loadColours.addActionListener(new ActionListener() { @Override @@ -1235,6 +1297,8 @@ public class FeatureSettings extends JPanel JButton saveColours = new JButton( MessageManager.getString("label.save_colours")); saveColours.setFont(JvSwingUtils.getLabelFont()); + saveColours.setToolTipText( + MessageManager.getString("label.save_colours_tooltip")); saveColours.addActionListener(new ActionListener() { @Override @@ -1251,7 +1315,7 @@ public class FeatureSettings extends JPanel if (!inConstruction) { fr.setTransparency((100 - transparency.getValue()) / 100f); - af.alignPanel.paintAlignment(true,true); + af.alignPanel.paintAlignment(true, true); } } }); @@ -1259,47 +1323,6 @@ public class FeatureSettings extends JPanel transparency.setMaximum(70); transparency.setToolTipText( MessageManager.getString("label.transparency_tip")); - fetchDAS.setText(MessageManager.getString("label.fetch_das_features")); - fetchDAS.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - fetchDAS_actionPerformed(e); - } - }); - saveDAS.setText(MessageManager.getString("action.save_as_default")); - saveDAS.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - saveDAS_actionPerformed(e); - } - }); - - JPanel dasButtonPanel = new JPanel(); - dasButtonPanel.setBorder(BorderFactory.createEtchedBorder()); - dasSettingsPane.setBorder(null); - cancelDAS.setEnabled(false); - cancelDAS.setText(MessageManager.getString("action.cancel_fetch")); - cancelDAS.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - cancelDAS_actionPerformed(e); - } - }); - - JTabbedPane tabbedPane = new JTabbedPane(); - this.add(tabbedPane, BorderLayout.CENTER); - tabbedPane.addTab(MessageManager.getString("label.feature_settings"), - settingsPane); - tabbedPane.addTab(MessageManager.getString("label.filters"), - filtersPane); - // tabbedPane.addTab(MessageManager.getString("label.das_settings"), - // dasSettingsPane); JPanel transPanel = new JPanel(new GridLayout(1, 2)); bigPanel.add(transPanel, BorderLayout.SOUTH); @@ -1319,647 +1342,93 @@ public class FeatureSettings extends JPanel buttonPanel.add(loadColours); buttonPanel.add(saveColours); bigPanel.add(scrollPane, BorderLayout.CENTER); - dasSettingsPane.add(dasButtonPanel, BorderLayout.SOUTH); - dasButtonPanel.add(fetchDAS); - dasButtonPanel.add(cancelDAS); - dasButtonPanel.add(saveDAS); settingsPane.add(bigPanel, BorderLayout.CENTER); settingsPane.add(buttonPanel, BorderLayout.SOUTH); - - initFiltersTab(); + this.add(settingsPane); } /** - * Populates initial layout of the feature attribute filters panel + * Answers a suitable tooltip to show on the colour cell of the table + * + * @param fcol + * @param withHint + * if true include 'click to edit' and similar text + * @return */ - protected void initFiltersTab() + public static String getColorTooltip(FeatureColourI fcol, + boolean withHint) { - filters = new ArrayList<>(); - - /* - * choose feature type - */ - JPanel chooseTypePanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); - chooseTypePanel.setBackground(Color.white); - JvSwingUtils.createItalicTitledBorder(chooseTypePanel, - MessageManager.getString("label.feature_type"), true); - filteredFeatureChoice = new JComboBox<>(); - filteredFeatureChoice.addItemListener(new ItemListener() - { - @Override - public void itemStateChanged(ItemEvent e) - { - refreshFiltersDisplay(); - } - }); - chooseTypePanel.add(new JLabel(MessageManager - .getString("label.feature_to_filter"))); - chooseTypePanel.add(filteredFeatureChoice); - populateFilterableFeatures(); - - /* - * the panel with the filters for the selected feature type - */ - JPanel filtersPanel = new JPanel(); - filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS)); - filtersPanel.setBackground(Color.white); - JvSwingUtils.createItalicTitledBorder(filtersPanel, - MessageManager.getString("label.filters"), true); - - /* - * add AND or OR radio buttons - */ - JPanel andOrPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); - andOrPanel.setBackground(Color.white); - andFilters = new JRadioButton("And"); - orFilters = new JRadioButton("Or"); - ActionListener actionListener = new ActionListener() + if (fcol == null) { - @Override - public void actionPerformed(ActionEvent e) - { - filtersChanged(); - } - }; - andFilters.addActionListener(actionListener); - orFilters.addActionListener(actionListener); - ButtonGroup andOr = new ButtonGroup(); - andOr.add(andFilters); - andOr.add(orFilters); - andFilters.setSelected(true); - andOrPanel.add(new JLabel(MessageManager - .getString("label.join_conditions"))); - andOrPanel.add(andFilters); - andOrPanel.add(orFilters); - filtersPanel.add(andOrPanel); - - /* - * panel with filters - populated by refreshFiltersDisplay - */ - chooseFiltersPanel = new JPanel(); - chooseFiltersPanel.setLayout(new BoxLayout(chooseFiltersPanel, - BoxLayout.Y_AXIS)); - filtersPanel.add(chooseFiltersPanel); - - /* - * a read-only text view of the current filters - */ - JPanel showFiltersPanel = new JPanel(new BorderLayout(5, 5)); - showFiltersPanel.setBackground(Color.white); - JvSwingUtils.createItalicTitledBorder(showFiltersPanel, - MessageManager.getString("label.match_condition"), true); - filtersAsText = new JTextArea(); - filtersAsText.setLineWrap(true); - filtersAsText.setWrapStyleWord(true); - showFiltersPanel.add(filtersAsText); - - filtersPane.setLayout(new BorderLayout()); - filtersPane.add(chooseTypePanel, BorderLayout.NORTH); - filtersPane.add(filtersPanel, BorderLayout.CENTER); - filtersPane.add(showFiltersPanel, BorderLayout.SOUTH); - - /* - * update display for initial feature type selection - */ - refreshFiltersDisplay(); - } - - /** - * Adds entries to the 'choose feature to filter' drop-down choice. Only - * feature types which have known attributes (so can be filtered) are - * included, so recall this method to update the list (check for newly added - * attributes). - */ - protected void populateFilterableFeatures() - { - /* - * suppress action handler while updating the list - */ - ItemListener listener = filteredFeatureChoice.getItemListeners()[0]; - filteredFeatureChoice.removeItemListener(listener); - - filteredFeatureChoice.removeAllItems(); - ReverseListIterator types = new ReverseListIterator<>( - fr.getRenderOrder()); - - boolean found = false; - while (types.hasNext()) + return null; + } + if (fcol.isSimpleColour()) { - String type = types.next(); - if (FeatureAttributes.getInstance().hasAttributes(type)) - { - filteredFeatureChoice.addItem(type); - found = true; - } + return withHint ? BASE_TOOLTIP : null; } - if (!found) + String description = fcol.getDescription(); + description = description.replaceAll("<", "<"); + description = description.replaceAll(">", ">"); + StringBuilder tt = new StringBuilder(description); + if (withHint) { - filteredFeatureChoice // todo i18n - .addItem("No filterable feature attributes known"); + tt.append("
    ").append(BASE_TOOLTIP).append("
    "); } - - filteredFeatureChoice.addItemListener(listener); - + return JvSwingUtils.wrapTooltip(true, tt.toString()); } - /** - * Refreshes the display to show any filters currently configured for the - * selected feature type (editable, with 'remove' option), plus one extra row - * for adding a condition. This should be called on change of selected feature - * type, or after a filter has been removed, added or amended. - */ - protected void refreshFiltersDisplay() + public static void renderGraduatedColor(JLabel comp, FeatureColourI gcol, + int w, int h) { - /* - * clear the panel and list of filter conditions - */ - chooseFiltersPanel.removeAll(); - filters.clear(); - - /* - * look up attributes known for feature type - */ - String selectedType = (String) filteredFeatureChoice.getSelectedItem(); - List attNames = FeatureAttributes.getInstance().getAttributes( - selectedType); - - /* - * if this feature type has filters set, load them first - */ - KeyedMatcherSetI featureFilters = fr.getFeatureFilter(selectedType); - filtersAsText.setText(""); - if (featureFilters != null) + boolean thr = false; + StringBuilder tx = new StringBuilder(); + + if (gcol.isColourByAttribute()) { - filtersAsText.setText(featureFilters.toString()); - if (!featureFilters.isAnded()) - { - orFilters.setSelected(true); - } - featureFilters.getMatchers().forEach(matcher -> filters.add(matcher)); + tx.append(FeatureMatcher + .toAttributeDisplayName(gcol.getAttributeName())); } - - /* - * and an empty filter for the user to populate (add) - */ - KeyedMatcherI noFilter = new KeyedMatcher("", Condition.values()[0], ""); - filters.add(noFilter); - - /* - * render the conditions in rows, each in its own JPanel - */ - int filterIndex = 0; - for (KeyedMatcherI filter : filters) - { - String key = filter.getKey(); - Condition condition = filter.getMatcher() - .getCondition(); - String pattern = filter.getMatcher().getPattern(); - JPanel row = addFilter(key, attNames, condition, pattern, filterIndex); - chooseFiltersPanel.add(row); - filterIndex++; + else if (!gcol.isColourByLabel()) + { + tx.append(MessageManager.getString("label.score")); } - - filtersPane.validate(); - filtersPane.repaint(); - } - - /** - * A helper method that constructs a panel with one filter condition: - *
      - *
    • a drop-down list of attribute names to choose from
    • - *
    • a drop-down list of conditions to choose from
    • - *
    • a text field for input of a match pattern
    • - *
    • optionally, a 'remove' button
    • - *
    - * If attribute, condition or pattern are not null, they are set as defaults - * for the input fields. The 'remove' button is added unless the pattern is - * null or empty (incomplete filter condition). - * - * @param attribute - * @param attNames - * @param cond - * @param pattern - * @param filterIndex - * @return - */ - protected JPanel addFilter(String attribute, List attNames, - Condition cond, String pattern, int filterIndex) - { - JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT)); - filterRow.setBackground(Color.white); - - /* - * inputs for attribute, condition, pattern - */ - /* - * drop-down choice of attribute, with description as a tooltip - * if we can obtain it - */ - String featureType = (String) filteredFeatureChoice.getSelectedItem(); - final JComboBox attCombo = populateAttributesDropdown( - featureType, attNames); - JComboBox condCombo = new JComboBox<>(); - JTextField patternField = new JTextField(8); - - /* - * action handlers that validate and (if valid) apply changes - */ - ActionListener actionListener = new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - if (attCombo.getSelectedItem() != null) - { - if (validateFilter(patternField, condCombo)) - { - updateFilter(attCombo, condCombo, patternField, filterIndex); - filtersChanged(); - } - } - } - }; - ItemListener itemListener = new ItemListener() - { - @Override - public void itemStateChanged(ItemEvent e) - { - actionListener.actionPerformed(null); - } - }; - - if ("".equals(attribute)) - { - attCombo.setSelectedItem(null); - } - else - { - attCombo.setSelectedItem(attribute); - } - attCombo.addItemListener(itemListener); - - filterRow.add(attCombo); - - /* - * drop-down choice of test condition - */ - for (Condition c : Condition.values()) - { - condCombo.addItem(c); - } - if (cond != null) + tx.append(" "); + if (gcol.isAboveThreshold()) { - condCombo.setSelectedItem(cond); + thr = true; + tx.append(">"); } - condCombo.addItemListener(itemListener); - filterRow.add(condCombo); - - /* - * pattern to match against - */ - patternField.setText(pattern); - patternField.addActionListener(actionListener); - patternField.addFocusListener(new FocusAdapter() - { - @Override - public void focusLost(FocusEvent e) - { - actionListener.actionPerformed(null); - } - }); - filterRow.add(patternField); - - /* - * add remove button if filter is populated (non-empty pattern) - */ - if (pattern != null && pattern.trim().length() > 0) + if (gcol.isBelowThreshold()) { - // todo: gif for - button - JButton removeCondition = new BasicArrowButton(SwingConstants.WEST); - removeCondition.setToolTipText(MessageManager - .getString("label.delete_row")); - removeCondition.addActionListener(new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - filters.remove(filterIndex); - filtersChanged(); - } - }); - filterRow.add(removeCondition); + thr = true; + tx.append("<"); } - - return filterRow; - } - - /** - * A helper method to build the drop-down choice of attributes for a feature. - * Where metadata is available with a description for an attribute, that is - * added as a tooltip. - * - * @param featureType - * @param attNames - */ - protected JComboBox populateAttributesDropdown( - String featureType, List attNames) - { - List tooltips = new ArrayList<>(); - FeatureAttributes fa = FeatureAttributes.getInstance(); - for (String attName : attNames) + if (gcol.isColourByLabel()) { - String desc = fa.getDescription(featureType, attName); - if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH) + if (thr) { - desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "..."; + tx.append(" "); } - tooltips.add(desc == null ? "" : desc); - } - - JComboBox attCombo = JvSwingUtils.buildComboWithTooltips( - attNames, tooltips); - if (attNames.isEmpty()) - { - attCombo.setToolTipText(MessageManager - .getString("label.no_attributes")); - } - return attCombo; - } - - /** - * Action on any change to feature filtering, namely - *
      - *
    • change of selected attribute
    • - *
    • change of selected condition
    • - *
    • change of match pattern
    • - *
    • removal of a condition
    • - *
    - * The action should be to - *
      - *
    • parse and validate the filters
    • - *
    • if valid, update the filter text box
    • - *
    • and apply the filters to the viewport
    • - *
    - */ - protected void filtersChanged() - { - /* - * update the filter conditions for the feature type - */ - String featureType = (String) filteredFeatureChoice.getSelectedItem(); - boolean anded = andFilters.isSelected(); - KeyedMatcherSetI combined = new KeyedMatcherSet(); - - for (KeyedMatcherI filter : filters) - { - String pattern = filter.getMatcher().getPattern(); - if (pattern.trim().length() > 0) + if (!gcol.isColourByAttribute()) { - if (anded) - { - combined.and(filter); - } - else - { - combined.or(filter); - } + tx.append("Label"); } - } - - /* - * save the filter conditions in the FeatureRenderer - * (note this might now be an empty filter with no conditions) - */ - fr.setFeatureFilter(featureType, combined); - - filtersAsText.setText(combined.toString()); - - refreshFiltersDisplay(); - - af.alignPanel.paintAlignment(true, true); - } - - /** - * Constructs a filter condition from the given input fields, and replaces the - * condition at filterIndex with the new one - * - * @param attCombo - * @param condCombo - * @param valueField - * @param filterIndex - */ - protected void updateFilter(JComboBox attCombo, - JComboBox condCombo, JTextField valueField, - int filterIndex) - { - String attName = (String) attCombo.getSelectedItem(); - Condition cond = (Condition) condCombo.getSelectedItem(); - String pattern = valueField.getText(); - KeyedMatcherI km = new KeyedMatcher(attName, cond, pattern); - - filters.set(filterIndex, km); - } - - public void fetchDAS_actionPerformed(ActionEvent e) - { - fetchDAS.setEnabled(false); - cancelDAS.setEnabled(true); - dassourceBrowser.setGuiEnabled(false); - Vector selectedSources = dassourceBrowser - .getSelectedSources(); - doDasFeatureFetch(selectedSources, true, true); - } - - /** - * get the features from selectedSources for all or the current selection - * - * @param selectedSources - * @param checkDbRefs - * @param promptFetchDbRefs - */ - private void doDasFeatureFetch(List selectedSources, - boolean checkDbRefs, boolean promptFetchDbRefs) - { - SequenceI[] dataset, seqs; - int iSize; - AlignmentViewport vp = af.getViewport(); - if (vp.getSelectionGroup() != null - && vp.getSelectionGroup().getSize() > 0) - { - iSize = vp.getSelectionGroup().getSize(); - dataset = new SequenceI[iSize]; - seqs = vp.getSelectionGroup().getSequencesInOrder(vp.getAlignment()); + comp.setIcon(null); } else { - iSize = vp.getAlignment().getHeight(); - seqs = vp.getAlignment().getSequencesArray(); - } - - dataset = new SequenceI[iSize]; - for (int i = 0; i < iSize; i++) - { - dataset[i] = seqs[i].getDatasetSequence(); - } - - cancelDAS.setEnabled(true); - dasFeatureFetcher = new jalview.ws.DasSequenceFeatureFetcher(dataset, - this, selectedSources, checkDbRefs, promptFetchDbRefs); - af.getViewport().setShowSequenceFeatures(true); - af.showSeqFeatures.setSelected(true); - } - - /** - * blocking call to initialise the das source browser - */ - public void initDasSources() - { - dassourceBrowser.initDasSources(); - } - - /** - * examine the current list of das sources and return any matching the given - * nicknames in sources - * - * @param sources - * Vector of Strings to resolve to DAS source nicknames. - * @return sources that are present in source list. - */ - public List resolveSourceNicknames(Vector sources) - { - return dassourceBrowser.sourceRegistry.resolveSourceNicknames(sources); - } - - /** - * get currently selected das sources. ensure you have called initDasSources - * before calling this. - * - * @return vector of selected das source nicknames - */ - public Vector getSelectedSources() - { - return dassourceBrowser.getSelectedSources(); - } - - /** - * properly initialise DAS fetcher and then initiate a new thread to fetch - * features from the named sources (rather than any turned on by default) - * - * @param sources - * @param block - * if true then runs in same thread, otherwise passes to the Swing - * executor - */ - public void fetchDasFeatures(Vector sources, boolean block) - { - initDasSources(); - List resolved = dassourceBrowser.sourceRegistry - .resolveSourceNicknames(sources); - if (resolved.size() == 0) - { - resolved = dassourceBrowser.getSelectedSources(); - } - if (resolved.size() > 0) - { - final List dassources = resolved; - fetchDAS.setEnabled(false); - // cancelDAS.setEnabled(true); doDasFetch does this. - Runnable fetcher = new Runnable() - { - - @Override - public void run() - { - doDasFeatureFetch(dassources, true, false); - - } - }; - if (block) - { - fetcher.run(); - } - else - { - SwingUtilities.invokeLater(fetcher); - } - } - } - - public void saveDAS_actionPerformed(ActionEvent e) - { - dassourceBrowser - .saveProperties(jalview.bin.Cache.applicationProperties); - } - - public void complete() - { - fetchDAS.setEnabled(true); - cancelDAS.setEnabled(false); - dassourceBrowser.setGuiEnabled(true); - - } - - public void cancelDAS_actionPerformed(ActionEvent e) - { - if (dasFeatureFetcher != null) - { - dasFeatureFetcher.cancel(); - } - complete(); - } - - public void noDasSourceActive() - { - complete(); - JvOptionPane.showInternalConfirmDialog(Desktop.desktop, - MessageManager.getString("label.no_das_sources_selected_warn"), - MessageManager.getString("label.no_das_sources_selected_title"), - JvOptionPane.DEFAULT_OPTION, JvOptionPane.INFORMATION_MESSAGE); - } - - /** - * Answers true unless a numeric condition has been selected with a - * non-numeric value. Sets the value field to RED with a tooltip if in error. - *

    - * If the pattern entered is empty, this method returns false, but does not - * mark the field as invalid. This supports selecting an attribute for a new - * condition before a match pattern has been entered. - * - * @param value - * @param condCombo - */ - protected boolean validateFilter(JTextField value, - JComboBox condCombo) - { - if (value == null || condCombo == null) - { - return true; // fields not populated - } - - Condition cond = (Condition) condCombo.getSelectedItem(); - value.setBackground(Color.white); - value.setToolTipText(""); - String v1 = value.getText().trim(); - if (v1.length() == 0) - { - return false; - } - - if (cond.isNumeric()) - { - try - { - Float.valueOf(v1); - } catch (NumberFormatException e) - { - value.setBackground(Color.red); - value.setToolTipText(MessageManager - .getString("label.numeric_required")); - return false; - } + Color newColor = gcol.getMaxColour(); + comp.setBackground(newColor); + // System.err.println("Width is " + w / 2); + Icon ficon = new FeatureIcon(gcol, comp.getBackground(), w, h, thr); + comp.setIcon(ficon); + // tt+="RGB value: Max (" + newColor.getRed() + ", " + // + newColor.getGreen() + ", " + newColor.getBlue() + // + ")\nMin (" + minCol.getRed() + ", " + minCol.getGreen() + // + ", " + minCol.getBlue() + ")"); } - - return true; + comp.setHorizontalAlignment(SwingConstants.CENTER); + comp.setText(tx.toString()); } // /////////////////////////////////////////////////////////////////////// @@ -1967,18 +1436,19 @@ public class FeatureSettings extends JPanel // /////////////////////////////////////////////////////////////////////// class FeatureTableModel extends AbstractTableModel { - FeatureTableModel(Object[][] data) - { - this.data = data; - } - private String[] columnNames = { MessageManager.getString("label.feature_type"), MessageManager.getString("action.colour"), - MessageManager.getString("label.display") }; + MessageManager.getString("label.filter"), + MessageManager.getString("label.show") }; private Object[][] data; + FeatureTableModel(Object[][] data) + { + this.data = data; + } + public Object[][] getData() { return data; @@ -2018,10 +1488,14 @@ public class FeatureSettings extends JPanel return data[row][col]; } + /** + * Answers the class of the object in column c of the first row of the table + */ @Override - public Class getColumnClass(int c) + public Class getColumnClass(int c) { - return getValueAt(0, c).getClass(); + Object v = getValueAt(0, c); + return v == null ? null : v.getClass(); } @Override @@ -2042,11 +1516,9 @@ public class FeatureSettings extends JPanel class ColorRenderer extends JLabel implements TableCellRenderer { - javax.swing.border.Border unselectedBorder = null; - - javax.swing.border.Border selectedBorder = null; + Border unselectedBorder = null; - final String baseTT = "Click to edit, right/apple click for menu."; + Border selectedBorder = null; public ColorRenderer() { @@ -2061,7 +1533,6 @@ public class FeatureSettings extends JPanel { FeatureColourI cellColour = (FeatureColourI) color; setOpaque(true); - setToolTipText(baseTT); setBackground(tbl.getBackground()); if (!cellColour.isSimpleColour()) { @@ -2098,6 +1569,54 @@ public class FeatureSettings extends JPanel } } + class FilterRenderer extends JLabel implements TableCellRenderer + { + javax.swing.border.Border unselectedBorder = null; + + javax.swing.border.Border selectedBorder = null; + + public FilterRenderer() + { + setOpaque(true); // MUST do this for background to show up. + setHorizontalTextPosition(SwingConstants.CENTER); + setVerticalTextPosition(SwingConstants.CENTER); + } + + @Override + public Component getTableCellRendererComponent(JTable tbl, + Object filter, boolean isSelected, boolean hasFocus, int row, + int column) + { + FeatureMatcherSetI theFilter = (FeatureMatcherSetI) filter; + setOpaque(true); + String asText = theFilter.toString(); + setBackground(tbl.getBackground()); + this.setText(asText); + this.setIcon(null); + + if (isSelected) + { + if (selectedBorder == null) + { + selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, + tbl.getSelectionBackground()); + } + setBorder(selectedBorder); + } + else + { + if (unselectedBorder == null) + { + unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, + tbl.getBackground()); + } + setBorder(unselectedBorder); + } + + return this; + } + } + /** * update comp using rendering settings from gcol * @@ -2120,75 +1639,233 @@ public class FeatureSettings extends JPanel renderGraduatedColor(comp, gcol, w, h); } - public static void renderGraduatedColor(JLabel comp, FeatureColourI gcol, - int w, int h) + class ColorEditor extends AbstractCellEditor + implements TableCellEditor, ActionListener { - boolean thr = false; - StringBuilder tt = new StringBuilder(); - StringBuilder tx = new StringBuilder(); + FeatureSettings me; - if (gcol.isColourByAttribute()) - { - tx.append(gcol.getAttributeName()); - } - else if (!gcol.isColourByLabel()) + FeatureColourI currentColor; + + FeatureTypeSettings chooser; + + String type; + + JButton button; + + protected static final String EDIT = "edit"; + + int rowSelected = 0; + + public ColorEditor(FeatureSettings fs) { - tx.append(MessageManager.getString("label.score")); + this.me = fs; + // Set up the editor (from the table's point of view), + // which is a button. + // This button brings up the color chooser dialog, + // which is the editor from the user's point of view. + button = new JButton(); + button.setActionCommand(EDIT); + button.addActionListener(this); + button.setBorderPainted(false); } - tx.append(" "); - if (gcol.isAboveThreshold()) + + /** + * Handles events from the editor button, and from the colour/filters + * dialog's OK button + */ + @Override + public void actionPerformed(ActionEvent e) { - thr = true; - tx.append(">"); - tt.append("Thresholded (Above ").append(gcol.getThreshold()) - .append(") "); + if (button == e.getSource()) + { + if (currentColor.isSimpleColour()) + { + /* + * simple colour chooser + */ + String ttl = MessageManager.getString("label.select_colour"); + ColourChooserListener listener = new ColourChooserListener() { + @Override + public void colourSelected(Color c) + { + currentColor = new FeatureColour(c); + me.table.setValueAt(currentColor, rowSelected, COLOUR_COLUMN); + } + }; + JalviewColourChooser.showColourChooser(button, ttl, currentColor.getColour(), listener); + } + else + { + /* + * variable colour and filters dialog + */ + chooser = new FeatureTypeSettings(me.fr, type); + /** + * @j2sNative + */ + { + chooser.setRequestFocusEnabled(true); + chooser.requestFocus(); + } + chooser.addActionListener(this); + // Make the renderer reappear. + fireEditingStopped(); + } + } + else + { + /* + * after OK in variable colour dialog, any changes to colour + * (or filters!) are already set in FeatureRenderer, so just + * update table data without triggering updateFeatureRenderer + */ + currentColor = fr.getFeatureColours().get(type); + FeatureMatcherSetI currentFilter = me.fr.getFeatureFilter(type); + if (currentFilter == null) + { + currentFilter = new FeatureMatcherSet(); + } + Object[] data = ((FeatureTableModel) table.getModel()) + .getData()[rowSelected]; + data[COLOUR_COLUMN] = currentColor; + data[FILTER_COLUMN] = currentFilter; + + fireEditingStopped(); + me.table.validate(); + } } - if (gcol.isBelowThreshold()) + + // Implement the one CellEditor method that AbstractCellEditor doesn't. + @Override + public Object getCellEditorValue() { - thr = true; - tx.append("<"); - tt.append("Thresholded (Below ").append(gcol.getThreshold()) - .append(") "); + return currentColor; } - if (gcol.isColourByLabel()) - { - tt.append("Coloured by label text. ").append(tt); - if (thr) - { - tx.append(" "); + + // Implement the one method defined by TableCellEditor. + @Override + public Component getTableCellEditorComponent(JTable theTable, Object value, + boolean isSelected, int row, int column) + { + currentColor = (FeatureColourI) value; + this.rowSelected = row; + type = me.table.getValueAt(row, TYPE_COLUMN).toString(); + button.setOpaque(true); + button.setBackground(me.getBackground()); + if (!currentColor.isSimpleColour()) + { + JLabel btn = new JLabel(); + btn.setSize(button.getSize()); + FeatureSettings.renderGraduatedColor(btn, currentColor); + button.setBackground(btn.getBackground()); + button.setIcon(btn.getIcon()); + button.setText(btn.getText()); } - if (!gcol.isColourByAttribute()) + else { - tx.append("Label"); + button.setText(""); + button.setIcon(null); + button.setBackground(currentColor.getColour()); } - comp.setIcon(null); + return button; } - else + } + + /** + * The cell editor for the Filter column. It displays the text of any filters + * for the feature type in that row (in full as a tooltip, possible abbreviated + * as display text). On click in the cell, opens the Feature Display Settings + * dialog at the Filters tab. + */ + class FilterEditor extends AbstractCellEditor + implements TableCellEditor, ActionListener + { + FeatureSettings me; + + FeatureMatcherSetI currentFilter; + + Point lastLocation; + + String type; + + JButton button; + + protected static final String EDIT = "edit"; + + int rowSelected = 0; + + public FilterEditor(FeatureSettings me) { - Color newColor = gcol.getMaxColour(); - comp.setBackground(newColor); - // System.err.println("Width is " + w / 2); - Icon ficon = new FeatureIcon(gcol, comp.getBackground(), w, h, thr); - comp.setIcon(ficon); - // tt+="RGB value: Max (" + newColor.getRed() + ", " - // + newColor.getGreen() + ", " + newColor.getBlue() - // + ")\nMin (" + minCol.getRed() + ", " + minCol.getGreen() - // + ", " + minCol.getBlue() + ")"); + this.me = me; + button = new JButton(); + button.setActionCommand(EDIT); + button.addActionListener(this); + button.setBorderPainted(false); } - comp.setHorizontalAlignment(SwingConstants.CENTER); - comp.setText(tx.toString()); - if (tt.length() > 0) + + /** + * Handles events from the editor button + */ + @Override + public void actionPerformed(ActionEvent e) { - if (comp.getToolTipText() == null) + if (button == e.getSource()) { - comp.setToolTipText(tt.toString()); + FeatureTypeSettings chooser = new FeatureTypeSettings(me.fr, type); + chooser.addActionListener(this); + chooser.setRequestFocusEnabled(true); + chooser.requestFocus(); + if (lastLocation != null) + { + // todo open at its last position on screen + chooser.setBounds(lastLocation.x, lastLocation.y, + chooser.getWidth(), chooser.getHeight()); + chooser.validate(); + } + fireEditingStopped(); } - else + else if (e.getSource() instanceof Component) { - comp.setToolTipText(tt.append(" ").append(comp.getToolTipText()) - .toString()); + + /* + * after OK in variable colour dialog, any changes to filter + * (or colours!) are already set in FeatureRenderer, so just + * update table data without triggering updateFeatureRenderer + */ + FeatureColourI currentColor = fr.getFeatureColours().get(type); + currentFilter = me.fr.getFeatureFilter(type); + if (currentFilter == null) + { + currentFilter = new FeatureMatcherSet(); + } + Object[] data = ((FeatureTableModel) table.getModel()) + .getData()[rowSelected]; + data[COLOUR_COLUMN] = currentColor; + data[FILTER_COLUMN] = currentFilter; + fireEditingStopped(); + me.table.validate(); } } + + @Override + public Object getCellEditorValue() + { + return currentFilter; + } + + @Override + public Component getTableCellEditorComponent(JTable theTable, Object value, + boolean isSelected, int row, int column) + { + currentFilter = (FeatureMatcherSetI) value; + this.rowSelected = row; + type = me.table.getValueAt(row, TYPE_COLUMN).toString(); + button.setOpaque(true); + button.setBackground(me.getBackground()); + button.setText(currentFilter.toString()); + button.setIcon(null); + return button; + } } } @@ -2273,125 +1950,3 @@ class FeatureIcon implements Icon } } } - -class ColorEditor extends AbstractCellEditor - implements TableCellEditor, ActionListener -{ - FeatureSettings me; - - FeatureColourI currentColor; - - FeatureColourChooser chooser; - - String type; - - JButton button; - - JColorChooser colorChooser; - - JDialog dialog; - - protected static final String EDIT = "edit"; - - int selectedRow = 0; - - public ColorEditor(FeatureSettings me) - { - this.me = me; - // Set up the editor (from the table's point of view), - // which is a button. - // This button brings up the color chooser dialog, - // which is the editor from the user's point of view. - button = new JButton(); - button.setActionCommand(EDIT); - button.addActionListener(this); - button.setBorderPainted(false); - // Set up the dialog that the button brings up. - colorChooser = new JColorChooser(); - dialog = JColorChooser.createDialog(button, - MessageManager.getString("label.select_new_colour"), true, // modal - colorChooser, this, // OK button handler - null); // no CANCEL button handler - } - - /** - * Handles events from the editor button and from the dialog's OK button. - */ - @Override - public void actionPerformed(ActionEvent e) - { - - if (EDIT.equals(e.getActionCommand())) - { - // The user has clicked the cell, so - // bring up the dialog. - if (currentColor.isSimpleColour()) - { - // bring up simple color chooser - button.setBackground(currentColor.getColour()); - colorChooser.setColor(currentColor.getColour()); - dialog.setVisible(true); - } - else - { - // bring up graduated chooser. - chooser = new FeatureColourChooser(me.fr, type); - chooser.setRequestFocusEnabled(true); - chooser.requestFocus(); - chooser.addActionListener(this); - } - // Make the renderer reappear. - fireEditingStopped(); - - } - else - { // User pressed dialog's "OK" button. - if (currentColor.isSimpleColour()) - { - currentColor = new FeatureColour(colorChooser.getColor()); - } - else - { - currentColor = chooser.getLastColour(); - } - me.table.setValueAt(getCellEditorValue(), selectedRow, 1); - fireEditingStopped(); - me.table.validate(); - } - } - - // Implement the one CellEditor method that AbstractCellEditor doesn't. - @Override - public Object getCellEditorValue() - { - return currentColor; - } - - // Implement the one method defined by TableCellEditor. - @Override - public Component getTableCellEditorComponent(JTable table, Object value, - boolean isSelected, int row, int column) - { - currentColor = (FeatureColourI) value; - this.selectedRow = row; - type = me.table.getValueAt(row, 0).toString(); - button.setOpaque(true); - button.setBackground(me.getBackground()); - if (!currentColor.isSimpleColour()) - { - JLabel btn = new JLabel(); - btn.setSize(button.getSize()); - FeatureSettings.renderGraduatedColor(btn, currentColor); - button.setBackground(btn.getBackground()); - button.setIcon(btn.getIcon()); - button.setText(btn.getText()); - } - else - { - button.setText(""); - button.setIcon(null); - button.setBackground(currentColor.getColour()); - } - return button; - } -}