X-Git-Url: http://source.jalview.org/gitweb/?a=blobdiff_plain;f=src%2Fjalview%2Fgui%2FFeatureSettings.java;h=a15a60777837c8f91957d8c325375770ad3d1077;hb=cc52d6f3b8199cb3e9eab962feeab735c5bdc310;hp=0928ec1be0cebb24575cf652a5f4157bebfa9323;hpb=ab106c5adab9123dbb03e8b187b4b45687646f15;p=jalview.git diff --git a/src/jalview/gui/FeatureSettings.java b/src/jalview/gui/FeatureSettings.java index 0928ec1..a15a607 100644 --- a/src/jalview/gui/FeatureSettings.java +++ b/src/jalview/gui/FeatureSettings.java @@ -22,42 +22,35 @@ 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.io.JalviewFileChooser; import jalview.io.JalviewFileView; -import jalview.schemabinding.version2.JalviewUserColours; 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.viewmodel.seqfeatures.FeatureRendererModel.FeatureSettingsBean; +import jalview.xml.binding.jalview.JalviewUserColours; +import jalview.xml.binding.jalview.JalviewUserColours.Colour; +import jalview.xml.binding.jalview.JalviewUserColours.Filter; +import jalview.xml.binding.jalview.ObjectFactory; 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,26 +64,23 @@ 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.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; @@ -98,35 +88,49 @@ 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.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.JTableHeader; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumn; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.Marshaller; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; 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; + + static final int COLOUR_COLUMN = 1; + + static final int FILTER_COLUMN = 2; + + static final int SHOW_COLUMN = 3; + + private static final int COLUMN_COUNT = 4; - DasSourceBrowser dassourceBrowser; + 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; @@ -139,7 +143,7 @@ public class FeatureSettings extends JPanel private float originalTransparency; - private Map originalFilters; + private Map originalFilters; final JInternalFrame frame; @@ -150,7 +154,7 @@ public class FeatureSettings extends JPanel JPanel groupPanel; JSlider transparency = new JSlider(); - + /* * when true, constructor is still executing - so ignore UI events */ @@ -158,12 +162,6 @@ public class FeatureSettings extends JPanel int selectedRow = -1; - JButton fetchDAS = new JButton(); - - JButton saveDAS = new JButton(); - - JButton cancelDAS = new JButton(); - boolean resettingTable = false; /* @@ -176,26 +174,6 @@ public class FeatureSettings extends JPanel */ 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 * @@ -211,7 +189,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 { @@ -226,25 +204,70 @@ 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.configure_feature_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)); + JTableHeader tableHeader = table.getTableHeader(); + tableHeader.setFont(new Font("Verdana", Font.PLAIN, 12)); + tableHeader.setReorderingAllowed(false); table.setFont(new Font("Verdana", Font.PLAIN, 12)); - table.setDefaultRenderer(Color.class, new ColorRenderer()); - - table.setDefaultEditor(Color.class, new ColorEditor(this)); 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() @@ -253,11 +276,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) { @@ -265,8 +289,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); } } @@ -277,9 +300,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()); } } }); @@ -316,9 +340,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! @@ -335,8 +356,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; } } @@ -367,14 +388,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) { @@ -414,84 +434,7 @@ public class FeatureSettings extends JPanel }); men.add(dens); - if (minmax != null) - { - final float[][] typeMinMax = minmax.get(type); - /* - * final JCheckBoxMenuItem chb = new JCheckBoxMenuItem("Vary Height"); // - * this is broken at the moment and isn't that useful anyway! - * chb.setSelected(minmax.get(type) != null); chb.addActionListener(new - * ActionListener() { - * - * public void actionPerformed(ActionEvent e) { - * chb.setState(chb.getState()); if (chb.getState()) { minmax.put(type, - * null); } else { minmax.put(type, typeMinMax); } } - * - * }); - * - * men.add(chb); - */ - if (typeMinMax != null && typeMinMax[0] != null) - { - // if (table.getValueAt(row, column)); - // graduated colourschemes for those where minmax exists for the - // positional features - final JCheckBoxMenuItem mxcol = new JCheckBoxMenuItem( - "Graduated Colour"); - mxcol.setSelected(!featureColour.isSimpleColour()); - men.add(mxcol); - mxcol.addActionListener(new ActionListener() - { - JColorChooser colorChooser; - @Override - public void actionPerformed(ActionEvent e) - { - if (e.getSource() == mxcol) - { - if (featureColour.isSimpleColour()) - { - FeatureColourChooser fc = new FeatureColourChooser(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); - } - } - else - { - if (e.getSource() instanceof FeatureColourChooser) - { - FeatureColourChooser fc = (FeatureColourChooser) e - .getSource(); - table.setValueAt(fc.getLastColour(), selectedRow, 1); - table.validate(); - } - else - { - // probably the color chooser! - table.setValueAt(new FeatureColour(colorChooser.getColor()), - selectedRow, 1); - table.validate(); - me.updateFeatureRenderer( - ((FeatureTableModel) table.getModel()).getData(), - false); - } - } - } - - }); - } - } JMenuItem selCols = new JMenuItem( MessageManager.getString("label.select_columns_containing")); selCols.addActionListener(new ActionListener() @@ -560,8 +503,6 @@ public class FeatureSettings extends JPanel } } - populateFilterableFeatures(); - resetTable(null); validate(); @@ -666,7 +607,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()) @@ -689,9 +630,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); @@ -705,27 +650,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 @@ -746,8 +694,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)
  • @@ -763,27 +711,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; } } @@ -796,10 +744,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; @@ -809,8 +759,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 */ @@ -853,10 +803,14 @@ 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")); @@ -867,88 +821,87 @@ public class FeatureSettings extends JPanel if (value == JalviewFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); + load(file); + } + } - try - { - InputStreamReader in = new InputStreamReader( - new FileInputStream(file), "UTF-8"); + /** + * Loads feature colours and filters from XML stored in the given file + * + * @param file + */ + void load(File file) + { + try + { + InputStreamReader in = new InputStreamReader( + new FileInputStream(file), "UTF-8"); - JalviewUserColours jucs = JalviewUserColours.unmarshal(in); + JAXBContext jc = JAXBContext + .newInstance("jalview.xml.binding.jalview"); + javax.xml.bind.Unmarshaller um = jc.createUnmarshaller(); + XMLStreamReader streamReader = XMLInputFactory.newInstance() + .createXMLStreamReader(in); + JAXBElement jbe = um.unmarshal(streamReader, + JalviewUserColours.class); + JalviewUserColours jucs = jbe.getValue(); - 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)); + // JalviewUserColours jucs = JalviewUserColours.unmarshal(in); - } 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 colours + */ + for (int i = jucs.getColour().size() - 1; i >= 0; i--) + { + Colour newcol = jucs.getColour().get(i); + FeatureColourI colour = jalview.project.Jalview2XML + .parseColour(newcol); + fr.setColour(newcol.getName(), colour); + fr.setOrder(newcol.getName(), i / (float) jucs.getColour().size()); + } + + /* + * load feature filters; loaded filters will replace any that are + * currently defined, other defined filters are left unchanged + */ + for (int i = 0; i < jucs.getFilter().size(); i++) + { + Filter filterModel = jucs.getFilter().get(i); + String featureType = filterModel.getFeatureType(); + FeatureMatcherSetI filter = jalview.project.Jalview2XML + .parseFilter(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")); @@ -958,68 +911,97 @@ public class FeatureSettings extends JPanel if (value == JalviewFileChooser.APPROVE_OPTION) { - 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")); + save(chooser.getSelectedFile()); + } + } + + /** + * Saves feature colours and filters to the given file + * + * @param file + */ + void save(File file) + { + JalviewUserColours ucs = new JalviewUserColours(); + ucs.setSchemeName("Sequence Features"); + try + { + 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); + Colour col = jalview.project.Jalview2XML.marshalColour(featureType, + fcol); + ucs.getColour().add(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(); + jalview.xml.binding.jalview.FeatureMatcherSet ms = jalview.project.Jalview2XML + .marshalFilter(firstMatcher, iterator, + filter.isAnded()); + Filter filterModel = new Filter(); + filterModel.setFeatureType(featureType); + filterModel.setMatcherSet(ms); + ucs.getFilter().add(filterModel); } - ucs.marshal(out); - out.close(); - } catch (Exception ex) - { - ex.printStackTrace(); } + JAXBContext jaxbContext = JAXBContext + .newInstance(JalviewUserColours.class); + Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); + jaxbMarshaller.marshal( + new ObjectFactory().createJalviewUserColours(ucs), out); + + // jaxbMarshaller.marshal(object, pout); + // marshaller.marshal(object); + out.flush(); + + // 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() @@ -1032,17 +1014,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 { @@ -1059,16 +1040,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) { @@ -1102,20 +1084,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) { - 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()); @@ -1123,10 +1125,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()); @@ -1241,6 +1239,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 @@ -1253,6 +1253,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 @@ -1269,7 +1271,7 @@ public class FeatureSettings extends JPanel if (!inConstruction) { fr.setTransparency((100 - transparency.getValue()) / 100f); - af.alignPanel.paintAlignment(true,true); + af.alignPanel.paintAlignment(true, true); } } }); @@ -1277,47 +1279,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); @@ -1337,677 +1298,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); - chooseTypePanel.setBorder(BorderFactory - .createTitledBorder(MessageManager - .getString("label.feature_type"))); - 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(new GridLayout(0, 1)); - filtersPanel.setBackground(Color.white); - filtersPanel.setBorder(BorderFactory - .createTitledBorder(MessageManager.getString("label.filters"))); - - /* - * 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(new GridLayout(0, 1)); - filtersPanel.add(chooseFiltersPanel); - - /* - * a read-only text view of the current filters - */ - JPanel showFiltersPanel = new JPanel(new BorderLayout(5, 5)); - showFiltersPanel.setBackground(Color.white); - showFiltersPanel.setBorder(BorderFactory - .createTitledBorder(MessageManager - .getString("label.match_condition"))); - 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 - .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(); - - String selectedType = (String) filteredFeatureChoice.getSelectedItem(); - - filters.clear(); - - /* - * look up attributes known for feature type - */ - 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); - } - Iterator matchers = featureFilters.getMatchers(); - while (matchers.hasNext()) - { - filters.add(matchers.next()); - } + 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 i = 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, i); - chooseFiltersPanel.add(row); - i++; - } - - 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 - */ - final JComboBox attCombo = new JComboBox<>(); - 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); - } - }; - - /* - * drop-down choice of attribute, with description as a tooltip - * if we can obtain it - */ - String featureType = (String) filteredFeatureChoice.getSelectedItem(); - populateAttributesDropdown(attCombo, featureType, attNames); - 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) - { - condCombo.setSelectedItem(cond); - } - 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) + else if (!gcol.isColourByLabel()) { - // 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); + tx.append(MessageManager.getString("label.score")); } - - 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 attCombo - * @param featureType - * @param attNames - */ - protected void populateAttributesDropdown( - final JComboBox attCombo, String featureType, - List attNames) - { - final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer(); - attCombo.setRenderer(renderer); - List tips = new ArrayList(); - if (attNames.isEmpty()) + tx.append(" "); + if (gcol.isAboveThreshold()) { - attCombo.addItem("---"); - attCombo.setToolTipText(MessageManager - .getString("label.no_attributes_known")); + thr = true; + tx.append(">"); } - else + if (gcol.isBelowThreshold()) { - attCombo.setToolTipText(""); - FeatureAttributes fs = FeatureAttributes.getInstance(); - for (String attName : attNames) - { - attCombo.addItem(attName); - String desc = fs.getDescription(featureType, attName); - tips.add(desc == null ? "" : desc); - } + thr = true; + tx.append("<"); } - renderer.setTooltips(tips); - final MouseAdapter mouseListener = new MouseAdapter() + if (gcol.isColourByLabel()) { - @Override - public void mouseEntered(MouseEvent e) + if (thr) { - int j = attCombo.getSelectedIndex(); - if (j > -1) - { - attCombo.setToolTipText(tips.get(j)); - } + tx.append(" "); } - - @Override - public void mouseExited(MouseEvent e) + if (!gcol.isColourByAttribute()) { - attCombo.setToolTipText(null); + tx.append("Label"); } - }; - for (Component c : attCombo.getComponents()) - { - c.addMouseListener(mouseListener); - } - } - - /** - * 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 (anded) - { - combined.and(filter); - } - else - { - combined.or(filter); - } - } - } - - /* - * 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()); } // /////////////////////////////////////////////////////////////////////// @@ -2015,18 +1392,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.configuration"), + MessageManager.getString("label.show") }; private Object[][] data; + FeatureTableModel(Object[][] data) + { + this.data = data; + } + public Object[][] getData() { return data; @@ -2066,10 +1444,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 @@ -2090,11 +1472,9 @@ public class FeatureSettings extends JPanel class ColorRenderer extends JLabel implements TableCellRenderer { - javax.swing.border.Border unselectedBorder = null; + Border unselectedBorder = null; - javax.swing.border.Border selectedBorder = null; - - final String baseTT = "Click to edit, right/apple click for menu."; + Border selectedBorder = null; public ColorRenderer() { @@ -2108,27 +1488,19 @@ public class FeatureSettings extends JPanel boolean isSelected, boolean hasFocus, int row, int column) { FeatureColourI cellColour = (FeatureColourI) color; - // JLabel comp = new JLabel(); - // comp. setOpaque(true); - // comp. - // setBounds(getBounds()); - Color newColor; - setToolTipText(baseTT); setBackground(tbl.getBackground()); if (!cellColour.isSimpleColour()) { Rectangle cr = tbl.getCellRect(row, column, false); FeatureSettings.renderGraduatedColor(this, cellColour, (int) cr.getWidth(), (int) cr.getHeight()); - } else { this.setText(""); this.setIcon(null); - newColor = cellColour.getColour(); - setBackground(newColor); + setBackground(cellColour.getColour()); } if (isSelected) { @@ -2153,6 +1525,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 * @@ -2175,59 +1595,244 @@ 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; - String tt = ""; - String tx = ""; - if (gcol.isAboveThreshold()) + FeatureSettings me; + + FeatureColourI currentColor; + + FeatureTypeSettings chooser; + + String type; + + JButton button; + + JColorChooser colorChooser; + + JDialog dialog; + + protected static final String EDIT = "edit"; + + int rowSelected = 0; + + public ColorEditor(FeatureSettings me) { - thr = true; - tx += ">"; - tt += "Thresholded (Above " + gcol.getThreshold() + ") "; + 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_colour"), true, // modal + colorChooser, this, // OK button handler + null); // no CANCEL button handler } - if (gcol.isBelowThreshold()) + + /** + * Handles events from the editor button and from the dialog's OK button. + */ + @Override + public void actionPerformed(ActionEvent e) { - thr = true; - tx += "<"; - tt += "Thresholded (Below " + gcol.getThreshold() + ") "; + // todo test e.getSource() instead here + 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 FeatureTypeSettings(me.fr, type); + /** + * @j2sNative + */ + { + chooser.setRequestFocusEnabled(true); + chooser.requestFocus(); + } + chooser.addActionListener(this); + // Make the renderer reappear. + fireEditingStopped(); + } + } + else + { + if (currentColor.isSimpleColour()) + { + /* + * read off colour picked in colour chooser after OK pressed + */ + currentColor = new FeatureColour(colorChooser.getColor()); + me.table.setValueAt(currentColor, rowSelected, COLOUR_COLUMN); + } + 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.isColourByLabel()) + + // Implement the one CellEditor method that AbstractCellEditor doesn't. + @Override + public Object getCellEditorValue() { - tt = "Coloured by label text. " + tt; - if (thr) + return currentColor; + } + + // 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()); + } + else { - tx += " "; + button.setText(""); + button.setIcon(null); + button.setBackground(currentColor.getColour()); } - tx += "Label"; - 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); - 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); + 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 + " " + comp.getToolTipText()); + + /* + * 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; + } } } @@ -2312,124 +1917,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, "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; - } -}