001 package net.sourceforge.mp3dings;
002
003 //TODO: Set new Value using Pattern builder
004 //TODO: apply filters on individual cells
005 /* Mp3dings - manage mp3 meta-information
006 * Copyright (C) 2003-2006 Moritz Ringler
007 * $Id: TableContextMenu.java 113 2007-11-05 19:15:10Z ringler $
008 *
009 * This program is free software; you can redistribute it and/or
010 * modify it under the terms of the GNU General Public License
011 * as published by the Free Software Foundation; either version 2
012 * of the License, or (at your option) any later version.
013 *
014 * This program is distributed in the hope that it will be useful,
015 * but WITHOUT ANY WARRANTY; without even the implied warranty of
016 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
017 * GNU General Public License for more details.
018 *
019 * You should have received a copy of the GNU General Public License
020 * along with this program; if not, write to the Free Software
021 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
022 */
023
024 import java.awt.Component;
025 import java.awt.Dimension;
026 import java.awt.KeyboardFocusManager;
027 import java.awt.Point;
028 import java.awt.Toolkit;
029 import java.awt.datatransfer.Clipboard;
030 import java.awt.datatransfer.Transferable;
031 import java.awt.event.ActionEvent;
032 import java.awt.event.ActionListener;
033 import java.awt.event.MouseAdapter;
034 import java.awt.event.MouseEvent;
035 import java.awt.event.MouseListener;
036 import java.beans.PropertyChangeEvent;
037 import java.beans.PropertyChangeListener;
038 import java.io.File;
039 import java.util.ArrayList;
040 import java.util.Arrays;
041 import java.util.HashMap;
042 import java.util.List;
043 import java.util.Properties;
044 import java.util.logging.Level;
045 import java.util.logging.Logger;
046 import java.util.prefs.BackingStoreException;
047 import java.util.prefs.Preferences;
048 import javax.swing.Action;
049 import javax.swing.JFileChooser;
050 import javax.swing.JMenu;
051 import javax.swing.JMenuItem;
052 import javax.swing.JOptionPane;
053 import javax.swing.JPopupMenu;
054 import javax.swing.SwingUtilities;
055 import javax.swing.TransferHandler;
056 import javax.swing.UIManager;
057 import de.mospace.lang.Array;
058 import de.mospace.lang.ExceptionHandler;
059 import de.mospace.lang.FullTextString;
060 import de.mospace.swing.MiniShell;
061 import de.mospace.swing.text.FullTextStringInputDialog;
062 import helliker.id3.APICImage;
063 import net.sourceforge.mp3dings.datatransfer.DataTransferHandler;
064 import net.sourceforge.mp3dings.editors.APICImageEditor;
065 import net.sourceforge.mp3dings.export.*;
066 import net.sourceforge.mp3dings.utils.*;
067
068 /** The Context Menu for all four mp3dings tables. Most user actions on table
069 * entries are defined here. **/
070 public class TableContextMenu extends JPopupMenu implements ActionListener,
071 DatabaseConfigPopup.Trigger{
072 private static final Logger logger = Logger.getLogger(TableContextMenu.class.getPackage().getName());
073 private int[] selectedRows;
074 private int[] selectedCols;
075 private ContextAction[] actions;
076 private JMenuItem[] changeCaseItems;
077 private List exportModes;
078 private final JMenuItem saveImages;
079 private Dimension mySize;
080 private Point screen;
081 private String cwd = null;
082 protected final static int ROW = 0;
083 protected final static int COL = 1;
084 protected final static int ALL = 2;
085 private final static int INVERTCOLS = 3;
086 private final static int INVERTROWS = 4;
087 private final static String[] EXPORTERS = AbstractExporter.getImplementations();
088 private final static int CTRL_MASK = ActionEvent.CTRL_MASK;
089 private final static int SHIFT_MASK = ActionEvent.SHIFT_MASK;
090 private final static int ALT_MASK = ActionEvent.ALT_MASK;
091 private final static int EXPORT_TO_DATABASE = Integer.MAX_VALUE;
092
093 private PopupListener pl;
094 private Mp3dingsTable activeTable;
095 private DataTableModel data;
096 private ReplaceDialogue replace;
097 private ReplaceDialogue findOnly;
098 private DatabaseExporter dbexporter;
099 /** Queue for copyTo operations.
100 * bgIOQueue == null <-> no copying in progress
101 * bgIOQueue != null && bgIOQueue.size() == 0 <->
102 * exactly one copy operation in progress
103 * bgIOQueue != null && bgIOQueue.size() == n != 0
104 * one copy operation in progress and n operations waiting.
105 * The copy operations are stored as FileCopyRunnables in the Queue.
106 **/
107 private List bgIOQueue;
108
109 /** Construts a new TableContextMenu operating on the specified
110 * DataTableModel and its dependant tables. **/
111 public TableContextMenu(DataTableModel d){
112 Toolkit tk = Toolkit.getDefaultToolkit();
113 data = d;
114 /* BUILDING THE MENU */
115 actions = buildActions();
116 int ctrlShift = CTRL_MASK + SHIFT_MASK;
117 int ctrlAlt = CTRL_MASK + ALT_MASK;
118
119 /* play, enqueue, export */
120 int pos = 0;
121 int len = 2;
122 ContextAction.addItems(this, actions, pos, len);
123 pos += len;
124
125 add(buildExportMenu());
126 addSeparator();
127
128 /* clear, set, counter, checksums, changecase */
129 len = 4;
130 ContextAction.addItems(this, actions, pos, len);
131 pos += len;
132
133 add(buildChangeCaseMenu());
134 addSeparator();
135
136 /* find, replace, find Dups */
137 len = 3;
138 ContextAction.addItems(this, actions, pos, len);
139 pos += len;
140 addSeparator();
141
142 /* selection */
143 len = 3;
144 JMenu jm = new JMenu(Globals.getString("CONTEXT_MENU_SELECT"));
145 ContextAction.addItems(jm, actions, pos, len).getAction();
146 pos += len;
147
148 add(jm);
149
150 /* edit */
151 jm = new JMenu(Globals.getString("CONTEXT_MENU_EDIT"));
152 len = 3;
153 ContextAction.addItems(jm, actions, pos, len).getAction();
154 add(jm);
155 pos += len;
156 this.addSeparator();
157
158 /* remove, copyTo, saveTo */
159 len = 3;
160 saveImages = ContextAction.addItems(this, actions, pos, len);
161 pos += len;
162 /* delete */
163 ContextAction.addItems(this, actions, pos++, 1);
164
165 String[] keys = new String[0];
166 try{
167 keys = ExternalApplication.getPrefNode().keys();
168 } catch (BackingStoreException ex){
169 logger.severe("Cannot load external applications.");
170 Globals.logStackTrace(logger, Level.SEVERE, ex);
171 }
172
173 jm = new ExternalApplicationMenu(Globals.getString("HELPER_APPLICATIONS")){
174 public File[] getFiles(int exporter){
175 if (activeTable.isEditing()){
176 activeTable.getCellEditor().stopCellEditing();
177 }
178 saveFocus();
179 try {
180 storeSelection();
181 } catch (Exception ex){
182 logger.warning("Cannot store selection");
183 Globals.logStackTrace(logger, ex);
184 return null;
185 }
186 return TableContextMenu.this.getFiles(exporter);
187 }
188 public MiniShell getConsole(){
189 return getOwner().getMiniShell();
190 }
191 };
192 add(jm);
193
194 pl = new PopupListener();
195 pack();
196 mySize = this.getPreferredSize();
197 Dimension scr = tk.getScreenSize();
198 java.awt.Insets ins = tk.getScreenInsets(
199 java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment()
200 .getDefaultScreenDevice().getDefaultConfiguration()
201 );
202 screen = new Point(scr.width-ins.right,scr.height-ins.bottom);
203
204 KeyboardFocusManager focusManager =
205 KeyboardFocusManager.getCurrentKeyboardFocusManager();
206 focusManager.addPropertyChangeListener(
207 new PropertyChangeListener() {
208 public void propertyChange(PropertyChangeEvent e) {
209 String prop = e.getPropertyName();
210 if (("focusOwner".equals(prop)) &&
211 (e.getNewValue() != null) &&
212 ((e.getNewValue()) instanceof Mp3dingsTable)) {
213 activeTable = (Mp3dingsTable) e.getNewValue();
214 }
215 }
216 }
217 );
218 }
219
220 private JMenu buildExportMenu(){
221 /* export */
222 final int expLength = EXPORTERS.length;
223 JMenu jm = new JMenu(Globals.getString("CONTEXT_MENU_EXPORT"));
224 jm.setMnemonic(((Integer) Globals.
225 getObject("CONTEXT_MENU_EXPORT_MNEMONICS")).intValue());
226 exportModes = new ArrayList(expLength * 2);
227 JMenuItem jmi;
228 for (int i = 0; i<expLength; i++){
229 Throwable error = null;
230 try{
231 jmi = new JMenuItem(
232 ((AbstractExporter) Class.forName(EXPORTERS[i]).newInstance())
233 .getName()
234 );
235 jmi.addActionListener(this);
236 jm.add(jmi);
237 exportModes.add(jmi);
238 } catch (InstantiationException ex){
239 error = ex;
240 } catch (IllegalAccessException ex){
241 error = ex;
242 } catch (ClassNotFoundException ex){
243 error = ex;
244 } finally {
245 if(error != null){
246 logger.warning("Error instantiating exporter "+ EXPORTERS[i]);
247 logger.warning(error.toString());
248 }
249 }
250 }
251 final JMenu jmDB = new DatabaseConfigPopup(this, DatabaseConfigPopup.EXPORT);
252 jmDB.setText("Database entries");
253 jm.add(jmDB);
254 return jm;
255 }
256
257 private JMenu buildChangeCaseMenu(){
258 JMenu jm = new JMenu(Globals.getString("CONTEXT_MENU_CHANGE_CASE"));
259 jm.setMnemonic(((Integer) Globals.
260 getObject("CONTEXT_MENU_CHANGE_CASE_MNEMONICS")).intValue());
261 int m = CaseChanger.getNumModes();
262 changeCaseItems = new JMenuItem[m];
263 for (int i = 0;i<m;i++){
264 changeCaseItems[i] = new JMenuItem(CaseChanger.getModeName(i));
265 changeCaseItems[i].addActionListener(this);
266 jm.add(changeCaseItems[i]);
267 }
268 return jm;
269 }
270
271 private ContextAction[] buildActions(){
272 int k = -1;
273 Integer key;
274 ContextAction[] self = new ContextAction[25];
275 String name;
276
277 /* play */
278 key = Globals.getKeyObject("CONTEXT_MENU_PLAY_MNEMONICS");
279 name = Globals.getString("CONTEXT_MENU_PLAY");
280 self[++k] = new ContextAction(name, key, this){
281 public void processEvent(ActionEvent e){
282 play(0);
283 }
284 };
285
286 /* enqueue */
287 key = Globals.getKeyObject("CONTEXT_MENU_ENQUEUE_MNEMONICS");
288 name = Globals.getString("CONTEXT_MENU_ENQUEUE");
289 self[++k] = new ContextAction(name, key, this){
290 public void processEvent(ActionEvent e){
291 play(1);
292 }
293 };
294
295 /* export goes here */
296
297 /* clear */
298 key = Globals.getKeyObject("CONTEXT_MENU_CLEAR_SELECTED_MNEMONICS");
299 name = Globals.getString("CONTEXT_MENU_CLEAR_SELECTED");
300 self[++k] =
301 new ContextAction(name, key, this){
302 public void processEvent(ActionEvent e){
303 setValue(null, true);//new String(""));
304 restoreSelection();
305 restoreFocus();
306 }
307 };
308
309 /* set */
310 key = Globals.getKeyObject("CONTEXT_MENU_SET_SELECTED_MNEMONICS");
311 name = Globals.getString("CONTEXT_MENU_SET_SELECTED");
312 self[++k] =
313 new ContextAction(name, key, this){
314 public void processEvent(ActionEvent e){
315 setValue(null, false);
316 restoreSelection();
317 restoreFocus();
318 }
319 };
320
321 /* counter */
322 key = Globals.getKeyObject("CONTEXT_MENU_COUNTER_MNX");
323 name = Globals.getString("CONTEXT_MENU_COUNTER");
324 self[++k] =
325 new ContextAction(name, key, this){
326 public void processEvent(ActionEvent e){
327 counter();
328 restoreSelection();
329 restoreFocus();
330 }
331 };
332
333 /* checksums */
334 key = Globals.getKeyObject("CONTEXT_MENU_CHECKSUM_MNEMONICS");
335 name = Globals.getString("CONTEXT_MENU_CHECKSUM");
336 self[++k] =
337 new ContextAction(name, key, this){
338 public void processEvent(ActionEvent e){
339 insertChecksums((Component) e.getSource());
340 }
341 };
342
343 /* find only */
344 key = Globals.getKeyObject("CONTEXT_MENU_FIND_MNEMONICS");
345 name = Globals.getString("CONTEXT_MENU_FIND");
346 self[++k] =
347 new ContextAction(name, key, this){
348 public void processEvent(ActionEvent e){
349 if (findOnly == null){
350 findOnly = new ReplaceDialogue(getOwner(),false);
351 }
352 findOnly.setScope(activeTable);
353 findOnly.actionPerformed(e);
354 }
355 };
356
357 /* find/replace */
358 key = Globals.getKeyObject("CONTEXT_MENU_RP_SELECTED_MNEMONICS");
359 name = Globals.getString("CONTEXT_MENU_RP_SELECTED");
360 self[++k] =
361 new ContextAction(name, key, this){
362 public void processEvent(ActionEvent e){
363 if (replace == null){
364 replace = new ReplaceDialogue(getOwner());
365 replace.invokeWhenDone(new Runnable(){
366 public void run(){
367 restoreSelection();
368 restoreFocus();
369 }
370 });
371 }
372 replace.setScope(activeTable);
373 replace.actionPerformed(e);
374 }
375 };
376
377 /* find duplicates */
378 key = Globals.getKeyObject("CONTEXT_MENU_FIND_DUPLICATES_MNEMONICS");
379 name = Globals.getString("CONTEXT_MENU_FIND_DUPLICATES");
380 self[++k] =
381 new ContextAction(name, key, this){
382 public void processEvent(ActionEvent e){
383 findDups();
384 }
385 };
386
387 /* change case goes here */
388
389 /* selection */
390 /* row *//* invert rows */
391 key = Globals.getKeyObject("CONTEXT_MENU_SELECT_ROW_MNEMONICS");
392 String[] names = new String[]{
393 Globals.getString("CONTEXT_MENU_SELECT_ROW"),
394 Globals.getString("SELECT_INVERTROWS")
395 };
396 self[++k] =
397 new ContextAction(names, key, this){
398 public void processEvent(ActionEvent e){
399 if((e.getModifiers() & SHIFT_MASK) == SHIFT_MASK){
400 select(INVERTROWS);
401 } else {
402 select(ROW);
403 }
404 }
405 };
406
407 /* column *//* invert cols */
408 key = Globals.getKeyObject("CONTEXT_MENU_SELECT_COL_MNEMONICS");
409 names = new String[]{
410 Globals.getString("CONTEXT_MENU_SELECT_COL"),
411 Globals.getString("SELECT_INVERTCOLS")
412 };
413 self[++k] =
414 new ContextAction(names , key, this){
415 public void processEvent(ActionEvent e){
416 if((e.getModifiers() & SHIFT_MASK) == SHIFT_MASK){
417 select(INVERTCOLS);
418 } else {
419 select(COL);
420 }
421 }
422 };
423
424 /* all */
425 key = Globals.getKeyObject("CONTEXT_MENU_SELECT_ALL_MNEMONICS");
426 name = Globals.getString("CONTEXT_MENU_SELECT_ALL");
427 self[++k] =
428 new ContextAction(name, key, this){
429 public void processEvent(ActionEvent e){
430 select(ALL);
431 }
432 };
433
434 /* cut, copy, paste */
435 /* cut */
436 key = Globals.getKeyObject("CUT_MNEMONIC");
437 name = Globals.getString("CUT");
438 self[++k] = new ContextAction(name, key, this){
439 public void processEvent(ActionEvent e){
440 cut();
441 }
442 };
443
444 /* copy */
445 key = Globals.getKeyObject("COPY_MNEMONIC");
446 name = Globals.getString("COPY");
447 self[++k] = new ContextAction(name, key, this){
448 public void processEvent(ActionEvent e){
449 copy();
450 }
451 };
452 /* paste */
453 key = Globals.getKeyObject("PASTE_MNEMONIC");
454 name = Globals.getString("PASTE");
455 self[++k] = new ContextAction(new String[]{
456 name,
457 Globals.getString("APPEND"),
458 Globals.getString("APPEND_WITH_SPACE")
459 }, key, this){
460 public void processEvent(ActionEvent e){
461 paste(e);
462 }
463 };
464
465
466 /* remove */
467 key = Globals.getKeyObject("CONTEXT_MENU_RM_SELECTED_MNEMONICS");
468 name = Globals.getString("CONTEXT_MENU_RM_SELECTED");
469 self[++k] =
470 new ContextAction(name, key, this){
471 public void processEvent(ActionEvent e){
472 removeSelectedRows();
473 }
474 };
475
476 /* copyTo */
477 key = Globals.getKeyObject("CONTEXT_MENU_COPY_MNEMONICS");
478 name = Globals.getString("CONTEXT_MENU_COPY");
479 self[++k] = new ContextAction(name, key, this){
480 public void processEvent(ActionEvent e){
481 copyTo();
482 }
483 };
484
485 /* save images to */
486 key = Globals.getKeyObject("SAVE_IMAGES_MNX");
487 name = Globals.getString("SAVE_IMAGES_TO");
488 self[++k] = new ContextAction(name, key, this){
489 public void processEvent(ActionEvent e){
490 saveImagesTo();
491 }
492 };
493
494 /* delete */
495 key = Globals.getKeyObject("CONTEXT_MENU_DELETE_MNEMONICS");
496 name = Globals.getString("CONTEXT_MENU_DELETE");
497 self[++k] = new ContextAction(name, key, this){
498 public void processEvent(ActionEvent e){
499 deleteFiles();
500 }
501 };
502
503 /* crop self[] array */
504 ContextAction[] a = self;
505 self = new ContextAction[++k];
506 System.arraycopy(a,0,self,0,k);
507 return self;
508 }
509
510 /** Returns the popup listener that triggers the display of the
511 * context menu. */
512 public MouseListener getPopupListener(){
513 return pl;
514 }
515
516 /** Returns the currently active table. **/
517 public Mp3dingsTable getActiveTable(){
518 return activeTable;
519 }
520
521 /** Removes the currently selected mp3 files from all tables. **/
522 private void removeSelectedRows(){
523 activeTable.clearSelection();
524 int[] rows = activeTableToDataTable(selectedRows);
525 data.removeRows(rows);
526 }
527
528 /** Transforms the given set of active table row numbers into data
529 * table entry numbers
530 * @throws ClassCastException if the active model is not a {@link SortableTableModel}
531 **/
532 private int[] activeTableToDataTable(int[] rows){
533 return data.getRows(getActiveModel().getEntries(rows));
534 }
535
536 /** Transforms the given active table row number into the corresponding data
537 * table entry number.
538 * @throws ClassCastException if the active model is not a {@link SortableTableModel}
539 **/
540 private int activeTableToDataTable(int row){
541 return data.getRows(getActiveModel().getEntries(row));
542 }
543
544 private Object[] getField(Field field, boolean fileFallback){
545 Mp3dingsTableModel tm;
546 Object[] obj = new Object[selectedRows.length];
547 int c;
548 int[] masterRows = activeTableToDataTable(selectedRows);
549 int[] rows = selectedRows;
550 try {
551 tm = getActiveModel();
552 } catch (ClassCastException ex){
553 tm = null;
554 }
555 if (
556 (tm == null || tm.getColumn(field)< 0)){
557 tm = data;
558 rows = masterRows;
559 }
560 Mp3FileReader mfr = new Mp3FileReader(tm.getFilters());
561 if ((c = tm.getColumn(field)) >= 0){
562 for (int i = 0; i<obj.length; i++){
563 obj[i] = tm.getValueAt(rows[i],c);
564 if(obj[i] == null && fileFallback){
565 obj[i] = mfr.getField(data.getFile(masterRows[i]),
566 field);
567 }
568 }
569 } else {
570 for (int i = 0; i<obj.length; i++){
571 obj[i] = mfr.getField(data.getFile(masterRows[i]),field);
572 }
573 }
574 return obj;
575 }
576
577 /** Exports the selected rows into a file.
578 * @param filename the name of the file into which dara will be written
579 * @param mode an integer indicating the file format
580 * @return number of rows exported
581 * @see #EXPORTERS
582 **/
583 private synchronized int exportData(int mode, StringBuffer filename){
584 Object[] exportFields;
585 Object[][] exportData;
586 Exporter exp = null;
587
588 /* get export filter (Exporter)*/
589 if(mode < EXPORTERS.length){
590 try{
591 Class cl = Class.forName(EXPORTERS[mode]);
592 java.lang.reflect.Constructor constr = cl.getConstructor(new Class[]{});
593 exp = (AbstractExporter) constr.newInstance(new Object[]{});
594 } catch (ClassNotFoundException ex){
595 setStatus(Globals.getString("EXPORT_FILTER_ERROR1")+" (" +
596 EXPORTERS[mode]+")");
597 return 0;
598 } catch (Exception ex){
599 setStatus(Globals.getString("EXPORT_FILTER_ERROR2")+" "+
600 EXPORTERS[mode]);
601 return 0;
602 }
603 } else if(mode == EXPORT_TO_DATABASE){
604 if(dbexporter == null || !dbexporter.isAlive()){
605 try{
606 Properties p = DatabaseExporter.loadConfig();
607 dbexporter = new DatabaseExporter(p, getOwner().app);
608 } catch(Exception ex){
609 (new DialogExceptionHandler("Export error\n{0}"/**/, getOwner())).handleException(ex);
610 return 0;
611 }
612 }
613 exp = dbexporter;
614 } else {
615 throw new IllegalArgumentException("Unknown export mode " + mode);
616 }
617
618 // for CSV-export: set the exporter keys dynamically
619 if(exp instanceof net.sourceforge.mp3dings.export.CSVExporter){
620 net.sourceforge.mp3dings.export.CSVExporter cexp =
621 (net.sourceforge.mp3dings.export.CSVExporter) exp;
622 final int nn = selectedCols.length;
623 Mp3dingsTableModel stm = getActiveModel();
624 Field[] keys = new Field[nn];
625 HashMap hd = new HashMap();
626 for (int c = 0; c<nn; c++){
627 keys[c] = stm.getField(selectedCols[c]);
628 hd.put(keys[c], activeTable.getColumnName(selectedCols[c]));
629 }
630 cexp.setKeys(keys,keys,null);
631 cexp.setHeaderData(hd);
632 }
633 // gather export data
634 exportFields = exp.getKeys();
635 exportData = new Object[selectedRows.length][exportFields.length];
636 Object[] fieldData;
637 for (int i = 0; i<exportFields.length; i++){
638 Field field = (Field) exportFields[i];
639 fieldData = getField(field, exp.getFileFallback());
640 for (int r = 0; r<selectedRows.length; r++){
641 exportData[r][i] = fieldData[r];
642 }
643 }
644 int rows = 0;
645 try{
646 if (exp instanceof AbstractExporter){
647 rows = ((AbstractExporter) exp).export(exportFields, exportData, filename);
648 } else {
649 rows = exp.export(exportFields, exportData);
650 }
651 if(rows > 0){
652 setStatus(Globals.getString("EXPORT_SUCCESS"));
653 }
654 } catch (ExportException ex) {
655 (new DialogExceptionHandler("Export error\n{0}"/**/, getOwner())).handleException(ex);
656 setStatus(Globals.getString("IO_ERROR"));
657 }
658 return rows;
659 }
660
661 private static File queryDirectory(Component owner, String cwd){
662 JFileChooser jfc = new JFileChooser();
663 if (cwd != null){
664 try{
665 jfc.setCurrentDirectory(
666 new File(cwd)
667 );
668 } catch (Exception ex){
669 }
670 }
671 jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
672 File xdest;
673 do{
674 if (jfc.showOpenDialog(owner) != JFileChooser.APPROVE_OPTION){
675 return null;
676 }
677 xdest = jfc.getSelectedFile();
678 if (!xdest.exists()){
679 int ret = JOptionPane.showConfirmDialog(owner,
680 Globals.getMessage("COPY_DIR_DOES_NOT_EXIST",
681 xdest.getAbsolutePath()),
682 Globals.getString("WARNING"),
683 JOptionPane.YES_NO_OPTION,
684 JOptionPane.WARNING_MESSAGE);
685 if ( ret == JOptionPane.YES_OPTION){
686 xdest.mkdirs();
687 }
688 }
689 }while(xdest == null || !xdest.exists() || !xdest.isDirectory());
690 return xdest;
691 }
692
693 private void copyTo(){
694 File target = queryDirectory(getOwner(), cwd);
695 if (target == null){
696 return;
697 }
698 cwd = target.toString();
699 FileCopyRunnable fcr = new FileCopyRunnable(target, getFiles()){
700 public void finished(){
701 setStatus(
702 Globals.getMessage("COPY_SUCCESS",
703 new Object[]{
704 new Integer(getFilesCopied()),
705 new Integer(getTotalFiles())
706 })
707 );
708 if (getOwner() != null){
709 getOwner().removeStatusBar(getStatusBar());
710 }
711 if (bgIOQueue != null){
712 if (bgIOQueue.size() == 0){
713 bgIOQueue = null;
714 } else {
715 new Thread((Runnable) bgIOQueue.remove(0)).start();
716 }
717 }
718 }
719 };
720
721 if (getOwner() != null){
722 getOwner().addStatusBar(fcr.getStatusBar());
723 }
724 if (bgIOQueue == null){
725 bgIOQueue = new ArrayList();
726 new Thread(fcr).start();
727 } else {
728 bgIOQueue.add(fcr);
729 }
730 setStatus(Globals.getString("COPY_START"));
731 }
732
733 private void saveImagesTo(){
734 final File targetdir = queryDirectory(getOwner(), cwd);
735 if (targetdir == null){
736 return;
737 }
738 cwd = targetdir.toString();
739 Mp3dingsTableModel activeModel = getActiveModel();
740 int imageCol = activeModel.getColumn(Field.ATTACHED_PICTURE);
741 if(imageCol == -1){
742 return;
743 }
744 final int rows = selectedRows.length;
745 final APICImage[] images = new APICImage[rows];
746 for(int i=0; i<rows; i++){
747 images[i] = (APICImage) activeModel.getValueAt(selectedRows[i], imageCol);
748 }
749 ImageSaveRunnable isr = new ImageSaveRunnable(targetdir, getFiles(), images){
750 public void finished(){
751 setStatus(Globals.getMessage("SAVE_IMAGES_SX",
752 new Object[]{new Integer(getImagesSaved()),
753 new Integer(getTotalImages())}));
754 if (getOwner() != null){
755 getOwner().removeStatusBar(getStatusBar());
756 }
757 if (bgIOQueue != null){
758 if (bgIOQueue.size() == 0){
759 bgIOQueue = null;
760 } else {
761 new Thread((Runnable) bgIOQueue.remove(0)).start();
762 }
763 }
764 }
765 };
766
767 if (getOwner() != null){
768 getOwner().addStatusBar(isr.getStatusBar());
769 }
770 if (bgIOQueue == null){
771 bgIOQueue = new ArrayList();
772 new Thread(isr).start();
773 } else {
774 bgIOQueue.add(isr);
775 }
776 setStatus("Saving images to " + targetdir);
777 ;//Globals.getString("COPY_START"));
778 }
779
780
781 /**
782 * Starts playback of the selected files.
783 * @param k Playback mode 0 for "play" and 1 for "enqueue"
784 **/
785 private void play(int k){
786 try{
787 Preferences pref = ExternalApplication.getPrefNode().node("builtin");
788 final ExternalApplication app = ExternalApplication.load(pref, k);
789 int exporter = (app.getCallMode() == ExternalApplication.PLAYLIST)
790 ? app.getExporter()
791 : -1;
792 final File[] f = getFiles(exporter);
793
794 Runnable runWhenDone = new Runnable(){
795 public void run(){
796 String msg = Globals.getMessage("EXT_APP_RETURNED", app.getName());
797 System.out.println(msg);
798 setStatus(msg);
799 }
800 };
801 if(app.needsMp3dingsConsole()){
802 getOwner().getMiniShell().getShowAction().actionPerformed(null);
803 }
804 app.execute(f,
805 getOwner().getMiniShell().getProcessIOPane(),
806 playExceptionHandler, runWhenDone);
807 } catch (Exception ex){
808 playExceptionHandler.handleException(ex);
809 }
810 }
811
812 private ExceptionHandler playExceptionHandler =
813 new DialogExceptionHandler(Globals.getString("PLAY_FAILED"), getOwner());
814
815 public MainFrame getOwner(){
816 return (activeTable != null)? activeTable.getFrame() : null;
817 }
818
819 private File[] getFiles(int exporter){
820 if (exporter < 0){
821 return getFiles();
822 } else {
823 int expmode = exporter;
824 StringBuffer fname = new StringBuffer();
825
826 /* get Extension */
827 try{
828 fname.append(((AbstractExporter)
829 Class.forName(EXPORTERS[expmode])
830 .newInstance()).getExtension());
831 } catch (InstantiationException ex){
832 handleException(ex);
833 } catch (IllegalAccessException ex){
834 handleException(ex);
835 } catch (ClassNotFoundException ex){
836 handleException(ex);
837 }
838
839 /* make tmpfile and tmpfile name */
840 try {
841 File f = File.createTempFile("mp3dings",fname.toString());
842 f.deleteOnExit();
843 fname = new StringBuffer(f.getAbsolutePath());
844 } catch (Exception ex){
845 fname = new StringBuffer("mp3dingsPlaylist");
846 }
847 int filecount = exportData(expmode,fname);
848 return new File[]{new File(fname.toString())};
849 }
850 }
851
852 public File[] getFiles(){
853 int[] masterRows = activeTableToDataTable(selectedRows);
854 int m = masterRows.length;
855 File[] result = new File[m];
856 for (int i = 0; i<m; i++){
857 result[i] = data.getFile(masterRows[i]);
858 }
859 return result;
860 }
861
862
863 private void deleteFiles(){
864 int confirmed = JOptionPane.showConfirmDialog(
865 getOwner(),
866 Globals.getString("CONFIRM_DELETE"),
867 Globals.getString("CONFIRM"),
868 JOptionPane.YES_NO_CANCEL_OPTION,
869 JOptionPane.QUESTION_MESSAGE);
870 if (confirmed != JOptionPane.YES_OPTION){
871 return;
872 }
873
874 File f;
875 int fileCounter = 0;
876 int[] masterRows = activeTableToDataTable(selectedRows);
877 int m = masterRows.length;
878 int[] success = new int[m];
879 for (int i = 0; i<m; i++){
880 f = data.getFile(masterRows[i]);
881 if(!f.delete()){
882 continue;
883 }
884 success[fileCounter] = masterRows[i];
885 fileCounter++;
886 }
887 f = null;
888
889 if(fileCounter>0){
890 int[] masterRowsToRemove = new int[fileCounter];
891 System.arraycopy(success, 0, masterRowsToRemove, 0, fileCounter);
892 data.removeRows(masterRowsToRemove);
893 }
894
895 String statusOut = Globals.getMessage("DELETE_SUCCESS", fileCounter);
896 //Succesfully deleted x file(s).
897 if (fileCounter<m){
898 statusOut += " " +
899 Globals.getMessage("DELETE_FAILURE", m-fileCounter);
900 // Failed to delete x file(s).
901 }
902 setStatus(statusOut);
903 activeTable.clearSelection();
904 }
905
906
907 private void caseChange(int mode){
908 int n = selectedRows.length;
909 int m = selectedCols.length;
910 Mp3dingsTableModel t = getActiveModel();
911 String v;
912 int coltype;
913 for (int j = 0;j<m; j++){
914 if (!t.isCellEditable(0,selectedCols[j])){
915 continue;
916 }
917 coltype = t.getField(selectedCols[j]).type();
918 if (coltype == Field.TYPE_STRING ||
919 coltype == Field.TYPE_LONGTEXT){
920 for (int i = 0; i<n; i++){
921 v = (String) t.get(selectedRows[i], selectedCols[j]);
922 if(v == null || v.equals("")){
923 continue;
924 }
925 t.set(CaseChanger.changeCase(v, mode),
926 selectedRows[i],
927 selectedCols[j]);
928 }
929 }
930 }
931 t.fireDataChanged(m*n);
932 t.fireTableDataChanged();
933 }
934
935 private APICImageEditor.EditorDialog imgdialog;
936 private Object getValueForObject(Object x, Class target, String colName){
937 String message =
938 Globals.getMessage("CONTEXT_MENU_PROMPT_FOR_VALUE", colName);
939 Object value = null;
940 if (target == Boolean.class){
941 value = JOptionPane.showInputDialog(
942 getOwner(),
943 message, null, JOptionPane.PLAIN_MESSAGE, null,
944 new Boolean[]{
945 Boolean.TRUE,
946 Boolean.FALSE
947 }, x);
948 } else if((target == de.mospace.lang.FullTextString.class)){
949 value = FullTextStringInputDialog.showDialog(getOwner(),
950 message, (FullTextString) x);
951 } else if (target == String.class && x != null && ((String) x).length() > 48){
952 value = FullTextStringInputDialog.showDialog(getOwner(),
953 message, new FullTextString((String) x));
954 if(value != null){
955 value = value.toString().replaceAll("\n"," ");
956 }
957 } else if (target == APICImage.class){
958 synchronized(this){
959 if(imgdialog == null){
960 imgdialog = APICImageEditor.getDialog(getOwner(),
961 message, APICImageEditor.getDefault());
962 imgdialog.setModal(true);
963 }
964 }
965 imgdialog.setImage((APICImage) x);
966 imgdialog.setVisible(true);
967 if(imgdialog.isOKPressed()){
968 try{
969 value = imgdialog.getImage();
970 } catch (Exception ex){
971 JOptionPane.showMessageDialog(getOwner(), ex, "Image not changed", JOptionPane.WARNING_MESSAGE);
972 }
973 }
974 } else {
975 value = JOptionPane.showInputDialog(
976 getOwner(),
977 message, x);
978 }
979 return value;
980 }
981
982 /**@throws ClassCastException if the model of the JTable is not an
983 * Mp3dingsTableModel.
984 **/
985 public Mp3dingsTableModel getActiveModel(){
986 return (Mp3dingsTableModel) activeTable.getModel();
987 }
988
989 private void insertChecksums(Component trigger){
990 Mp3dingsTableModel t = getActiveModel();
991
992 int targetCol = -1;
993 if(selectedCols.length > 0){
994 int col = selectedCols[0];
995 Field field = t.getField(col);
996 int type = field.type();
997 if(t.getEditable(field) &&
998 (type == Field.TYPE_STRING || type == Field.TYPE_LONGTEXT)){
999 targetCol = col;
1000 }
1001 }
1002 if(targetCol == -1){
1003 setStatus(Globals.getString("CHECKSUM_INVALID_COLUMN"));
1004 return;
1005 }
1006 (new InsertChecksumTask( getOwner(),
1007 trigger,
1008 t,
1009 selectedRows,
1010 targetCol,
1011 getOwner().app){
1012 public void finished(){
1013 super.finished();
1014 TableContextMenu.this.setStatus(getStatus());
1015 }
1016 }).start();
1017 }
1018
1019 /** Sets the value of the active cells by prompting the user for input.
1020 * @param obj default cell content
1021 * @param clear if clear is true and obj is null all cells will be emptied
1022 **/
1023 private void setValue(Object obj, boolean clear){
1024 int[] rows = selectedRows;
1025 int[] cols = selectedCols;
1026 int fieldCount = 0;
1027 Mp3dingsTableModel t = getActiveModel();
1028 Object v = obj;
1029 Object model = null;
1030 int[] colnull = new int[1];
1031
1032 /* loop over selected columns, skip non-editable columns */
1033 for (int j = 0; j<cols.length; j++){
1034 int col = cols[j];
1035 Field field = t.getField(col);
1036 if (!t.getEditable(field)){
1037 continue;
1038 }
1039 /* determine column class */
1040 Class colClass = t.getColumnClass(col);
1041 /* If obj is non-null and of the appropriate class use it as the
1042 * new value for the selected cells in the current column */
1043 if (obj != null && colClass.isAssignableFrom(obj.getClass())){
1044 v = obj;
1045 /* otherwise clear or prompt for a new value (depending on
1046 * whether clear is true) */
1047 } else {
1048 if (clear){
1049 /* Fill in the appropriate empty values */
1050 v = Globals.getNullFor(colClass);
1051 } else {
1052 /* Construct an appropriate default value for the current
1053 * field type. Use the value of the first selected cell
1054 * in this column if possible. Otherwise try the last
1055 * default value or if that fails too, use a blank default
1056 * value.
1057 */
1058 v = t.getValueAt(rows[0], col);
1059 if (v != null && !v.toString().equals("")){
1060 model = v;
1061 }
1062 if (model == null || !colClass.isAssignableFrom(model.getClass())){
1063
1064 /* construct default value */
1065 model = Globals.getNullFor(colClass);
1066 int fieldType = field.type();
1067 if(fieldType == Field.TYPE_NUMERIC){
1068 model = (Number) (Globals.asInteger(0));
1069 }
1070 if(model == null && fieldType != Field.TYPE_PICTURE){
1071 model = "";
1072 }
1073 }
1074 /* Prompt for a new value. */
1075 v = getValueForObject(model, colClass, field.longname());
1076 }
1077 }
1078 /* Set cells to new value. Increase field count. */
1079 if(v != null || clear){
1080 colnull[0] = col;
1081 t.setValueAt(v, rows, colnull);
1082 fieldCount += rows.length;
1083 }
1084 /* Display status message.
1085 * "Changed x field(s) to y." */
1086 setStatus(
1087 Globals.getMessage("CONTEXT_MENU_SET_SELECTED_STATUS",
1088 new Object[]{
1089 new Integer(fieldCount),
1090 String.valueOf(v)
1091 }
1092 )
1093 );
1094 fieldCount = 0;
1095 }
1096 }
1097
1098 private boolean hasSelection(){
1099 return selectedCols != null && selectedCols.length != 0 &&
1100 selectedRows != null && selectedCols.length != 0;
1101 }
1102
1103 protected void copy(){
1104 Clipboard clipboard = activeTable.getToolkit().getSystemClipboard();
1105 TransferHandler th = activeTable.getCopyPasteHandler();
1106 if ((clipboard != null) && (th != null)) {
1107 try{
1108 th.exportToClipboard(activeTable,
1109 clipboard, TransferHandler.COPY);
1110 } catch (IllegalStateException ise) {
1111 UIManager.getLookAndFeel().provideErrorFeedback(activeTable);
1112 return;
1113 }
1114 }
1115 }
1116
1117 protected void cut(){
1118 Clipboard clipboard = activeTable.getToolkit().getSystemClipboard();
1119 TransferHandler th = activeTable.getCopyPasteHandler();
1120 if ((clipboard != null) && (th != null)) {
1121 try{
1122 th.exportToClipboard(activeTable,
1123 clipboard, TransferHandler.MOVE);
1124 } catch (IllegalStateException ise) {
1125 UIManager.getLookAndFeel().provideErrorFeedback(activeTable);
1126 return;
1127 }
1128 }
1129 restoreSelection();
1130 restoreFocus();
1131 }
1132
1133 protected void paste(ActionEvent e){
1134 Clipboard clipboard = activeTable.getToolkit().getSystemClipboard();
1135 TransferHandler th = activeTable.getCopyPasteHandler();
1136 Transferable trans = null;
1137 if ((clipboard != null) && (th != null)) {
1138 try{
1139 trans = clipboard.getContents(null);
1140 } catch (IllegalStateException ise) {
1141 UIManager.getLookAndFeel().provideErrorFeedback(activeTable);
1142 return;
1143 }
1144 }
1145 if (trans != null) {
1146 if(th instanceof DataTransferHandler){
1147 int pasteMode = DataTransferHandler.PASTE_OVERWRITE;
1148 if((e.getModifiers() & SHIFT_MASK) == SHIFT_MASK){
1149 pasteMode = DataTransferHandler.PASTE_APPEND;
1150 } else if((e.getModifiers() & ALT_MASK) == ALT_MASK){
1151 pasteMode = DataTransferHandler.PASTE_APPEND_WITH_SPACE;
1152 }
1153 ((DataTransferHandler) th).importData(activeTable, trans, pasteMode);
1154 } else {
1155 th.importData(activeTable, trans);
1156 }
1157 }
1158 }
1159
1160 protected void counter(){
1161 int col = -1;
1162 int targetType = -1;
1163 Mp3dingsTableModel model = getActiveModel();
1164
1165 for(int i=0; col == -1 && i<selectedCols.length;i++){
1166 Field f = model.getField(selectedCols[i]);
1167 if(model.getEditable(f)){
1168 targetType = f.type();
1169 if(targetType == Field.TYPE_STRING ||
1170 targetType == Field.TYPE_LONGTEXT ||
1171 targetType == Field.TYPE_NUMERIC)
1172 {
1173 col = selectedCols[i];
1174 }
1175 }
1176 }
1177 if(col == -1){
1178 return;
1179 }
1180 selectedCols = new int[]{col};
1181 restoreSelection();
1182
1183 final boolean numeric = targetType == Field.TYPE_NUMERIC;
1184 CounterCustomizer ccz = new CounterCustomizer();
1185 ccz.setFormatVisible(!numeric);
1186 int result = JOptionPane.showOptionDialog(
1187 mainFrame(),
1188 ccz.getUI(),
1189 Globals.getString("CONTEXT_MENU_COUNTER"),
1190 numeric
1191 ? JOptionPane.OK_CANCEL_OPTION
1192 : JOptionPane.YES_NO_CANCEL_OPTION,
1193 JOptionPane.QUESTION_MESSAGE,
1194 null,
1195 numeric
1196 ? null
1197 : new String[]{Globals.getString("APPEND"),
1198 Globals.getString("REPLACE"),
1199 Globals.CANCEL},
1200 null);
1201 if(result == JOptionPane.CANCEL_OPTION ||
1202 result == JOptionPane.CLOSED_OPTION){
1203 return;
1204 }
1205 final boolean append = (result == JOptionPane.YES_OPTION);
1206 Counter cnt = ccz.getCounter();
1207 for(int i=0; i<selectedRows.length; i++){
1208 Object newValue = null;
1209 int row = selectedRows[i];
1210 switch(targetType){
1211 case Field.TYPE_LONGTEXT:
1212 case Field.TYPE_STRING:
1213 Object value = null;
1214 if(append){
1215 value = model.getValueAt(row, col);
1216 }
1217 String newval = cnt.getNextFormattedValue();
1218 if(value != null){
1219 newval = value.toString() + newval;
1220 }
1221 newValue = (targetType == Field.TYPE_LONGTEXT)
1222 ? (Object) new FullTextString(newval)
1223 : (Object) newval;
1224 break;
1225 case Field.TYPE_NUMERIC:
1226 newValue = new Integer(cnt.getNextValue());
1227 }
1228 model.setValueAt(newValue, row, col);
1229 }
1230 }
1231
1232
1233 protected void select(int what){
1234 int mode = what;
1235 if(!hasSelection() && (what==INVERTROWS || what == INVERTCOLS)){
1236 mode = ALL;
1237 }
1238 switch(mode){
1239 case ROW:
1240 activeTable.setColumnSelectionInterval(0,
1241 activeTable.getColumnCount() - 1);
1242 break;
1243 case COL:
1244 activeTable.setRowSelectionInterval(0,
1245 activeTable.getRowCount() - 1);
1246 break;
1247 case ALL:
1248 activeTable.selectAll();
1249 break;
1250 case INVERTROWS:
1251 activeTable.invertRowSelection();
1252 break;
1253 case INVERTCOLS:
1254 activeTable.invertColumnSelection();
1255 break;
1256 default:
1257 }
1258 }
1259
1260 protected void findDups(){
1261 (new DuplicateFinder(this)).run();
1262 }
1263
1264 /** Returns the actions provided by this ContextMenu. **/
1265 public Action[] getActions(){
1266 return actions;
1267 }
1268
1269 /** Handles the ActionEvents arising from this ContextMenu's actions. */
1270 public void actionPerformed(ActionEvent e) {
1271 if(activeTable == null){
1272 return;
1273 }
1274 storeSelection();
1275 if (activeTable.isEditing()){
1276 activeTable.getCellEditor().stopCellEditing();
1277 }
1278 Object source = (e.getSource());
1279 /* handle export action */
1280 int sourceIndex = exportModes.indexOf(source);
1281 final String cmd = e.getActionCommand();
1282 if (sourceIndex != -1){
1283 exportData(sourceIndex, null);
1284 } else if (cmd.equals(DatabaseConfigPopup.ACTION_COMMAND)){
1285 exportData(EXPORT_TO_DATABASE, null);
1286 } else if (cmd.equals(DatabaseConfigPopup.CONFIG_CHANGED)){
1287 if(dbexporter != null && dbexporter.isAlive()){
1288 try{
1289 dbexporter.close();
1290 } catch (Exception ex){
1291 logger.severe("Error closing SQL connection.");
1292 logger.severe(ex.toString());
1293 }
1294 }
1295 dbexporter = null;
1296 } else {
1297 /* handle change case action */
1298 sourceIndex = Arrays.asList(changeCaseItems).indexOf(source);
1299 if (sourceIndex != -1){
1300 caseChange(sourceIndex);
1301 }
1302 }
1303 }
1304
1305 protected void restoreSelection(){
1306 if(selectedRows == null || selectedCols == null ||
1307 selectedRows.length == 0 || selectedCols.length == 0){
1308 return;
1309 }
1310
1311 /* clear selection and select first cell with extend=false */
1312 activeTable.changeSelection(selectedRows[0], selectedCols[0],
1313 false, false);
1314
1315 /* select cells */
1316 int[][] sel = Array.getIntervals(selectedRows);
1317 for (int i=0; i<sel.length; i++){
1318 activeTable.addRowSelectionInterval(sel[i][0],sel[i][1]);
1319 }
1320 sel = Array.getIntervals(selectedCols);
1321 for (int i=0; i<sel.length; i++){
1322 activeTable.addColumnSelectionInterval(sel[i][0],sel[i][1]);
1323 }
1324 }
1325
1326 protected void restoreFocus(){
1327 activeTable.restoreFocus();
1328 }
1329
1330 protected void saveFocus(){
1331 activeTable.saveFocus();
1332 }
1333
1334 protected void storeSelection(){
1335 if(activeTable != null){
1336 selectedRows = activeTable.getSelectedRows();
1337 selectedCols = activeTable.getSelectedColumns();
1338 }
1339 }
1340
1341
1342
1343 /** The PopupListener that triggers this ContextMenu. **/
1344 class PopupListener extends MouseAdapter {
1345
1346 public PopupListener(){
1347 }
1348
1349 public void mousePressed(MouseEvent e) {
1350 if(e.getSource() instanceof Mp3dingsTable){
1351 activeTable = (Mp3dingsTable) e.getSource();
1352 if(activeTable.isAncestorOf(e.getComponent())){
1353 activeTable.remove(e.getComponent());
1354 }
1355 maybeShowPopup(e);
1356 }
1357 }
1358 public void mouseReleased(MouseEvent e) {
1359 maybeShowPopup(e);
1360 }
1361 private void maybeShowPopup(MouseEvent e) {
1362 saveFocus();
1363 int mouseRow, mouseCol;
1364 if(e.getSource() instanceof Mp3dingsTable){
1365 activeTable = (Mp3dingsTable) e.getSource();
1366 } else {
1367 return;
1368 }
1369 if (!e.isPopupTrigger()) {
1370 return;
1371 }
1372 Point mouseXY = e.getPoint();
1373 mouseCol = activeTable.columnAtPoint(mouseXY);
1374 mouseRow = activeTable.rowAtPoint(mouseXY);
1375 if( activeTable.getSelectedColumnCount()+
1376 activeTable.getSelectedRowCount() < 1){
1377 activeTable.addColumnSelectionInterval(mouseCol,mouseCol);
1378 activeTable.addRowSelectionInterval(mouseRow,mouseRow);
1379 }
1380 saveImages.setVisible(
1381 ((Mp3dingsTableModel) activeTable.getModel())
1382 .getColumn(Field.ATTACHED_PICTURE) != -1);
1383 Point scr = (Point) screen.clone();
1384 SwingUtilities.convertPointFromScreen(scr,activeTable);
1385 show(e.getComponent(),
1386 (int) Math.min(e.getX(),scr.getX()-mySize.width),
1387 (int) Math.min(e.getY(),scr.getY()-mySize.height));
1388 }
1389 }
1390
1391 /** @deprecated use {@link #getOwner} instead */
1392 public MainFrame mainFrame(){
1393 return getOwner();
1394 }
1395
1396 public void setStatus(String s){
1397 if (getOwner() == null){
1398 System.out.println(s);
1399 } else {
1400 getOwner().setStatus(s);
1401 }
1402 }
1403
1404 private void handleException(Throwable ex){
1405 logger.warning(ex.getMessage());
1406 }
1407
1408 }