Clover icon

Coverage Report

  1. Project Clover database Mon Nov 11 2024 16:01:40 GMT
  2. Package jalview.util

File TableSorter.java

 

Coverage histogram

../../img/srcFileCovDistChart0.png
59% of files have more coverage

Code metrics

78
163
40
7
617
437
83
0.51
4.07
5.71
2.08

Classes

Class Line # Actions
TableSorter 92 84 50
0.00%
TableSorter.Row 376 19 9
0.00%
TableSorter.TableModelHandler 425 16 7
0.00%
TableSorter.MouseHandler 489 11 4
0.00%
TableSorter.Arrow 515 23 9
0.00%
TableSorter.SortableHeaderRenderer 578 8 3
0.00%
TableSorter.Directive 605 2 1
0.00%
 

Contributing tests

No tests hitting this source file were found.

Source view

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.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  0 toggle public int compare(Object o1, Object o2)
107    {
108  0 return ((Comparable) o1).compareTo(o2);
109    }
110    };
111   
112    public static final Comparator LEXICAL_COMPARATOR = new Comparator()
113    {
 
114  0 toggle public int compare(Object o1, Object o2)
115    {
116  0 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  0 toggle public TableSorter()
135    {
136  0 this.mouseListener = new MouseHandler();
137  0 this.tableModelListener = new TableModelHandler();
138    }
139   
 
140  0 toggle public TableSorter(TableModel tableModel)
141    {
142  0 this();
143  0 setTableModel(tableModel);
144    }
145   
 
146  0 toggle public TableSorter(TableModel tableModel, JTableHeader tableHeader)
147    {
148  0 this();
149  0 setTableHeader(tableHeader);
150  0 setTableModel(tableModel);
151    }
152   
 
153  0 toggle private void clearSortingState()
154    {
155  0 viewToModel = null;
156  0 modelToView = null;
157    }
158   
 
159  0 toggle public TableModel getTableModel()
160    {
161  0 return tableModel;
162    }
163   
 
164  0 toggle public void setTableModel(TableModel tableModel)
165    {
166  0 if (this.tableModel != null)
167    {
168  0 this.tableModel.removeTableModelListener(tableModelListener);
169    }
170   
171  0 this.tableModel = tableModel;
172  0 if (this.tableModel != null)
173    {
174  0 this.tableModel.addTableModelListener(tableModelListener);
175    }
176   
177  0 clearSortingState();
178  0 fireTableStructureChanged();
179    }
180   
 
181  0 toggle public JTableHeader getTableHeader()
182    {
183  0 return tableHeader;
184    }
185   
 
186  0 toggle public void setTableHeader(JTableHeader tableHeader)
187    {
188  0 if (this.tableHeader != null)
189    {
190  0 this.tableHeader.removeMouseListener(mouseListener);
191  0 TableCellRenderer defaultRenderer = this.tableHeader
192    .getDefaultRenderer();
193  0 if (defaultRenderer instanceof SortableHeaderRenderer)
194    {
195  0 this.tableHeader.setDefaultRenderer(
196    ((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
197    }
198    }
199  0 this.tableHeader = tableHeader;
200  0 if (this.tableHeader != null)
201    {
202  0 this.tableHeader.addMouseListener(mouseListener);
203  0 this.tableHeader.setDefaultRenderer(new SortableHeaderRenderer(
204    this.tableHeader.getDefaultRenderer()));
205    }
206    }
207   
 
208  0 toggle public boolean isSorting()
209    {
210  0 return sortingColumns.size() != 0;
211    }
212   
 
213  0 toggle private Directive getDirective(int column)
214    {
215  0 for (int i = 0; i < sortingColumns.size(); i++)
216    {
217  0 Directive directive = (Directive) sortingColumns.get(i);
218  0 if (directive.column == column)
219    {
220  0 return directive;
221    }
222    }
223  0 return EMPTY_DIRECTIVE;
224    }
225   
 
226  0 toggle public int getSortingStatus(int column)
227    {
228  0 return getDirective(column).direction;
229    }
230   
 
231  0 toggle private void sortingStatusChanged()
232    {
233  0 clearSortingState();
234  0 fireTableDataChanged();
235  0 if (tableHeader != null)
236    {
237  0 tableHeader.repaint();
238    }
239    }
240   
 
241  0 toggle public void setSortingStatus(int column, int status)
242    {
243  0 Directive directive = getDirective(column);
244  0 if (directive != EMPTY_DIRECTIVE)
245    {
246  0 sortingColumns.remove(directive);
247    }
248  0 if (status != NOT_SORTED)
249    {
250  0 sortingColumns.add(new Directive(column, status));
251    }
252  0 sortingStatusChanged();
253    }
254   
 
255  0 toggle protected Icon getHeaderRendererIcon(int column, int size)
256    {
257  0 Directive directive = getDirective(column);
258  0 if (directive == EMPTY_DIRECTIVE)
259    {
260  0 return null;
261    }
262  0 return new Arrow(directive.direction == DESCENDING, size,
263    sortingColumns.indexOf(directive));
264    }
265   
 
266  0 toggle private void cancelSorting()
267    {
268  0 sortingColumns.clear();
269  0 sortingStatusChanged();
270    }
271   
 
272  0 toggle public void setColumnComparator(Class type, Comparator comparator)
273    {
274  0 if (comparator == null)
275    {
276  0 columnComparators.remove(type);
277    }
278    else
279    {
280  0 columnComparators.put(type, comparator);
281    }
282    }
283   
 
284  0 toggle protected Comparator getComparator(int column)
285    {
286  0 Class columnType = tableModel.getColumnClass(column);
287  0 Comparator comparator = (Comparator) columnComparators.get(columnType);
288  0 if (comparator != null)
289    {
290  0 return comparator;
291    }
292  0 if (Comparable.class.isAssignableFrom(columnType))
293    {
294  0 return COMPARABLE_COMAPRATOR;
295    }
296  0 return LEXICAL_COMPARATOR;
297    }
298   
 
299  0 toggle private Row[] getViewToModel()
300    {
301  0 if (viewToModel == null)
302    {
303  0 int tableModelRowCount = tableModel.getRowCount();
304  0 viewToModel = new Row[tableModelRowCount];
305  0 for (int row = 0; row < tableModelRowCount; row++)
306    {
307  0 viewToModel[row] = new Row(row);
308    }
309   
310  0 if (isSorting())
311    {
312  0 Arrays.sort(viewToModel);
313    }
314    }
315  0 return viewToModel;
316    }
317   
 
318  0 toggle public int modelIndex(int viewIndex)
319    {
320  0 return getViewToModel()[viewIndex].modelIndex;
321    }
322   
 
323  0 toggle private int[] getModelToView()
324    {
325  0 if (modelToView == null)
326    {
327  0 int n = getViewToModel().length;
328  0 modelToView = new int[n];
329  0 for (int i = 0; i < n; i++)
330    {
331  0 modelToView[modelIndex(i)] = i;
332    }
333    }
334  0 return modelToView;
335    }
336   
337    // TableModel interface methods
338   
 
339  0 toggle public int getRowCount()
340    {
341  0 return (tableModel == null) ? 0 : tableModel.getRowCount();
342    }
343   
 
344  0 toggle public int getColumnCount()
345    {
346  0 return (tableModel == null) ? 0 : tableModel.getColumnCount();
347    }
348   
 
349  0 toggle public String getColumnName(int column)
350    {
351  0 return tableModel.getColumnName(column);
352    }
353   
 
354  0 toggle public Class getColumnClass(int column)
355    {
356  0 return tableModel.getColumnClass(column);
357    }
358   
 
359  0 toggle public boolean isCellEditable(int row, int column)
360    {
361  0 return tableModel.isCellEditable(modelIndex(row), column);
362    }
363   
 
364  0 toggle public Object getValueAt(int row, int column)
365    {
366  0 return tableModel.getValueAt(modelIndex(row), column);
367    }
368   
 
369  0 toggle public void setValueAt(Object aValue, int row, int column)
370    {
371  0 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  0 toggle public Row(int index)
381    {
382  0 this.modelIndex = index;
383    }
384   
 
385  0 toggle public int compareTo(Object o)
386    {
387  0 int row1 = modelIndex;
388  0 int row2 = ((Row) o).modelIndex;
389   
390  0 for (Iterator it = sortingColumns.iterator(); it.hasNext();)
391    {
392  0 Directive directive = (Directive) it.next();
393  0 int column = directive.column;
394  0 Object o1 = tableModel.getValueAt(row1, column);
395  0 Object o2 = tableModel.getValueAt(row2, column);
396   
397  0 int comparison = 0;
398    // Define null less than everything, except null.
399  0 if (o1 == null && o2 == null)
400    {
401  0 comparison = 0;
402    }
403  0 else if (o1 == null)
404    {
405  0 comparison = -1;
406    }
407  0 else if (o2 == null)
408    {
409  0 comparison = 1;
410    }
411    else
412    {
413  0 comparison = getComparator(column).compare(o1, o2);
414    }
415  0 if (comparison != 0)
416    {
417  0 return directive.direction == DESCENDING ? -comparison
418    : comparison;
419    }
420    }
421  0 return 0;
422    }
423    }
424   
 
425    private class TableModelHandler implements TableModelListener
426    {
 
427  0 toggle public void tableChanged(TableModelEvent e)
428    {
429    // If we're not sorting by anything, just pass the event along.
430  0 if (!isSorting())
431    {
432  0 clearSortingState();
433  0 fireTableChanged(e);
434  0 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  0 if (e.getFirstRow() == TableModelEvent.HEADER_ROW)
441    {
442  0 cancelSorting();
443  0 fireTableChanged(e);
444  0 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  0 int column = e.getColumn();
470  0 if (e.getFirstRow() == e.getLastRow()
471    && column != TableModelEvent.ALL_COLUMNS
472    && getSortingStatus(column) == NOT_SORTED
473    && modelToView != null)
474    {
475  0 int viewIndex = getModelToView()[e.getFirstRow()];
476  0 fireTableChanged(new TableModelEvent(TableSorter.this, viewIndex,
477    viewIndex, column, e.getType()));
478  0 return;
479    }
480   
481    // Something has happened to the data that may have invalidated the row
482    // order.
483  0 clearSortingState();
484  0 fireTableDataChanged();
485  0 return;
486    }
487    }
488   
 
489    private class MouseHandler extends MouseAdapter
490    {
 
491  0 toggle public void mouseClicked(MouseEvent e)
492    {
493  0 JTableHeader h = (JTableHeader) e.getSource();
494  0 TableColumnModel columnModel = h.getColumnModel();
495  0 int viewColumn = columnModel.getColumnIndexAtX(e.getX());
496  0 int column = columnModel.getColumn(viewColumn).getModelIndex();
497  0 if (column != -1)
498    {
499  0 int status = getSortingStatus(column);
500  0 if (!e.isControlDown())
501    {
502  0 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  0 status = status + (e.isShiftDown() ? -1 : 1);
509  0 status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
510  0 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  0 toggle public Arrow(boolean descending, int size, int priority)
524    {
525  0 this.descending = descending;
526  0 this.size = size;
527  0 this.priority = priority;
528    }
529   
 
530  0 toggle public void paintIcon(Component c, Graphics g, int x, int y)
531    {
532  0 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  0 int dx = (int) (size / 2 * Math.pow(0.8, priority));
536  0 int dy = descending ? dx : -dx;
537    // Align icon (roughly) with font baseline.
538  0 y = y + 5 * size / 6 + (descending ? -dy : 0);
539  0 int shift = descending ? 1 : -1;
540  0 g.translate(x, y);
541   
542    // Right diagonal.
543  0 g.setColor(color.darker());
544  0 g.drawLine(dx / 2, dy, 0, 0);
545  0 g.drawLine(dx / 2, dy + shift, 0, shift);
546   
547    // Left diagonal.
548  0 g.setColor(color.brighter());
549  0 g.drawLine(dx / 2, dy, dx, 0);
550  0 g.drawLine(dx / 2, dy + shift, dx, shift);
551   
552    // Horizontal line.
553  0 if (descending)
554    {
555  0 g.setColor(color.darker().darker());
556    }
557    else
558    {
559  0 g.setColor(color.brighter().brighter());
560    }
561  0 g.drawLine(dx, 0, 0, 0);
562   
563  0 g.setColor(color);
564  0 g.translate(-x, -y);
565    }
566   
 
567  0 toggle public int getIconWidth()
568    {
569  0 return size;
570    }
571   
 
572  0 toggle public int getIconHeight()
573    {
574  0 return size;
575    }
576    }
577   
 
578    private class SortableHeaderRenderer implements TableCellRenderer
579    {
580    private TableCellRenderer tableCellRenderer;
581   
 
582  0 toggle public SortableHeaderRenderer(TableCellRenderer tableCellRenderer)
583    {
584  0 this.tableCellRenderer = tableCellRenderer;
585    }
586   
 
587  0 toggle public Component getTableCellRendererComponent(JTable table,
588    Object value, boolean isSelected, boolean hasFocus, int row,
589    int column)
590    {
591  0 Component c = tableCellRenderer.getTableCellRendererComponent(table,
592    value, isSelected, hasFocus, row, column);
593  0 if (c instanceof JLabel)
594    {
595  0 JLabel l = (JLabel) c;
596  0 l.setHorizontalTextPosition(JLabel.LEFT);
597  0 int modelColumn = table.convertColumnIndexToModel(column);
598  0 l.setIcon(
599    getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
600    }
601  0 return c;
602    }
603    }
604   
 
605    private static class Directive
606    {
607    private int column;
608   
609    private int direction;
610   
 
611  0 toggle public Directive(int column, int direction)
612    {
613  0 this.column = column;
614  0 this.direction = direction;
615    }
616    }
617    }