JAL-2808 set (read-only) condition text field as disabled
[jalview.git] / src / jalview / gui / FeatureSettings.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.api.FeatureColourI;
24 import jalview.api.FeatureSettingsControllerI;
25 import jalview.bin.Cache;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.SequenceI;
28 import jalview.datamodel.features.FeatureAttributes;
29 import jalview.gui.Help.HelpId;
30 import jalview.io.JalviewFileChooser;
31 import jalview.io.JalviewFileView;
32 import jalview.schemabinding.version2.JalviewUserColours;
33 import jalview.schemes.FeatureColour;
34 import jalview.util.Format;
35 import jalview.util.MessageManager;
36 import jalview.util.Platform;
37 import jalview.util.QuickSort;
38 import jalview.util.ReverseListIterator;
39 import jalview.util.matcher.Condition;
40 import jalview.util.matcher.KeyedMatcher;
41 import jalview.util.matcher.KeyedMatcherI;
42 import jalview.util.matcher.KeyedMatcherSet;
43 import jalview.util.matcher.KeyedMatcherSetI;
44 import jalview.viewmodel.AlignmentViewport;
45 import jalview.ws.DasSequenceFeatureFetcher;
46 import jalview.ws.dbsources.das.api.jalviewSourceI;
47
48 import java.awt.BorderLayout;
49 import java.awt.Color;
50 import java.awt.Component;
51 import java.awt.Dimension;
52 import java.awt.FlowLayout;
53 import java.awt.Font;
54 import java.awt.Graphics;
55 import java.awt.GridLayout;
56 import java.awt.LayoutManager;
57 import java.awt.Rectangle;
58 import java.awt.event.ActionEvent;
59 import java.awt.event.ActionListener;
60 import java.awt.event.FocusAdapter;
61 import java.awt.event.FocusEvent;
62 import java.awt.event.ItemEvent;
63 import java.awt.event.ItemListener;
64 import java.awt.event.MouseAdapter;
65 import java.awt.event.MouseEvent;
66 import java.awt.event.MouseMotionAdapter;
67 import java.beans.PropertyChangeEvent;
68 import java.beans.PropertyChangeListener;
69 import java.io.File;
70 import java.io.FileInputStream;
71 import java.io.FileOutputStream;
72 import java.io.InputStreamReader;
73 import java.io.OutputStreamWriter;
74 import java.io.PrintWriter;
75 import java.util.ArrayList;
76 import java.util.Arrays;
77 import java.util.HashSet;
78 import java.util.Hashtable;
79 import java.util.Iterator;
80 import java.util.List;
81 import java.util.Map;
82 import java.util.Set;
83 import java.util.Vector;
84
85 import javax.help.HelpSetException;
86 import javax.swing.AbstractCellEditor;
87 import javax.swing.BorderFactory;
88 import javax.swing.BoxLayout;
89 import javax.swing.ButtonGroup;
90 import javax.swing.Icon;
91 import javax.swing.JButton;
92 import javax.swing.JCheckBox;
93 import javax.swing.JCheckBoxMenuItem;
94 import javax.swing.JColorChooser;
95 import javax.swing.JComboBox;
96 import javax.swing.JDialog;
97 import javax.swing.JInternalFrame;
98 import javax.swing.JLabel;
99 import javax.swing.JLayeredPane;
100 import javax.swing.JMenuItem;
101 import javax.swing.JPanel;
102 import javax.swing.JPopupMenu;
103 import javax.swing.JRadioButton;
104 import javax.swing.JScrollPane;
105 import javax.swing.JSlider;
106 import javax.swing.JTabbedPane;
107 import javax.swing.JTable;
108 import javax.swing.JTextArea;
109 import javax.swing.JTextField;
110 import javax.swing.ListSelectionModel;
111 import javax.swing.SwingConstants;
112 import javax.swing.SwingUtilities;
113 import javax.swing.event.ChangeEvent;
114 import javax.swing.event.ChangeListener;
115 import javax.swing.plaf.basic.BasicArrowButton;
116 import javax.swing.table.AbstractTableModel;
117 import javax.swing.table.TableCellEditor;
118 import javax.swing.table.TableCellRenderer;
119
120 public class FeatureSettings extends JPanel
121         implements FeatureSettingsControllerI
122 {
123   private static final String COLON = ":";
124
125   private static final int MIN_WIDTH = 400;
126
127   private static final int MIN_HEIGHT = 400;
128
129   private static final int MAX_TOOLTIP_LENGTH = 50;
130
131   DasSourceBrowser dassourceBrowser;
132
133   DasSequenceFeatureFetcher dasFeatureFetcher;
134
135   JPanel dasSettingsPane = new JPanel();
136
137   final FeatureRenderer fr;
138
139   public final AlignFrame af;
140
141   /*
142    * 'original' fields hold settings to restore on Cancel
143    */
144   Object[][] originalData;
145
146   private float originalTransparency;
147
148   private Map<String, KeyedMatcherSetI> originalFilters;
149
150   final JInternalFrame frame;
151
152   JScrollPane scrollPane = new JScrollPane();
153
154   JTable table;
155
156   JPanel groupPanel;
157
158   JSlider transparency = new JSlider();
159   
160   /*
161    * when true, constructor is still executing - so ignore UI events
162    */
163   protected volatile boolean inConstruction = true;
164
165   int selectedRow = -1;
166
167   JButton fetchDAS = new JButton();
168
169   JButton saveDAS = new JButton();
170
171   JButton cancelDAS = new JButton();
172
173   boolean resettingTable = false;
174
175   /*
176    * true when Feature Settings are updating from feature renderer
177    */
178   private boolean handlingUpdate = false;
179
180   /*
181    * holds {featureCount, totalExtent} for each feature type
182    */
183   Map<String, float[]> typeWidth = null;
184
185   /*
186    * fields of the feature filters tab
187    */
188   private JPanel filtersPane;
189
190   private JPanel chooseFiltersPanel;
191
192   private JComboBox<String> filteredFeatureChoice;
193
194   private JRadioButton andFilters;
195
196   private JRadioButton orFilters;
197
198   /*
199    * filters for the currently selected feature type
200    */
201   private List<KeyedMatcherI> filters;
202
203   private JTextArea filtersAsText;
204
205   // set white normally, black to debug layout
206   private Color debugBorderColour = Color.white;
207
208   /**
209    * Constructor
210    * 
211    * @param af
212    */
213   public FeatureSettings(AlignFrame alignFrame)
214   {
215     this.af = alignFrame;
216     fr = af.getFeatureRenderer();
217
218     // save transparency for restore on Cancel
219     originalTransparency = fr.getTransparency();
220     int originalTransparencyAsPercent = (int) (originalTransparency * 100);
221     transparency.setMaximum(100 - originalTransparencyAsPercent);
222
223     originalFilters = fr.getFeatureFilters();
224
225     try
226     {
227       jbInit();
228     } catch (Exception ex)
229     {
230       ex.printStackTrace();
231     }
232
233     table = new JTable()
234     {
235       @Override
236       public String getToolTipText(MouseEvent e)
237       {
238         if (table.columnAtPoint(e.getPoint()) == 0)
239         {
240           /*
241            * Tooltip for feature name only
242            */
243           return JvSwingUtils.wrapTooltip(true, MessageManager
244                   .getString("label.feature_settings_click_drag"));
245         }
246         return null;
247       }
248     };
249     table.getTableHeader().setFont(new Font("Verdana", Font.PLAIN, 12));
250     table.setFont(new Font("Verdana", Font.PLAIN, 12));
251     table.setDefaultRenderer(Color.class, new ColorRenderer());
252
253     table.setDefaultEditor(Color.class, new ColorEditor(this));
254
255     table.setDefaultEditor(FeatureColour.class, new ColorEditor(this));
256     table.setDefaultRenderer(FeatureColour.class, new ColorRenderer());
257     table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
258
259     table.addMouseListener(new MouseAdapter()
260     {
261       @Override
262       public void mousePressed(MouseEvent evt)
263       {
264         selectedRow = table.rowAtPoint(evt.getPoint());
265         if (evt.isPopupTrigger())
266         {
267           popupSort(selectedRow, (String) table.getValueAt(selectedRow, 0),
268                   table.getValueAt(selectedRow, 1), fr.getMinMax(),
269                   evt.getX(), evt.getY());
270         }
271         else if (evt.getClickCount() == 2)
272         {
273           boolean invertSelection = evt.isAltDown();
274           boolean toggleSelection = Platform.isControlDown(evt);
275           boolean extendSelection = evt.isShiftDown();
276           fr.ap.alignFrame.avc.markColumnsContainingFeatures(
277                   invertSelection, extendSelection, toggleSelection,
278                   (String) table.getValueAt(selectedRow, 0));
279         }
280       }
281
282       // isPopupTrigger fires on mouseReleased on Windows
283       @Override
284       public void mouseReleased(MouseEvent evt)
285       {
286         selectedRow = table.rowAtPoint(evt.getPoint());
287         if (evt.isPopupTrigger())
288         {
289           popupSort(selectedRow, (String) table.getValueAt(selectedRow, 0),
290                   table.getValueAt(selectedRow, 1), fr.getMinMax(),
291                   evt.getX(), evt.getY());
292         }
293       }
294     });
295
296     table.addMouseMotionListener(new MouseMotionAdapter()
297     {
298       @Override
299       public void mouseDragged(MouseEvent evt)
300       {
301         int newRow = table.rowAtPoint(evt.getPoint());
302         if (newRow != selectedRow && selectedRow != -1 && newRow != -1)
303         {
304           /*
305            * reposition 'selectedRow' to 'newRow' (the dragged to location)
306            * this could be more than one row away for a very fast drag action
307            * so just swap it with adjacent rows until we get it there
308            */
309           Object[][] data = ((FeatureTableModel) table.getModel())
310                   .getData();
311           int direction = newRow < selectedRow ? -1 : 1;
312           for (int i = selectedRow; i != newRow; i += direction)
313           {
314             Object[] temp = data[i];
315             data[i] = data[i + direction];
316             data[i + direction] = temp;
317           }
318           updateFeatureRenderer(data);
319           table.repaint();
320           selectedRow = newRow;
321         }
322       }
323     });
324     // table.setToolTipText(JvSwingUtils.wrapTooltip(true,
325     // MessageManager.getString("label.feature_settings_click_drag")));
326     scrollPane.setViewportView(table);
327
328     dassourceBrowser = new DasSourceBrowser(this);
329     dasSettingsPane.add(dassourceBrowser, BorderLayout.CENTER);
330
331     if (af.getViewport().isShowSequenceFeatures() || !fr.hasRenderOrder())
332     {
333       fr.findAllFeatures(true); // display everything!
334     }
335
336     discoverAllFeatureData();
337     final PropertyChangeListener change;
338     final FeatureSettings fs = this;
339     fr.addPropertyChangeListener(change = new PropertyChangeListener()
340     {
341       @Override
342       public void propertyChange(PropertyChangeEvent evt)
343       {
344         if (!fs.resettingTable && !fs.handlingUpdate)
345         {
346           fs.handlingUpdate = true;
347           fs.resetTable(null); // new groups may be added with new seuqence
348           // feature types only
349           fs.handlingUpdate = false;
350         }
351       }
352
353     });
354
355     frame = new JInternalFrame();
356     frame.setContentPane(this);
357     if (Platform.isAMac())
358     {
359       Desktop.addInternalFrame(frame,
360               MessageManager.getString("label.sequence_feature_settings"),
361               600, 480);
362     }
363     else
364     {
365       Desktop.addInternalFrame(frame,
366               MessageManager.getString("label.sequence_feature_settings"),
367               600, 450);
368     }
369     frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
370
371     frame.addInternalFrameListener(
372             new javax.swing.event.InternalFrameAdapter()
373             {
374               @Override
375               public void internalFrameClosed(
376                       javax.swing.event.InternalFrameEvent evt)
377               {
378                 fr.removePropertyChangeListener(change);
379                 dassourceBrowser.fs = null;
380               };
381             });
382     frame.setLayer(JLayeredPane.PALETTE_LAYER);
383     inConstruction = false;
384   }
385
386   protected void popupSort(final int selectedRow, final String type,
387           final Object typeCol, final Map<String, float[][]> minmax, int x,
388           int y)
389   {
390     final FeatureColourI featureColour = (FeatureColourI) typeCol;
391
392     JPopupMenu men = new JPopupMenu(MessageManager
393             .formatMessage("label.settings_for_param", new String[]
394             { type }));
395     JMenuItem scr = new JMenuItem(
396             MessageManager.getString("label.sort_by_score"));
397     men.add(scr);
398     final FeatureSettings me = this;
399     scr.addActionListener(new ActionListener()
400     {
401
402       @Override
403       public void actionPerformed(ActionEvent e)
404       {
405         me.af.avc
406                 .sortAlignmentByFeatureScore(Arrays.asList(new String[]
407                 { type }));
408       }
409
410     });
411     JMenuItem dens = new JMenuItem(
412             MessageManager.getString("label.sort_by_density"));
413     dens.addActionListener(new ActionListener()
414     {
415
416       @Override
417       public void actionPerformed(ActionEvent e)
418       {
419         me.af.avc
420                 .sortAlignmentByFeatureDensity(Arrays.asList(new String[]
421                 { type }));
422       }
423
424     });
425     men.add(dens);
426
427     /*
428      * variable colour options include colour by label, by score,
429      * by selected attribute text, or attribute value
430      */
431     final JCheckBoxMenuItem mxcol = new JCheckBoxMenuItem(
432             MessageManager.getString("label.variable_colour"));
433     mxcol.setSelected(!featureColour.isSimpleColour());
434     men.add(mxcol);
435     mxcol.addActionListener(new ActionListener()
436     {
437       JColorChooser colorChooser;
438
439       @Override
440       public void actionPerformed(ActionEvent e)
441       {
442         if (e.getSource() == mxcol)
443         {
444           if (featureColour.isSimpleColour())
445           {
446             FeatureColourChooser fc = new FeatureColourChooser(me.fr, type);
447             fc.addActionListener(this);
448           }
449           else
450           {
451             // bring up simple color chooser
452             colorChooser = new JColorChooser();
453             JDialog dialog = JColorChooser.createDialog(me,
454                     "Select new Colour", true, // modal
455                     colorChooser, this, // OK button handler
456                     null); // no CANCEL button handler
457             colorChooser.setColor(featureColour.getMaxColour());
458             dialog.setVisible(true);
459           }
460         }
461         else
462         {
463           if (e.getSource() instanceof FeatureColourChooser)
464           {
465             FeatureColourChooser fc = (FeatureColourChooser) e.getSource();
466             table.setValueAt(fc.getLastColour(), selectedRow, 1);
467             table.validate();
468           }
469           else
470           {
471             // probably the color chooser!
472             table.setValueAt(new FeatureColour(colorChooser.getColor()),
473                     selectedRow, 1);
474             table.validate();
475             me.updateFeatureRenderer(
476                     ((FeatureTableModel) table.getModel()).getData(), false);
477           }
478         }
479       }
480
481     });
482
483     JMenuItem selCols = new JMenuItem(
484             MessageManager.getString("label.select_columns_containing"));
485     selCols.addActionListener(new ActionListener()
486     {
487       @Override
488       public void actionPerformed(ActionEvent arg0)
489       {
490         fr.ap.alignFrame.avc.markColumnsContainingFeatures(false, false,
491                 false, type);
492       }
493     });
494     JMenuItem clearCols = new JMenuItem(MessageManager
495             .getString("label.select_columns_not_containing"));
496     clearCols.addActionListener(new ActionListener()
497     {
498       @Override
499       public void actionPerformed(ActionEvent arg0)
500       {
501         fr.ap.alignFrame.avc.markColumnsContainingFeatures(true, false,
502                 false, type);
503       }
504     });
505     JMenuItem hideCols = new JMenuItem(
506             MessageManager.getString("label.hide_columns_containing"));
507     hideCols.addActionListener(new ActionListener()
508     {
509       @Override
510       public void actionPerformed(ActionEvent arg0)
511       {
512         fr.ap.alignFrame.hideFeatureColumns(type, true);
513       }
514     });
515     JMenuItem hideOtherCols = new JMenuItem(
516             MessageManager.getString("label.hide_columns_not_containing"));
517     hideOtherCols.addActionListener(new ActionListener()
518     {
519       @Override
520       public void actionPerformed(ActionEvent arg0)
521       {
522         fr.ap.alignFrame.hideFeatureColumns(type, false);
523       }
524     });
525     men.add(selCols);
526     men.add(clearCols);
527     men.add(hideCols);
528     men.add(hideOtherCols);
529     men.show(table, x, y);
530   }
531
532   @Override
533   synchronized public void discoverAllFeatureData()
534   {
535     Set<String> allGroups = new HashSet<>();
536     AlignmentI alignment = af.getViewport().getAlignment();
537
538     for (int i = 0; i < alignment.getHeight(); i++)
539     {
540       SequenceI seq = alignment.getSequenceAt(i);
541       for (String group : seq.getFeatures().getFeatureGroups(true))
542       {
543         if (group != null && !allGroups.contains(group))
544         {
545           allGroups.add(group);
546           checkGroupState(group);
547         }
548       }
549     }
550
551     populateFilterableFeatures();
552
553     resetTable(null);
554
555     validate();
556   }
557
558   /**
559    * Synchronise gui group list and check visibility of group
560    * 
561    * @param group
562    * @return true if group is visible
563    */
564   private boolean checkGroupState(String group)
565   {
566     boolean visible = fr.checkGroupVisibility(group, true);
567
568     for (int g = 0; g < groupPanel.getComponentCount(); g++)
569     {
570       if (((JCheckBox) groupPanel.getComponent(g)).getText().equals(group))
571       {
572         ((JCheckBox) groupPanel.getComponent(g)).setSelected(visible);
573         return visible;
574       }
575     }
576
577     final String grp = group;
578     final JCheckBox check = new JCheckBox(group, visible);
579     check.setFont(new Font("Serif", Font.BOLD, 12));
580     check.setToolTipText(group);
581     check.addItemListener(new ItemListener()
582     {
583       @Override
584       public void itemStateChanged(ItemEvent evt)
585       {
586         fr.setGroupVisibility(check.getText(), check.isSelected());
587         resetTable(new String[] { grp });
588         af.alignPanel.paintAlignment(true, true);
589       }
590     });
591     groupPanel.add(check);
592     return visible;
593   }
594
595   synchronized void resetTable(String[] groupChanged)
596   {
597     if (resettingTable)
598     {
599       return;
600     }
601     resettingTable = true;
602     typeWidth = new Hashtable<>();
603     // TODO: change avWidth calculation to 'per-sequence' average and use long
604     // rather than float
605
606     Set<String> displayableTypes = new HashSet<>();
607     Set<String> foundGroups = new HashSet<>();
608
609     /*
610      * determine which feature types may be visible depending on 
611      * which groups are selected, and recompute average width data
612      */
613     for (int i = 0; i < af.getViewport().getAlignment().getHeight(); i++)
614     {
615
616       SequenceI seq = af.getViewport().getAlignment().getSequenceAt(i);
617
618       /*
619        * get the sequence's groups for positional features
620        * and keep track of which groups are visible
621        */
622       Set<String> groups = seq.getFeatures().getFeatureGroups(true);
623       Set<String> visibleGroups = new HashSet<>();
624       for (String group : groups)
625       {
626         if (group == null || checkGroupState(group))
627         {
628           visibleGroups.add(group);
629         }
630       }
631       foundGroups.addAll(groups);
632
633       /*
634        * get distinct feature types for visible groups
635        * record distinct visible types, and their count and total length
636        */
637       Set<String> types = seq.getFeatures().getFeatureTypesForGroups(true,
638               visibleGroups.toArray(new String[visibleGroups.size()]));
639       for (String type : types)
640       {
641         displayableTypes.add(type);
642         float[] avWidth = typeWidth.get(type);
643         if (avWidth == null)
644         {
645           avWidth = new float[2];
646           typeWidth.put(type, avWidth);
647         }
648         // todo this could include features with a non-visible group
649         // - do we greatly care?
650         // todo should we include non-displayable features here, and only
651         // update when features are added?
652         avWidth[0] += seq.getFeatures().getFeatureCount(true, type);
653         avWidth[1] += seq.getFeatures().getTotalFeatureLength(type);
654       }
655     }
656
657     Object[][] data = new Object[displayableTypes.size()][3];
658     int dataIndex = 0;
659
660     if (fr.hasRenderOrder())
661     {
662       if (!handlingUpdate)
663       {
664         fr.findAllFeatures(groupChanged != null); // prod to update
665         // colourschemes. but don't
666         // affect display
667         // First add the checks in the previous render order,
668         // in case the window has been closed and reopened
669       }
670       List<String> frl = fr.getRenderOrder();
671       for (int ro = frl.size() - 1; ro > -1; ro--)
672       {
673         String type = frl.get(ro);
674
675         if (!displayableTypes.contains(type))
676         {
677           continue;
678         }
679
680         data[dataIndex][0] = type;
681         data[dataIndex][1] = fr.getFeatureStyle(type);
682         data[dataIndex][2] = new Boolean(
683                 af.getViewport().getFeaturesDisplayed().isVisible(type));
684         dataIndex++;
685         displayableTypes.remove(type);
686       }
687     }
688
689     /*
690      * process any extra features belonging only to 
691      * a group which was just selected
692      */
693     while (!displayableTypes.isEmpty())
694     {
695       String type = displayableTypes.iterator().next();
696       data[dataIndex][0] = type;
697
698       data[dataIndex][1] = fr.getFeatureStyle(type);
699       if (data[dataIndex][1] == null)
700       {
701         // "Colour has been updated in another view!!"
702         fr.clearRenderOrder();
703         return;
704       }
705
706       data[dataIndex][2] = new Boolean(true);
707       dataIndex++;
708       displayableTypes.remove(type);
709     }
710
711     if (originalData == null)
712     {
713       originalData = new Object[data.length][3];
714       for (int i = 0; i < data.length; i++)
715       {
716         System.arraycopy(data[i], 0, originalData[i], 0, 3);
717       }
718     }
719     else
720     {
721       updateOriginalData(data);
722     }
723
724     table.setModel(new FeatureTableModel(data));
725     table.getColumnModel().getColumn(0).setPreferredWidth(200);
726
727     groupPanel.setLayout(
728             new GridLayout(fr.getFeatureGroupsSize() / 4 + 1, 4));
729     pruneGroups(foundGroups);
730     groupPanel.validate();
731
732     updateFeatureRenderer(data, groupChanged != null);
733     resettingTable = false;
734   }
735
736   /**
737    * Updates 'originalData' (used for restore on Cancel) if we detect that
738    * changes have been made outwith this dialog
739    * <ul>
740    * <li>a new feature type added (and made visible)</li>
741    * <li>a feature colour changed (in the Amend Features dialog)</li>
742    * </ul>
743    * 
744    * @param foundData
745    */
746   protected void updateOriginalData(Object[][] foundData)
747   {
748     // todo LinkedHashMap instead of Object[][] would be nice
749
750     Object[][] currentData = ((FeatureTableModel) table.getModel())
751             .getData();
752     for (Object[] row : foundData)
753     {
754       String type = (String) row[0];
755       boolean found = false;
756       for (Object[] current : currentData)
757       {
758         if (type.equals(current[0]))
759         {
760           found = true;
761           /*
762            * currently dependent on object equality here;
763            * really need an equals method on FeatureColour
764            */
765           if (!row[1].equals(current[1]))
766           {
767             /*
768              * feature colour has changed externally - update originalData
769              */
770             for (Object[] original : originalData)
771             {
772               if (type.equals(original[0]))
773               {
774                 original[1] = row[1];
775                 break;
776               }
777             }
778           }
779           break;
780         }
781       }
782       if (!found)
783       {
784         /*
785          * new feature detected - add to original data (on top)
786          */
787         Object[][] newData = new Object[originalData.length + 1][3];
788         for (int i = 0; i < originalData.length; i++)
789         {
790           System.arraycopy(originalData[i], 0, newData[i + 1], 0, 3);
791         }
792         newData[0] = row;
793         originalData = newData;
794       }
795     }
796   }
797
798   /**
799    * Remove from the groups panel any checkboxes for groups that are not in the
800    * foundGroups set. This enables removing a group from the display when the
801    * last feature in that group is deleted.
802    * 
803    * @param foundGroups
804    */
805   protected void pruneGroups(Set<String> foundGroups)
806   {
807     for (int g = 0; g < groupPanel.getComponentCount(); g++)
808     {
809       JCheckBox checkbox = (JCheckBox) groupPanel.getComponent(g);
810       if (!foundGroups.contains(checkbox.getText()))
811       {
812         groupPanel.remove(checkbox);
813       }
814     }
815   }
816
817   /**
818    * reorder data based on the featureRenderers global priority list.
819    * 
820    * @param data
821    */
822   private void ensureOrder(Object[][] data)
823   {
824     boolean sort = false;
825     float[] order = new float[data.length];
826     for (int i = 0; i < order.length; i++)
827     {
828       order[i] = fr.getOrder(data[i][0].toString());
829       if (order[i] < 0)
830       {
831         order[i] = fr.setOrder(data[i][0].toString(), i / order.length);
832       }
833       if (i > 1)
834       {
835         sort = sort || order[i - 1] > order[i];
836       }
837     }
838     if (sort)
839     {
840       jalview.util.QuickSort.sort(order, data);
841     }
842   }
843
844   void load()
845   {
846     JalviewFileChooser chooser = new JalviewFileChooser("fc",
847             "Sequence Feature Colours");
848     chooser.setFileView(new JalviewFileView());
849     chooser.setDialogTitle(
850             MessageManager.getString("label.load_feature_colours"));
851     chooser.setToolTipText(MessageManager.getString("action.load"));
852
853     int value = chooser.showOpenDialog(this);
854
855     if (value == JalviewFileChooser.APPROVE_OPTION)
856     {
857       File file = chooser.getSelectedFile();
858
859       try
860       {
861         InputStreamReader in = new InputStreamReader(
862                 new FileInputStream(file), "UTF-8");
863
864         JalviewUserColours jucs = JalviewUserColours.unmarshal(in);
865
866         for (int i = jucs.getColourCount() - 1; i >= 0; i--)
867         {
868           String name;
869           jalview.schemabinding.version2.Colour newcol = jucs.getColour(i);
870           if (newcol.hasMax())
871           {
872             Color mincol = null, maxcol = null;
873             try
874             {
875               mincol = new Color(Integer.parseInt(newcol.getMinRGB(), 16));
876               maxcol = new Color(Integer.parseInt(newcol.getRGB(), 16));
877
878             } catch (Exception e)
879             {
880               Cache.log.warn("Couldn't parse out graduated feature color.",
881                       e);
882             }
883             FeatureColourI gcol = new FeatureColour(mincol, maxcol,
884                     newcol.getMin(), newcol.getMax());
885             if (newcol.hasAutoScale())
886             {
887               gcol.setAutoScaled(newcol.getAutoScale());
888             }
889             if (newcol.hasColourByLabel())
890             {
891               gcol.setColourByLabel(newcol.getColourByLabel());
892             }
893             if (newcol.hasThreshold())
894             {
895               gcol.setThreshold(newcol.getThreshold());
896             }
897             if (newcol.getThreshType().length() > 0)
898             {
899               String ttyp = newcol.getThreshType();
900               if (ttyp.equalsIgnoreCase("ABOVE"))
901               {
902                 gcol.setAboveThreshold(true);
903               }
904               if (ttyp.equalsIgnoreCase("BELOW"))
905               {
906                 gcol.setBelowThreshold(true);
907               }
908             }
909             fr.setColour(name = newcol.getName(), gcol);
910           }
911           else
912           {
913             Color color = new Color(
914                     Integer.parseInt(jucs.getColour(i).getRGB(), 16));
915             fr.setColour(name = jucs.getColour(i).getName(),
916                     new FeatureColour(color));
917           }
918           fr.setOrder(name, (i == 0) ? 0 : i / jucs.getColourCount());
919         }
920         if (table != null)
921         {
922           resetTable(null);
923           Object[][] data = ((FeatureTableModel) table.getModel())
924                   .getData();
925           ensureOrder(data);
926           updateFeatureRenderer(data, false);
927           table.repaint();
928         }
929       } catch (Exception ex)
930       {
931         System.out.println("Error loading User Colour File\n" + ex);
932       }
933     }
934   }
935
936   void save()
937   {
938     JalviewFileChooser chooser = new JalviewFileChooser("fc",
939             "Sequence Feature Colours");
940     chooser.setFileView(new JalviewFileView());
941     chooser.setDialogTitle(
942             MessageManager.getString("label.save_feature_colours"));
943     chooser.setToolTipText(MessageManager.getString("action.save"));
944
945     int value = chooser.showSaveDialog(this);
946
947     if (value == JalviewFileChooser.APPROVE_OPTION)
948     {
949       String choice = chooser.getSelectedFile().getPath();
950       jalview.schemabinding.version2.JalviewUserColours ucs = new jalview.schemabinding.version2.JalviewUserColours();
951       ucs.setSchemeName("Sequence Features");
952       try
953       {
954         PrintWriter out = new PrintWriter(new OutputStreamWriter(
955                 new FileOutputStream(choice), "UTF-8"));
956
957         Set<String> fr_colours = fr.getAllFeatureColours();
958         Iterator<String> e = fr_colours.iterator();
959         float[] sortOrder = new float[fr_colours.size()];
960         String[] sortTypes = new String[fr_colours.size()];
961         int i = 0;
962         while (e.hasNext())
963         {
964           sortTypes[i] = e.next();
965           sortOrder[i] = fr.getOrder(sortTypes[i]);
966           i++;
967         }
968         QuickSort.sort(sortOrder, sortTypes);
969         sortOrder = null;
970         for (i = 0; i < sortTypes.length; i++)
971         {
972           jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
973           col.setName(sortTypes[i]);
974           FeatureColourI fcol = fr.getFeatureStyle(sortTypes[i]);
975           if (fcol.isSimpleColour())
976           {
977             col.setRGB(Format.getHexString(fcol.getColour()));
978           }
979           else
980           {
981             col.setRGB(Format.getHexString(fcol.getMaxColour()));
982             col.setMin(fcol.getMin());
983             col.setMax(fcol.getMax());
984             col.setMinRGB(
985                     jalview.util.Format.getHexString(fcol.getMinColour()));
986             col.setAutoScale(fcol.isAutoScaled());
987             col.setThreshold(fcol.getThreshold());
988             col.setColourByLabel(fcol.isColourByLabel());
989             col.setThreshType(fcol.isAboveThreshold() ? "ABOVE"
990                     : (fcol.isBelowThreshold() ? "BELOW" : "NONE"));
991           }
992           ucs.addColour(col);
993         }
994         ucs.marshal(out);
995         out.close();
996       } catch (Exception ex)
997       {
998         ex.printStackTrace();
999       }
1000     }
1001   }
1002
1003   public void invertSelection()
1004   {
1005     for (int i = 0; i < table.getRowCount(); i++)
1006     {
1007       Boolean value = (Boolean) table.getValueAt(i, 2);
1008
1009       table.setValueAt(new Boolean(!value.booleanValue()), i, 2);
1010     }
1011   }
1012
1013   public void orderByAvWidth()
1014   {
1015     if (table == null || table.getModel() == null)
1016     {
1017       return;
1018     }
1019     Object[][] data = ((FeatureTableModel) table.getModel()).getData();
1020     float[] width = new float[data.length];
1021     float[] awidth;
1022     float max = 0;
1023     int num = 0;
1024     for (int i = 0; i < data.length; i++)
1025     {
1026       awidth = typeWidth.get(data[i][0]);
1027       if (awidth[0] > 0)
1028       {
1029         width[i] = awidth[1] / awidth[0];// *awidth[0]*awidth[2]; - better
1030         // weight - but have to make per
1031         // sequence, too (awidth[2])
1032         // if (width[i]==1) // hack to distinguish single width sequences.
1033         num++;
1034       }
1035       else
1036       {
1037         width[i] = 0;
1038       }
1039       if (max < width[i])
1040       {
1041         max = width[i];
1042       }
1043     }
1044     boolean sort = false;
1045     for (int i = 0; i < width.length; i++)
1046     {
1047       // awidth = (float[]) typeWidth.get(data[i][0]);
1048       if (width[i] == 0)
1049       {
1050         width[i] = fr.getOrder(data[i][0].toString());
1051         if (width[i] < 0)
1052         {
1053           width[i] = fr.setOrder(data[i][0].toString(), i / data.length);
1054         }
1055       }
1056       else
1057       {
1058         width[i] /= max; // normalize
1059         fr.setOrder(data[i][0].toString(), width[i]); // store for later
1060       }
1061       if (i > 0)
1062       {
1063         sort = sort || width[i - 1] > width[i];
1064       }
1065     }
1066     if (sort)
1067     {
1068       jalview.util.QuickSort.sort(width, data);
1069       // update global priority order
1070     }
1071
1072     updateFeatureRenderer(data, false);
1073     table.repaint();
1074   }
1075
1076   public void close()
1077   {
1078     try
1079     {
1080       frame.setClosed(true);
1081     } catch (Exception exe)
1082     {
1083     }
1084
1085   }
1086
1087   public void updateFeatureRenderer(Object[][] data)
1088   {
1089     updateFeatureRenderer(data, true);
1090   }
1091
1092   /**
1093    * Update the priority order of features; only repaint if this changed the
1094    * order of visible features
1095    * 
1096    * @param data
1097    * @param visibleNew
1098    */
1099   private void updateFeatureRenderer(Object[][] data, boolean visibleNew)
1100   {
1101     if (fr.setFeaturePriority(data, visibleNew))
1102     {
1103       af.alignPanel.paintAlignment(true, true);
1104     }
1105   }
1106
1107   private void jbInit() throws Exception
1108   {
1109     this.setLayout(new BorderLayout());
1110
1111     JPanel settingsPane = new JPanel();
1112     settingsPane.setLayout(new BorderLayout());
1113
1114     filtersPane = new JPanel();
1115
1116     dasSettingsPane.setLayout(new BorderLayout());
1117
1118     JPanel bigPanel = new JPanel();
1119     bigPanel.setLayout(new BorderLayout());
1120
1121     groupPanel = new JPanel();
1122     bigPanel.add(groupPanel, BorderLayout.NORTH);
1123
1124     JButton invert = new JButton(
1125             MessageManager.getString("label.invert_selection"));
1126     invert.setFont(JvSwingUtils.getLabelFont());
1127     invert.addActionListener(new ActionListener()
1128     {
1129       @Override
1130       public void actionPerformed(ActionEvent e)
1131       {
1132         invertSelection();
1133       }
1134     });
1135
1136     JButton optimizeOrder = new JButton(
1137             MessageManager.getString("label.optimise_order"));
1138     optimizeOrder.setFont(JvSwingUtils.getLabelFont());
1139     optimizeOrder.addActionListener(new ActionListener()
1140     {
1141       @Override
1142       public void actionPerformed(ActionEvent e)
1143       {
1144         orderByAvWidth();
1145       }
1146     });
1147
1148     JButton sortByScore = new JButton(
1149             MessageManager.getString("label.seq_sort_by_score"));
1150     sortByScore.setFont(JvSwingUtils.getLabelFont());
1151     sortByScore.addActionListener(new ActionListener()
1152     {
1153       @Override
1154       public void actionPerformed(ActionEvent e)
1155       {
1156         af.avc.sortAlignmentByFeatureScore(null);
1157       }
1158     });
1159     JButton sortByDens = new JButton(
1160             MessageManager.getString("label.sequence_sort_by_density"));
1161     sortByDens.setFont(JvSwingUtils.getLabelFont());
1162     sortByDens.addActionListener(new ActionListener()
1163     {
1164       @Override
1165       public void actionPerformed(ActionEvent e)
1166       {
1167         af.avc.sortAlignmentByFeatureDensity(null);
1168       }
1169     });
1170
1171     JButton help = new JButton(MessageManager.getString("action.help"));
1172     help.setFont(JvSwingUtils.getLabelFont());
1173     help.addActionListener(new ActionListener()
1174     {
1175       @Override
1176       public void actionPerformed(ActionEvent e)
1177       {
1178         try
1179         {
1180           Help.showHelpWindow(HelpId.SequenceFeatureSettings);
1181         } catch (HelpSetException e1)
1182         {
1183           e1.printStackTrace();
1184         }
1185       }
1186     });
1187     help.setFont(JvSwingUtils.getLabelFont());
1188     help.setText(MessageManager.getString("action.help"));
1189     help.addActionListener(new ActionListener()
1190     {
1191       @Override
1192       public void actionPerformed(ActionEvent e)
1193       {
1194         try
1195         {
1196           Help.showHelpWindow(HelpId.SequenceFeatureSettings);
1197         } catch (HelpSetException e1)
1198         {
1199           e1.printStackTrace();
1200         }
1201       }
1202     });
1203
1204     JButton cancel = new JButton(MessageManager.getString("action.cancel"));
1205     cancel.setFont(JvSwingUtils.getLabelFont());
1206     cancel.addActionListener(new ActionListener()
1207     {
1208       @Override
1209       public void actionPerformed(ActionEvent e)
1210       {
1211         fr.setTransparency(originalTransparency);
1212         fr.setFeatureFilters(originalFilters);
1213         updateFeatureRenderer(originalData);
1214         close();
1215       }
1216     });
1217
1218     JButton ok = new JButton(MessageManager.getString("action.ok"));
1219     ok.setFont(JvSwingUtils.getLabelFont());
1220     ok.addActionListener(new ActionListener()
1221     {
1222       @Override
1223       public void actionPerformed(ActionEvent e)
1224       {
1225         close();
1226       }
1227     });
1228
1229     JButton loadColours = new JButton(
1230             MessageManager.getString("label.load_colours"));
1231     loadColours.setFont(JvSwingUtils.getLabelFont());
1232     loadColours.addActionListener(new ActionListener()
1233     {
1234       @Override
1235       public void actionPerformed(ActionEvent e)
1236       {
1237         load();
1238       }
1239     });
1240
1241     JButton saveColours = new JButton(
1242             MessageManager.getString("label.save_colours"));
1243     saveColours.setFont(JvSwingUtils.getLabelFont());
1244     saveColours.addActionListener(new ActionListener()
1245     {
1246       @Override
1247       public void actionPerformed(ActionEvent e)
1248       {
1249         save();
1250       }
1251     });
1252     transparency.addChangeListener(new ChangeListener()
1253     {
1254       @Override
1255       public void stateChanged(ChangeEvent evt)
1256       {
1257         if (!inConstruction)
1258         {
1259           fr.setTransparency((100 - transparency.getValue()) / 100f);
1260           af.alignPanel.paintAlignment(true,true);
1261         }
1262       }
1263     });
1264
1265     transparency.setMaximum(70);
1266     transparency.setToolTipText(
1267             MessageManager.getString("label.transparency_tip"));
1268     fetchDAS.setText(MessageManager.getString("label.fetch_das_features"));
1269     fetchDAS.addActionListener(new ActionListener()
1270     {
1271       @Override
1272       public void actionPerformed(ActionEvent e)
1273       {
1274         fetchDAS_actionPerformed(e);
1275       }
1276     });
1277     saveDAS.setText(MessageManager.getString("action.save_as_default"));
1278     saveDAS.addActionListener(new ActionListener()
1279     {
1280       @Override
1281       public void actionPerformed(ActionEvent e)
1282       {
1283         saveDAS_actionPerformed(e);
1284       }
1285     });
1286
1287     JPanel dasButtonPanel = new JPanel();
1288     dasButtonPanel.setBorder(BorderFactory.createEtchedBorder());
1289     dasSettingsPane.setBorder(null);
1290     cancelDAS.setEnabled(false);
1291     cancelDAS.setText(MessageManager.getString("action.cancel_fetch"));
1292     cancelDAS.addActionListener(new ActionListener()
1293     {
1294       @Override
1295       public void actionPerformed(ActionEvent e)
1296       {
1297         cancelDAS_actionPerformed(e);
1298       }
1299     });
1300
1301     JTabbedPane tabbedPane = new JTabbedPane();
1302     this.add(tabbedPane, BorderLayout.CENTER);
1303     tabbedPane.addTab(MessageManager.getString("label.feature_settings"),
1304             settingsPane);
1305     tabbedPane.addTab(MessageManager.getString("label.filters"),
1306             filtersPane);
1307     // tabbedPane.addTab(MessageManager.getString("label.das_settings"),
1308     // dasSettingsPane);
1309
1310     JPanel transPanel = new JPanel(new GridLayout(1, 2));
1311     bigPanel.add(transPanel, BorderLayout.SOUTH);
1312
1313     JPanel transbuttons = new JPanel(new GridLayout(5, 1));
1314     transbuttons.add(optimizeOrder);
1315     transbuttons.add(invert);
1316     transbuttons.add(sortByScore);
1317     transbuttons.add(sortByDens);
1318     transbuttons.add(help);
1319     transPanel.add(transparency);
1320     transPanel.add(transbuttons);
1321
1322     JPanel buttonPanel = new JPanel();
1323     buttonPanel.add(ok);
1324     buttonPanel.add(cancel);
1325     buttonPanel.add(loadColours);
1326     buttonPanel.add(saveColours);
1327     bigPanel.add(scrollPane, BorderLayout.CENTER);
1328     dasSettingsPane.add(dasButtonPanel, BorderLayout.SOUTH);
1329     dasButtonPanel.add(fetchDAS);
1330     dasButtonPanel.add(cancelDAS);
1331     dasButtonPanel.add(saveDAS);
1332     settingsPane.add(bigPanel, BorderLayout.CENTER);
1333     settingsPane.add(buttonPanel, BorderLayout.SOUTH);
1334
1335     initFiltersTab();
1336   }
1337
1338   /**
1339    * Populates initial layout of the feature attribute filters panel
1340    */
1341   protected void initFiltersTab()
1342   {
1343     filters = new ArrayList<>();
1344
1345     /*
1346      * choose feature type
1347      */
1348     JPanel chooseTypePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
1349     chooseTypePanel.setBackground(Color.white);
1350     JvSwingUtils.createItalicTitledBorder(chooseTypePanel,
1351             MessageManager.getString("label.feature_type"), true);
1352     filteredFeatureChoice = new JComboBox<>();
1353     filteredFeatureChoice.addItemListener(new ItemListener()
1354     {
1355       @Override
1356       public void itemStateChanged(ItemEvent e)
1357       {
1358         refreshFiltersDisplay();
1359       }
1360     });
1361     chooseTypePanel.add(new JLabel(MessageManager
1362             .getString("label.feature_to_filter")));
1363     chooseTypePanel.add(filteredFeatureChoice);
1364     populateFilterableFeatures();
1365
1366     /*
1367      * the panel with the filters for the selected feature type
1368      */
1369     JPanel filtersPanel = new JPanel();
1370     filtersPanel.setLayout(new BoxLayout(filtersPanel, BoxLayout.Y_AXIS));
1371     filtersPanel.setBackground(Color.white);
1372     JvSwingUtils.createItalicTitledBorder(filtersPanel,
1373             MessageManager.getString("label.filters"), true);
1374
1375     /*
1376      * add AND or OR radio buttons
1377      */
1378     JPanel andOrPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
1379     andOrPanel.setBackground(Color.white);
1380     andOrPanel.setBorder(BorderFactory.createLineBorder(debugBorderColour));
1381     andFilters = new JRadioButton("And");
1382     orFilters = new JRadioButton("Or");
1383     ActionListener actionListener = new ActionListener()
1384     {
1385       @Override
1386       public void actionPerformed(ActionEvent e)
1387       {
1388         filtersChanged();
1389       }
1390     };
1391     andFilters.addActionListener(actionListener);
1392     orFilters.addActionListener(actionListener);
1393     ButtonGroup andOr = new ButtonGroup();
1394     andOr.add(andFilters);
1395     andOr.add(orFilters);
1396     andFilters.setSelected(true);
1397     andOrPanel.add(new JLabel(MessageManager
1398             .getString("label.join_conditions")));
1399     andOrPanel.add(andFilters);
1400     andOrPanel.add(orFilters);
1401     filtersPanel.add(andOrPanel);
1402
1403     /*
1404      * panel with filters - populated by refreshFiltersDisplay
1405      */
1406     chooseFiltersPanel = new JPanel();
1407     LayoutManager box = new BoxLayout(chooseFiltersPanel,
1408             BoxLayout.Y_AXIS);
1409     chooseFiltersPanel.setLayout(box);
1410     filtersPanel.add(chooseFiltersPanel);
1411
1412     /*
1413      * a read-only text view of the current filters
1414      */
1415     JPanel showFiltersPanel = new JPanel(new BorderLayout(5, 5));
1416     showFiltersPanel.setBackground(Color.white);
1417     JvSwingUtils.createItalicTitledBorder(showFiltersPanel,
1418             MessageManager.getString("label.match_condition"), true);
1419     filtersAsText = new JTextArea();
1420     filtersAsText.setLineWrap(true);
1421     filtersAsText.setWrapStyleWord(true);
1422     filtersAsText.setEnabled(false); // for display only
1423     showFiltersPanel.add(filtersAsText);
1424
1425     filtersPane.setLayout(new BorderLayout());
1426     filtersPane.add(chooseTypePanel, BorderLayout.NORTH);
1427     filtersPane.add(filtersPanel, BorderLayout.CENTER);
1428     filtersPane.add(showFiltersPanel, BorderLayout.SOUTH);
1429
1430     /*
1431      * update display for initial feature type selection
1432      */
1433     refreshFiltersDisplay();
1434   }
1435
1436   /**
1437    * Adds entries to the 'choose feature to filter' drop-down choice. Only
1438    * feature types which have known attributes (so can be filtered) are
1439    * included, so recall this method to update the list (check for newly added
1440    * attributes).
1441    */
1442   protected void populateFilterableFeatures()
1443   {
1444     /*
1445      * suppress action handler while updating the list
1446      */
1447     ItemListener listener = filteredFeatureChoice.getItemListeners()[0];
1448     filteredFeatureChoice.removeItemListener(listener);
1449
1450     filteredFeatureChoice.removeAllItems();
1451     ReverseListIterator<String> types = new ReverseListIterator<>(
1452             fr.getRenderOrder());
1453
1454     boolean found = false;
1455     while (types.hasNext())
1456     {
1457       String type = types.next();
1458       if (FeatureAttributes.getInstance().hasAttributes(type))
1459       {
1460         filteredFeatureChoice.addItem(type);
1461         found = true;
1462       }
1463     }
1464     if (!found)
1465     {
1466       filteredFeatureChoice.addItem(MessageManager
1467               .getString("label.no_feature_attributes"));
1468       filteredFeatureChoice.setEnabled(false);
1469     }
1470
1471     filteredFeatureChoice.addItemListener(listener);
1472   }
1473
1474   /**
1475    * Refreshes the display to show any filters currently configured for the
1476    * selected feature type (editable, with 'remove' option), plus one extra row
1477    * for adding a condition. This should be called on change of selected feature
1478    * type, or after a filter has been removed, added or amended.
1479    */
1480   protected void refreshFiltersDisplay()
1481   {
1482     /*
1483      * clear the panel and list of filter conditions
1484      */
1485     chooseFiltersPanel.removeAll();
1486     filters.clear();
1487
1488     /*
1489      * look up attributes known for feature type
1490      */
1491     String selectedType = (String) filteredFeatureChoice.getSelectedItem();
1492     List<String[]> attNames = FeatureAttributes.getInstance()
1493             .getAttributes(selectedType);
1494
1495     /*
1496      * if this feature type has filters set, load them first
1497      */
1498     KeyedMatcherSetI featureFilters = fr.getFeatureFilter(selectedType);
1499     filtersAsText.setText("");
1500     if (featureFilters != null)
1501     {
1502       filtersAsText.setText(featureFilters.toString());
1503       if (!featureFilters.isAnded())
1504       {
1505         orFilters.setSelected(true);
1506       }
1507       featureFilters.getMatchers().forEach(matcher -> filters.add(matcher));
1508     }
1509
1510     /*
1511      * and an empty filter for the user to populate (add)
1512      */
1513     KeyedMatcherI noFilter = new KeyedMatcher(Condition.values()[0], "",
1514             (String) null);
1515     filters.add(noFilter);
1516
1517     /*
1518      * render the conditions in rows, each in its own JPanel
1519      */
1520     int filterIndex = 0;
1521     for (KeyedMatcherI filter : filters)
1522     {
1523       String[] attName = filter.getKey();
1524       Condition condition = filter.getMatcher()
1525               .getCondition();
1526       String pattern = filter.getMatcher().getPattern();
1527       JPanel row = addFilter(attName, attNames, condition, pattern, filterIndex);
1528       row.setBorder(BorderFactory.createLineBorder(debugBorderColour));
1529       chooseFiltersPanel.add(row);
1530       filterIndex++;
1531     }
1532     // chooseFiltersPanel.add(Box.createVerticalGlue());
1533
1534     filtersPane.validate();
1535     filtersPane.repaint();
1536   }
1537
1538   /**
1539    * A helper method that constructs a panel with one filter condition:
1540    * <ul>
1541    * <li>a drop-down list of attribute names to choose from</li>
1542    * <li>a drop-down list of conditions to choose from</li>
1543    * <li>a text field for input of a match pattern</li>
1544    * <li>optionally, a 'remove' button</li>
1545    * </ul>
1546    * If attribute, condition or pattern are not null, they are set as defaults for
1547    * the input fields. The 'remove' button is added unless the pattern is null or
1548    * empty (incomplete filter condition).
1549    * 
1550    * @param attName
1551    * @param attNames
1552    * @param cond
1553    * @param pattern
1554    * @param filterIndex
1555    * @return
1556    */
1557   protected JPanel addFilter(String[] attName, List<String[]> attNames,
1558           Condition cond, String pattern, int filterIndex)
1559   {
1560     JPanel filterRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
1561     filterRow.setBackground(Color.white);
1562
1563     /*
1564      * drop-down choice of attribute, with description as a tooltip 
1565      * if we can obtain it
1566      */
1567     String featureType = (String) filteredFeatureChoice.getSelectedItem();
1568     final JComboBox<String> attCombo = populateAttributesDropdown(
1569             featureType, attNames);
1570     JComboBox<Condition> condCombo = new JComboBox<>();
1571     JTextField patternField = new JTextField(8);
1572
1573     /*
1574      * action handlers that validate and (if valid) apply changes
1575      */
1576     ActionListener actionListener = new ActionListener()
1577     {
1578       @Override
1579       public void actionPerformed(ActionEvent e)
1580       {
1581         if (attCombo.getSelectedItem() != null)
1582         {
1583           if (validateFilter(patternField, condCombo))
1584           {
1585             updateFilter(attCombo, condCombo, patternField, filterIndex);
1586             filtersChanged();
1587           }
1588         }
1589       }
1590     };
1591     ItemListener itemListener = new ItemListener()
1592     {
1593       @Override
1594       public void itemStateChanged(ItemEvent e)
1595       {
1596         actionListener.actionPerformed(null);
1597       }
1598     };
1599
1600     if (attName == null) // the 'add a condition' row
1601     {
1602       attCombo.setSelectedItem(null);
1603     }
1604     else
1605     {
1606       attCombo.setSelectedItem(String.join(COLON, attName));
1607     }
1608     attCombo.addItemListener(itemListener);
1609
1610     filterRow.add(attCombo);
1611
1612     /*
1613      * drop-down choice of test condition
1614      */
1615     for (Condition c : Condition.values())
1616     {
1617       condCombo.addItem(c);
1618     }
1619     if (cond != null)
1620     {
1621       condCombo.setSelectedItem(cond);
1622     }
1623     condCombo.addItemListener(itemListener);
1624     filterRow.add(condCombo);
1625
1626     /*
1627      * pattern to match against
1628      */
1629     patternField.setText(pattern);
1630     patternField.addActionListener(actionListener);
1631     patternField.addFocusListener(new FocusAdapter()
1632     {
1633       @Override
1634       public void focusLost(FocusEvent e)
1635       {
1636         actionListener.actionPerformed(null);
1637       }
1638     });
1639     filterRow.add(patternField);
1640
1641     /*
1642      * add remove button if filter is populated (non-empty pattern)
1643      */
1644     if (pattern != null && pattern.trim().length() > 0)
1645     {
1646       // todo: gif for button drawing '-' or 'x'
1647       JButton removeCondition = new BasicArrowButton(SwingConstants.WEST);
1648       removeCondition.setToolTipText(MessageManager
1649               .getString("label.delete_row"));
1650       removeCondition.addActionListener(new ActionListener()
1651       {
1652         @Override
1653         public void actionPerformed(ActionEvent e)
1654         {
1655           filters.remove(filterIndex);
1656           filtersChanged();
1657         }
1658       });
1659       filterRow.add(removeCondition);
1660     }
1661
1662     return filterRow;
1663   }
1664
1665   /**
1666    * A helper method to build the drop-down choice of attributes for a feature.
1667    * Where metadata is available with a description for an attribute, that is
1668    * added as a tooltip.
1669    * 
1670    * @param featureType
1671    * @param attNames
1672    */
1673   protected JComboBox<String> populateAttributesDropdown(
1674           String featureType, List<String[]> attNames)
1675   {
1676     List<String> displayNames = new ArrayList<>();
1677     List<String> tooltips = new ArrayList<>();
1678     FeatureAttributes fa = FeatureAttributes.getInstance();
1679     for (String[] attName : attNames)
1680     {
1681       String desc = fa.getDescription(featureType, attName);
1682       if (desc != null && desc.length() > MAX_TOOLTIP_LENGTH)
1683       {
1684         desc = desc.substring(0, MAX_TOOLTIP_LENGTH) + "...";
1685       }
1686       displayNames.add(String.join(COLON, attName));
1687       tooltips.add(desc == null ? "" : desc);
1688     }
1689
1690     JComboBox<String> attCombo = JvSwingUtils.buildComboWithTooltips(
1691             displayNames, tooltips);
1692     if (attNames.isEmpty())
1693     {
1694       attCombo.setToolTipText(MessageManager
1695               .getString("label.no_attributes"));
1696     }
1697     return attCombo;
1698   }
1699
1700   /**
1701    * Action on any change to feature filtering, namely
1702    * <ul>
1703    * <li>change of selected attribute</li>
1704    * <li>change of selected condition</li>
1705    * <li>change of match pattern</li>
1706    * <li>removal of a condition</li>
1707    * </ul>
1708    * The action should be to
1709    * <ul>
1710    * <li>parse and validate the filters</li>
1711    * <li>if valid, update the filter text box</li>
1712    * <li>and apply the filters to the viewport</li>
1713    * </ul>
1714    */
1715   protected void filtersChanged()
1716   {
1717     /*
1718      * update the filter conditions for the feature type
1719      */
1720     String featureType = (String) filteredFeatureChoice.getSelectedItem();
1721     boolean anded = andFilters.isSelected();
1722     KeyedMatcherSetI combined = new KeyedMatcherSet();
1723
1724     for (KeyedMatcherI filter : filters)
1725     {
1726       String pattern = filter.getMatcher().getPattern();
1727       if (pattern.trim().length() > 0)
1728       {
1729         if (anded)
1730         {
1731           combined.and(filter);
1732         }
1733         else
1734         {
1735           combined.or(filter);
1736         }
1737       }
1738     }
1739
1740     /*
1741      * save the filter conditions in the FeatureRenderer
1742      * (note this might now be an empty filter with no conditions)
1743      */
1744     fr.setFeatureFilter(featureType, combined);
1745
1746     filtersAsText.setText(combined.toString());
1747
1748     refreshFiltersDisplay();
1749
1750     af.alignPanel.paintAlignment(true, true);
1751   }
1752
1753   /**
1754    * Constructs a filter condition from the given input fields, and replaces the
1755    * condition at filterIndex with the new one
1756    * 
1757    * @param attCombo
1758    * @param condCombo
1759    * @param valueField
1760    * @param filterIndex
1761    */
1762   protected void updateFilter(JComboBox<String> attCombo,
1763           JComboBox<Condition> condCombo, JTextField valueField,
1764           int filterIndex)
1765   {
1766     String attName = (String) attCombo.getSelectedItem();
1767     Condition cond = (Condition) condCombo.getSelectedItem();
1768     String pattern = valueField.getText();
1769     KeyedMatcherI km = new KeyedMatcher(cond, pattern,
1770             attName.split(COLON));
1771
1772     filters.set(filterIndex, km);
1773   }
1774
1775   public void fetchDAS_actionPerformed(ActionEvent e)
1776   {
1777     fetchDAS.setEnabled(false);
1778     cancelDAS.setEnabled(true);
1779     dassourceBrowser.setGuiEnabled(false);
1780     Vector<jalviewSourceI> selectedSources = dassourceBrowser
1781             .getSelectedSources();
1782     doDasFeatureFetch(selectedSources, true, true);
1783   }
1784
1785   /**
1786    * get the features from selectedSources for all or the current selection
1787    * 
1788    * @param selectedSources
1789    * @param checkDbRefs
1790    * @param promptFetchDbRefs
1791    */
1792   private void doDasFeatureFetch(List<jalviewSourceI> selectedSources,
1793           boolean checkDbRefs, boolean promptFetchDbRefs)
1794   {
1795     SequenceI[] dataset, seqs;
1796     int iSize;
1797     AlignmentViewport vp = af.getViewport();
1798     if (vp.getSelectionGroup() != null
1799             && vp.getSelectionGroup().getSize() > 0)
1800     {
1801       iSize = vp.getSelectionGroup().getSize();
1802       dataset = new SequenceI[iSize];
1803       seqs = vp.getSelectionGroup().getSequencesInOrder(vp.getAlignment());
1804     }
1805     else
1806     {
1807       iSize = vp.getAlignment().getHeight();
1808       seqs = vp.getAlignment().getSequencesArray();
1809     }
1810
1811     dataset = new SequenceI[iSize];
1812     for (int i = 0; i < iSize; i++)
1813     {
1814       dataset[i] = seqs[i].getDatasetSequence();
1815     }
1816
1817     cancelDAS.setEnabled(true);
1818     dasFeatureFetcher = new jalview.ws.DasSequenceFeatureFetcher(dataset,
1819             this, selectedSources, checkDbRefs, promptFetchDbRefs);
1820     af.getViewport().setShowSequenceFeatures(true);
1821     af.showSeqFeatures.setSelected(true);
1822   }
1823
1824   /**
1825    * blocking call to initialise the das source browser
1826    */
1827   public void initDasSources()
1828   {
1829     dassourceBrowser.initDasSources();
1830   }
1831
1832   /**
1833    * examine the current list of das sources and return any matching the given
1834    * nicknames in sources
1835    * 
1836    * @param sources
1837    *          Vector of Strings to resolve to DAS source nicknames.
1838    * @return sources that are present in source list.
1839    */
1840   public List<jalviewSourceI> resolveSourceNicknames(Vector<String> sources)
1841   {
1842     return dassourceBrowser.sourceRegistry.resolveSourceNicknames(sources);
1843   }
1844
1845   /**
1846    * get currently selected das sources. ensure you have called initDasSources
1847    * before calling this.
1848    * 
1849    * @return vector of selected das source nicknames
1850    */
1851   public Vector<jalviewSourceI> getSelectedSources()
1852   {
1853     return dassourceBrowser.getSelectedSources();
1854   }
1855
1856   /**
1857    * properly initialise DAS fetcher and then initiate a new thread to fetch
1858    * features from the named sources (rather than any turned on by default)
1859    * 
1860    * @param sources
1861    * @param block
1862    *          if true then runs in same thread, otherwise passes to the Swing
1863    *          executor
1864    */
1865   public void fetchDasFeatures(Vector<String> sources, boolean block)
1866   {
1867     initDasSources();
1868     List<jalviewSourceI> resolved = dassourceBrowser.sourceRegistry
1869             .resolveSourceNicknames(sources);
1870     if (resolved.size() == 0)
1871     {
1872       resolved = dassourceBrowser.getSelectedSources();
1873     }
1874     if (resolved.size() > 0)
1875     {
1876       final List<jalviewSourceI> dassources = resolved;
1877       fetchDAS.setEnabled(false);
1878       // cancelDAS.setEnabled(true); doDasFetch does this.
1879       Runnable fetcher = new Runnable()
1880       {
1881
1882         @Override
1883         public void run()
1884         {
1885           doDasFeatureFetch(dassources, true, false);
1886
1887         }
1888       };
1889       if (block)
1890       {
1891         fetcher.run();
1892       }
1893       else
1894       {
1895         SwingUtilities.invokeLater(fetcher);
1896       }
1897     }
1898   }
1899
1900   public void saveDAS_actionPerformed(ActionEvent e)
1901   {
1902     dassourceBrowser
1903             .saveProperties(jalview.bin.Cache.applicationProperties);
1904   }
1905
1906   public void complete()
1907   {
1908     fetchDAS.setEnabled(true);
1909     cancelDAS.setEnabled(false);
1910     dassourceBrowser.setGuiEnabled(true);
1911
1912   }
1913
1914   public void cancelDAS_actionPerformed(ActionEvent e)
1915   {
1916     if (dasFeatureFetcher != null)
1917     {
1918       dasFeatureFetcher.cancel();
1919     }
1920     complete();
1921   }
1922
1923   public void noDasSourceActive()
1924   {
1925     complete();
1926     JvOptionPane.showInternalConfirmDialog(Desktop.desktop,
1927             MessageManager.getString("label.no_das_sources_selected_warn"),
1928             MessageManager.getString("label.no_das_sources_selected_title"),
1929             JvOptionPane.DEFAULT_OPTION, JvOptionPane.INFORMATION_MESSAGE);
1930   }
1931
1932   /**
1933    * Answers true unless a numeric condition has been selected with a
1934    * non-numeric value. Sets the value field to RED with a tooltip if in error.
1935    * <p>
1936    * If the pattern entered is empty, this method returns false, but does not
1937    * mark the field as invalid. This supports selecting an attribute for a new
1938    * condition before a match pattern has been entered.
1939    * 
1940    * @param value
1941    * @param condCombo
1942    */
1943   protected boolean validateFilter(JTextField value,
1944           JComboBox<Condition> condCombo)
1945   {
1946     if (value == null || condCombo == null)
1947     {
1948       return true; // fields not populated
1949     }
1950   
1951     Condition cond = (Condition) condCombo.getSelectedItem();
1952     value.setBackground(Color.white);
1953     value.setToolTipText("");
1954     String v1 = value.getText().trim();
1955     if (v1.length() == 0)
1956     {
1957       return false;
1958     }
1959
1960     if (cond.isNumeric())
1961     {
1962       try
1963       {
1964         Float.valueOf(v1);
1965       } catch (NumberFormatException e)
1966       {
1967         value.setBackground(Color.red);
1968         value.setToolTipText(MessageManager
1969                 .getString("label.numeric_required"));
1970         return false;
1971       }
1972     }
1973   
1974     return true;
1975   }
1976
1977   // ///////////////////////////////////////////////////////////////////////
1978   // http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
1979   // ///////////////////////////////////////////////////////////////////////
1980   class FeatureTableModel extends AbstractTableModel
1981   {
1982     FeatureTableModel(Object[][] data)
1983     {
1984       this.data = data;
1985     }
1986
1987     private String[] columnNames = {
1988         MessageManager.getString("label.feature_type"),
1989         MessageManager.getString("action.colour"),
1990         MessageManager.getString("label.display") };
1991
1992     private Object[][] data;
1993
1994     public Object[][] getData()
1995     {
1996       return data;
1997     }
1998
1999     public void setData(Object[][] data)
2000     {
2001       this.data = data;
2002     }
2003
2004     @Override
2005     public int getColumnCount()
2006     {
2007       return columnNames.length;
2008     }
2009
2010     public Object[] getRow(int row)
2011     {
2012       return data[row];
2013     }
2014
2015     @Override
2016     public int getRowCount()
2017     {
2018       return data.length;
2019     }
2020
2021     @Override
2022     public String getColumnName(int col)
2023     {
2024       return columnNames[col];
2025     }
2026
2027     @Override
2028     public Object getValueAt(int row, int col)
2029     {
2030       return data[row][col];
2031     }
2032
2033     @Override
2034     public Class getColumnClass(int c)
2035     {
2036       return getValueAt(0, c).getClass();
2037     }
2038
2039     @Override
2040     public boolean isCellEditable(int row, int col)
2041     {
2042       return col == 0 ? false : true;
2043     }
2044
2045     @Override
2046     public void setValueAt(Object value, int row, int col)
2047     {
2048       data[row][col] = value;
2049       fireTableCellUpdated(row, col);
2050       updateFeatureRenderer(data);
2051     }
2052
2053   }
2054
2055   class ColorRenderer extends JLabel implements TableCellRenderer
2056   {
2057     javax.swing.border.Border unselectedBorder = null;
2058
2059     javax.swing.border.Border selectedBorder = null;
2060
2061     final String baseTT = "Click to edit, right/apple click for menu.";
2062
2063     public ColorRenderer()
2064     {
2065       setOpaque(true); // MUST do this for background to show up.
2066       setHorizontalTextPosition(SwingConstants.CENTER);
2067       setVerticalTextPosition(SwingConstants.CENTER);
2068     }
2069
2070     @Override
2071     public Component getTableCellRendererComponent(JTable tbl, Object color,
2072             boolean isSelected, boolean hasFocus, int row, int column)
2073     {
2074       FeatureColourI cellColour = (FeatureColourI) color;
2075       setOpaque(true);
2076       setToolTipText(baseTT);
2077       setBackground(tbl.getBackground());
2078       if (!cellColour.isSimpleColour())
2079       {
2080         Rectangle cr = tbl.getCellRect(row, column, false);
2081         FeatureSettings.renderGraduatedColor(this, cellColour,
2082                 (int) cr.getWidth(), (int) cr.getHeight());
2083       }
2084       else
2085       {
2086         this.setText("");
2087         this.setIcon(null);
2088         setBackground(cellColour.getColour());
2089       }
2090       if (isSelected)
2091       {
2092         if (selectedBorder == null)
2093         {
2094           selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
2095                   tbl.getSelectionBackground());
2096         }
2097         setBorder(selectedBorder);
2098       }
2099       else
2100       {
2101         if (unselectedBorder == null)
2102         {
2103           unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
2104                   tbl.getBackground());
2105         }
2106         setBorder(unselectedBorder);
2107       }
2108
2109       return this;
2110     }
2111   }
2112
2113   /**
2114    * update comp using rendering settings from gcol
2115    * 
2116    * @param comp
2117    * @param gcol
2118    */
2119   public static void renderGraduatedColor(JLabel comp, FeatureColourI gcol)
2120   {
2121     int w = comp.getWidth(), h = comp.getHeight();
2122     if (w < 20)
2123     {
2124       w = (int) comp.getPreferredSize().getWidth();
2125       h = (int) comp.getPreferredSize().getHeight();
2126       if (w < 20)
2127       {
2128         w = 80;
2129         h = 12;
2130       }
2131     }
2132     renderGraduatedColor(comp, gcol, w, h);
2133   }
2134
2135   public static void renderGraduatedColor(JLabel comp, FeatureColourI gcol,
2136           int w, int h)
2137   {
2138     boolean thr = false;
2139     StringBuilder tt = new StringBuilder();
2140     StringBuilder tx = new StringBuilder();
2141
2142     if (gcol.isColourByAttribute())
2143     {
2144       tx.append(String.join(":", gcol.getAttributeName()));
2145     }
2146     else if (!gcol.isColourByLabel())
2147     {
2148       tx.append(MessageManager.getString("label.score"));
2149     }
2150     tx.append(" ");
2151     if (gcol.isAboveThreshold())
2152     {
2153       thr = true;
2154       tx.append(">");
2155       tt.append("Thresholded (Above ").append(gcol.getThreshold())
2156               .append(") ");
2157     }
2158     if (gcol.isBelowThreshold())
2159     {
2160       thr = true;
2161       tx.append("<");
2162       tt.append("Thresholded (Below ").append(gcol.getThreshold())
2163               .append(") ");
2164     }
2165     if (gcol.isColourByLabel())
2166     {
2167       tt.append("Coloured by label text. ").append(tt);
2168       if (thr)
2169       {
2170         tx.append(" ");
2171       }
2172       if (!gcol.isColourByAttribute())
2173       {
2174         tx.append("Label");
2175       }
2176       comp.setIcon(null);
2177     }
2178     else
2179     {
2180       Color newColor = gcol.getMaxColour();
2181       comp.setBackground(newColor);
2182       // System.err.println("Width is " + w / 2);
2183       Icon ficon = new FeatureIcon(gcol, comp.getBackground(), w, h, thr);
2184       comp.setIcon(ficon);
2185       // tt+="RGB value: Max (" + newColor.getRed() + ", "
2186       // + newColor.getGreen() + ", " + newColor.getBlue()
2187       // + ")\nMin (" + minCol.getRed() + ", " + minCol.getGreen()
2188       // + ", " + minCol.getBlue() + ")");
2189     }
2190     comp.setHorizontalAlignment(SwingConstants.CENTER);
2191     comp.setText(tx.toString());
2192     if (tt.length() > 0)
2193     {
2194       if (comp.getToolTipText() == null)
2195       {
2196         comp.setToolTipText(tt.toString());
2197       }
2198       else
2199       {
2200         comp.setToolTipText(tt.append(" ").append(comp.getToolTipText())
2201                 .toString());
2202       }
2203     }
2204   }
2205 }
2206
2207 class FeatureIcon implements Icon
2208 {
2209   FeatureColourI gcol;
2210
2211   Color backg;
2212
2213   boolean midspace = false;
2214
2215   int width = 50, height = 20;
2216
2217   int s1, e1; // start and end of midpoint band for thresholded symbol
2218
2219   Color mpcolour = Color.white;
2220
2221   FeatureIcon(FeatureColourI gfc, Color bg, int w, int h, boolean mspace)
2222   {
2223     gcol = gfc;
2224     backg = bg;
2225     width = w;
2226     height = h;
2227     midspace = mspace;
2228     if (midspace)
2229     {
2230       s1 = width / 3;
2231       e1 = s1 * 2;
2232     }
2233     else
2234     {
2235       s1 = width / 2;
2236       e1 = s1;
2237     }
2238   }
2239
2240   @Override
2241   public int getIconWidth()
2242   {
2243     return width;
2244   }
2245
2246   @Override
2247   public int getIconHeight()
2248   {
2249     return height;
2250   }
2251
2252   @Override
2253   public void paintIcon(Component c, Graphics g, int x, int y)
2254   {
2255
2256     if (gcol.isColourByLabel())
2257     {
2258       g.setColor(backg);
2259       g.fillRect(0, 0, width, height);
2260       // need an icon here.
2261       g.setColor(gcol.getMaxColour());
2262
2263       g.setFont(new Font("Verdana", Font.PLAIN, 9));
2264
2265       // g.setFont(g.getFont().deriveFont(
2266       // AffineTransform.getScaleInstance(
2267       // width/g.getFontMetrics().stringWidth("Label"),
2268       // height/g.getFontMetrics().getHeight())));
2269
2270       g.drawString(MessageManager.getString("label.label"), 0, 0);
2271
2272     }
2273     else
2274     {
2275       Color minCol = gcol.getMinColour();
2276       g.setColor(minCol);
2277       g.fillRect(0, 0, s1, height);
2278       if (midspace)
2279       {
2280         g.setColor(Color.white);
2281         g.fillRect(s1, 0, e1 - s1, height);
2282       }
2283       g.setColor(gcol.getMaxColour());
2284       g.fillRect(0, e1, width - e1, height);
2285     }
2286   }
2287 }
2288
2289 class ColorEditor extends AbstractCellEditor
2290         implements TableCellEditor, ActionListener
2291 {
2292   FeatureSettings me;
2293
2294   FeatureColourI currentColor;
2295
2296   FeatureColourChooser chooser;
2297
2298   String type;
2299
2300   JButton button;
2301
2302   JColorChooser colorChooser;
2303
2304   JDialog dialog;
2305
2306   protected static final String EDIT = "edit";
2307
2308   int selectedRow = 0;
2309
2310   public ColorEditor(FeatureSettings me)
2311   {
2312     this.me = me;
2313     // Set up the editor (from the table's point of view),
2314     // which is a button.
2315     // This button brings up the color chooser dialog,
2316     // which is the editor from the user's point of view.
2317     button = new JButton();
2318     button.setActionCommand(EDIT);
2319     button.addActionListener(this);
2320     button.setBorderPainted(false);
2321     // Set up the dialog that the button brings up.
2322     colorChooser = new JColorChooser();
2323     dialog = JColorChooser.createDialog(button,
2324             MessageManager.getString("label.select_new_colour"), true, // modal
2325             colorChooser, this, // OK button handler
2326             null); // no CANCEL button handler
2327   }
2328
2329   /**
2330    * Handles events from the editor button and from the dialog's OK button.
2331    */
2332   @Override
2333   public void actionPerformed(ActionEvent e)
2334   {
2335
2336     if (EDIT.equals(e.getActionCommand()))
2337     {
2338       // The user has clicked the cell, so
2339       // bring up the dialog.
2340       if (currentColor.isSimpleColour())
2341       {
2342         // bring up simple color chooser
2343         button.setBackground(currentColor.getColour());
2344         colorChooser.setColor(currentColor.getColour());
2345         dialog.setVisible(true);
2346       }
2347       else
2348       {
2349         // bring up graduated chooser.
2350         chooser = new FeatureColourChooser(me.fr, type);
2351         chooser.setRequestFocusEnabled(true);
2352         chooser.requestFocus();
2353         chooser.addActionListener(this);
2354       }
2355       // Make the renderer reappear.
2356       fireEditingStopped();
2357
2358     }
2359     else
2360     { // User pressed dialog's "OK" button.
2361       if (currentColor.isSimpleColour())
2362       {
2363         currentColor = new FeatureColour(colorChooser.getColor());
2364       }
2365       else
2366       {
2367         currentColor = chooser.getLastColour();
2368       }
2369       me.table.setValueAt(getCellEditorValue(), selectedRow, 1);
2370       fireEditingStopped();
2371       me.table.validate();
2372     }
2373   }
2374
2375   // Implement the one CellEditor method that AbstractCellEditor doesn't.
2376   @Override
2377   public Object getCellEditorValue()
2378   {
2379     return currentColor;
2380   }
2381
2382   // Implement the one method defined by TableCellEditor.
2383   @Override
2384   public Component getTableCellEditorComponent(JTable table, Object value,
2385           boolean isSelected, int row, int column)
2386   {
2387     currentColor = (FeatureColourI) value;
2388     this.selectedRow = row;
2389     type = me.table.getValueAt(row, 0).toString();
2390     button.setOpaque(true);
2391     button.setBackground(me.getBackground());
2392     if (!currentColor.isSimpleColour())
2393     {
2394       JLabel btn = new JLabel();
2395       btn.setSize(button.getSize());
2396       FeatureSettings.renderGraduatedColor(btn, currentColor);
2397       button.setBackground(btn.getBackground());
2398       button.setIcon(btn.getIcon());
2399       button.setText(btn.getText());
2400     }
2401     else
2402     {
2403       button.setText("");
2404       button.setIcon(null);
2405       button.setBackground(currentColor.getColour());
2406     }
2407     return button;
2408   }
2409 }