JAL-1645 Version-Rel Version 2.9 Year-Rel 2015 Licensing glob
[jalview.git] / src / jalview / util / TableSorter.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9)
3  * Copyright (C) 2015 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.util;
22
23 import java.awt.Color;
24 import java.awt.Component;
25 import java.awt.Graphics;
26 import java.awt.event.MouseAdapter;
27 import java.awt.event.MouseEvent;
28 import java.awt.event.MouseListener;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Comparator;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36
37 import javax.swing.Icon;
38 import javax.swing.JLabel;
39 import javax.swing.JTable;
40 import javax.swing.event.TableModelEvent;
41 import javax.swing.event.TableModelListener;
42 import javax.swing.table.AbstractTableModel;
43 import javax.swing.table.JTableHeader;
44 import javax.swing.table.TableCellRenderer;
45 import javax.swing.table.TableColumnModel;
46 import javax.swing.table.TableModel;
47
48 /**
49  * TableSorter is a decorator for TableModels; adding sorting functionality to a
50  * supplied TableModel. TableSorter does not store or copy the data in its
51  * TableModel; instead it maintains a map from the row indexes of the view to
52  * the row indexes of the model. As requests are made of the sorter (like
53  * getValueAt(row, col)) they are passed to the underlying model after the row
54  * numbers have been translated via the internal mapping array. This way, the
55  * TableSorter appears to hold another copy of the table with the rows in a
56  * different order.
57  * <p/>
58  * TableSorter registers itself as a listener to the underlying model, just as
59  * the JTable itself would. Events recieved from the model are examined,
60  * sometimes manipulated (typically widened), and then passed on to the
61  * TableSorter's listeners (typically the JTable). If a change to the model has
62  * invalidated the order of TableSorter's rows, a note of this is made and the
63  * sorter will resort the rows the next time a value is requested.
64  * <p/>
65  * When the tableHeader property is set, either by using the setTableHeader()
66  * method or the two argument constructor, the table header may be used as a
67  * complete UI for TableSorter. The default renderer of the tableHeader is
68  * decorated with a renderer that indicates the sorting status of each column.
69  * In addition, a mouse listener is installed with the following behavior:
70  * <ul>
71  * <li>Mouse-click: Clears the sorting status of all other columns and advances
72  * the sorting status of that column through three values: {NOT_SORTED,
73  * ASCENDING, DESCENDING} (then back to NOT_SORTED again).
74  * <li>SHIFT-mouse-click: Clears the sorting status of all other columns and
75  * cycles the sorting status of the column through the same three values, in the
76  * opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
77  * <li>CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except that
78  * the changes to the column do not cancel the statuses of columns that are
79  * already sorting - giving a way to initiate a compound sort.
80  * </ul>
81  * <p/>
82  * This is a long overdue rewrite of a class of the same name that first
83  * appeared in the swing table demos in 1997.
84  * 
85  * @author Philip Milne
86  * @author Brendon McLean
87  * @author Dan van Enckevort
88  * @author Parwinder Sekhon
89  * @version 2.0 02/27/04
90  */
91
92 public class TableSorter extends AbstractTableModel
93 {
94   protected TableModel tableModel;
95
96   public static final int DESCENDING = -1;
97
98   public static final int NOT_SORTED = 0;
99
100   public static final int ASCENDING = 1;
101
102   private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
103
104   public static final Comparator COMPARABLE_COMAPRATOR = new Comparator()
105   {
106     public int compare(Object o1, Object o2)
107     {
108       return ((Comparable) o1).compareTo(o2);
109     }
110   };
111
112   public static final Comparator LEXICAL_COMPARATOR = new Comparator()
113   {
114     public int compare(Object o1, Object o2)
115     {
116       return o1.toString().compareTo(o2.toString());
117     }
118   };
119
120   private Row[] viewToModel;
121
122   private int[] modelToView;
123
124   private JTableHeader tableHeader;
125
126   private MouseListener mouseListener;
127
128   private TableModelListener tableModelListener;
129
130   private Map columnComparators = new HashMap();
131
132   private List sortingColumns = new ArrayList();
133
134   public TableSorter()
135   {
136     this.mouseListener = new MouseHandler();
137     this.tableModelListener = new TableModelHandler();
138   }
139
140   public TableSorter(TableModel tableModel)
141   {
142     this();
143     setTableModel(tableModel);
144   }
145
146   public TableSorter(TableModel tableModel, JTableHeader tableHeader)
147   {
148     this();
149     setTableHeader(tableHeader);
150     setTableModel(tableModel);
151   }
152
153   private void clearSortingState()
154   {
155     viewToModel = null;
156     modelToView = null;
157   }
158
159   public TableModel getTableModel()
160   {
161     return tableModel;
162   }
163
164   public void setTableModel(TableModel tableModel)
165   {
166     if (this.tableModel != null)
167     {
168       this.tableModel.removeTableModelListener(tableModelListener);
169     }
170
171     this.tableModel = tableModel;
172     if (this.tableModel != null)
173     {
174       this.tableModel.addTableModelListener(tableModelListener);
175     }
176
177     clearSortingState();
178     fireTableStructureChanged();
179   }
180
181   public JTableHeader getTableHeader()
182   {
183     return tableHeader;
184   }
185
186   public void setTableHeader(JTableHeader tableHeader)
187   {
188     if (this.tableHeader != null)
189     {
190       this.tableHeader.removeMouseListener(mouseListener);
191       TableCellRenderer defaultRenderer = this.tableHeader
192               .getDefaultRenderer();
193       if (defaultRenderer instanceof SortableHeaderRenderer)
194       {
195         this.tableHeader
196                 .setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
197       }
198     }
199     this.tableHeader = tableHeader;
200     if (this.tableHeader != null)
201     {
202       this.tableHeader.addMouseListener(mouseListener);
203       this.tableHeader.setDefaultRenderer(new SortableHeaderRenderer(
204               this.tableHeader.getDefaultRenderer()));
205     }
206   }
207
208   public boolean isSorting()
209   {
210     return sortingColumns.size() != 0;
211   }
212
213   private Directive getDirective(int column)
214   {
215     for (int i = 0; i < sortingColumns.size(); i++)
216     {
217       Directive directive = (Directive) sortingColumns.get(i);
218       if (directive.column == column)
219       {
220         return directive;
221       }
222     }
223     return EMPTY_DIRECTIVE;
224   }
225
226   public int getSortingStatus(int column)
227   {
228     return getDirective(column).direction;
229   }
230
231   private void sortingStatusChanged()
232   {
233     clearSortingState();
234     fireTableDataChanged();
235     if (tableHeader != null)
236     {
237       tableHeader.repaint();
238     }
239   }
240
241   public void setSortingStatus(int column, int status)
242   {
243     Directive directive = getDirective(column);
244     if (directive != EMPTY_DIRECTIVE)
245     {
246       sortingColumns.remove(directive);
247     }
248     if (status != NOT_SORTED)
249     {
250       sortingColumns.add(new Directive(column, status));
251     }
252     sortingStatusChanged();
253   }
254
255   protected Icon getHeaderRendererIcon(int column, int size)
256   {
257     Directive directive = getDirective(column);
258     if (directive == EMPTY_DIRECTIVE)
259     {
260       return null;
261     }
262     return new Arrow(directive.direction == DESCENDING, size,
263             sortingColumns.indexOf(directive));
264   }
265
266   private void cancelSorting()
267   {
268     sortingColumns.clear();
269     sortingStatusChanged();
270   }
271
272   public void setColumnComparator(Class type, Comparator comparator)
273   {
274     if (comparator == null)
275     {
276       columnComparators.remove(type);
277     }
278     else
279     {
280       columnComparators.put(type, comparator);
281     }
282   }
283
284   protected Comparator getComparator(int column)
285   {
286     Class columnType = tableModel.getColumnClass(column);
287     Comparator comparator = (Comparator) columnComparators.get(columnType);
288     if (comparator != null)
289     {
290       return comparator;
291     }
292     if (Comparable.class.isAssignableFrom(columnType))
293     {
294       return COMPARABLE_COMAPRATOR;
295     }
296     return LEXICAL_COMPARATOR;
297   }
298
299   private Row[] getViewToModel()
300   {
301     if (viewToModel == null)
302     {
303       int tableModelRowCount = tableModel.getRowCount();
304       viewToModel = new Row[tableModelRowCount];
305       for (int row = 0; row < tableModelRowCount; row++)
306       {
307         viewToModel[row] = new Row(row);
308       }
309
310       if (isSorting())
311       {
312         Arrays.sort(viewToModel);
313       }
314     }
315     return viewToModel;
316   }
317
318   public int modelIndex(int viewIndex)
319   {
320     return getViewToModel()[viewIndex].modelIndex;
321   }
322
323   private int[] getModelToView()
324   {
325     if (modelToView == null)
326     {
327       int n = getViewToModel().length;
328       modelToView = new int[n];
329       for (int i = 0; i < n; i++)
330       {
331         modelToView[modelIndex(i)] = i;
332       }
333     }
334     return modelToView;
335   }
336
337   // TableModel interface methods
338
339   public int getRowCount()
340   {
341     return (tableModel == null) ? 0 : tableModel.getRowCount();
342   }
343
344   public int getColumnCount()
345   {
346     return (tableModel == null) ? 0 : tableModel.getColumnCount();
347   }
348
349   public String getColumnName(int column)
350   {
351     return tableModel.getColumnName(column);
352   }
353
354   public Class getColumnClass(int column)
355   {
356     return tableModel.getColumnClass(column);
357   }
358
359   public boolean isCellEditable(int row, int column)
360   {
361     return tableModel.isCellEditable(modelIndex(row), column);
362   }
363
364   public Object getValueAt(int row, int column)
365   {
366     return tableModel.getValueAt(modelIndex(row), column);
367   }
368
369   public void setValueAt(Object aValue, int row, int column)
370   {
371     tableModel.setValueAt(aValue, modelIndex(row), column);
372   }
373
374   // Helper classes
375
376   private class Row implements Comparable
377   {
378     private int modelIndex;
379
380     public Row(int index)
381     {
382       this.modelIndex = index;
383     }
384
385     public int compareTo(Object o)
386     {
387       int row1 = modelIndex;
388       int row2 = ((Row) o).modelIndex;
389
390       for (Iterator it = sortingColumns.iterator(); it.hasNext();)
391       {
392         Directive directive = (Directive) it.next();
393         int column = directive.column;
394         Object o1 = tableModel.getValueAt(row1, column);
395         Object o2 = tableModel.getValueAt(row2, column);
396
397         int comparison = 0;
398         // Define null less than everything, except null.
399         if (o1 == null && o2 == null)
400         {
401           comparison = 0;
402         }
403         else if (o1 == null)
404         {
405           comparison = -1;
406         }
407         else if (o2 == null)
408         {
409           comparison = 1;
410         }
411         else
412         {
413           comparison = getComparator(column).compare(o1, o2);
414         }
415         if (comparison != 0)
416         {
417           return directive.direction == DESCENDING ? -comparison
418                   : comparison;
419         }
420       }
421       return 0;
422     }
423   }
424
425   private class TableModelHandler implements TableModelListener
426   {
427     public void tableChanged(TableModelEvent e)
428     {
429       // If we're not sorting by anything, just pass the event along.
430       if (!isSorting())
431       {
432         clearSortingState();
433         fireTableChanged(e);
434         return;
435       }
436
437       // If the table structure has changed, cancel the sorting; the
438       // sorting columns may have been either moved or deleted from
439       // the model.
440       if (e.getFirstRow() == TableModelEvent.HEADER_ROW)
441       {
442         cancelSorting();
443         fireTableChanged(e);
444         return;
445       }
446
447       // We can map a cell event through to the view without widening
448       // when the following conditions apply:
449       //
450       // a) all the changes are on one row (e.getFirstRow() == e.getLastRow())
451       // and,
452       // b) all the changes are in one column (column !=
453       // TableModelEvent.ALL_COLUMNS) and,
454       // c) we are not sorting on that column (getSortingStatus(column) ==
455       // NOT_SORTED) and,
456       // d) a reverse lookup will not trigger a sort (modelToView != null)
457       //
458       // Note: INSERT and DELETE events fail this test as they have column ==
459       // ALL_COLUMNS.
460       //
461       // The last check, for (modelToView != null) is to see if modelToView
462       // is already allocated. If we don't do this check; sorting can become
463       // a performance bottleneck for applications where cells
464       // change rapidly in different parts of the table. If cells
465       // change alternately in the sorting column and then outside of
466       // it this class can end up re-sorting on alternate cell updates -
467       // which can be a performance problem for large tables. The last
468       // clause avoids this problem.
469       int column = e.getColumn();
470       if (e.getFirstRow() == e.getLastRow()
471               && column != TableModelEvent.ALL_COLUMNS
472               && getSortingStatus(column) == NOT_SORTED
473               && modelToView != null)
474       {
475         int viewIndex = getModelToView()[e.getFirstRow()];
476         fireTableChanged(new TableModelEvent(TableSorter.this, viewIndex,
477                 viewIndex, column, e.getType()));
478         return;
479       }
480
481       // Something has happened to the data that may have invalidated the row
482       // order.
483       clearSortingState();
484       fireTableDataChanged();
485       return;
486     }
487   }
488
489   private class MouseHandler extends MouseAdapter
490   {
491     public void mouseClicked(MouseEvent e)
492     {
493       JTableHeader h = (JTableHeader) e.getSource();
494       TableColumnModel columnModel = h.getColumnModel();
495       int viewColumn = columnModel.getColumnIndexAtX(e.getX());
496       int column = columnModel.getColumn(viewColumn).getModelIndex();
497       if (column != -1)
498       {
499         int status = getSortingStatus(column);
500         if (!e.isControlDown())
501         {
502           cancelSorting();
503         }
504         // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING}
505         // or
506         // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is
507         // pressed.
508         status = status + (e.isShiftDown() ? -1 : 1);
509         status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
510         setSortingStatus(column, status);
511       }
512     }
513   }
514
515   private static class Arrow implements Icon
516   {
517     private boolean descending;
518
519     private int size;
520
521     private int priority;
522
523     public Arrow(boolean descending, int size, int priority)
524     {
525       this.descending = descending;
526       this.size = size;
527       this.priority = priority;
528     }
529
530     public void paintIcon(Component c, Graphics g, int x, int y)
531     {
532       Color color = c == null ? Color.GRAY : c.getBackground();
533       // In a compound sort, make each succesive triangle 20%
534       // smaller than the previous one.
535       int dx = (int) (size / 2 * Math.pow(0.8, priority));
536       int dy = descending ? dx : -dx;
537       // Align icon (roughly) with font baseline.
538       y = y + 5 * size / 6 + (descending ? -dy : 0);
539       int shift = descending ? 1 : -1;
540       g.translate(x, y);
541
542       // Right diagonal.
543       g.setColor(color.darker());
544       g.drawLine(dx / 2, dy, 0, 0);
545       g.drawLine(dx / 2, dy + shift, 0, shift);
546
547       // Left diagonal.
548       g.setColor(color.brighter());
549       g.drawLine(dx / 2, dy, dx, 0);
550       g.drawLine(dx / 2, dy + shift, dx, shift);
551
552       // Horizontal line.
553       if (descending)
554       {
555         g.setColor(color.darker().darker());
556       }
557       else
558       {
559         g.setColor(color.brighter().brighter());
560       }
561       g.drawLine(dx, 0, 0, 0);
562
563       g.setColor(color);
564       g.translate(-x, -y);
565     }
566
567     public int getIconWidth()
568     {
569       return size;
570     }
571
572     public int getIconHeight()
573     {
574       return size;
575     }
576   }
577
578   private class SortableHeaderRenderer implements TableCellRenderer
579   {
580     private TableCellRenderer tableCellRenderer;
581
582     public SortableHeaderRenderer(TableCellRenderer tableCellRenderer)
583     {
584       this.tableCellRenderer = tableCellRenderer;
585     }
586
587     public Component getTableCellRendererComponent(JTable table,
588             Object value, boolean isSelected, boolean hasFocus, int row,
589             int column)
590     {
591       Component c = tableCellRenderer.getTableCellRendererComponent(table,
592               value, isSelected, hasFocus, row, column);
593       if (c instanceof JLabel)
594       {
595         JLabel l = (JLabel) c;
596         l.setHorizontalTextPosition(JLabel.LEFT);
597         int modelColumn = table.convertColumnIndexToModel(column);
598         l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
599       }
600       return c;
601     }
602   }
603
604   private static class Directive
605   {
606     private int column;
607
608     private int direction;
609
610     public Directive(int column, int direction)
611     {
612       this.column = column;
613       this.direction = direction;
614     }
615   }
616 }