001    package net.sourceforge.mp3dings.datatransfer;
002    
003    /*
004     *  Mp3dings - manage mp3 meta-information
005     *  Copyright (C) 2006 Moritz Ringler
006     *  $Id: DataTransferHandler.java 148 2008-12-03 22:00:50Z 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    
023    import java.awt.datatransfer.Clipboard;
024    import java.awt.datatransfer.DataFlavor;
025    import java.awt.datatransfer.StringSelection;
026    import java.awt.datatransfer.Transferable;
027    import java.awt.datatransfer.UnsupportedFlavorException;
028    import java.awt.event.InputEvent;
029    import java.io.File;
030    import java.io.IOException;
031    import java.util.Arrays;
032    import java.util.Collection;
033    import java.util.Collections;
034    import java.util.HashSet;
035    import java.util.Iterator;
036    import java.util.List;
037    import java.net.URI;
038    import java.net.URISyntaxException;
039    import java.util.ArrayList;
040    import java.util.StringTokenizer;
041    import java.util.Set;
042    import java.util.logging.Logger;
043    import javax.swing.JComponent;
044    import javax.swing.JTable;
045    import javax.swing.SwingUtilities;
046    import javax.swing.TransferHandler;
047    import javax.swing.event.TableModelEvent;
048    import de.mospace.lang.FullTextString;
049    import net.sourceforge.mp3dings.AbstractTableModel;
050    import net.sourceforge.mp3dings.DataTableModel;
051    import net.sourceforge.mp3dings.DependentTableModel;
052    import net.sourceforge.mp3dings.Globals;
053    import net.sourceforge.mp3dings.MainFrame;
054    import net.sourceforge.mp3dings.Mp3dingsTable;
055    import net.sourceforge.mp3dings.Mp3dingsTableModel;
056    
057    /**
058     * A TransferHandler that manages Copy/Paste for Mp3dingsTables.
059     * In principle I would like to use it for Drag and Drop as well
060     * but there is a problem when activating Swing Drag and Drop support:
061     * <ol>
062     * <li>You can only register one TransferHandler with
063     * {@link JComponent#setTransferHandler}, you cannot register
064     * one for DnD and one for Copy/Paste.
065     * <li> The TransferHandler has a method
066     * {@link #getSourceActions(JComponent c)} which takes neither the type
067     * of operation (DnD or C/P) nor the DataFlavor (text or files)
068     * as an argument.<br>
069     * If our TransferHandler returns COPY we cannot use 'Cut' on the
070     * contents of the JTables. So this won't work.<br>
071     * If on the other hand it returns COPY_OR_MOVE the default
072     * drag and drop operation will be MOVE and in the case of
073     * files this will (sometimes) lead to moving the files, which
074     * is also unacceptable.
075     * </ol>
076     *
077     *@author    ringler
078     */
079    public class DataTransferHandler extends TransferHandler {
080        private static final Logger logger = Logger.getLogger(DataTransferHandler.class.getPackage().getName());
081        /** Overwrite current table cell contents on paste. **/
082        public final static int PASTE_OVERWRITE = 0;
083        /** Append imported data to current table cell contents on paste. **/
084        public final static int PASTE_APPEND = 1;
085        /** Append a blank character and imported data to current table cell
086            contents on paste. **/
087        public final static int PASTE_APPEND_WITH_SPACE = 2;
088     
089    
090    
091        /** Whether this TransferHandler supports Drag and Drop operations.
092        * @see #exportAsDrag
093        **/
094        protected boolean dndSupported = false;
095        /** Whether this TransferHandler supports Copy/Paste operations.
096        * @see #exportToClipboard
097        **/
098        protected boolean cpSupported = false;
099        private int sourceActions = COPY;
100        private Set disabledExportFlavors = new HashSet();
101        /** a Set containing disjunct groups of flavors that are enabled or
102         *  disabled together */
103        private static Set linkedFlavors = new HashSet();
104        static{
105            Set htmlFlavors = new HashSet();
106            htmlFlavors.add(TransferData.HTML0);
107            htmlFlavors.add(TransferData.HTML1);
108            linkedFlavors.add(htmlFlavors);
109            linkedFlavors.add(Arrays.asList(
110                    (new StringSelection("")).getTransferDataFlavors() ));
111            Set fileFlavors = new HashSet();
112            fileFlavors.add(TransferData.URI_FILE_LIST);
113            fileFlavors.add(DataFlavor.javaFileListFlavor);
114            linkedFlavors.add(fileFlavors);
115        }
116    
117        int[] rows;
118        int[] cols;
119        private static Class objarray = (new Object[][]{{}}).getClass();
120    
121        //Constructors
122    
123        /**  Constructs a new DataTransferHandler that allows the COPY sourceAction
124        *  and all export flavors returned by {@link #getDefaultFlavors()}.
125          *  @param isDnDHandler whether this TransferHandler should handle Drag and
126          *                      Drop operations
127          *  @param isCpHandler whether this TransferHandler should handle
128          *                     Copy/Paste operations
129          */
130        public DataTransferHandler(boolean isDnDHandler, boolean isCpHandler) {
131            dndSupported = isDnDHandler;
132            cpSupported = isCpHandler;
133        }
134    
135        /** Constructs a new DataTransferHandler that supports the specified
136         *  source actions and all export flavors returned by
137         *  {@link #getDefaultFlavors()}.
138         *  @param isDnDHandler whether this TransferHandler should handle Drag and
139         *                      Drop operations
140         *  @param isCpHandler whether this TransferHandler should handle
141         *                     Copy/Paste operations
142         *  @param sourceActions the source actions that this TransferHandler will
143         *                       support, one of
144         *                       TransferHandler.COPY, COPY_OR_MOVE, MOVE, NONE
145         * @see #getSourceActions
146         */
147        public DataTransferHandler(boolean isDnDHandler,
148                                   boolean isCpHandler,
149                                   int sourceActions){
150           this(isDnDHandler, isCpHandler);
151           this.sourceActions = sourceActions;
152        }
153    
154        /** Constructs a new DataTransferHandler that supports the specified
155         *  source actions and export flavors.
156         *  @param isDnDHandler whether this TransferHandler should handle Drag and
157         *                      Drop operations
158         *  @param isCpHandler whether this TransferHandler should handle
159         *                     Copy/Paste operations
160         *  @param sourceActions the source actions that this TransferHandler will
161         *                       support, one of
162         *                       TransferHandler.COPY, COPY_OR_MOVE, MOVE, NONE
163         *  @param initialExportFlavors an array of DataFlavors that this
164         *                              TransferHandler should export.
165         * @see #getSourceActions
166         */
167        public DataTransferHandler(boolean isDnDHandler,
168                                   boolean isCpHandler,
169                                   int sourceActions,
170                                   DataFlavor[] initialExportFlavors){
171            this(isDnDHandler, isCpHandler, sourceActions);
172            disabledExportFlavors.addAll(Arrays.asList(getDefaultFlavors()));
173            disabledExportFlavors.removeAll(Arrays.asList(initialExportFlavors));
174        }
175    
176        //export flavor management
177        /** Returns the DataFlavors that this class can im- and export by default.
178        * @return the DataFlavors supported by this class
179        **/
180        public static DataFlavor[] getDefaultFlavors(){
181            return TransferData.getDefaultFlavors();
182        }
183    
184        /** Returns all flavors that belong to the same group as the argument.
185          * @param flavor the DataFlavor whose group should be returned
186          * @return a Collection containing the DataFlavor that are
187          *         enabled or disabled together with <code>flavor</code>.
188          *         This collection will always contain the method argument.
189          **/
190        private static Collection getLinkedFlavors(DataFlavor flavor){
191            Iterator it = linkedFlavors.iterator();
192            while(it.hasNext()){
193                Collection s = (Collection) it.next();
194                if(s.contains(flavor)){
195                    return s;
196                }
197            }
198            return Collections.singleton(flavor);
199        }
200    
201        /** Disables or enables the export of all default flavors.
202        *  @param b whether export is enabled (true) or disabled (false)
203        * @see #getDefaultFlavors
204        * @see #isExportEnabled
205        **/
206        public void setExportEnabled(boolean b){
207            if(b){
208                disabledExportFlavors.removeAll(Arrays.asList(getDefaultFlavors()));
209            } else {
210                disabledExportFlavors.addAll(Arrays.asList(getDefaultFlavors()));
211            }
212        }
213    
214        /** Disables or enables the export of a specific flavor and its
215        *   linked flavors.
216        *   @param b whether export is enabled (true) or disabled (false)
217        *   @param flavor the flavor whose export should be enabled or disabled
218        *   @see #isExportEnabled
219        **/
220        public void setExportEnabled(DataFlavor flavor, boolean b){
221            Iterator it = getLinkedFlavors(flavor).iterator();
222            while(it.hasNext()){
223                DataFlavor flav = (DataFlavor) it.next();
224                if(b){
225                    disabledExportFlavors.remove(flav);
226                } else {
227                    disabledExportFlavors.add(flav);
228                }
229            }
230        }
231    
232        /** Returns whether export of the specified flavor is currently
233        *   enabled or disabled.
234        *   @param flavor the flavor whose export should be enabled or
235        *                    disabled
236        *   @return whether export of the specified flavor is currently
237        *   enabled or disabled
238        *   @see #setExportEnabled(DataFlavor, boolean)
239        **/
240        public boolean isExportEnabled(DataFlavor flavor){
241            return ! disabledExportFlavors.contains(flavor);
242        }
243    
244        //transfer handler implementation
245        /** Sets the source actions that this TransferHandler should support.
246         *  @param actions the source actions that this TransferHandler will
247         *                       support, one of
248         *                       TransferHandler.COPY, COPY_OR_MOVE, MOVE, NONE
249         * @see #getSourceActions
250         **/
251        public void setSourceActions(int actions){
252            sourceActions = actions;
253        }
254    
255        /**
256        *  Creates a Transferable from the current selection in an
257        * {@link net.sourceforge.mp3dings.Mp3dingsTable}. The transferable will
258        * support those default flavors whose export is currently enabled.
259        * @param  c  the Mp3dingsTable whose selection should be exported
260        * @return a transferable containing the data in the current selection
261        *         in <code>c</code> if <code>c</code> is an Mp3dingsTable,
262        *         <code>null</code> otherwise.
263        * @see #getDefaultFlavors
264        * @see #isExportEnabled
265        */
266        protected Transferable createTransferable(JComponent c) {
267            if(! (c instanceof Mp3dingsTable)){
268                return null;
269            }
270            Mp3dingsTable table = (Mp3dingsTable) c;
271            Mp3dingsTableModel model = (Mp3dingsTableModel) table.getModel();
272    
273            rows = table.getSelectedRows();
274            cols = table.getSelectedColumns();
275    
276            Object[][] obj = new Object[rows.length][cols.length];
277            File[] files = new File[rows.length];
278            StringBuffer textBuff = new StringBuffer(rows.length * cols.length * 10);
279            StringBuffer htmlBuff = new StringBuffer(rows.length * cols.length * 15);
280    
281            htmlBuff.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">");
282            htmlBuff.append("<html>\n  <head></head>\n  <body>\n");
283            htmlBuff.append("    <table>\n");
284    
285            for (int i = 0; i < rows.length; i++) {
286    
287                htmlBuff.append("      <tr>\n");
288                files[i] = model.getFile(rows[i]);
289    
290                for (int j = 0; j < cols.length; j++) {
291    
292                    Object val = model.getValueAt(rows[i], cols[j]);
293                    obj[i][j] = (val != null && val.getClass().equals(FullTextString.class) ? val.toString() : val);
294    
295                    htmlBuff.append("        <td>");
296                    htmlBuff.append(val == null ? "" : val.toString());
297                    htmlBuff.append("</td>\n");
298    
299                    textBuff.append(val == null ? "" : val.toString().replaceAll("\n", " "));
300                    if (j != cols.length - 1) {
301                        textBuff.append("\t");
302                    }
303                }
304    
305                htmlBuff.append("      </tr>\n");
306    
307                textBuff.append("\n");
308            }
309            htmlBuff.append("    </table>");
310    
311            htmlBuff.append("\n  </body>\n</html>\n");
312    
313            return new TransferData(
314                isExportEnabled(TransferData.OBJECT) ? obj : null,
315                isExportEnabled(DataFlavor.stringFlavor)? textBuff.toString() : null,
316                isExportEnabled(TransferData.HTML0)? htmlBuff.toString() : null,
317                isExportEnabled(DataFlavor.javaFileListFlavor)? files : null
318            );
319        }
320    
321    
322        /**
323         *  Gets the sourceActions attribute of the TransferHandler object
324         *
325         *@param  c  Description of the Parameter
326         *@return    The sourceActions value
327         */
328        public int getSourceActions(JComponent c) {
329            if(c instanceof Mp3dingsTable){
330                return sourceActions;
331            } else {
332                return NONE;
333            }
334        }
335    
336        public boolean importData(JComponent c, Transferable t, int pasteMode) {
337            boolean result = false;
338            if(canImport(c, t.getTransferDataFlavors())) {
339                if(c instanceof Mp3dingsTable){
340                    Mp3dingsTable target = (Mp3dingsTable) c;
341                    if (t.isDataFlavorSupported(TransferData.OBJECT)) {
342                        try {
343                            Object o = t.getTransferData(TransferData.OBJECT);
344                            if (objarray.isInstance(o)) {
345                                importObjectArray(target, (Object[][]) o, pasteMode);
346                            }
347                            result = true;
348                        } catch (UnsupportedFlavorException error) {
349                            throw new Error(error);
350                        } catch (IOException ioe) {
351                            logger.warning("Error importing data from Clipboard.");
352                            logger.warning(ioe.toString());
353                        }
354                    } else if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
355                        try {
356                            String str = (String) t.getTransferData(DataFlavor.stringFlavor);
357                            importString(target, str, pasteMode);
358                            result = true;
359                        } catch (UnsupportedFlavorException error) {
360                            throw new Error(error);
361                        } catch (IOException ioe) {
362                            logger.warning("Error importing data from Clipboard.");
363                            logger.warning(ioe.toString());
364                        }
365                    }
366                }
367                boolean jFileList = t.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
368                boolean uriFileList = t.isDataFlavorSupported(TransferData.URI_FILE_LIST);
369                if (jFileList || uriFileList){
370                    MainFrame mf = (MainFrame) SwingUtilities
371                            .getAncestorOfClass(MainFrame.class, c);
372                    try{
373                        List filelist = (List) (
374                                (jFileList)
375                                ?  t.getTransferData(DataFlavor.javaFileListFlavor)
376                                :  textURIListToFileList((String) t.getTransferData(TransferData.URI_FILE_LIST)));
377                        File[] files = (File[]) filelist.toArray(new File[filelist.size()]);
378                        importFiles(mf, files);
379                        result = true;
380                    } catch (UnsupportedFlavorException error) {
381                        throw new Error(error);
382                    } catch (IOException ioe) {
383                        logger.warning("Error importing data from Clipboard.");
384                        logger.warning(ioe.toString());
385                    }
386                }
387            }
388            return result;
389        }
390    
391        /**
392         *  Description of the Method
393         *
394         *@param  c  Description of the Parameter
395         *@param  t  Description of the Parameter
396         *@return    Description of the Return Value
397         */
398        public boolean importData(JComponent c, Transferable t) {
399            return importData(c, t, PASTE_OVERWRITE);
400        }
401    
402        public void exportAsDrag(JComponent comp, InputEvent e, int action){
403            if(!dndSupported){
404                throw new UnsupportedOperationException();
405            }
406            super.exportAsDrag(comp, e, action);
407        }
408    
409        public void exportToClipboard(JComponent comp, Clipboard clip, int action){
410            if(!cpSupported){
411                throw new UnsupportedOperationException();
412            }
413            super.exportToClipboard(comp, clip, action);
414        }
415    
416    
417    
418        /**
419         *  Description of the Method
420         *
421         *@param  src     Description of the Parameter
422         *@param  data    Description of the Parameter
423         *@param  action  Description of the Parameter
424         */
425        protected void exportDone(JComponent src, Transferable data, int action) {
426            if (action != MOVE) {
427                return;
428            }
429            Mp3dingsTableModel model = (Mp3dingsTableModel) ((JTable) src).getModel();
430            int[] col = new int[1];
431            for (int j = 0; j < cols.length; j++) {
432                if (!model.getEditable(model.getField(cols[j]))) {
433                    continue;
434                }
435                Class colClass = model.getColumnClass(cols[j]);
436                final Object nil = Globals.getNullFor(colClass);
437                col[0] = cols[j];
438                model.setValueAt(nil, rows, col);
439            }
440            cols = null;
441            rows = null;
442        }
443    
444    
445        /**
446         *  Description of the Method
447         *
448         *@param  c        Description of the Parameter
449         *@param  flavors  Description of the Parameter
450         *@return          Description of the Return Value
451         */
452        public boolean canImport(JComponent c, DataFlavor[] flavors) {
453            boolean result = false;
454            if(SwingUtilities.getAncestorOfClass(MainFrame.class, c) != null){
455                if(c instanceof Mp3dingsTable) {
456                    for (int i = 0; i < flavors.length && !result; i++) {
457                        if (DataFlavor.stringFlavor.equals(flavors[i]) ||
458                            TransferData.OBJECT.equals(flavors[i]) ||
459                            DataFlavor.javaFileListFlavor.equals(flavors[i]) ||
460                            TransferData.URI_FILE_LIST.equals(flavors[i])
461                        ) {
462                            result = true;
463                            break;
464                        }
465                    }
466                } else {
467                        List flavorlist = Arrays.asList(flavors);
468                    result = flavorlist
469                            .contains(DataFlavor.javaFileListFlavor)
470                            || flavorlist.contains(TransferData.URI_FILE_LIST);
471                }
472            }
473            return result;
474        }
475    
476    
477        /**
478         *  Description of the Method
479         *
480         *@param  target    Description of the Parameter
481         *@param  obj  Description of the Parameter
482         *@param  pasteMode  Description of the Parameter
483         */
484        protected void importObjectArray(Mp3dingsTable target, Object[][] obj, int pasteMode) {
485            if (obj == null) {
486                return;
487            }
488            AbstractTableModel model = (AbstractTableModel) target.getModel();
489            int firstTargetRow = target.getSelectedRow();
490            int targetRow = firstTargetRow;
491            int firstTargetCol = target.getSelectedColumn();
492            int colCount = target.getColumnCount();
493            int rowCount = target.getRowCount();
494            int cellCount = 0;
495    
496            if (obj.length == 0) {
497                return;
498            }
499    
500            Class targetClass;
501    
502            Class sourceClass;
503            Object objji;
504            COLUMNLOOP :
505            for (
506                    int i = 0, targetCol = firstTargetCol;
507                    i < obj[0].length && targetCol < colCount;
508                    i++) {
509                if (targetCol > 0 &&
510                        model.getEditable(model.getField(targetCol))) {
511                    targetRow = firstTargetRow;
512                    /*
513                     *  find target class
514                     */
515                    targetClass = target.getColumnClass(targetCol);
516                    if (targetClass.equals(FullTextString.class)) {
517                        targetClass = String.class;
518                    }
519    
520                    ROWLOOP :
521                    for (int j = 0;
522                            j < obj.length && targetRow < rowCount;
523                            j++) {
524                        objji = obj[j][i];
525                        if (objji != null) {
526                            if (targetClass.equals(String.class)) {
527                                Object value = model.get(targetRow, targetCol);
528                                String newValue = objji.toString();
529                                if(value != null && !value.equals("")){
530                                    if(pasteMode == PASTE_APPEND){
531                                        newValue = value.toString() + objji.toString();
532                                    } else if (pasteMode == PASTE_APPEND_WITH_SPACE){
533                                        newValue = value.toString() + " " + objji.toString();
534                                    }
535                                }
536                                model.set(newValue, targetRow, targetCol);
537                                cellCount++;
538                            } else if (targetClass.isInstance(objji)) {
539                                model.set(objji, targetRow, targetCol);
540                                cellCount++;
541                            }
542                        }
543                        targetRow++;
544                    }
545                    //End of ROWLOOP
546                    model.fireTableChanged(
547                            new TableModelEvent(
548                            model,
549                            firstTargetRow,
550                            targetRow - 1,
551                            targetCol
552                            )
553                            );
554                }
555                targetCol++;
556            }
557            //End of COLUMNLOOP
558            model.fireDataChanged(cellCount);
559        }
560    
561        protected void importFiles(MainFrame mf, File[] files){
562            Mp3dingsTableModel model = mf.getModel(0);
563            DataTableModel fileTarget = (model instanceof DataTableModel)
564                    ? (DataTableModel) model
565                    : ((model instanceof DependentTableModel)
566                            ? ((DependentTableModel) model).getMaster()
567                            : null);
568            if(fileTarget != null){
569                fileTarget.addRecursively(files, mf);
570            }
571        }
572    
573        /**
574         *  Description of the Method
575         *
576         *@param  target     Description of the Parameter
577         *@param  strg  Description of the Parameter
578         *@param  pasteMode  Description of the Parameter
579         */
580        protected void importString(Mp3dingsTable target, String strg, int pasteMode) {
581            AbstractTableModel model = (AbstractTableModel) target.getModel();
582            int firstTargetRow = target.getSelectedRow();
583            int targetRow = firstTargetRow;
584            int firstTargetCol = target.getSelectedColumn();
585            /* implementation note:
586             * Java will do new line conversion for us, when importing from
587             * native applications. see e. g.
588             * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4481292 ,
589             * Evaluation 2.
590             * Therefore we can use just "\n" as our record separator.
591             */
592            final String separator =  "\n";
593            //remove trailing newlines
594            final String str = strg.replaceAll("\n+$", "");
595            String[] srows = str.split(separator);
596            int colCount = target.getColumnCount();
597            int rowCount = target.getRowCount();
598            int cellCount = 0;
599    
600            if (srows.length > 0) {
601                int imax = srows[0].split("\t", -1).length;
602                for (int i = 0, targetCol = firstTargetCol;
603                        i < imax && targetCol < colCount;
604                        i++) {
605                    if (targetCol > 0 && model.getEditable(model.getField(targetCol))) {
606                        targetRow = firstTargetRow;
607                        for (int j = 0;
608                                j < srows.length && targetRow < rowCount;
609                                j++) {
610                            String rowDatai = srows[j].split("\t", -1)[i];
611                            Object value = model.get(targetRow, targetCol);
612                            if(value instanceof String && ! value.equals("")){
613                                if(pasteMode == PASTE_APPEND){
614                                    rowDatai = value + rowDatai;
615                                } else if (pasteMode == PASTE_APPEND_WITH_SPACE){
616                                    rowDatai = value + " " +rowDatai;
617                                }
618                            }
619                            model.set(rowDatai, targetRow, targetCol);
620                            cellCount++;
621                            targetRow++;
622                        }
623                    }
624                    model.fireTableChanged(new TableModelEvent(
625                            model,
626                            firstTargetRow,
627                            targetRow - 1,
628                            targetCol
629                            ));
630                    targetCol++;
631                }
632                model.fireDataChanged(cellCount);
633            }
634        }
635        
636        private static List textURIListToFileList(String data) {
637                List list = new ArrayList();
638                for (StringTokenizer st = new StringTokenizer(data, "\r\n"); st.hasMoreTokens();) {
639                        String s = st.nextToken();
640                        if (s.startsWith("#")) {
641                                // the line is a comment (as per the RFC 2483)
642                                continue;
643                        }
644                        try {
645                                URI uri = new URI(s);
646                                File file = new File(uri);
647                                list.add(file);
648                        } catch (URISyntaxException e) {
649                                e.printStackTrace();
650                        } catch (IllegalArgumentException e) {
651                                e.printStackTrace();
652                        }
653                }
654                return list;
655        }
656    
657    }