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