001 package net.sourceforge.mp3dings;
002
003 /* Mp3dings - manage mp3 meta-information
004 * Copyright (C) 2003 Moritz Ringler
005 * $Id: Mp3dingsTable.java 110 2007-11-05 17:35:50Z ringler $
006 *
007 * This program is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU General Public License
009 * as published by the Free Software Foundation; either version 2
010 * of the License, or (at your option) any later version.
011 *
012 * This program is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
015 * GNU General Public License for more details.
016 *
017 * You should have received a copy of the GNU General Public License
018 * along with this program; if not, write to the Free Software
019 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
020 */
021
022 import java.awt.Component;
023 import java.awt.Dimension;
024 import java.awt.Point;
025 import java.awt.Rectangle;
026 import java.awt.Toolkit;
027 import java.awt.Window;
028 import java.awt.datatransfer.DataFlavor;
029 import java.awt.event.FocusAdapter;
030 import java.awt.event.MouseMotionAdapter;
031 import java.awt.event.FocusEvent;
032 import java.awt.event.MouseEvent;
033 import java.awt.event.InputEvent;
034 import java.util.logging.Logger;
035 import javax.swing.Action;
036 import javax.swing.DefaultCellEditor;
037 import javax.swing.JTable;
038 import javax.swing.JTextField;
039 import javax.swing.KeyStroke;
040 import javax.swing.SwingUtilities;
041 import javax.swing.ToolTipManager;
042 import javax.swing.TransferHandler;
043 import javax.swing.event.ListSelectionEvent;
044 import javax.swing.event.ListSelectionListener;
045 import javax.swing.table.TableCellRenderer;
046 import javax.swing.table.TableColumn;
047 import javax.swing.text.AttributeSet;
048 import javax.swing.text.BadLocationException;
049 import javax.swing.text.Document;
050 import javax.swing.text.PlainDocument;
051 import de.mospace.lang.Array;
052 import de.mospace.lang.FullTextString;
053 import de.mospace.swing.event.DataChangeEvent;
054 import de.mospace.swing.event.DataChangeListener;
055 import de.mospace.swing.table.SortHeader;
056 import de.mospace.swing.text.FullTextStringCellEditor;
057 import de.mospace.swing.text.FullTextStringCellRenderer;
058 import helliker.id3.APICImage;
059 import net.sourceforge.mp3dings.datatransfer.DataTransferHandler;
060 import net.sourceforge.mp3dings.editors.ImageCellEditor;
061
062 /** Common components of all four mp3dings tables. **/
063 public class Mp3dingsTable extends JTable implements DataChangeListener{
064 private static final Logger logger = Logger.getLogger(Mp3dingsTable.class.getPackage().getName());
065 final public static int FIT_CELL_WIDTH = 0;
066 final public static int FIT_WINDOW = 1;
067 final public static int NO_RESIZE = 2;
068 final private static int EXTRA_PADDING = 3;
069 final private static int SORT_ICON_WIDTH= 15;
070 final private static int defaultTTDD = ToolTipManager.sharedInstance().getDismissDelay();
071
072 Mp3dingsTableModel model;
073
074 final private static DataTransferHandler COPY_PASTE_HANDLER =
075 new DataTransferHandler(false, true, TransferHandler.COPY_OR_MOVE);
076 final private static DataTransferHandler DND_HANDLER =
077 new DataTransferHandler(true, false, TransferHandler.COPY,
078 new DataFlavor[]{DataFlavor.javaFileListFlavor});
079 static {
080 COPY_PASTE_HANDLER.setExportEnabled(DataFlavor.javaFileListFlavor, false);
081 }
082
083 private int focusRow = -1;
084 private int focusCol = -1;
085 private TransferHandler cphandler;
086
087 /*
088 private final Runnable doLayout = new Runnable(){
089 public void run(){
090 doLayout();
091 }
092 };
093 */
094
095 public Mp3dingsTable(Mp3dingsTableModel tm){
096 super(tm);
097 model = tm;
098 setCopyPasteHandler(COPY_PASTE_HANDLER);
099 setTransferHandler(DND_HANDLER);
100 setDragEnabled(true);
101
102 getTableHeader().setReorderingAllowed(false);
103
104 /* the following line causes a problem together with the focus listener:
105 * If you move the cursor to a cell and type two letters the first
106 * keystroke causes the cell to gain the focus. So the first letter is
107 * selected and subsequently overwritten by the second.*/
108 //setSurrendersFocusOnKeystroke(true);
109
110 setupCellEditorsAndRenderers();
111
112 getSelectionModel().addListSelectionListener(new SelectionHandler());
113
114 model.addDataChangeListener(this);
115 addMouseMotionListener(new MouseMotionAdapter(){
116 private Object lastValue;
117
118 public void mouseMoved(MouseEvent e){
119 Point mouseXY = e.getPoint();
120 int col = columnAtPoint(mouseXY);
121 int row = rowAtPoint(mouseXY);
122 if(col >= 0 && row >= 0){
123 Object v = model.getValueAt(row, col);
124 if(v == null){
125 setToolTipText(null);
126 setToolTipVisible(0);
127 } else if (!v.equals(lastValue)){
128 setToolTipText(greedyWrap(v.toString(), 70));
129 lastValue = v;
130 }
131 }
132 }
133 });
134
135 loadColumnSizes();
136 doLayout();
137 }
138
139 private static void setToolTipVisible(int millis){
140 ToolTipManager.sharedInstance().
141 setDismissDelay(Math.max(defaultTTDD, millis));
142 }
143
144 private static String greedyWrap(String str, int len){
145 if(str.length() <= len){
146 ToolTipManager.sharedInstance().setDismissDelay(defaultTTDD);
147 return str;
148 }
149 final StringBuffer sb = new StringBuffer("<html><font face=\"serif\">");
150 final String[] lines = str.split("\n");
151 int linecount = lines.length;
152 for(int i = 0; i < lines.length; i++){
153 final String[] words = lines[i].split("\\s+");
154 int remaining = len;
155 for(int j=0; j < words.length; j++){
156 final boolean firstWord = (remaining == len);
157 final int wlen = words[j].length() + (firstWord? 0 : 1);
158 if(wlen > remaining){
159 if(firstWord){
160 sb.append(words[j]);
161 } else {
162 j--;
163 }
164 sb.append("<br>");
165 linecount++;
166 remaining = len;
167 } else{
168 if(!firstWord){
169 sb.append(' ');
170 }
171 sb.append(words[j]);
172 remaining -= wlen;
173 }
174 }
175 sb.append("<br>");
176 }
177 //allow three seconds per line for slow readers
178 setToolTipVisible(3000 * linecount);
179 return sb.append("</font></html>").toString();
180 }
181
182 public void setCopyPasteHandler(TransferHandler t){
183 cphandler = t;
184 }
185
186 public TransferHandler getCopyPasteHandler(){
187 return cphandler;
188 }
189
190
191 private TableColumn getColumn(int i){
192 return getColumnModel().getColumn(i);
193 }
194
195 public void dataChanged(DataChangeEvent e){
196 //AbstractTableModel.aggregator.aggregatedInvokeLater(doLayout);
197 doLayout();
198 }
199
200 private void setupCellEditorsAndRenderers(){
201 /* Set up the CellEditor for String data */
202 final JTextField strInput = new JTextField();
203 strInput.setHorizontalAlignment(JTextField.TRAILING);
204 strInput.addFocusListener(new FocusAdapter(){
205 public void focusGained(FocusEvent e){
206 ((JTextField) e.getComponent()).selectAll();
207 }
208 });
209 setDefaultEditor(String.class, new DefaultCellEditor(strInput));
210
211 /* Set up the CellEditor for numeric data,
212 * a JTextField that accepts only numbers */
213 final NumberInputField numInput = new NumberInputField();
214 numInput.setHorizontalAlignment(JTextField.RIGHT);
215 numInput.addFocusListener(new FocusAdapter(){
216 public void focusGained(FocusEvent e){
217 ((JTextField) e.getComponent()).selectAll();
218 }
219 });
220
221 /* CellEditor that returns Double or Long values */
222 setDefaultEditor(Number.class, new NumberCellEditor(numInput));
223
224 /* Set up the Cell Editor and Renderer for FullTextStrings */
225 setDefaultRenderer(FullTextString.class,
226 new FullTextStringCellRenderer());
227 setDefaultEditor(FullTextString.class,
228 new FullTextStringCellEditor());
229
230 /* Set up the Cell Editor for APICImage objects */
231 setDefaultEditor(APICImage.class, new ImageCellEditor());
232 }
233
234 public void doLayout(){
235 int mode = Globals.getPrefNode().getInt("ResizeMode",FIT_CELL_WIDTH);
236 switch (mode){
237 case FIT_CELL_WIDTH:
238 setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
239 setColumnSizes();
240 break;
241 case FIT_WINDOW:
242 setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
243 break;
244 default:
245 setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
246 }
247 /* must call super.doLayout() after (!) setColumnSizes
248 otherwise table column model will hold wrong column widths */
249 super.doLayout();
250 getTableHeader().repaint();
251 saveColumnSizes();
252 }
253
254 private void saveColumnSizes(){
255 StringBuffer result = new StringBuffer(128);
256 for (int i=0, n=getColumnCount(); i<n; i++){
257 result.append(model.getField(i)+":");
258 result.append(getColumn(i).getPreferredWidth()+",");
259 }
260 model.getPrefs().put("columnwidth",result.toString());
261 }
262
263 private void loadColumnSizes(){
264 /* don't use split(",", -1) here!! */
265 String[] savedSizes = model.getPrefs().get("columnwidth","").split(",");
266 int colon = 0, width = 0;
267 Field field;
268 for (int i=0, n=savedSizes.length; i<n; i++){
269 colon = savedSizes[i].indexOf(':');
270 if(colon == -1){
271 continue;
272 }
273 field = Field.forName(savedSizes[i].substring(0,colon));
274 boolean failed = (field == null);
275 try{
276 width = Integer.parseInt(savedSizes[i].substring(colon+1));
277 } catch (NumberFormatException ex){
278 logger.severe(ex.toString());
279 }
280 if(failed){
281 logger.severe("Error parsing saved column widths!");
282 continue;
283 }
284 int column = model.getColumn(field);
285 if(column >= 0){
286 getColumn(column).setPreferredWidth(width);
287 }
288 }
289 }
290
291 private void setColumnSizes() {
292 final int maxWidth = Globals.getPrefNode().getInt("MaximumColumnWidth", Integer.MAX_VALUE);
293 final int nCol = getColumnCount();
294 int[] cellWidth = new int[nCol];
295
296 /* get optimized cell widths */
297 for (int i = 0; i < nCol; i++) {
298 /* get optimized body cell width */
299 cellWidth[i] = Math.min(bodyCellWidth(i, headerWidth(i)), maxWidth);
300 }
301
302 /* calculate additional padding */
303 int w = 0;
304 if (getRootPane() != null){
305 w = getRootPane().getWidth();
306 for (int i=0;i<nCol;i++){
307 w -= (cellWidth[i] + EXTRA_PADDING);
308 }
309 }
310 int wr = w % nCol;
311 w = (int) Math.floor(w/nCol);
312
313
314 /* don't shrink */
315 if (w<0){
316 w=0;
317 }
318
319 /* set column widths */
320 int m = nCol-1;
321 for (int i=0; i<m; i ++){
322 int wi = cellWidth[i] + w + EXTRA_PADDING;
323 getColumn(i).setPreferredWidth(wi);
324 }
325 int wi = cellWidth[m] + w + EXTRA_PADDING + wr;
326 getColumn(m).setPreferredWidth(wi);
327
328 }
329
330
331 private int headerWidth(int col){
332 TableCellRenderer headerRenderer = getColumn(col).getHeaderRenderer();
333 if (headerRenderer == null){
334 headerRenderer = getTableHeader().getDefaultRenderer();
335 }
336 return headerRenderer.getTableCellRendererComponent(
337 this,
338 getColumn(col).getHeaderValue(),
339 false,
340 false,
341 0,
342 col).getPreferredSize().width + SORT_ICON_WIDTH;
343 }
344
345 private int bodyCellWidth(int col, int minWidth){
346 final int nr = getRowCount();
347 int result = minWidth;
348 for (int j = 0; j < nr; j++){
349 result = Math.max(
350 getDefaultRenderer(getColumnClass(col)).
351 getTableCellRendererComponent(
352 this,
353 model.getValueAt(j,col),
354 false,
355 false,
356 j,
357 col
358 ).getPreferredSize().width,
359 result);
360 }
361 return result;
362 }
363
364 public void addKeyBindings(Action[] a){
365 int key;
366 int ctrl = InputEvent.CTRL_MASK;
367 int alt = InputEvent.ALT_MASK;
368 int shift = InputEvent.SHIFT_MASK;
369 int m = a.length;
370 javax.swing.InputMap im = this.getInputMap();
371 javax.swing.ActionMap am = this.getActionMap();
372 for (int i=0; i<m; i++){
373 key = ((Integer) a[i].getValue(Action.MNEMONIC_KEY)).intValue();
374 String action = "importedAction" + i;
375 im.put(KeyStroke.getKeyStroke(key, ctrl), action);
376 im.put(KeyStroke.getKeyStroke(key, alt + ctrl), action );
377 im.put(KeyStroke.getKeyStroke(key, shift + ctrl), action);
378 am.put(action, a[i]);
379 }
380 }
381
382 protected void saveFocus(){
383 focusRow = getSelectionModel().getLeadSelectionIndex();
384 focusCol = getColumnModel().getSelectionModel().getLeadSelectionIndex();
385 }
386
387 protected void restoreFocus(){
388 if (focusRow != -1 && focusCol != -1){
389 if (isCellSelected(focusRow, focusCol)){
390 addRowSelectionInterval(focusRow, focusRow);
391 addColumnSelectionInterval(focusCol, focusCol);
392 } else {
393 removeRowSelectionInterval(focusRow, focusRow);
394 removeColumnSelectionInterval(focusCol, focusCol);
395 }
396 }
397 }
398
399 public void invertRowSelection(){
400 int[] rows = getSelectedRows();
401 int[] cols = getSelectedColumns();
402 int selr[][] = Array.getIntervals(rows);
403 int selc[][] = Array.getIntervals(cols);
404 int firstCol = cols[0];
405 int firstRow = (selr[0][0] == 0)? selr[0][1] + 1 : 0;
406 /* clear selection */
407 clearSelection();
408
409 /* select first row of cells */
410 if(firstRow == getRowCount()){
411 return;
412 }
413 changeSelection(firstRow, firstCol,false, false);
414 for (int i=0; i<selc.length; i++){
415 addColumnSelectionInterval(selc[i][0],selc[i][1]);
416 }
417 selc = null;
418
419 /* add other rows */
420 if(selr[0][0] != 0){
421 addRowSelectionInterval(0, selr[0][0] - 1);
422 }
423 for (int i = 1; i < selr.length; i++){
424 addRowSelectionInterval(selr[i - 1][1] + 1,
425 selr[i][0] - 1);
426 }
427 if (selr[selr.length - 1][1] != getRowCount() - 1){
428 addRowSelectionInterval(selr[selr.length - 1][1] + 1,
429 getRowCount() - 1);
430 }
431 }
432
433 public void invertColumnSelection(){
434 int[] rows = getSelectedRows();
435 int[] cols = getSelectedColumns();
436 int selr[][] = Array.getIntervals(rows);
437 int selc[][] = Array.getIntervals(cols);
438 int firstCol = (selc[0][0] == 0)? selc[0][1] + 1 : 0;
439 int firstRow = rows[0];
440
441 /* clear selection */
442 clearSelection();
443
444
445 /* select first column of cells */
446 if(firstCol == getColumnCount()){
447 return;
448 }
449 changeSelection(firstRow, firstCol,false, false);
450 for (int i=0; i<selr.length; i++){
451 addRowSelectionInterval(selr[i][0],selr[i][1]);
452 }
453 selr = null;
454
455 /* add other columns */
456 if(selc[0][0] != 0){
457 addColumnSelectionInterval(0, selc[0][0] - 1);
458 }
459 for (int i = 1; i < selc.length; i++){
460 addColumnSelectionInterval(selc[i - 1][1] + 1,
461 selc[i][0] - 1);
462 }
463 if (selc[selc.length - 1][1] !=
464 getColumnCount() - 1){
465 addColumnSelectionInterval(
466 selc[selc.length - 1][1] + 1,
467 getColumnCount() - 1);
468 }
469 }
470
471
472
473
474
475 protected MainFrame getFrame(){
476 return (MainFrame) SwingUtilities.getAncestorOfClass(MainFrame.class,this);
477 }
478
479 /** This Selection Handler informs the user via the status bar
480 * about the number and the size of the currently selected files. **/
481 private class SelectionHandler implements ListSelectionListener{
482 public SelectionHandler(){
483 }
484
485 public void valueChanged(ListSelectionEvent e){
486 int[] rows = getSelectedRows();
487 if (rows.length == 0){
488 return;
489 }
490 int i;
491 long fileSize = 0;
492 try {
493 for (i=0; i<rows.length; i++){
494 fileSize += model.getFile(rows[i]).length();
495 }
496 } catch (Exception ex){
497 /* when deleting several files with the delete files context menu
498 command the following exception was raised:
499 Exception in thread "AWT-EventQueue-0"
500 java.lang.ArrayIndexOutOfBoundsException:
501 Array index out of range: 3
502 at java.util.Vector.get(Vector.java:710)
503 at net.sourceforge.mp3dings.DataTableModel.getFile(DataTableModel.java:514)
504 at net.sourceforge.mp3dings.Mp3dingsTable$SelectionHandler.valueChanged(Mp3dingsTable.java:485)
505 at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:187)
506 at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:167)
507 at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:214)
508 at javax.swing.DefaultListSelectionModel.removeIndexInterval(DefaultListSelectionModel.java:611)
509 at javax.swing.JTable.tableRowsDeleted(JTable.java:3126)
510 at javax.swing.JTable.tableChanged(JTable.java:3029)
511 at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:280)
512 at javax.swing.table.AbstractTableModel.fireTableRowsDeleted(AbstractTableModel.java:245)
513 at net.sourceforge.mp3dings.DataTableModel.removeRows(DataTableModel.java:293)
514 at net.sourceforge.mp3dings.TableContextMenu.deleteFiles(TableContextMenu.java:959)
515 [...]
516 That means the selection handler tried to get a file that was no longer
517 there (due to a lack of synchronization?). I couldn't reproduce the
518 error. So I just added this try/catch clause. */
519 return;
520 }
521 getFrame().setStatus(
522 Globals.getMessage("SELECTION_SIZE",
523 new Object[]{
524 new Double(fileSize/1048576.),
525 new Long(fileSize),
526 new Integer(i)
527 }
528 )
529 );
530 }
531 }
532
533 /**
534 * The table header for mp3dings tables. It has all the features
535 * of a {@link de.mospace.swing.table.SortHeader}. Additionally the color in which
536 * the column name is rendered depends on whether a column is currently
537 * filtered or not.
538 *
539 * @author Moritz Ringler
540 *
541 * @see Mp3dingsTableModel#isFiltered(int col)
542 */
543 public static class SortHeader extends de.mospace.swing.table.SortHeader{
544 public SortHeader(Mp3dingsTable table){
545 super(table);
546 }
547
548 public Component getTableCellRendererComponent(JTable table,
549 Object value, boolean isSelected, boolean hasFocus, int row, int col){
550 Component button = super.getTableCellRendererComponent(
551 table, value, isSelected, hasFocus, row, col);
552 //System.out.println("Rendering header for column " + col);
553 button.setForeground(Globals.getColor(
554 (((Mp3dingsTableModel) table.getModel()).isFiltered(col))
555 ? Globals.COLOR_FILTERED
556 : Globals.COLOR_UNFILTERED));
557 return button;
558 }
559 }
560
561 private static class NumberInputField extends JTextField{
562 public NumberInputField(){
563 super();
564 }
565
566 protected Document createDefaultModel() {
567 return new PlainDocument(){
568 public void insertString(int offs, String str,
569 AttributeSet a) throws BadLocationException {
570 char[] source = str.toCharArray();
571 char[] result = new char[source.length];
572 int j = 0;
573 for (int i = 0; i < source.length; i++) {
574 if (Character.isDigit(source[i]) || source[i]=='.'){
575 result[j++] = source[i];
576 }
577 }
578 String res = (j<=0)? str : new String(result, 0, j);
579 super.insertString(offs, res, a);
580 }
581 };
582 }
583
584 public Number getNumber(){
585 String val = getText();
586 Number self;
587 if (val.equals("") || val == null){
588 self = null;
589 } else {
590 try {
591 double d = Double.parseDouble(val);
592 long l = (long) d;
593 if (d == l){
594 self = new Long(l);
595 } else {
596 self = new Double(d);
597 }
598 } catch (NumberFormatException ex){
599 self = null;
600 }
601 }
602 return self;
603 }
604 }
605
606 private static class NumberCellEditor extends DefaultCellEditor{
607 public NumberCellEditor(NumberInputField numInput){
608 super(numInput);
609 }
610
611 public Object getCellEditorValue() {
612 return ((NumberInputField) getComponent()).getNumber();
613 }
614 }
615
616 public void placeWindow(Window window, int rtop, int cleft, int rbottom, int cright){
617 /* calculate the screen rectangle of the cells */
618 Rectangle cells = getCellRect(rtop, cleft, true);
619 Point p = cells.getLocation();
620 SwingUtilities.convertPointToScreen(p, this);
621 Rectangle cellsOnScreen = new Rectangle(p);
622 cells = getCellRect(rbottom, cright, true);
623 p = cells.getLocation();
624 SwingUtilities.convertPointToScreen(p, this);
625 p.x += cells.width;
626 p.y += cells.height;
627 cellsOnScreen.add(p);
628 cells = cellsOnScreen;
629
630 /* determine window location */
631 Rectangle windowBounds = window.getBounds();
632
633 /* if the rectangles intersect move the window */
634 if(windowBounds.intersects(cells)){
635 Dimension scrn = Toolkit.getDefaultToolkit().getScreenSize();
636 int left = cells.x;
637 int right = scrn.width - cells.x - cells.width;
638 int top = cells.y;
639 int bottom = scrn.height - cells.y - cells.height;
640 if (right >= windowBounds.width){
641 windowBounds.x = cells.x + cells.width;
642 } else if(left >= windowBounds.width){
643 windowBounds.x = left - windowBounds.width;
644 } else if(bottom >= windowBounds.height){
645 windowBounds.y = cells.y + cells.height;
646 } else if (top >= windowBounds.height){
647 windowBounds.y = top;
648 } else {
649 windowBounds.x = (left > right)
650 ? 0
651 : scrn.width - windowBounds.width;
652 windowBounds.y = (top > bottom)
653 ? 0
654 : scrn.height - windowBounds.height;
655 }
656 window.setLocation(windowBounds.getLocation());
657 }
658 }
659 }