JAL-3060 more extensive extract method refactoring of FeatureEditor
[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.datamodel.AlignmentI;
26 import jalview.datamodel.SequenceI;
27 import jalview.datamodel.features.FeatureMatcher;
28 import jalview.datamodel.features.FeatureMatcherI;
29 import jalview.datamodel.features.FeatureMatcherSet;
30 import jalview.datamodel.features.FeatureMatcherSetI;
31 import jalview.gui.Help.HelpId;
32 import jalview.gui.JalviewColourChooser.ColourChooserListener;
33 import jalview.io.JalviewFileChooser;
34 import jalview.io.JalviewFileView;
35 import jalview.schemabinding.version2.Filter;
36 import jalview.schemabinding.version2.JalviewUserColours;
37 import jalview.schemabinding.version2.MatcherSet;
38 import jalview.schemes.FeatureColour;
39 import jalview.util.MessageManager;
40 import jalview.util.Platform;
41 import jalview.viewmodel.seqfeatures.FeatureRendererModel.FeatureSettingsBean;
42
43 import java.awt.BorderLayout;
44 import java.awt.Color;
45 import java.awt.Component;
46 import java.awt.Dimension;
47 import java.awt.Font;
48 import java.awt.Graphics;
49 import java.awt.GridLayout;
50 import java.awt.Point;
51 import java.awt.Rectangle;
52 import java.awt.event.ActionEvent;
53 import java.awt.event.ActionListener;
54 import java.awt.event.ItemEvent;
55 import java.awt.event.ItemListener;
56 import java.awt.event.MouseAdapter;
57 import java.awt.event.MouseEvent;
58 import java.awt.event.MouseMotionAdapter;
59 import java.beans.PropertyChangeEvent;
60 import java.beans.PropertyChangeListener;
61 import java.io.File;
62 import java.io.FileInputStream;
63 import java.io.FileOutputStream;
64 import java.io.InputStreamReader;
65 import java.io.OutputStreamWriter;
66 import java.io.PrintWriter;
67 import java.util.Arrays;
68 import java.util.Comparator;
69 import java.util.HashMap;
70 import java.util.HashSet;
71 import java.util.Hashtable;
72 import java.util.Iterator;
73 import java.util.List;
74 import java.util.Map;
75 import java.util.Set;
76
77 import javax.help.HelpSetException;
78 import javax.swing.AbstractCellEditor;
79 import javax.swing.BorderFactory;
80 import javax.swing.Icon;
81 import javax.swing.JButton;
82 import javax.swing.JCheckBox;
83 import javax.swing.JCheckBoxMenuItem;
84 import javax.swing.JInternalFrame;
85 import javax.swing.JLabel;
86 import javax.swing.JLayeredPane;
87 import javax.swing.JMenuItem;
88 import javax.swing.JPanel;
89 import javax.swing.JPopupMenu;
90 import javax.swing.JScrollPane;
91 import javax.swing.JSlider;
92 import javax.swing.JTable;
93 import javax.swing.ListSelectionModel;
94 import javax.swing.SwingConstants;
95 import javax.swing.ToolTipManager;
96 import javax.swing.border.Border;
97 import javax.swing.event.ChangeEvent;
98 import javax.swing.event.ChangeListener;
99 import javax.swing.table.AbstractTableModel;
100 import javax.swing.table.TableCellEditor;
101 import javax.swing.table.TableCellRenderer;
102 import javax.swing.table.TableColumn;
103
104 public class FeatureSettings extends JPanel
105         implements FeatureSettingsControllerI
106 {
107   private static final String SEQUENCE_FEATURE_COLOURS = MessageManager
108           .getString("label.sequence_feature_colours");
109
110   /*
111    * column indices of fields in Feature Settings table
112    */
113   static final int TYPE_COLUMN = 0;
114
115   static final int COLOUR_COLUMN = 1;
116
117   static final int FILTER_COLUMN = 2;
118
119   static final int SHOW_COLUMN = 3;
120
121   private static final int COLUMN_COUNT = 4;
122
123   private static final int MIN_WIDTH = 400;
124
125   private static final int MIN_HEIGHT = 400;
126
127   private final static String BASE_TOOLTIP = "Click to edit, right-click for menu";
128
129   final FeatureRenderer fr;
130
131   public final AlignFrame af;
132
133   /*
134    * 'original' fields hold settings to restore on Cancel
135    */
136   Object[][] originalData;
137
138   float originalTransparency;
139
140   Map<String, FeatureMatcherSetI> originalFilters;
141
142   final JInternalFrame frame;
143
144   JScrollPane scrollPane = new JScrollPane();
145
146   JTable table;
147
148   JPanel groupPanel;
149
150   JSlider transparency = new JSlider();
151
152   /*
153    * when true, constructor is still executing - so ignore UI events
154    */
155   protected volatile boolean inConstruction = true;
156
157   int selectedRow = -1;
158
159   JButton fetchDAS = new JButton();
160
161   JButton saveDAS = new JButton();
162
163   JButton cancelDAS = new JButton();
164
165   boolean resettingTable = false;
166
167   /*
168    * true when Feature Settings are updating from feature renderer
169    */
170   boolean handlingUpdate = false;
171
172   /*
173    * holds {featureCount, totalExtent} for each feature type
174    */
175   Map<String, float[]> typeWidth = null;
176
177   /**
178    * Constructor
179    * 
180    * @param af
181    */
182   public FeatureSettings(AlignFrame alignFrame)
183   {
184     this.af = alignFrame;
185     fr = af.getFeatureRenderer();
186
187     // save transparency for restore on Cancel
188     originalTransparency = fr.getTransparency();
189     int originalTransparencyAsPercent = (int) (originalTransparency * 100);
190     transparency.setMaximum(100 - originalTransparencyAsPercent);
191
192     originalFilters = new HashMap<>(fr.getFeatureFilters()); // shallow copy
193
194     try
195     {
196       jbInit();
197     } catch (Exception ex)
198     {
199       ex.printStackTrace();
200     }
201
202     table = new JTable()
203     {
204       static final String tt = "Click to edit, right-click for menu"; // todo i18n
205       
206       @Override
207       public String getToolTipText(MouseEvent e)
208       {
209         String tip = null;
210         int column = table.columnAtPoint(e.getPoint());
211         int row = table.rowAtPoint(e.getPoint());
212
213         switch (column)
214         {
215         case TYPE_COLUMN:
216           tip = JvSwingUtils.wrapTooltip(true, MessageManager
217                   .getString("label.feature_settings_click_drag"));
218           break;
219         case COLOUR_COLUMN:
220           FeatureColourI colour = (FeatureColourI) table.getValueAt(row,
221                   column);
222           tip = getColorTooltip(colour, true);
223           break;
224         case FILTER_COLUMN:
225           FeatureMatcherSet o = (FeatureMatcherSet) table.getValueAt(row,
226                   column);
227           tip = o.isEmpty()
228                   ? MessageManager.getString("label.filters_tooltip")
229                   : o.toString();
230           break;
231         default:
232           break;
233         }
234         return tip;
235       }
236
237       /**
238        * Position the tooltip near the bottom edge of, and half way across, the
239        * current cell
240        */
241       @Override
242       public Point getToolTipLocation(MouseEvent e)
243       {
244         Point point = e.getPoint();
245         int column = table.columnAtPoint(point);
246         int row = table.rowAtPoint(point);
247         Rectangle r = getCellRect(row, column, false);
248         Point loc = new Point(r.x + r.width / 2, r.y + r.height - 3);
249         return loc;
250       }
251     };
252     table.getTableHeader().setFont(new Font("Verdana", Font.PLAIN, 12));
253     table.setFont(new Font("Verdana", Font.PLAIN, 12));
254     ToolTipManager.sharedInstance().registerComponent(table);
255
256     // table.setDefaultRenderer(Color.class, new ColorRenderer());
257     // table.setDefaultEditor(Color.class, new ColorEditor(this));
258     //
259     table.setDefaultEditor(FeatureColour.class, new ColorEditor(this));
260     table.setDefaultRenderer(FeatureColour.class, new ColorRenderer());
261
262     table.setDefaultEditor(FeatureMatcherSet.class, new FilterEditor(this));
263     table.setDefaultRenderer(FeatureMatcherSet.class, new FilterRenderer());
264     
265     TableColumn colourColumn = new TableColumn(COLOUR_COLUMN, 75,
266             new ColorRenderer(), new ColorEditor(this));
267     table.addColumn(colourColumn);
268
269     TableColumn filterColumn = new TableColumn(FILTER_COLUMN, 75,
270             new FilterRenderer(), new FilterEditor(this));
271     table.addColumn(filterColumn);
272
273     table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
274
275     table.addMouseListener(new MouseAdapter()
276     {
277       @Override
278       public void mousePressed(MouseEvent evt)
279       {
280         selectedRow = table.rowAtPoint(evt.getPoint());
281         String type = (String) table.getValueAt(selectedRow, TYPE_COLUMN);
282         if (evt.isPopupTrigger())
283         {
284           Object colour = table.getValueAt(selectedRow, COLOUR_COLUMN);
285           popupSort(selectedRow, type, colour, fr.getMinMax(), evt.getX(),
286                   evt.getY());
287         }
288         else if (evt.getClickCount() == 2)
289         {
290           boolean invertSelection = evt.isAltDown();
291           boolean toggleSelection = Platform.isControlDown(evt);
292           boolean extendSelection = evt.isShiftDown();
293           fr.ap.alignFrame.avc.markColumnsContainingFeatures(
294                   invertSelection, extendSelection, toggleSelection, type);
295         }
296       }
297
298       // isPopupTrigger fires on mouseReleased on Windows
299       @Override
300       public void mouseReleased(MouseEvent evt)
301       {
302         selectedRow = table.rowAtPoint(evt.getPoint());
303         if (evt.isPopupTrigger())
304         {
305           String type = (String) table.getValueAt(selectedRow, TYPE_COLUMN);
306           Object colour = table.getValueAt(selectedRow, COLOUR_COLUMN);
307           popupSort(selectedRow, type, colour, fr.getMinMax(), evt.getX(),
308                   evt.getY());
309         }
310       }
311     });
312
313     table.addMouseMotionListener(new MouseMotionAdapter()
314     {
315       @Override
316       public void mouseDragged(MouseEvent evt)
317       {
318         int newRow = table.rowAtPoint(evt.getPoint());
319         if (newRow != selectedRow && selectedRow != -1 && newRow != -1)
320         {
321           /*
322            * reposition 'selectedRow' to 'newRow' (the dragged to location)
323            * this could be more than one row away for a very fast drag action
324            * so just swap it with adjacent rows until we get it there
325            */
326           Object[][] data = ((FeatureTableModel) table.getModel())
327                   .getData();
328           int direction = newRow < selectedRow ? -1 : 1;
329           for (int i = selectedRow; i != newRow; i += direction)
330           {
331             Object[] temp = data[i];
332             data[i] = data[i + direction];
333             data[i + direction] = temp;
334           }
335           updateFeatureRenderer(data);
336           table.repaint();
337           selectedRow = newRow;
338         }
339       }
340     });
341     // table.setToolTipText(JvSwingUtils.wrapTooltip(true,
342     // MessageManager.getString("label.feature_settings_click_drag")));
343     scrollPane.setViewportView(table);
344
345     if (af.getViewport().isShowSequenceFeatures() || !fr.hasRenderOrder())
346     {
347       fr.findAllFeatures(true); // display everything!
348     }
349
350     discoverAllFeatureData();
351     final PropertyChangeListener change;
352     final FeatureSettings fs = this;
353     fr.addPropertyChangeListener(change = new PropertyChangeListener()
354     {
355       @Override
356       public void propertyChange(PropertyChangeEvent evt)
357       {
358         if (!fs.resettingTable && !fs.handlingUpdate)
359         {
360           fs.handlingUpdate = true;
361           fs.resetTable(null);
362           // new groups may be added with new sequence feature types only
363           fs.handlingUpdate = false;
364         }
365       }
366
367     });
368
369     frame = new JInternalFrame();
370     frame.setContentPane(this);
371     if (Platform.isAMac())
372     {
373       Desktop.addInternalFrame(frame,
374               MessageManager.getString("label.sequence_feature_settings"),
375               600, 480);
376     }
377     else
378     {
379       Desktop.addInternalFrame(frame,
380               MessageManager.getString("label.sequence_feature_settings"),
381               600, 450);
382     }
383     frame.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
384
385     frame.addInternalFrameListener(
386             new javax.swing.event.InternalFrameAdapter()
387             {
388               @Override
389               public void internalFrameClosed(
390                       javax.swing.event.InternalFrameEvent evt)
391               {
392                 fr.removePropertyChangeListener(change);
393               };
394             });
395     frame.setLayer(JLayeredPane.PALETTE_LAYER);
396     inConstruction = false;
397   }
398
399   protected void popupSort(final int rowSelected, final String type,
400           final Object typeCol, final Map<String, float[][]> minmax, int x,
401           int y)
402   {
403     final FeatureColourI featureColour = (FeatureColourI) typeCol;
404
405     JPopupMenu men = new JPopupMenu(MessageManager
406             .formatMessage("label.settings_for_param", new String[]
407             { type }));
408     JMenuItem scr = new JMenuItem(
409             MessageManager.getString("label.sort_by_score"));
410     men.add(scr);
411     final FeatureSettings me = this;
412     scr.addActionListener(new ActionListener()
413     {
414
415       @Override
416       public void actionPerformed(ActionEvent e)
417       {
418         me.af.avc
419                 .sortAlignmentByFeatureScore(Arrays.asList(new String[]
420                 { type }));
421       }
422
423     });
424     JMenuItem dens = new JMenuItem(
425             MessageManager.getString("label.sort_by_density"));
426     dens.addActionListener(new ActionListener()
427     {
428
429       @Override
430       public void actionPerformed(ActionEvent e)
431       {
432         me.af.avc
433                 .sortAlignmentByFeatureDensity(Arrays.asList(new String[]
434                 { type }));
435       }
436
437     });
438     men.add(dens);
439
440     /*
441      * variable colour options include colour by label, by score,
442      * by selected attribute text, or attribute value
443      */
444     final JCheckBoxMenuItem variableColourCB = new JCheckBoxMenuItem(
445             MessageManager.getString("label.variable_colour"));
446     variableColourCB.setSelected(!featureColour.isSimpleColour());
447     men.add(variableColourCB);
448     
449     /*
450      * checkbox action listener doubles up as listener to OK
451      * from the variable colour / filters dialog
452      */
453     variableColourCB.addActionListener(new ActionListener()
454     {
455       @Override
456       public void actionPerformed(ActionEvent e)
457       {
458         if (e.getSource() == variableColourCB)
459         {
460           if (featureColour.isSimpleColour())
461           {
462             /*
463              * toggle simple colour to variable colour - show dialog
464              */
465             FeatureTypeSettings fc = new FeatureTypeSettings(me.fr, type);
466             fc.addActionListener(this);
467           }
468           else
469           {
470             /*
471              * toggle variable to simple colour - show colour chooser
472              */
473             String title = MessageManager.getString("label.select_colour");
474             ColourChooserListener listener = new ColourChooserListener()
475             {
476               @Override
477               public void colourSelected(Color c)
478               {
479                 table.setValueAt(new FeatureColour(c), rowSelected,
480                         COLOUR_COLUMN);
481                 table.validate();
482                 me.updateFeatureRenderer(
483                         ((FeatureTableModel) table.getModel()).getData(),
484                         false);
485               }
486             };
487             JalviewColourChooser.showColourChooser(me, title, featureColour.getMaxColour(), listener);
488           }
489         }
490         else    {
491           if (e.getSource() instanceof FeatureTypeSettings)
492           {
493             /*
494              * update after OK in feature colour dialog; the updated
495              * colour will have already been set in the FeatureRenderer
496              */
497             FeatureColourI fci = fr.getFeatureColours().get(type);
498             table.setValueAt(fci, rowSelected, COLOUR_COLUMN);
499             table.validate();
500           }
501         }
502       }
503
504     });
505
506     JMenuItem selCols = new JMenuItem(
507             MessageManager.getString("label.select_columns_containing"));
508     selCols.addActionListener(new ActionListener()
509     {
510       @Override
511       public void actionPerformed(ActionEvent arg0)
512       {
513         fr.ap.alignFrame.avc.markColumnsContainingFeatures(false, false,
514                 false, type);
515       }
516     });
517     JMenuItem clearCols = new JMenuItem(MessageManager
518             .getString("label.select_columns_not_containing"));
519     clearCols.addActionListener(new ActionListener()
520     {
521       @Override
522       public void actionPerformed(ActionEvent arg0)
523       {
524         fr.ap.alignFrame.avc.markColumnsContainingFeatures(true, false,
525                 false, type);
526       }
527     });
528     JMenuItem hideCols = new JMenuItem(
529             MessageManager.getString("label.hide_columns_containing"));
530     hideCols.addActionListener(new ActionListener()
531     {
532       @Override
533       public void actionPerformed(ActionEvent arg0)
534       {
535         fr.ap.alignFrame.hideFeatureColumns(type, true);
536       }
537     });
538     JMenuItem hideOtherCols = new JMenuItem(
539             MessageManager.getString("label.hide_columns_not_containing"));
540     hideOtherCols.addActionListener(new ActionListener()
541     {
542       @Override
543       public void actionPerformed(ActionEvent arg0)
544       {
545         fr.ap.alignFrame.hideFeatureColumns(type, false);
546       }
547     });
548     men.add(selCols);
549     men.add(clearCols);
550     men.add(hideCols);
551     men.add(hideOtherCols);
552     men.show(table, x, y);
553   }
554
555   @Override
556   synchronized public void discoverAllFeatureData()
557   {
558     Set<String> allGroups = new HashSet<>();
559     AlignmentI alignment = af.getViewport().getAlignment();
560
561     for (int i = 0; i < alignment.getHeight(); i++)
562     {
563       SequenceI seq = alignment.getSequenceAt(i);
564       for (String group : seq.getFeatures().getFeatureGroups(true))
565       {
566         if (group != null && !allGroups.contains(group))
567         {
568           allGroups.add(group);
569           checkGroupState(group);
570         }
571       }
572     }
573
574     resetTable(null);
575
576     validate();
577   }
578
579   /**
580    * Synchronise gui group list and check visibility of group
581    * 
582    * @param group
583    * @return true if group is visible
584    */
585   private boolean checkGroupState(String group)
586   {
587     boolean visible = fr.checkGroupVisibility(group, true);
588
589     for (int g = 0; g < groupPanel.getComponentCount(); g++)
590     {
591       if (((JCheckBox) groupPanel.getComponent(g)).getText().equals(group))
592       {
593         ((JCheckBox) groupPanel.getComponent(g)).setSelected(visible);
594         return visible;
595       }
596     }
597
598     final String grp = group;
599     final JCheckBox check = new JCheckBox(group, visible);
600     check.setFont(new Font("Serif", Font.BOLD, 12));
601     check.setToolTipText(group);
602     check.addItemListener(new ItemListener()
603     {
604       @Override
605       public void itemStateChanged(ItemEvent evt)
606       {
607         fr.setGroupVisibility(check.getText(), check.isSelected());
608         resetTable(new String[] { grp });
609         af.alignPanel.paintAlignment(true, true);
610       }
611     });
612     groupPanel.add(check);
613     return visible;
614   }
615
616   synchronized void resetTable(String[] groupChanged)
617   {
618     if (resettingTable)
619     {
620       return;
621     }
622     resettingTable = true;
623     typeWidth = new Hashtable<>();
624     // TODO: change avWidth calculation to 'per-sequence' average and use long
625     // rather than float
626
627     Set<String> displayableTypes = new HashSet<>();
628     Set<String> foundGroups = new HashSet<>();
629
630     /*
631      * determine which feature types may be visible depending on 
632      * which groups are selected, and recompute average width data
633      */
634     for (int i = 0; i < af.getViewport().getAlignment().getHeight(); i++)
635     {
636
637       SequenceI seq = af.getViewport().getAlignment().getSequenceAt(i);
638
639       /*
640        * get the sequence's groups for positional features
641        * and keep track of which groups are visible
642        */
643       Set<String> groups = seq.getFeatures().getFeatureGroups(true);
644       Set<String> visibleGroups = new HashSet<>();
645       for (String group : groups)
646       {
647         if (group == null || checkGroupState(group))
648         {
649           visibleGroups.add(group);
650         }
651       }
652       foundGroups.addAll(groups);
653
654       /*
655        * get distinct feature types for visible groups
656        * record distinct visible types, and their count and total length
657        */
658       Set<String> types = seq.getFeatures().getFeatureTypesForGroups(true,
659               visibleGroups.toArray(new String[visibleGroups.size()]));
660       for (String type : types)
661       {
662         displayableTypes.add(type);
663         float[] avWidth = typeWidth.get(type);
664         if (avWidth == null)
665         {
666           avWidth = new float[2];
667           typeWidth.put(type, avWidth);
668         }
669         // todo this could include features with a non-visible group
670         // - do we greatly care?
671         // todo should we include non-displayable features here, and only
672         // update when features are added?
673         avWidth[0] += seq.getFeatures().getFeatureCount(true, type);
674         avWidth[1] += seq.getFeatures().getTotalFeatureLength(type);
675       }
676     }
677
678     Object[][] data = new Object[displayableTypes.size()][COLUMN_COUNT];
679     int dataIndex = 0;
680
681     if (fr.hasRenderOrder())
682     {
683       if (!handlingUpdate)
684       {
685         fr.findAllFeatures(groupChanged != null); // prod to update
686         // colourschemes. but don't
687         // affect display
688         // First add the checks in the previous render order,
689         // in case the window has been closed and reopened
690       }
691       List<String> frl = fr.getRenderOrder();
692       for (int ro = frl.size() - 1; ro > -1; ro--)
693       {
694         String type = frl.get(ro);
695
696         if (!displayableTypes.contains(type))
697         {
698           continue;
699         }
700
701         data[dataIndex][TYPE_COLUMN] = type;
702         data[dataIndex][COLOUR_COLUMN] = fr.getFeatureStyle(type);
703         FeatureMatcherSetI featureFilter = fr.getFeatureFilter(type);
704         data[dataIndex][FILTER_COLUMN] = featureFilter == null
705                 ? new FeatureMatcherSet()
706                 : featureFilter;
707         data[dataIndex][SHOW_COLUMN] = new Boolean(
708                 af.getViewport().getFeaturesDisplayed().isVisible(type));
709         dataIndex++;
710         displayableTypes.remove(type);
711       }
712     }
713
714     /*
715      * process any extra features belonging only to 
716      * a group which was just selected
717      */
718     while (!displayableTypes.isEmpty())
719     {
720       String type = displayableTypes.iterator().next();
721       data[dataIndex][TYPE_COLUMN] = type;
722
723       data[dataIndex][COLOUR_COLUMN] = fr.getFeatureStyle(type);
724       if (data[dataIndex][COLOUR_COLUMN] == null)
725       {
726         // "Colour has been updated in another view!!"
727         fr.clearRenderOrder();
728         return;
729       }
730       FeatureMatcherSetI featureFilter = fr.getFeatureFilter(type);
731       data[dataIndex][FILTER_COLUMN] = featureFilter == null
732               ? new FeatureMatcherSet()
733               : featureFilter;
734       data[dataIndex][SHOW_COLUMN] = new Boolean(true);
735       dataIndex++;
736       displayableTypes.remove(type);
737     }
738
739     if (originalData == null)
740     {
741       originalData = new Object[data.length][COLUMN_COUNT];
742       for (int i = 0; i < data.length; i++)
743       {
744         System.arraycopy(data[i], 0, originalData[i], 0, COLUMN_COUNT);
745       }
746     }
747     else
748     {
749       updateOriginalData(data);
750     }
751
752     table.setModel(new FeatureTableModel(data));
753     table.getColumnModel().getColumn(0).setPreferredWidth(200);
754
755     groupPanel.setLayout(
756             new GridLayout(fr.getFeatureGroupsSize() / 4 + 1, 4));
757     pruneGroups(foundGroups);
758     groupPanel.validate();
759
760     updateFeatureRenderer(data, groupChanged != null);
761     resettingTable = false;
762   }
763
764   /**
765    * Updates 'originalData' (used for restore on Cancel) if we detect that changes
766    * have been made outwith this dialog
767    * <ul>
768    * <li>a new feature type added (and made visible)</li>
769    * <li>a feature colour changed (in the Amend Features dialog)</li>
770    * </ul>
771    * 
772    * @param foundData
773    */
774   protected void updateOriginalData(Object[][] foundData)
775   {
776     // todo LinkedHashMap instead of Object[][] would be nice
777
778     Object[][] currentData = ((FeatureTableModel) table.getModel())
779             .getData();
780     for (Object[] row : foundData)
781     {
782       String type = (String) row[TYPE_COLUMN];
783       boolean found = false;
784       for (Object[] current : currentData)
785       {
786         if (type.equals(current[TYPE_COLUMN]))
787         {
788           found = true;
789           /*
790            * currently dependent on object equality here;
791            * really need an equals method on FeatureColour
792            */
793           if (!row[COLOUR_COLUMN].equals(current[COLOUR_COLUMN]))
794           {
795             /*
796              * feature colour has changed externally - update originalData
797              */
798             for (Object[] original : originalData)
799             {
800               if (type.equals(original[TYPE_COLUMN]))
801               {
802                 original[COLOUR_COLUMN] = row[COLOUR_COLUMN];
803                 break;
804               }
805             }
806           }
807           break;
808         }
809       }
810       if (!found)
811       {
812         /*
813          * new feature detected - add to original data (on top)
814          */
815         Object[][] newData = new Object[originalData.length
816                 + 1][COLUMN_COUNT];
817         for (int i = 0; i < originalData.length; i++)
818         {
819           System.arraycopy(originalData[i], 0, newData[i + 1], 0,
820                   COLUMN_COUNT);
821         }
822         newData[0] = row;
823         originalData = newData;
824       }
825     }
826   }
827
828   /**
829    * Remove from the groups panel any checkboxes for groups that are not in the
830    * foundGroups set. This enables removing a group from the display when the last
831    * feature in that group is deleted.
832    * 
833    * @param foundGroups
834    */
835   protected void pruneGroups(Set<String> foundGroups)
836   {
837     for (int g = 0; g < groupPanel.getComponentCount(); g++)
838     {
839       JCheckBox checkbox = (JCheckBox) groupPanel.getComponent(g);
840       if (!foundGroups.contains(checkbox.getText()))
841       {
842         groupPanel.remove(checkbox);
843       }
844     }
845   }
846
847   /**
848    * reorder data based on the featureRenderers global priority list.
849    * 
850    * @param data
851    */
852   private void ensureOrder(Object[][] data)
853   {
854     boolean sort = false;
855     float[] order = new float[data.length];
856     for (int i = 0; i < order.length; i++)
857     {
858       order[i] = fr.getOrder(data[i][0].toString());
859       if (order[i] < 0)
860       {
861         order[i] = fr.setOrder(data[i][0].toString(), i / order.length);
862       }
863       if (i > 1)
864       {
865         sort = sort || order[i - 1] > order[i];
866       }
867     }
868     if (sort)
869     {
870       jalview.util.QuickSort.sort(order, data);
871     }
872   }
873
874   /**
875    * Offers a file chooser dialog, and then loads the feature colours and
876    * filters from file in XML format and unmarshals to Jalview feature settings
877    */
878   void load()
879   {
880     // TODO: JAL-3048 relies on Castor XML parsing: not needed for JS-jalview core
881     // functionalty
882
883     JalviewFileChooser chooser = new JalviewFileChooser("fc",
884             SEQUENCE_FEATURE_COLOURS);
885     chooser.setFileView(new JalviewFileView());
886     chooser.setDialogTitle(
887             MessageManager.getString("label.load_feature_colours"));
888     chooser.setToolTipText(MessageManager.getString("action.load"));
889
890     int value = chooser.showOpenDialog(this);
891
892     if (value == JalviewFileChooser.APPROVE_OPTION)
893     {
894       File file = chooser.getSelectedFile();
895       load(file);
896     }
897   }
898
899   /**
900    * Loads feature colours and filters from XML stored in the given file
901    * 
902    * @param file
903    */
904   void load(File file)
905   {
906     try
907     {
908       InputStreamReader in = new InputStreamReader(
909               new FileInputStream(file), "UTF-8");
910
911       JalviewUserColours jucs = JalviewUserColours.unmarshal(in);
912
913       /*
914        * load feature colours
915        */
916       for (int i = jucs.getColourCount() - 1; i >= 0; i--)
917       {
918         jalview.schemabinding.version2.Colour newcol = jucs.getColour(i);
919         FeatureColourI colour = Jalview2XML.unmarshalColour(newcol);
920         fr.setColour(newcol.getName(), colour);
921         fr.setOrder(newcol.getName(), i / (float) jucs.getColourCount());
922       }
923
924       /*
925        * load feature filters; loaded filters will replace any that are
926        * currently defined, other defined filters are left unchanged 
927        */
928       for (int i = 0; i < jucs.getFilterCount(); i++)
929       {
930         jalview.schemabinding.version2.Filter filterModel = jucs
931                 .getFilter(i);
932         String featureType = filterModel.getFeatureType();
933         FeatureMatcherSetI filter = Jalview2XML.unmarshalFilter(featureType,
934                 filterModel.getMatcherSet());
935         if (!filter.isEmpty())
936         {
937           fr.setFeatureFilter(featureType, filter);
938         }
939       }
940
941       /*
942        * update feature settings table
943        */
944       if (table != null)
945       {
946         resetTable(null);
947         Object[][] data = ((FeatureTableModel) table.getModel())
948                 .getData();
949         ensureOrder(data);
950         updateFeatureRenderer(data, false);
951         table.repaint();
952       }
953     } catch (Exception ex)
954     {
955       System.out.println("Error loading User Colour File\n" + ex);
956     }
957   }
958
959   /**
960    * Offers a file chooser dialog, and then saves the current feature colours
961    * and any filters to the selected file in XML format
962    */
963   void save()
964   {
965     // TODO: JAL-3048 not needed for Jalview-JS - save colours
966     JalviewFileChooser chooser = new JalviewFileChooser("fc",
967             SEQUENCE_FEATURE_COLOURS);
968     chooser.setFileView(new JalviewFileView());
969     chooser.setDialogTitle(
970             MessageManager.getString("label.save_feature_colours"));
971     chooser.setToolTipText(MessageManager.getString("action.save"));
972
973     int value = chooser.showSaveDialog(this);
974
975     if (value == JalviewFileChooser.APPROVE_OPTION)
976     {
977       save(chooser.getSelectedFile());
978     }
979   }
980
981   /**
982    * Saves feature colours and filters to the given file
983    * 
984    * @param file
985    */
986   void save(File file)
987   {
988     JalviewUserColours ucs = new JalviewUserColours();
989     ucs.setSchemeName("Sequence Features");
990     try
991     {
992       PrintWriter out = new PrintWriter(new OutputStreamWriter(
993               new FileOutputStream(file), "UTF-8"));
994
995       /*
996        * sort feature types by colour order, from 0 (highest)
997        * to 1 (lowest)
998        */
999       Set<String> fr_colours = fr.getAllFeatureColours();
1000       String[] sortedTypes = fr_colours
1001               .toArray(new String[fr_colours.size()]);
1002       Arrays.sort(sortedTypes, new Comparator<String>()
1003       {
1004         @Override
1005         public int compare(String type1, String type2)
1006         {
1007           return Float.compare(fr.getOrder(type1), fr.getOrder(type2));
1008         }
1009       });
1010
1011       /*
1012        * save feature colours
1013        */
1014       for (String featureType : sortedTypes)
1015       {
1016         FeatureColourI fcol = fr.getFeatureStyle(featureType);
1017         jalview.schemabinding.version2.Colour col = Jalview2XML.marshalColour(
1018                 featureType, fcol);
1019         ucs.addColour(col);
1020       }
1021
1022       /*
1023        * save any feature filters
1024        */
1025       for (String featureType : sortedTypes)
1026       {
1027         FeatureMatcherSetI filter = fr.getFeatureFilter(featureType);
1028         if (filter != null && !filter.isEmpty())
1029         {
1030           Iterator<FeatureMatcherI> iterator = filter.getMatchers().iterator();
1031           FeatureMatcherI firstMatcher = iterator.next();
1032           MatcherSet ms = Jalview2XML.marshalFilter(firstMatcher, iterator,
1033                   filter.isAnded());
1034           Filter filterModel = new Filter();
1035           filterModel.setFeatureType(featureType);
1036           filterModel.setMatcherSet(ms);
1037           ucs.addFilter(filterModel);
1038         }
1039       }
1040
1041       ucs.marshal(out);
1042       out.close();
1043     } catch (Exception ex)
1044     {
1045       ex.printStackTrace();
1046     }
1047   }
1048
1049   public void invertSelection()
1050   {
1051     Object[][] data = ((FeatureTableModel) table.getModel()).getData();
1052     for (int i = 0; i < data.length; i++)
1053     {
1054       data[i][SHOW_COLUMN] = !(Boolean) data[i][SHOW_COLUMN];
1055     }
1056     updateFeatureRenderer(data, true);
1057     table.repaint();
1058   }
1059
1060   public void orderByAvWidth()
1061   {
1062     if (table == null || table.getModel() == null)
1063     {
1064       return;
1065     }
1066     Object[][] data = ((FeatureTableModel) table.getModel()).getData();
1067     float[] width = new float[data.length];
1068     float[] awidth;
1069     float max = 0;
1070
1071     for (int i = 0; i < data.length; i++)
1072     {
1073       awidth = typeWidth.get(data[i][TYPE_COLUMN]);
1074       if (awidth[0] > 0)
1075       {
1076         width[i] = awidth[1] / awidth[0];// *awidth[0]*awidth[2]; - better
1077         // weight - but have to make per
1078         // sequence, too (awidth[2])
1079         // if (width[i]==1) // hack to distinguish single width sequences.
1080       }
1081       else
1082       {
1083         width[i] = 0;
1084       }
1085       if (max < width[i])
1086       {
1087         max = width[i];
1088       }
1089     }
1090     boolean sort = false;
1091     for (int i = 0; i < width.length; i++)
1092     {
1093       // awidth = (float[]) typeWidth.get(data[i][0]);
1094       if (width[i] == 0)
1095       {
1096         width[i] = fr.getOrder(data[i][TYPE_COLUMN].toString());
1097         if (width[i] < 0)
1098         {
1099           width[i] = fr.setOrder(data[i][TYPE_COLUMN].toString(),
1100                   i / data.length);
1101         }
1102       }
1103       else
1104       {
1105         width[i] /= max; // normalize
1106         fr.setOrder(data[i][TYPE_COLUMN].toString(), width[i]); // store for later
1107       }
1108       if (i > 0)
1109       {
1110         sort = sort || width[i - 1] > width[i];
1111       }
1112     }
1113     if (sort)
1114     {
1115       jalview.util.QuickSort.sort(width, data);
1116       // update global priority order
1117     }
1118
1119     updateFeatureRenderer(data, false);
1120     table.repaint();
1121   }
1122
1123   public void close()
1124   {
1125     try
1126     {
1127       frame.setClosed(true);
1128     } catch (Exception exe)
1129     {
1130     }
1131
1132   }
1133
1134   public void updateFeatureRenderer(Object[][] data)
1135   {
1136     updateFeatureRenderer(data, true);
1137   }
1138
1139   /**
1140    * Update the priority order of features; only repaint if this changed the order
1141    * of visible features
1142    * 
1143    * @param data
1144    * @param visibleNew
1145    */
1146   void updateFeatureRenderer(Object[][] data, boolean visibleNew)
1147   {
1148     FeatureSettingsBean[] rowData = getTableAsBeans(data);
1149
1150     if (fr.setFeaturePriority(rowData, visibleNew))
1151     {
1152       af.alignPanel.paintAlignment(true, true);
1153     }
1154   }
1155
1156   /**
1157    * Converts table data into an array of data beans
1158    */
1159   private FeatureSettingsBean[] getTableAsBeans(Object[][] data)
1160   {
1161     FeatureSettingsBean[] rowData = new FeatureSettingsBean[data.length];
1162     for (int i = 0; i < data.length; i++)
1163     {
1164       String type = (String) data[i][TYPE_COLUMN];
1165       FeatureColourI colour = (FeatureColourI) data[i][COLOUR_COLUMN];
1166       FeatureMatcherSetI theFilter = (FeatureMatcherSetI) data[i][FILTER_COLUMN];
1167       Boolean isShown = (Boolean) data[i][SHOW_COLUMN];
1168       rowData[i] = new FeatureSettingsBean(type, colour, theFilter,
1169               isShown);
1170     }
1171     return rowData;
1172   }
1173
1174   private void jbInit() throws Exception
1175   {
1176     this.setLayout(new BorderLayout());
1177
1178     JPanel settingsPane = new JPanel();
1179     settingsPane.setLayout(new BorderLayout());
1180
1181     JPanel bigPanel = new JPanel();
1182     bigPanel.setLayout(new BorderLayout());
1183
1184     groupPanel = new JPanel();
1185     bigPanel.add(groupPanel, BorderLayout.NORTH);
1186
1187     JButton invert = new JButton(
1188             MessageManager.getString("label.invert_selection"));
1189     invert.setFont(JvSwingUtils.getLabelFont());
1190     invert.addActionListener(new ActionListener()
1191     {
1192       @Override
1193       public void actionPerformed(ActionEvent e)
1194       {
1195         invertSelection();
1196       }
1197     });
1198
1199     JButton optimizeOrder = new JButton(
1200             MessageManager.getString("label.optimise_order"));
1201     optimizeOrder.setFont(JvSwingUtils.getLabelFont());
1202     optimizeOrder.addActionListener(new ActionListener()
1203     {
1204       @Override
1205       public void actionPerformed(ActionEvent e)
1206       {
1207         orderByAvWidth();
1208       }
1209     });
1210
1211     JButton sortByScore = new JButton(
1212             MessageManager.getString("label.seq_sort_by_score"));
1213     sortByScore.setFont(JvSwingUtils.getLabelFont());
1214     sortByScore.addActionListener(new ActionListener()
1215     {
1216       @Override
1217       public void actionPerformed(ActionEvent e)
1218       {
1219         af.avc.sortAlignmentByFeatureScore(null);
1220       }
1221     });
1222     JButton sortByDens = new JButton(
1223             MessageManager.getString("label.sequence_sort_by_density"));
1224     sortByDens.setFont(JvSwingUtils.getLabelFont());
1225     sortByDens.addActionListener(new ActionListener()
1226     {
1227       @Override
1228       public void actionPerformed(ActionEvent e)
1229       {
1230         af.avc.sortAlignmentByFeatureDensity(null);
1231       }
1232     });
1233
1234     JButton help = new JButton(MessageManager.getString("action.help"));
1235     help.setFont(JvSwingUtils.getLabelFont());
1236     help.addActionListener(new ActionListener()
1237     {
1238       @Override
1239       public void actionPerformed(ActionEvent e)
1240       {
1241         try
1242         {
1243           Help.showHelpWindow(HelpId.SequenceFeatureSettings);
1244         } catch (HelpSetException e1)
1245         {
1246           e1.printStackTrace();
1247         }
1248       }
1249     });
1250     help.setFont(JvSwingUtils.getLabelFont());
1251     help.setText(MessageManager.getString("action.help"));
1252     help.addActionListener(new ActionListener()
1253     {
1254       @Override
1255       public void actionPerformed(ActionEvent e)
1256       {
1257         try
1258         {
1259           Help.showHelpWindow(HelpId.SequenceFeatureSettings);
1260         } catch (HelpSetException e1)
1261         {
1262           e1.printStackTrace();
1263         }
1264       }
1265     });
1266
1267     JButton cancel = new JButton(MessageManager.getString("action.cancel"));
1268     cancel.setFont(JvSwingUtils.getLabelFont());
1269     cancel.addActionListener(new ActionListener()
1270     {
1271       @Override
1272       public void actionPerformed(ActionEvent e)
1273       {
1274         fr.setTransparency(originalTransparency);
1275         fr.setFeatureFilters(originalFilters);
1276         updateFeatureRenderer(originalData);
1277         close();
1278       }
1279     });
1280
1281     JButton ok = new JButton(MessageManager.getString("action.ok"));
1282     ok.setFont(JvSwingUtils.getLabelFont());
1283     ok.addActionListener(new ActionListener()
1284     {
1285       @Override
1286       public void actionPerformed(ActionEvent e)
1287       {
1288         close();
1289       }
1290     });
1291
1292     JButton loadColours = new JButton(
1293             MessageManager.getString("label.load_colours"));
1294     loadColours.setFont(JvSwingUtils.getLabelFont());
1295     loadColours.setToolTipText(
1296             MessageManager.getString("label.load_colours_tooltip"));
1297     loadColours.addActionListener(new ActionListener()
1298     {
1299       @Override
1300       public void actionPerformed(ActionEvent e)
1301       {
1302         load();
1303       }
1304     });
1305
1306     JButton saveColours = new JButton(
1307             MessageManager.getString("label.save_colours"));
1308     saveColours.setFont(JvSwingUtils.getLabelFont());
1309     saveColours.setToolTipText(
1310             MessageManager.getString("label.save_colours_tooltip"));
1311     saveColours.addActionListener(new ActionListener()
1312     {
1313       @Override
1314       public void actionPerformed(ActionEvent e)
1315       {
1316         save();
1317       }
1318     });
1319     transparency.addChangeListener(new ChangeListener()
1320     {
1321       @Override
1322       public void stateChanged(ChangeEvent evt)
1323       {
1324         if (!inConstruction)
1325         {
1326           fr.setTransparency((100 - transparency.getValue()) / 100f);
1327           af.alignPanel.paintAlignment(true, true);
1328         }
1329       }
1330     });
1331
1332     transparency.setMaximum(70);
1333     transparency.setToolTipText(
1334             MessageManager.getString("label.transparency_tip"));
1335
1336     JPanel transPanel = new JPanel(new GridLayout(1, 2));
1337     bigPanel.add(transPanel, BorderLayout.SOUTH);
1338
1339     JPanel transbuttons = new JPanel(new GridLayout(5, 1));
1340     transbuttons.add(optimizeOrder);
1341     transbuttons.add(invert);
1342     transbuttons.add(sortByScore);
1343     transbuttons.add(sortByDens);
1344     transbuttons.add(help);
1345     transPanel.add(transparency);
1346     transPanel.add(transbuttons);
1347
1348     JPanel buttonPanel = new JPanel();
1349     buttonPanel.add(ok);
1350     buttonPanel.add(cancel);
1351     buttonPanel.add(loadColours);
1352     buttonPanel.add(saveColours);
1353     bigPanel.add(scrollPane, BorderLayout.CENTER);
1354     settingsPane.add(bigPanel, BorderLayout.CENTER);
1355     settingsPane.add(buttonPanel, BorderLayout.SOUTH);
1356     this.add(settingsPane);
1357   }
1358
1359   /**
1360    * Answers a suitable tooltip to show on the colour cell of the table
1361    * 
1362    * @param fcol
1363    * @param withHint
1364    *          if true include 'click to edit' and similar text
1365    * @return
1366    */
1367   public static String getColorTooltip(FeatureColourI fcol,
1368           boolean withHint)
1369   {
1370     if (fcol == null)
1371     {
1372       return null;
1373     }
1374     if (fcol.isSimpleColour() && withHint)
1375     {
1376       return BASE_TOOLTIP;
1377     }
1378     String description = fcol.getDescription();
1379     description = description.replaceAll("<", "&lt;");
1380     description = description.replaceAll(">", "&gt;");
1381     StringBuilder tt = new StringBuilder(description);
1382     if (withHint)
1383     {
1384       tt.append("<br>").append(BASE_TOOLTIP).append("</br>");
1385     }
1386     return JvSwingUtils.wrapTooltip(true, tt.toString());
1387   }
1388
1389   public static void renderGraduatedColor(JLabel comp, FeatureColourI gcol,
1390           int w, int h)
1391   {
1392     boolean thr = false;
1393     StringBuilder tx = new StringBuilder();
1394   
1395     if (gcol.isColourByAttribute())
1396     {
1397       tx.append(FeatureMatcher
1398               .toAttributeDisplayName(gcol.getAttributeName()));
1399     }
1400     else if (!gcol.isColourByLabel())
1401     {
1402       tx.append(MessageManager.getString("label.score"));
1403     }
1404     tx.append(" ");
1405     if (gcol.isAboveThreshold())
1406     {
1407       thr = true;
1408       tx.append(">");
1409     }
1410     if (gcol.isBelowThreshold())
1411     {
1412       thr = true;
1413       tx.append("<");
1414     }
1415     if (gcol.isColourByLabel())
1416     {
1417       if (thr)
1418       {
1419         tx.append(" ");
1420       }
1421       if (!gcol.isColourByAttribute())
1422       {
1423         tx.append("Label");
1424       }
1425       comp.setIcon(null);
1426     }
1427     else
1428     {
1429       Color newColor = gcol.getMaxColour();
1430       comp.setBackground(newColor);
1431       // System.err.println("Width is " + w / 2);
1432       Icon ficon = new FeatureIcon(gcol, comp.getBackground(), w, h, thr);
1433       comp.setIcon(ficon);
1434       // tt+="RGB value: Max (" + newColor.getRed() + ", "
1435       // + newColor.getGreen() + ", " + newColor.getBlue()
1436       // + ")\nMin (" + minCol.getRed() + ", " + minCol.getGreen()
1437       // + ", " + minCol.getBlue() + ")");
1438     }
1439     comp.setHorizontalAlignment(SwingConstants.CENTER);
1440     comp.setText(tx.toString());
1441   }
1442
1443   // ///////////////////////////////////////////////////////////////////////
1444   // http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
1445   // ///////////////////////////////////////////////////////////////////////
1446   class FeatureTableModel extends AbstractTableModel
1447   {
1448     private String[] columnNames = {
1449         MessageManager.getString("label.feature_type"),
1450         MessageManager.getString("action.colour"),
1451         MessageManager.getString("label.filter"),
1452         MessageManager.getString("label.show") };
1453
1454     private Object[][] data;
1455
1456     FeatureTableModel(Object[][] data)
1457     {
1458       this.data = data;
1459     }
1460
1461     public Object[][] getData()
1462     {
1463       return data;
1464     }
1465
1466     public void setData(Object[][] data)
1467     {
1468       this.data = data;
1469     }
1470
1471     @Override
1472     public int getColumnCount()
1473     {
1474       return columnNames.length;
1475     }
1476
1477     public Object[] getRow(int row)
1478     {
1479       return data[row];
1480     }
1481
1482     @Override
1483     public int getRowCount()
1484     {
1485       return data.length;
1486     }
1487
1488     @Override
1489     public String getColumnName(int col)
1490     {
1491       return columnNames[col];
1492     }
1493
1494     @Override
1495     public Object getValueAt(int row, int col)
1496     {
1497       return data[row][col];
1498     }
1499
1500     /**
1501      * Answers the class of the object in column c of the first row of the table
1502      */
1503     @Override
1504     public Class<?> getColumnClass(int c)
1505     {
1506       Object v = getValueAt(0, c);
1507       return v == null ? null : v.getClass();
1508     }
1509
1510     @Override
1511     public boolean isCellEditable(int row, int col)
1512     {
1513       return col == 0 ? false : true;
1514     }
1515
1516     @Override
1517     public void setValueAt(Object value, int row, int col)
1518     {
1519       data[row][col] = value;
1520       fireTableCellUpdated(row, col);
1521       updateFeatureRenderer(data);
1522     }
1523
1524   }
1525
1526   class ColorRenderer extends JLabel implements TableCellRenderer
1527   {
1528     Border unselectedBorder = null;
1529
1530     Border selectedBorder = null;
1531
1532     public ColorRenderer()
1533     {
1534       setOpaque(true); // MUST do this for background to show up.
1535       setHorizontalTextPosition(SwingConstants.CENTER);
1536       setVerticalTextPosition(SwingConstants.CENTER);
1537     }
1538
1539     @Override
1540     public Component getTableCellRendererComponent(JTable tbl, Object color,
1541             boolean isSelected, boolean hasFocus, int row, int column)
1542     {
1543       FeatureColourI cellColour = (FeatureColourI) color;
1544       setOpaque(true);
1545       setBackground(tbl.getBackground());
1546       if (!cellColour.isSimpleColour())
1547       {
1548         Rectangle cr = tbl.getCellRect(row, column, false);
1549         FeatureSettings.renderGraduatedColor(this, cellColour,
1550                 (int) cr.getWidth(), (int) cr.getHeight());
1551       }
1552       else
1553       {
1554         this.setText("");
1555         this.setIcon(null);
1556         setBackground(cellColour.getColour());
1557       }
1558       if (isSelected)
1559       {
1560         if (selectedBorder == null)
1561         {
1562           selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
1563                   tbl.getSelectionBackground());
1564         }
1565         setBorder(selectedBorder);
1566       }
1567       else
1568       {
1569         if (unselectedBorder == null)
1570         {
1571           unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
1572                   tbl.getBackground());
1573         }
1574         setBorder(unselectedBorder);
1575       }
1576
1577       return this;
1578     }
1579   }
1580
1581   class FilterRenderer extends JLabel implements TableCellRenderer
1582   {
1583     javax.swing.border.Border unselectedBorder = null;
1584
1585     javax.swing.border.Border selectedBorder = null;
1586
1587     public FilterRenderer()
1588     {
1589       setOpaque(true); // MUST do this for background to show up.
1590       setHorizontalTextPosition(SwingConstants.CENTER);
1591       setVerticalTextPosition(SwingConstants.CENTER);
1592     }
1593
1594     @Override
1595     public Component getTableCellRendererComponent(JTable tbl,
1596             Object filter, boolean isSelected, boolean hasFocus, int row,
1597             int column)
1598     {
1599       FeatureMatcherSetI theFilter = (FeatureMatcherSetI) filter;
1600       setOpaque(true);
1601       String asText = theFilter.toString();
1602       setBackground(tbl.getBackground());
1603       this.setText(asText);
1604       this.setIcon(null);
1605
1606       if (isSelected)
1607       {
1608         if (selectedBorder == null)
1609         {
1610           selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
1611                   tbl.getSelectionBackground());
1612         }
1613         setBorder(selectedBorder);
1614       }
1615       else
1616       {
1617         if (unselectedBorder == null)
1618         {
1619           unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
1620                   tbl.getBackground());
1621         }
1622         setBorder(unselectedBorder);
1623       }
1624
1625       return this;
1626     }
1627   }
1628
1629   /**
1630    * update comp using rendering settings from gcol
1631    * 
1632    * @param comp
1633    * @param gcol
1634    */
1635   public static void renderGraduatedColor(JLabel comp, FeatureColourI gcol)
1636   {
1637     int w = comp.getWidth(), h = comp.getHeight();
1638     if (w < 20)
1639     {
1640       w = (int) comp.getPreferredSize().getWidth();
1641       h = (int) comp.getPreferredSize().getHeight();
1642       if (w < 20)
1643       {
1644         w = 80;
1645         h = 12;
1646       }
1647     }
1648     renderGraduatedColor(comp, gcol, w, h);
1649   }
1650
1651   class ColorEditor extends AbstractCellEditor
1652           implements TableCellEditor, ActionListener
1653   {
1654     FeatureSettings me;
1655
1656     FeatureColourI currentColor;
1657
1658     FeatureTypeSettings chooser;
1659
1660     String type;
1661
1662     JButton button;
1663
1664     protected static final String EDIT = "edit";
1665
1666     int rowSelected = 0;
1667
1668     public ColorEditor(FeatureSettings fs)
1669     {
1670       this.me = fs;
1671       // Set up the editor (from the table's point of view),
1672       // which is a button.
1673       // This button brings up the color chooser dialog,
1674       // which is the editor from the user's point of view.
1675       button = new JButton();
1676       button.setActionCommand(EDIT);
1677       button.addActionListener(this);
1678       button.setBorderPainted(false);
1679     }
1680
1681     /**
1682      * Handles events from the editor button, and from the colour/filters
1683      * dialog's OK button
1684      */
1685     @Override
1686     public void actionPerformed(ActionEvent e)
1687     {
1688       if (button == e.getSource())
1689       {
1690         if (currentColor.isSimpleColour())
1691         {
1692           /*
1693            * simple colour chooser
1694            */
1695           String ttl = MessageManager.getString("label.select_colour");
1696           ColourChooserListener listener = new ColourChooserListener() {
1697             @Override
1698             public void colourSelected(Color c)
1699             {
1700               currentColor = new FeatureColour(c);
1701               me.table.setValueAt(currentColor, rowSelected, COLOUR_COLUMN);
1702             }
1703           };
1704           JalviewColourChooser.showColourChooser(button,  ttl,  currentColor.getColour(), listener);
1705         }
1706         else
1707         {
1708           /*
1709            * variable colour and filters dialog
1710            */
1711           chooser = new FeatureTypeSettings(me.fr, type);
1712           /**
1713            * @j2sNative
1714            */
1715           {
1716             chooser.setRequestFocusEnabled(true);
1717             chooser.requestFocus();
1718           }
1719           chooser.addActionListener(this);
1720           // Make the renderer reappear.
1721           fireEditingStopped();
1722         }
1723       }
1724       else
1725       {
1726         /*
1727          * after OK in variable colour dialog, any changes to colour 
1728          * (or filters!) are already set in FeatureRenderer, so just
1729          * update table data without triggering updateFeatureRenderer
1730          */
1731         currentColor = fr.getFeatureColours().get(type);
1732         FeatureMatcherSetI currentFilter = me.fr.getFeatureFilter(type);
1733         if (currentFilter == null)
1734         {
1735           currentFilter = new FeatureMatcherSet();
1736         }
1737         Object[] data = ((FeatureTableModel) table.getModel())
1738                 .getData()[rowSelected];
1739         data[COLOUR_COLUMN] = currentColor;
1740         data[FILTER_COLUMN] = currentFilter;
1741
1742         fireEditingStopped();
1743         me.table.validate();
1744       }
1745     }
1746
1747     // Implement the one CellEditor method that AbstractCellEditor doesn't.
1748     @Override
1749     public Object getCellEditorValue()
1750     {
1751       return currentColor;
1752     }
1753
1754     // Implement the one method defined by TableCellEditor.
1755     @Override
1756     public Component getTableCellEditorComponent(JTable theTable, Object value,
1757             boolean isSelected, int row, int column)
1758     {
1759       currentColor = (FeatureColourI) value;
1760       this.rowSelected = row;
1761       type = me.table.getValueAt(row, TYPE_COLUMN).toString();
1762       button.setOpaque(true);
1763       button.setBackground(me.getBackground());
1764       if (!currentColor.isSimpleColour())
1765       {
1766         JLabel btn = new JLabel();
1767         btn.setSize(button.getSize());
1768         FeatureSettings.renderGraduatedColor(btn, currentColor);
1769         button.setBackground(btn.getBackground());
1770         button.setIcon(btn.getIcon());
1771         button.setText(btn.getText());
1772       }
1773       else
1774       {
1775         button.setText("");
1776         button.setIcon(null);
1777         button.setBackground(currentColor.getColour());
1778       }
1779       return button;
1780     }
1781   }
1782
1783   /**
1784    * The cell editor for the Filter column. It displays the text of any filters
1785    * for the feature type in that row (in full as a tooltip, possible abbreviated
1786    * as display text). On click in the cell, opens the Feature Display Settings
1787    * dialog at the Filters tab.
1788    */
1789   class FilterEditor extends AbstractCellEditor
1790           implements TableCellEditor, ActionListener
1791   {
1792     FeatureSettings me;
1793
1794     FeatureMatcherSetI currentFilter;
1795
1796     Point lastLocation;
1797
1798     String type;
1799
1800     JButton button;
1801
1802     protected static final String EDIT = "edit";
1803
1804     int rowSelected = 0;
1805
1806     public FilterEditor(FeatureSettings me)
1807     {
1808       this.me = me;
1809       button = new JButton();
1810       button.setActionCommand(EDIT);
1811       button.addActionListener(this);
1812       button.setBorderPainted(false);
1813     }
1814
1815     /**
1816      * Handles events from the editor button
1817      */
1818     @Override
1819     public void actionPerformed(ActionEvent e)
1820     {
1821       if (button == e.getSource())
1822       {
1823         FeatureTypeSettings chooser = new FeatureTypeSettings(me.fr, type);
1824         chooser.addActionListener(this);
1825         chooser.setRequestFocusEnabled(true);
1826         chooser.requestFocus();
1827         if (lastLocation != null)
1828         {
1829           // todo open at its last position on screen
1830           chooser.setBounds(lastLocation.x, lastLocation.y,
1831                   chooser.getWidth(), chooser.getHeight());
1832           chooser.validate();
1833         }
1834         fireEditingStopped();
1835       }
1836       else if (e.getSource() instanceof Component)
1837       {
1838
1839         /*
1840          * after OK in variable colour dialog, any changes to filter
1841          * (or colours!) are already set in FeatureRenderer, so just
1842          * update table data without triggering updateFeatureRenderer
1843          */
1844         FeatureColourI currentColor = fr.getFeatureColours().get(type);
1845         currentFilter = me.fr.getFeatureFilter(type);
1846         if (currentFilter == null)
1847         {
1848           currentFilter = new FeatureMatcherSet();
1849         }
1850         Object[] data = ((FeatureTableModel) table.getModel())
1851                 .getData()[rowSelected];
1852         data[COLOUR_COLUMN] = currentColor;
1853         data[FILTER_COLUMN] = currentFilter;
1854         fireEditingStopped();
1855         me.table.validate();
1856       }
1857     }
1858
1859     @Override
1860     public Object getCellEditorValue()
1861     {
1862       return currentFilter;
1863     }
1864
1865     @Override
1866     public Component getTableCellEditorComponent(JTable theTable, Object value,
1867             boolean isSelected, int row, int column)
1868     {
1869       currentFilter = (FeatureMatcherSetI) value;
1870       this.rowSelected = row;
1871       type = me.table.getValueAt(row, TYPE_COLUMN).toString();
1872       button.setOpaque(true);
1873       button.setBackground(me.getBackground());
1874       button.setText(currentFilter.toString());
1875       button.setIcon(null);
1876       return button;
1877     }
1878   }
1879 }
1880
1881 class FeatureIcon implements Icon
1882 {
1883   FeatureColourI gcol;
1884
1885   Color backg;
1886
1887   boolean midspace = false;
1888
1889   int width = 50, height = 20;
1890
1891   int s1, e1; // start and end of midpoint band for thresholded symbol
1892
1893   Color mpcolour = Color.white;
1894
1895   FeatureIcon(FeatureColourI gfc, Color bg, int w, int h, boolean mspace)
1896   {
1897     gcol = gfc;
1898     backg = bg;
1899     width = w;
1900     height = h;
1901     midspace = mspace;
1902     if (midspace)
1903     {
1904       s1 = width / 3;
1905       e1 = s1 * 2;
1906     }
1907     else
1908     {
1909       s1 = width / 2;
1910       e1 = s1;
1911     }
1912   }
1913
1914   @Override
1915   public int getIconWidth()
1916   {
1917     return width;
1918   }
1919
1920   @Override
1921   public int getIconHeight()
1922   {
1923     return height;
1924   }
1925
1926   @Override
1927   public void paintIcon(Component c, Graphics g, int x, int y)
1928   {
1929
1930     if (gcol.isColourByLabel())
1931     {
1932       g.setColor(backg);
1933       g.fillRect(0, 0, width, height);
1934       // need an icon here.
1935       g.setColor(gcol.getMaxColour());
1936
1937       g.setFont(new Font("Verdana", Font.PLAIN, 9));
1938
1939       // g.setFont(g.getFont().deriveFont(
1940       // AffineTransform.getScaleInstance(
1941       // width/g.getFontMetrics().stringWidth("Label"),
1942       // height/g.getFontMetrics().getHeight())));
1943
1944       g.drawString(MessageManager.getString("label.label"), 0, 0);
1945
1946     }
1947     else
1948     {
1949       Color minCol = gcol.getMinColour();
1950       g.setColor(minCol);
1951       g.fillRect(0, 0, s1, height);
1952       if (midspace)
1953       {
1954         g.setColor(Color.white);
1955         g.fillRect(s1, 0, e1 - s1, height);
1956       }
1957       g.setColor(gcol.getMaxColour());
1958       g.fillRect(0, e1, width - e1, height);
1959     }
1960   }
1961 }