001 package net.sourceforge.mp3dings;
002
003 /*
004 * Mp3dings - manage mp3 meta-information
005 * Copyright (C) 2003 Moritz Ringler
006 * $Id: AbstractTableModel.java 119 2007-11-23 18:36:15Z ringler $
007 *
008 * This program is free software; you can redistribute it and/or
009 * modify it under the terms of the GNU General Public License
010 * as published by the Free Software Foundation; either version 2
011 * of the License, or (at your option) any later version.
012 *
013 * This program is distributed in the hope that it will be useful,
014 * but WITHOUT ANY WARRANTY; without even the implied warranty of
015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
016 * GNU General Public License for more details.
017 *
018 * You should have received a copy of the GNU General Public License
019 * along with this program; if not, write to the Free Software
020 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
021 */
022 import java.awt.Component;
023 import java.awt.event.ActionEvent;
024 import java.awt.event.ActionListener;
025 import java.awt.event.MouseEvent;
026 import java.awt.EventQueue;
027 import java.awt.Frame;
028 import java.awt.Point;
029 import java.io.File;
030 import java.lang.reflect.Constructor;
031 import java.util.Arrays;
032 import java.util.HashMap;
033 import java.util.Map;
034 import java.util.prefs.PreferenceChangeEvent;
035 import java.util.prefs.PreferenceChangeListener;
036 import java.util.prefs.Preferences;
037 import java.util.TreeMap;
038 import java.util.ArrayList;
039 import java.util.List;
040 import javax.swing.event.TableModelEvent;
041 import javax.swing.JMenuItem;
042 import javax.swing.JOptionPane;
043 import javax.swing.JPopupMenu;
044 import javax.swing.JTable;
045 import javax.swing.SwingUtilities;
046 import javax.swing.table.JTableHeader;
047 import de.mospace.lang.Array;
048 import de.mospace.lang.FullTextString;
049 import net.sourceforge.mp3dings.filter.FilterCollection;
050 import net.sourceforge.mp3dings.preferences.FieldFilterEditor;
051 import net.sourceforge.mp3dings.preferences.FilteredField;
052 import de.mospace.swing.event.Aggregator;
053 import de.mospace.swing.event.DataChangeEvent;
054 import de.mospace.swing.event.DataChangeListener;
055 import de.mospace.swing.event.MessageEvent;
056 import de.mospace.swing.event.MessageListener;
057 import de.mospace.swing.table.SortableTableModel;
058 import de.mospace.swing.table.TableSorter;
059
060 /**
061 * Aspects of the implementation of an Mp3dingsTableModel that are shared by all
062 * mp3dings tables.
063 *
064 * @author Moritz Ringler
065 */
066 public abstract class AbstractTableModel extends javax.swing.table.AbstractTableModel
067 implements Mp3dingsTableModel {
068 private int[] rowForEntry, entryForRow;
069 //sort forward and backward
070 private int dataLength;
071 Field[] fields;
072 private Map columns = new HashMap();
073 private transient int changeCount = 0;
074 private int changedWarnLevel;
075 private boolean sorted = false;
076 /** The filters acting on the fields in this table. */
077 protected FilterCollection filters;
078 /** This aggregator aggregates preference change events and updates
079 this table model on the awt event thread. */
080 protected final static Aggregator aggregator = new Aggregator(500L, false);
081
082 /**
083 * The current sorting parameters.
084 * sortOrder[n][0] is the column number sortOrder[n][1] is DESCENDING or
085 * ASCENDING. sortOrder[0] has the highest precedence and so on
086 */
087 private int[][] sortOrder;
088 private Preferences prefs;
089 private DataChangeListener changeCounter;
090
091 /*
092 * EVENT GENERATION AND LISTENER MANAGEMENT
093 */
094 /*
095 * message events and listeners
096 */
097 MessageEvent messageEvent = null;
098
099 DataChangeEvent dataChange = null;
100
101
102 /** Constructs a new AbstractTableModel. */
103 public AbstractTableModel() { }
104
105
106 abstract List getData();
107
108
109 /** Returns a popup menu that allows to configure the filters acting on
110 * a specific column in this model.
111 * If the mouse event occured on the column header of a table
112 * that gets its data from this model then this method will return a
113 * popup menu that allows to configure the filters
114 * acting on that column.
115 *
116 * @param e a mouse click on the column header of a table
117 * displaying this model
118 * @return The popup menu that allows to configure filters or
119 * <code>null</code> if <code>e</code> is not the right
120 * kind of event.
121 *
122 * @see #getHeaderPopup(MouseEvent)
123 */
124 public JPopupMenu getFilterEditPopup(MouseEvent e) {
125 JPopupMenu filterEditPopup = null;
126 if (e.getSource() instanceof JTableHeader) {
127 final JTable activeTable = ((JTableHeader) e.getSource()).getTable();
128 if(activeTable.getModel() != this){
129 return null;
130 }
131 Point mouseXY = e.getPoint();
132 final int mouseCol = activeTable.columnAtPoint(mouseXY);
133 if(mouseCol != -1){
134 Field field = getField(mouseCol);
135 filterEditPopup = getFilterEditPopup(e, field);
136 }
137 }
138 return filterEditPopup;
139 }
140
141
142 /** Returns a popup menu that allows to configure the filters acting on
143 * a specific field in this model.
144 * If the mouse event occured on the column header of an Mp3dingsTable
145 * that gets its data from this model then this method will return a
146 * popup menu that allows to configure the filters
147 * acting on that column. <em>You should usually not call this method
148 * directly, use {@link #getFilterEditPopup(MouseEvent)} instead.</em>
149 *
150 * @param evt the mouse event that triggered the popup
151 * @param field the field whose filters will be edited
152 * @return a new popup menu for editing field filters
153 *
154 * @see #getFilterEditPopup(MouseEvent)
155 */
156 protected JPopupMenu getFilterEditPopup(MouseEvent evt, final Field field) {
157 JPopupMenu filterEditPopup = new JPopupMenu();
158 JMenuItem jmi = new JMenuItem(Globals.getString("EDIT_FILTERS"));
159 Point mouseXY = evt.getPoint();
160 final FilteredField ff = filters.getFilteredField(field);
161 SwingUtilities.convertPointToScreen(mouseXY, (Component) evt.getSource());
162 final Point mousePoint = mouseXY;
163 jmi.addActionListener(
164 new ActionListener() {
165 public void actionPerformed(ActionEvent e) {
166 boolean wasFiltered = ff.isFiltered();
167 FieldFilterEditor ffe =
168 new FieldFilterEditor(
169 (Component) e.getSource(),
170 filters.getFilterSet());
171 Object[] result = ffe.showDialog(ff, mousePoint);
172 if (result != null) {
173 ff.setFilters(Arrays.asList(result));
174 /*
175 * filters will also be updated via the
176 * pref change listener and buildFilters.
177 * But this might be later than the isFiltered()
178 * request by the Mp3dingsTable when repainting the
179 * header, therefore we need to do a preliminary update
180 * here.
181 */
182 filters.setFilteredField(field, ff);
183 ff.save(getPrefs().node("filters"));
184 if (wasFiltered != ff.isFiltered()) {
185 /*
186 * Tell the Mp3dingsTable that we have updated
187 * the header cell and need to repaint it
188 */
189 fireTableChanged(new TableModelEvent(
190 AbstractTableModel.this,
191 TableModelEvent.HEADER_ROW,
192 TableModelEvent.HEADER_ROW,
193 getColumn(field)));
194 }
195 }
196 }
197 });
198 filterEditPopup.add(jmi);
199 return filterEditPopup;
200 }
201
202
203 /*
204 * IMPLEMENTATION OF TABLE MODEL
205 */
206 /**
207 * Gets the name of the specified column.
208 *
209 * @param col a column in this table model
210 * @return the name of the column
211 */
212 public String getColumnName(int col) {
213 return fields[col].longname();
214 }
215
216
217 /**
218 * Gets the number of columns in this model.
219 *
220 * @return the number of columns in this model.
221 */
222 public int getColumnCount() {
223 return fields.length;
224 }
225
226
227 /**
228 * Gets the class of objects in the specified column.
229 *
230 * @param c a column
231 * @return the class of the column
232 */
233 public Class getColumnClass(int c) {
234 return getField(c).typeAsClass();
235 }
236
237
238 /**
239 * Returns whether the specified field can be edited in this
240 * model. This method can either return true or false for
241 * fields that are not currently included in this model, but it
242 * must not throw an exception for non-null arguments.
243 *
244 * @param field a field that can be displayed by this model
245 * @return whether the field can be edited
246 *
247 * @throws RuntimeException this method can throw a
248 * runtime exception if <code>field</code> is <code>null</code>.
249 *
250 * @see #isCellEditable
251 */
252 public abstract boolean getEditable(Field field);
253
254
255 /** Returns whether the specified table cell can be edited.
256 * @param row the row of the cell
257 * @param c the column of the cell
258 * @return whether the specified cell is editable
259 * @throws RuntimeException this method can throw a
260 * runtime exception if c is not a valid column number *
261 */
262 public boolean isCellEditable(int row, int c) {
263 return getEditable(getField(c));
264 }
265
266
267 /**
268 * Gets the value of the specified table cell.
269 *
270 * @param row the row of the cell
271 * @param c the column of the cell
272 * @return the value of the cell
273 */
274 public Object getValueAt(int row, int c) {
275 int entry = getEntries(row);
276 Object result = getData(entry)[c];
277 if (getColumnClass(c) == Number.class &&
278 String.valueOf(result).equals("")) {
279 return null;
280 }
281 assert(result == null || getColumnClass(c).isInstance(result));
282 return result;
283 }
284
285
286 /**
287 * Gets the value of the specified table cell, converting FullTextString
288 * values to strings on the fly.
289 *
290 * @param row the row of the cell
291 * @param c the column of the cell
292 * @return the value of the cell
293 */
294 public Object get(int row, int c) {
295 Object result = getValueAt(row, c);
296 return (result instanceof FullTextString) ? result.toString() : result;
297 }
298
299
300 /** Updates the value of the specified table cell and notifies
301 * tables displaying this model of the change in the data.<p>
302 * <em>This method must only be called from the AWT event dispatching
303 * thread, use {@link #set(Object, int, int)} if you want to update the
304 * table from another thread.</em>
305 *
306 * @param row the row of the cell
307 * @param c the column of the cell
308 * @param v the new value of the cell
309 */
310 public void setValueAt(Object v, int row, int c) {
311 set(v, row, c);
312 fireDataChanged();
313 fireTableCellUpdated(row, c);
314 }
315
316
317 /**
318 * Updates a range of cells and notifies
319 * tables displaying this model of the change in the data.
320 * This is faster than calling {@link #setValueAt(Object, int,
321 * int)} for each cell.<p>
322 * <em>This method must only be called from the AWT event dispatching
323 * thread, use {@link #set(Object, int[], int[])} if you want to update the
324 * table from another thread.</em>
325 *
326 * @param rows the rows of the cells
327 * @param cols the columns of the cells
328 * @param v the new value of the cells
329 */
330 public void setValueAt(Object v, int[] rows, int[] cols) {
331 set(v, rows, cols);
332 fireDataChanged(rows.length * cols.length);
333 fireTableDataChanged();
334 }
335
336
337 /** Updates the value of the specified table cell without firing any
338 * events. If you want a table displaying this model to reflect the change
339 * in the data you must explicitly ask it to do so.
340 *
341 * @param row the row of the cell
342 * @param c the column of the cell
343 * @param v the new value of the cell
344 *
345 * @see #setValueAt(Object, int, int)
346 */
347 public void set(Object v, int row, int c) {
348 int entry = getEntries(row);
349 getData(entry)[c] = makeValue(v, getColumnClass(c));
350 }
351
352
353 /**
354 * Updates a range of cells without firing any
355 * events. If you want a table displaying this model to reflect the change
356 * in the data you must explicitly ask it to do so.
357 *
358 * @param rows the rows of the cells
359 * @param cols the columns of the cells
360 * @param v the new value of the cells
361 *
362 * @see #setValueAt(Object, int[], int[])
363 */
364 public void set(Object v, int[] rows, int[] cols) {
365 int[] entries = getEntries(rows);
366 java.util.Arrays.sort(entries);
367 final int max = getData().size();
368 final int nc = cols.length;
369 final int nr = entries.length;
370 for (int j = 0; j < nc; j++) {
371 int col = cols[j];
372 Object val = makeValue(v, getColumnClass(col));
373 for (int i = 0; i < nr && entries[i] < max; i++) {
374 getData(entries[i])[col] = val;
375 }
376 }
377 }
378
379
380 /*
381 * IMPLEMENTATION OF SORTABLE TABLE MODEL
382 */
383 /** Sorts the entries in this TableModel according to the criteria
384 * set by {@link #setSortBy}.
385 * @see de.mospace.swing.table.TableSorter#sort
386 */
387 public void sort() {
388 TableSorter ts = new TableSorter();
389 int[][] mapping = ts.sort((SortableTableModel) this);
390 rowForEntry = mapping[TableSorter.FWD];
391 entryForRow = mapping[TableSorter.INV];
392 sorted = true;
393 fireTableDataChanged();
394 }
395
396
397 /** Shuffles the entries in this TableModel.
398 * @see de.mospace.swing.table.TableSorter#randomize
399 */
400 public void randomize() {
401 TableSorter ts = new TableSorter();
402 int[][] mapping = ts.randomize((SortableTableModel) this);
403 rowForEntry = mapping[TableSorter.FWD];
404 entryForRow = mapping[TableSorter.INV];
405 sorted = false;
406 fireTableDataChanged();
407 }
408
409
410 /** Sets the column with top sorting precedence. If <code>col</code> is
411 * already the column with top sorting precedence the sort order will
412 * be reversed, otherwise the entries in this model will be sorted in
413 * ascending order. This implementation remembers previous calls
414 * to this method to determine what to do when two entries have equal fields
415 * in <code>col</code>.
416 *
417 * @param col the table column
418 *
419 * @see #setSortBy(int, boolean)
420 */
421 public void setSortBy(int col) {
422 setSortBy(col, !(isSorted() &&
423 col == sortOrder[0][0] && sortOrder[0][1] == ASCENDING));
424 }
425
426
427 /** Sets the columns by which this table is sorted. The entries will
428 * be sorted in ascending order.
429 *
430 * @param cols the columns to sort by in order of decreasing precedence
431 *
432 * @see #setSortBy(int, boolean)
433 */
434 public void setSortBy(int[] cols) {
435 for (int i = cols.length - 1; i >= 0; i--) {
436 setSortBy(cols[i], true);
437 }
438 }
439
440
441 /**
442 * Looks for consecutive duplicates in <code>rows</code>, starting at
443 * <code>startRowIndex</code>.
444 * The returned array contains the index of the first and the last rows
445 * that are identical in all columns specified by <code>cols</code>.<p>
446 * Consider calling {@link #setSortBy(int[] cols)} and {@link #sort}
447 * before calling this method.
448 *
449 * @param rows an array of table model rows to search for duplicates
450 * @param startRowIndex the index where the search will begin
451 * @param cols the cols that will be taken into account for comparison, if
452 * <code>null</code> all columns are used.
453 * @return the bounds of the next set of consecutive duplicate rows
454 */
455 public int[] getNextDuplicates(int[] rows, int startRowIndex, int[] cols) {
456 int ri = startRowIndex - 1;
457 int[] result = null;
458 final int maxnri = rows.length - 1;
459
460 ROWLOOP :
461 for (int nextri = startRowIndex; nextri < maxnri; ) {
462 boolean nonNull = false;
463 boolean equal = false;
464 Object[] row = getData(getEntries(rows[++ri]));
465 Object[] nextrow = getData(getEntries(rows[++nextri]));
466 for (int ci = 0; ci < cols.length; ci++) {
467 int col = cols[ci];
468 Object a = row[col];
469 if ("".equals(a)) {
470 a = null;
471 }
472 Object b = nextrow[col];
473 if ("".equals(b)) {
474 b = null;
475 }
476 nonNull = nonNull || (a != null);
477 equal = (a == b) ||
478 (a != null) &&
479 (
480 a.equals(b) ||
481 (
482 (a instanceof String) &&
483 ((String) a).equalsIgnoreCase((String) b)
484 )
485 );
486
487 if (!equal) {
488 /*
489 * rows differ
490 */
491 if (result == null) {
492 /*
493 * we have not found duplicates yet
494 * so we continue
495 */
496 continue ROWLOOP;
497 } else {
498 /*
499 * we already have some identical rows
500 * so we return
501 */
502 break ROWLOOP;
503 }
504 }
505 }
506 /*
507 * all columns are equal in row and nextrow
508 */
509 if (nonNull) {
510 /*
511 * create a new result vector if necessary
512 */
513 if (result == null) {
514 result = new int[2];
515 result[0] = ri;
516 }
517 /*
518 * add dup row to result
519 */
520 result[1] = nextri;
521 }
522 }
523
524 return result;
525 }
526
527
528 /** Sets the column with top sorting precedence
529 * and the way it is to be sorted. This implementation remembers previous calls
530 * to this method to determine what to do when two entries have equal fields
531 * in <code>col</code>.
532 *
533 * @param col the table column
534 * @param asc true for ascending order
535 */
536 public void setSortBy(int col, boolean asc) {
537 int m = 0;
538 /*
539 * find col in the sortOrder array if it is in there
540 */
541 for (m = 0; m < sortOrder.length && sortOrder[m][0] != col; m++) {
542 ;
543 }
544 if (m == sortOrder.length) {
545 m--;
546 }
547 /*
548 * move all entries with lower index one up
549 */
550 for (int i = m; i > 0; ) {
551 sortOrder[i] = sortOrder[--i];
552 }
553 /*
554 * if col wasn't at index 0
555 * allocate a new int[2] array at index 0
556 * and put col in its first element
557 */
558 if (m != 0) {
559 sortOrder[0] = new int[2];
560 sortOrder[0][0] = col;
561 }
562 /*
563 * set the ASCENDING/DESCENDING flag
564 */
565 sortOrder[0][1] = (asc) ? ASCENDING : DESCENDING;
566 }
567
568
569 /** Gets the column with top sorting precedence.
570 *
571 * @return the column by which this table model is sorted.
572 */
573 public int getSortingColumn() {
574 return sortOrder[0][0];
575 }
576
577
578 /** Gets the columns by which this table is sorted. The returned array
579 * holds the information used for sorting the table.
580 * The array holds n pairs of integers in the order of decreasing sorting
581 * precedence. The first integer in each pair is a column number, if it is
582 * -1 this element and all following elements are ignored. The second integer
583 * is either <code>ASCENDING</code> or <code>DESCENDING</code>.
584 * @return an array of {column, order} pairs with decreasing sorting precedence
585 */
586 public int[][] getSortOrder() {
587 return sortOrder;
588 }
589
590
591 /** Gets the current row number of an entry.*/
592 public int getRows(int entry) {
593 if (entry < rowForEntry.length) {
594 return rowForEntry[entry];
595 } else {
596 return entry;
597 }
598 }
599
600
601 /** Gets the current row numbers for a list of entries.*/
602 public int[] getRows(int[] entries) {
603 int m = entries.length;
604 int[] rows = new int[entries.length];
605 for (int i = 0; i < m; i++) {
606 rows[i] = rowForEntry[entries[i]];
607 }
608 return rows;
609 }
610
611
612 /** Gets the entry represented by the specified row in the current sorting.*/
613 public int getEntries(int row) {
614 return entryForRow[row];
615 }
616
617
618 /** Gets the entries represented by the specified rows in the current sorting.*/
619 public int[] getEntries(int[] rows) {
620 int m = rows.length;
621 int[] entry = new int[rows.length];
622 for (int i = 0; i < m; i++) {
623 entry[i] = entryForRow[rows[i]];
624 }
625 return entry;
626 }
627
628 /**
629 * Returns the field for a table column.
630 *
631 * @param col the column number for which to retrieve the field
632 * @return the field or null if col is invalid
633 */
634 public Field getField(int col) {
635 return fields[col];
636 }
637
638
639 /**
640 * Returns the table column for a field.
641 *
642 * @param field the field
643 * @return the column or -1 if there is no column for that field in this
644 * table
645 */
646 public int getColumn(Field field) {
647 Integer col = (Integer) columns.get(field);
648 return (col == null) ? -1 : col.intValue();
649 }
650
651
652 /**
653 * Gets the fields that are currently displayed.
654 *
655 * @return the fields that are currently displayed
656 */
657 public Field[] getFields() {
658 return (Field[]) fields.clone();
659 }
660
661
662 /*
663 * (PARTIAL) IMPLEMENTATION OF MP3DINGSTABLEMODEL
664 */
665 /**
666 * Gets the number of rows in this model.
667 *
668 * @return the number of table rows
669 */
670 public int getRowCount() {
671 return getData().size();
672 }
673
674
675 /** Loads the filters for this model from the user
676 * preferences.
677 *
678 * @return the filters for this model
679 */
680 public FilterCollection buildFilters() {
681 //System.out.println("buildFilters "+this.getClass().getName());
682 FilterCollection newFilters = new FilterCollection(Globals.getPrefNode().node("FilterSet"));
683 Preferences filterNode = getPrefs().node("filters");
684 newFilters.load(filterNode);
685 filters = newFilters;
686 //seems to be unnecessary (what was it for? repainting headers?)
687 /*
688 * final Runnable facu = new Runnable(){
689 * public void run(){
690 * fireAllColumnsUpdated();
691 * }
692 * };
693 * if(EventQueue.isDispatchThread()){
694 * facu.run();
695 * } else {
696 * SwingUtilities.invokeLater(facu);
697 * }
698 */
699 return filters;
700 }
701
702
703 /** Notifies listeners that all columns in this model have been updated. */
704 protected void fireAllColumnsUpdated() {
705 for (int c = 0; c < getColumnCount(); c++) {
706 fireTableCellUpdated(0, c);
707 }
708 }
709
710
711 /**
712 * Gets the filtered attribute of the AbstractTableModel object
713 *
714 * @param column Description of the Parameter
715 * @return The filtered value
716 */
717 public boolean isFiltered(int column) {
718 return filters.isFiltered(getField(column));
719 }
720
721
722 /**
723 * Gets the prefs attribute of the AbstractTableModel object
724 *
725 * @return The prefs value
726 */
727 public Preferences getPrefs() {
728 return prefs;
729 }
730
731
732 /*
733 * change tracking
734 */
735 /**
736 * Description of the Method
737 *
738 * @param parent Description of the Parameter
739 * @return Description of the Return Value
740 */
741 public boolean discardChanges(Frame parent) {
742 changedWarnLevel = prefs.getInt("WarnChangedLevel", 1);
743 if (changedWarnLevel < 1 || changeCount < changedWarnLevel) {
744 return true;
745 }
746 int discardChanges = JOptionPane.showConfirmDialog(
747 parent,
748 Globals.getString("DISCARD_CHANGES_PROMPT"),
749 Globals.getString("DISCARD_CHANGES_TITLE"),
750 JOptionPane.YES_NO_CANCEL_OPTION,
751 JOptionPane.QUESTION_MESSAGE);
752 if (discardChanges == JOptionPane.YES_OPTION) {
753 resetChangeCounter();
754 return true;
755 }
756 return false;
757 }
758
759
760 /** Description of the Method */
761 public void resetChangeCounter() {
762 changeCount = 0;
763 }
764
765
766 /*
767 * file size
768 */
769 /**
770 * Gets the file attribute of the AbstractTableModel object
771 *
772 * @param row Description of the Parameter
773 * @return The file value
774 */
775 public abstract File getFile(int row);
776
777
778 /**
779 * allows changing the fields in the mp3dings tables without restarting
780 * mp3dings
781 */
782 void updateColumns() {
783 Field[] newActiveFields = buildActiveFields();
784
785 /*
786 * test for change
787 */
788 if (Arrays.equals(newActiveFields, fields)) {
789 return;
790 }
791
792 /*
793 * if the columns have changed construct the mapping from old to new
794 * use -1 if a field has completely disappeared
795 */
796 int[] old2new = new int[fields.length];
797 Arrays.fill(old2new, -1);
798 for (int i = 0, nc = fields.length; i < nc; i++) {
799 for (int j = 0, nj = newActiveFields.length; j < nj; j++) {
800 if (newActiveFields[j] == fields[i]) {
801 old2new[i] = j;
802 break;
803 }
804 }
805 }
806 /*
807 * prepare new data in background
808 */
809 List newData = reorganizeData(old2new, newActiveFields.length);
810 int[][] newSortOrder = buildNewSortOrder(old2new, newActiveFields.length);
811 Map newColumns = buildColumns(newActiveFields);
812
813 /*
814 * update fields
815 * do i need to make this thread-safe?
816 */
817 synchronized (this) {
818 columns = newColumns;
819 fields = newActiveFields;
820 sortOrder = newSortOrder;
821 setData(newData);
822 }
823 final Runnable ftsc =
824 new Runnable() {
825 public void run() {
826 fireTableStructureChanged();
827 }
828 };
829 if (EventQueue.isDispatchThread()) {
830 ftsc.run();
831 } else {
832 SwingUtilities.invokeLater(ftsc);
833 }
834 }
835
836
837 /**
838 * Description of the Method
839 *
840 * @param old2new Description of the Parameter
841 * @param newlength Description of the Parameter
842 * @return Description of the Return Value
843 */
844 protected abstract List reorganizeData(int[] old2new, int newlength);
845
846
847 /**
848 * Sets the data attribute of the AbstractTableModel object
849 *
850 * @param v The new data value
851 */
852 protected abstract void setData(List v);
853
854
855 /*
856 * IMPLEMENTATION DETAILS
857 */
858 Field[] buildActiveFields() {
859
860 // get active fields
861 String pString = prefs.get("activeFields", "");
862 boolean fail = pString.equals("");
863 Field[] result = new Field[]{};
864 if (!fail) {
865 String[] pActive = pString.split(";");
866 final int m = pActive.length;
867 result = new Field[m];
868 for (int i = 0; i < m; i++) {
869 result[i] = Field.forName(pActive[i]);
870 if (result[i] == null) {
871 fail = true;
872 break;
873 }
874 }
875 }
876 if (fail) {
877 result = getDefaultFields();
878 prefs.put("activeFields", Array.join(result, ';'));
879 }
880 return result;
881 }
882
883
884 private Map buildColumns(Field[] fields) {
885 Map ncolumns = new TreeMap();
886 for (int i = 0, nc = fields.length; i < nc; i++) {
887 ncolumns.put(fields[i], Globals.asInteger(i));
888 }
889 return ncolumns;
890 }
891
892
893 private int[][] buildNewSortOrder(int[] old2new, int newlength) {
894 int[][] nso = new int[newlength][2];
895 for (int c = 0; c < newlength; c++) {
896 nso[c] = new int[2];
897 nso[c][0] = 0;
898 nso[c][1] = 1;
899 }
900 for (int p = 0, k = 0, oldcol = 0;
901 p < sortOrder.length && k < newlength;
902 p++) {
903 oldcol = sortOrder[p][0];
904 if (old2new[oldcol] != -1) {
905 nso[k][0] = old2new[oldcol];
906 nso[k][1] = sortOrder[p][1];
907 k++;
908 }
909 }
910 return nso;
911 }
912
913
914 /** new more comprehensive initialization routine */
915 protected void init() {
916 // get preference node for this class
917 prefs = Globals.getPrefNode();
918 prefs = prefs.node(getPrefKey());
919
920 final int n = getAllowedFields().length;
921 fields = buildActiveFields();
922
923 /*
924 * fields must be initialized when PreferenceChangeListener is added.
925 */
926 PreferenceChangeListener pcl =
927 new PreferenceChangeListener() {
928 private Runnable buildFilters =
929 new Runnable() {
930 public void run() {
931 buildFilters();
932 }
933 };
934
935
936 public void preferenceChange(PreferenceChangeEvent evt) {
937 /*
938 * we must be very specific here to prevent
939 * unwanted side effects, more specifically we should ignore
940 * changes to the column width key which occur quite often
941 * (every time the table is laid out)
942 */
943 if (evt.getNode().equals(getPrefs().node("filters")) ||
944 evt.getNode().equals(Globals.getPrefNode().node("FilterSet"))) {
945 //System.out.println(evt.getNode()+"/"+evt.getKey());
946 /*
947 * rebuild the FilterCollection
948 */
949 aggregator.aggregatedInvokeLater(buildFilters);
950 } else if (evt.getNode().equals(getPrefs()) &&
951 evt.getKey().equals("activeFields")) {
952
953 /*
954 * update columns if necessary
955 */
956 updateColumns();
957 }
958 }
959 };
960
961 //listen to changes in active fields
962 prefs.addPreferenceChangeListener(pcl);
963
964 //listen to changes in which filters act on this model's columns
965 prefs.node("filters").addPreferenceChangeListener(pcl);
966
967 //listen to changes in the filterset
968 Globals.getPrefNode().node("FilterSet").addPreferenceChangeListener(pcl);
969
970 //initialize table columns
971 columns = buildColumns(fields);
972
973 //start change control
974 changeCounter =
975 new DataChangeListener() {
976 public void dataChanged(DataChangeEvent e) {
977 changeCount += e.getChangeCount();
978 }
979 };
980 this.addDataChangeListener(changeCounter);
981 changedWarnLevel = prefs.getInt("WarnChangedLevel", 1);
982
983 //initialize sortOrder
984 sortOrder = new int[getColumnCount()][2];
985 for (int col = 0; col < sortOrder.length; col++) {
986 sortOrder[col][0] = col;
987 sortOrder[col][1] = ASCENDING;
988 }
989
990 buildFilters();
991 }
992
993
994 /**
995 * Gets the filters attribute of the AbstractTableModel object
996 *
997 * @return The filters value
998 */
999 public FilterCollection getFilters() {
1000 return new FilterCollection(filters);
1001 }
1002
1003
1004 /*
1005 * Sorting implementation
1006 */
1007 /**
1008 * Gets the sorted attribute of the AbstractTableModel object
1009 *
1010 * @return The sorted value
1011 */
1012 public boolean isSorted() {
1013 return sorted;
1014 }
1015
1016
1017 /**
1018 * Sets the sorted attribute of the AbstractTableModel object
1019 *
1020 * @param b The new sorted value
1021 */
1022 protected void setSorted(boolean b) {
1023 sorted = b;
1024 }
1025
1026
1027 /** Description of the Method */
1028 public void remAllRowsFromSorter() {
1029 rowForEntry = new int[]{};
1030 entryForRow = new int[]{};
1031 }
1032
1033
1034 /**
1035 * Description of the Method
1036 *
1037 * @param entry Description of the Parameter
1038 */
1039 public void remRowFromSorter(int entry) {
1040 int n = --dataLength;
1041 int row = rowForEntry[entry];
1042 for (int j = entry; j < n; j++) {
1043 rowForEntry[j] = rowForEntry[j + 1];
1044 }
1045 for (int j = 0; j < n; j++) {
1046 if (rowForEntry[j] > row) {
1047 rowForEntry[j]--;
1048 }
1049 }
1050 for (int i = 0; i < n; i++) {
1051 entryForRow[rowForEntry[i]] = i;
1052 }
1053 }
1054
1055
1056 /*
1057 * not tested! potentially buggy
1058 */
1059 /**
1060 * Description of the Method
1061 *
1062 * @param entry Description of the Parameter
1063 */
1064 public void remRowFromSorter(int[] entry) {
1065 int n = dataLength - 1;
1066 int m = entry.length;
1067 /*
1068 * for each entry to be deleted ...
1069 */
1070 for (int i = 0; i < m; i++) {
1071 int row = rowForEntry[entry[i]];
1072 /*
1073 * ...decrease all entry numbers bigger than row ...
1074 */
1075 for (int j = entry[i]; j < n; j++) {
1076 rowForEntry[j] = rowForEntry[j + 1];
1077 }
1078 /*
1079 * ... and decrease all values bigger than rowForEntry[row]
1080 */
1081 for (int j = 0; j < n; j++) {
1082 if (rowForEntry[j] > row) {
1083 rowForEntry[j]--;
1084 }
1085 }
1086 n--;
1087 }
1088 n = (dataLength -= entry.length);
1089 for (int i = 0; i < n; i++) {
1090 entryForRow[rowForEntry[i]] = i;
1091 }
1092 }
1093
1094
1095 /**
1096 * Adds a feature to the RowsToSorter attribute of the AbstractTableModel
1097 * object
1098 *
1099 * @param rowCount The feature to be added to the RowsToSorter attribute
1100 * @param newSize The feature to be added to the RowsToSorter attribute
1101 */
1102 public void addRowsToSorter(int rowCount, int newSize) {
1103 int n = newSize;
1104 int[] x = new int[n];
1105 int[] y = new int[n];
1106 int m = n - rowCount;
1107 if (m > 0) {
1108 System.arraycopy(rowForEntry, 0, x, 0, m);
1109 System.arraycopy(entryForRow, 0, y, 0, m);
1110 }
1111 for (int i = m; i < n; i++) {
1112 x[i] = i;
1113 y[i] = i;
1114 }
1115 rowForEntry = x;
1116 entryForRow = y;
1117 dataLength = n;
1118 }
1119
1120
1121 /*
1122 * IMPLEMENTATION OF HEADERPOPUPTABLEMODEL
1123 */
1124 /**
1125 * Gets the context menu for the column header of a table displaying
1126 * this model. By default this method delegates to
1127 * {@link #getFilterEditPopup(MouseEvent)}.
1128 *
1129 * @param e a mouse click on a column header of a table displaying this
1130 * model
1131 * @return a context menu or null
1132 *
1133 * @see #getFilterEditPopup(MouseEvent)
1134 */
1135 public JPopupMenu getHeaderPopup(MouseEvent e) {
1136 return getFilterEditPopup(e);
1137 }
1138
1139
1140 abstract Object[] getData(int entry);
1141
1142
1143 /*
1144 * helper function for setValueAt
1145 */
1146 static Object makeValue(Object v, Class c) throws NumberFormatException {
1147
1148 Object result = null;
1149 /*
1150 * if we can cast v to c and v is non-null return v
1151 */
1152 if (c.isInstance(v) || v == null) {
1153 result = v;
1154
1155 /*
1156 * if target class is String (not FullTextString!) return
1157 * v.toString() without any line terminators
1158 */
1159 } else if (c == String.class) {
1160 result = (v == null)
1161 ? ""
1162 : v.toString().replaceAll("\n\r", " ").replaceAll("\n", " ");
1163
1164 /*
1165 * try parsing v.toString() as a number
1166 */
1167 } else if (c == Number.class) {
1168 if (v.equals("")) {
1169 return null;
1170 } else {
1171 try {
1172 double d = Double.parseDouble(v.toString());
1173 long l = (long) d;
1174 /*
1175 * if the new number is an integer make a Long
1176 * object, otherwise make a Double
1177 */
1178 if (d == 0 || Math.abs((d - l) / d) < 1e-9) {
1179 return new Long(l);
1180 } else {
1181 return new Double(d);
1182 }
1183 } catch (NumberFormatException ex) {
1184 return null;
1185 }
1186 }
1187
1188 /*
1189 * look for String constructor or return v
1190 */
1191 } else {
1192 final Class[] singleString = new Class[]{String.class};
1193 try {
1194 Constructor cc = c.getConstructor(singleString);
1195 result = cc.newInstance(new Object[]{v.toString()});
1196 } catch (Exception ex) {
1197 //we cannot construct a new value;
1198 result = null;
1199 }
1200 }
1201 assert(result == null || c.isInstance(result));
1202 return result;
1203 }
1204
1205
1206 /**
1207 * Adds a feature to the MessageListener attribute of the AbstractTableModel
1208 * object
1209 *
1210 * @param l The feature to be added to the MessageListener attribute
1211 */
1212 public void addMessageListener(MessageListener l) {
1213 listenerList.add(MessageListener.class, l);
1214 }
1215
1216
1217 /**
1218 * Description of the Method
1219 *
1220 * @param l Description of the Parameter
1221 */
1222 public void removeMessageListener(MessageListener l) {
1223 listenerList.remove(MessageListener.class, l);
1224 }
1225
1226
1227 // Notify all listeners that have registered interest for
1228 // notification on this event type. The event instance
1229 // is lazily created using the parameters passed into
1230 // the fire method.
1231 /**
1232 * Description of the Method
1233 *
1234 * @param s Description of the Parameter
1235 * @param t Description of the Parameter
1236 */
1237 protected void fireMessageSent(String s, int t) {
1238 // Guaranteed to return a non-null array
1239 Object[] listeners = listenerList.getListenerList();
1240 // Process the listeners last to first, notifying
1241 // those that are interested in this event
1242 messageEvent = new MessageEvent(this, s, MessageEvent.TYPE_INFO, t);
1243 for (int i = listeners.length - 2; i >= 0; i -= 2) {
1244 if (listeners[i] == MessageListener.class) {
1245 ((MessageListener) listeners[i + 1]).messageSent(messageEvent);
1246 }
1247 }
1248 }
1249
1250
1251 /**
1252 * Description of the Method
1253 *
1254 * @param s Description of the Parameter
1255 */
1256 protected void fireMessageSent(String s) {
1257 fireMessageSent(s, MessageEvent.DEFAULT_TIMEOUT);
1258 }
1259
1260
1261 /**
1262 * Adds a feature to the DataChangeListener attribute of the
1263 * AbstractTableModel object
1264 *
1265 * @param l The feature to be added to the DataChangeListener attribute
1266 */
1267 public void addDataChangeListener(DataChangeListener l) {
1268 listenerList.add(DataChangeListener.class, l);
1269 }
1270
1271
1272 /**
1273 * Description of the Method
1274 *
1275 * @param l Description of the Parameter
1276 */
1277 public void removeDataChangeListener(DataChangeListener l) {
1278 listenerList.remove(DataChangeListener.class, l);
1279 }
1280
1281
1282 /**
1283 * Description of the Method
1284 *
1285 * @param n Description of the Parameter
1286 */
1287 public void fireDataChanged(int n) {
1288 // Guaranteed to return a non-null array
1289 Object[] listeners = listenerList.getListenerList();
1290 // Process the listeners last to first, notifying
1291 // those that are interested in this event
1292 dataChange = new DataChangeEvent(this, n);
1293 for (int i = listeners.length - 2; i >= 0; i -= 2) {
1294 if (listeners[i] == DataChangeListener.class) {
1295 ((DataChangeListener) listeners[i + 1]).dataChanged(dataChange);
1296 }
1297 }
1298 }
1299
1300
1301 /** Description of the Method */
1302 public void fireDataChanged() {
1303 fireDataChanged(1);
1304 }
1305
1306
1307 /*
1308 * CLASS UPDATE RUNNABLE
1309 */
1310 /**
1311 * Description of the Class
1312 *
1313 * @author ringler
1314 */
1315 protected class UpdateRunnable implements Runnable {
1316 private int firstRow;
1317 private int lastRow;
1318
1319
1320 /**
1321 * Constructs a new UpdateRunnable.
1322 *
1323 * @param first Description of the Parameter
1324 * @param last Description of the Parameter
1325 */
1326 public UpdateRunnable(int first, int last) {
1327 firstRow = first;
1328 lastRow = last;
1329 }
1330
1331
1332 /** Main processing method for the UpdateRunnable object */
1333 public void run() {
1334 fireTableRowsUpdated(firstRow, lastRow);
1335 setFirstRow(lastRow);
1336 }
1337
1338
1339 /**
1340 * Sets the firstRow attribute of the UpdateRunnable object
1341 *
1342 * @param row The new firstRow value
1343 */
1344 public void setFirstRow(int row) {
1345 firstRow = row;
1346 }
1347
1348
1349 /**
1350 * Sets the lastRow attribute of the UpdateRunnable object
1351 *
1352 * @param row The new lastRow value
1353 */
1354 public void setLastRow(int row) {
1355 lastRow = row;
1356 }
1357
1358 }
1359 }