Debian Codegraph @

src/dr/app/treestat/TableSorter.java

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