source: josm/trunk/src/org/openstreetmap/josm/gui/FileDrop.java@ 8256

Last change on this file since 8256 was 8151, checked in by Don-vip, 9 years ago

fix #11259 - catch InvalidDnDOperationException

  • Property svn:eol-style set to native
File size: 26.5 KB
Line 
1/* code from: http://iharder.sourceforge.net/current/java/filedrop/
2 (public domain) with only very small additions */
3package org.openstreetmap.josm.gui;
4
5import java.awt.Color;
6import java.awt.Component;
7import java.awt.Container;
8import java.awt.datatransfer.DataFlavor;
9import java.awt.datatransfer.Transferable;
10import java.awt.datatransfer.UnsupportedFlavorException;
11import java.awt.dnd.DnDConstants;
12import java.awt.dnd.DropTarget;
13import java.awt.dnd.DropTargetDragEvent;
14import java.awt.dnd.DropTargetDropEvent;
15import java.awt.dnd.DropTargetEvent;
16import java.awt.dnd.DropTargetListener;
17import java.awt.dnd.InvalidDnDOperationException;
18import java.awt.event.HierarchyEvent;
19import java.awt.event.HierarchyListener;
20import java.io.BufferedReader;
21import java.io.File;
22import java.io.IOException;
23import java.io.Reader;
24import java.net.URI;
25import java.util.ArrayList;
26import java.util.Arrays;
27import java.util.List;
28import java.util.TooManyListenersException;
29
30import javax.swing.BorderFactory;
31import javax.swing.JComponent;
32import javax.swing.border.Border;
33
34import org.openstreetmap.josm.Main;
35import org.openstreetmap.josm.actions.OpenFileAction;
36
37/**
38 * This class makes it easy to drag and drop files from the operating
39 * system to a Java program. Any {@link java.awt.Component} can be
40 * dropped onto, but only {@link javax.swing.JComponent}s will indicate
41 * the drop event with a changed border.
42 * <p>
43 * To use this class, construct a new <tt>FileDrop</tt> by passing
44 * it the target component and a <tt>Listener</tt> to receive notification
45 * when file(s) have been dropped. Here is an example:
46 * <p>
47 * <code>
48 * JPanel myPanel = new JPanel();
49 * new FileDrop( myPanel, new FileDrop.Listener()
50 * { public void filesDropped( java.io.File[] files )
51 * {
52 * // handle file drop
53 * ...
54 * } // end filesDropped
55 * }); // end FileDrop.Listener
56 * </code>
57 * <p>
58 * You can specify the border that will appear when files are being dragged by
59 * calling the constructor with a {@link javax.swing.border.Border}. Only
60 * <tt>JComponent</tt>s will show any indication with a border.
61 * <p>
62 * You can turn on some debugging features by passing a <tt>PrintStream</tt>
63 * object (such as <tt>System.out</tt>) into the full constructor. A <tt>null</tt>
64 * value will result in no extra debugging information being output.
65 * <p>
66 *
67 * <p>I'm releasing this code into the Public Domain. Enjoy.
68 * </p>
69 * <p><em>Original author: Robert Harder, rharder@usa.net</em></p>
70 * <p>2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.</p>
71 *
72 * @author Robert Harder
73 * @author rharder@users.sf.net
74 * @version 1.0.1
75 * @since 1231
76 */
77public class FileDrop
78{
79 private transient Border normalBorder;
80 private transient DropTargetListener dropListener;
81
82 /** Discover if the running JVM is modern enough to have drag and drop. */
83 private static Boolean supportsDnD;
84
85 // Default border color
86 private static Color defaultBorderColor = new Color( 0f, 0f, 1f, 0.25f );
87
88 /**
89 * Constructor for JOSM file drop
90 * @param c The drop target
91 */
92 public FileDrop(final Component c){
93 this(
94 c, // Drop target
95 BorderFactory.createMatteBorder( 2, 2, 2, 2, defaultBorderColor ), // Drag border
96 true, // Recursive
97 new FileDrop.Listener(){
98 @Override
99 public void filesDropped( File[] files ){
100 // start asynchronous loading of files
101 OpenFileAction.OpenFileTask task = new OpenFileAction.OpenFileTask(Arrays.asList(files), null);
102 task.setRecordHistory(true);
103 Main.worker.submit(task);
104 }
105 }
106 );
107 }
108
109 /**
110 * Full constructor with a specified border and debugging optionally turned on.
111 * With Debugging turned on, more status messages will be displayed to
112 * <tt>out</tt>. A common way to use this constructor is with
113 * <tt>System.out</tt> or <tt>System.err</tt>. A <tt>null</tt> value for
114 * the parameter <tt>out</tt> will result in no debugging output.
115 *
116 * @param c Component on which files will be dropped.
117 * @param dragBorder Border to use on <tt>JComponent</tt> when dragging occurs.
118 * @param recursive Recursively set children as drop targets.
119 * @param listener Listens for <tt>filesDropped</tt>.
120 */
121 public FileDrop(
122 final Component c,
123 final Border dragBorder,
124 final boolean recursive,
125 final Listener listener)
126 {
127
128 if( supportsDnD() )
129 { // Make a drop listener
130 dropListener = new DropTargetListener()
131 { @Override
132 public void dragEnter( DropTargetDragEvent evt )
133 { Main.trace("FileDrop: dragEnter event." );
134
135 // Is this an acceptable drag event?
136 if( isDragOk( evt ) )
137 {
138 // If it's a Swing component, set its border
139 if( c instanceof JComponent )
140 { JComponent jc = (JComponent) c;
141 normalBorder = jc.getBorder();
142 Main.trace("FileDrop: normal border saved." );
143 jc.setBorder( dragBorder );
144 Main.trace("FileDrop: drag border set." );
145 } // end if: JComponent
146
147 // Acknowledge that it's okay to enter
148 evt.acceptDrag( DnDConstants.ACTION_COPY );
149 Main.trace("FileDrop: event accepted." );
150 } // end if: drag ok
151 else
152 { // Reject the drag event
153 evt.rejectDrag();
154 Main.trace("FileDrop: event rejected." );
155 } // end else: drag not ok
156 } // end dragEnter
157
158 @Override
159 public void dragOver( DropTargetDragEvent evt )
160 { // This is called continually as long as the mouse is
161 // over the drag target.
162 } // end dragOver
163
164 @Override
165 public void drop( DropTargetDropEvent evt )
166 { Main.trace("FileDrop: drop event." );
167 try
168 { // Get whatever was dropped
169 Transferable tr = evt.getTransferable();
170
171 // Is it a file list?
172 if (tr.isDataFlavorSupported (DataFlavor.javaFileListFlavor))
173 {
174 // Say we'll take it.
175 evt.acceptDrop ( DnDConstants.ACTION_COPY );
176 Main.trace("FileDrop: file list accepted." );
177
178 // Get a useful list
179 List<?> fileList = (List<?>)tr.getTransferData(DataFlavor.javaFileListFlavor);
180
181 // Convert list to array
182 final File[] files = fileList.toArray(new File[fileList.size()]);
183
184 // Alert listener to drop.
185 if( listener != null ) {
186 listener.filesDropped( files );
187 }
188
189 // Mark that drop is completed.
190 evt.getDropTargetContext().dropComplete(true);
191 Main.trace("FileDrop: drop complete." );
192 } // end if: file list
193 else // this section will check for a reader flavor.
194 {
195 // Thanks, Nathan!
196 // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
197 DataFlavor[] flavors = tr.getTransferDataFlavors();
198 boolean handled = false;
199 for (DataFlavor flavor : flavors) {
200 if (flavor.isRepresentationClassReader()) {
201 // Say we'll take it.
202 evt.acceptDrop(DnDConstants.ACTION_COPY);
203 Main.trace("FileDrop: reader accepted.");
204
205 Reader reader = flavor.getReaderForText(tr);
206
207 BufferedReader br = new BufferedReader(reader);
208
209 if (listener != null) {
210 listener.filesDropped(createFileArray(br));
211 }
212
213 // Mark that drop is completed.
214 evt.getDropTargetContext().dropComplete(true);
215 Main.trace("FileDrop: drop complete.");
216 handled = true;
217 break;
218 }
219 }
220 if(!handled){
221 Main.trace("FileDrop: not a file list or reader - abort." );
222 evt.rejectDrop();
223 }
224 // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
225 } // end else: not a file list
226 } // end try
227 catch (IOException | UnsupportedFlavorException e) {
228 Main.warn("FileDrop: "+e.getClass().getSimpleName()+" - abort:" );
229 Main.error(e);
230 try {
231 evt.rejectDrop();
232 } catch (InvalidDnDOperationException ex) {
233 // Catch InvalidDnDOperationException to fix #11259
234 Main.error(ex);
235 }
236 } finally {
237 // If it's a Swing component, reset its border
238 if( c instanceof JComponent )
239 { JComponent jc = (JComponent) c;
240 jc.setBorder( normalBorder );
241 Main.debug("FileDrop: normal border restored." );
242 } // end if: JComponent
243 } // end finally
244 } // end drop
245
246 @Override
247 public void dragExit( DropTargetEvent evt )
248 { Main.debug("FileDrop: dragExit event." );
249 // If it's a Swing component, reset its border
250 if( c instanceof JComponent )
251 { JComponent jc = (JComponent) c;
252 jc.setBorder( normalBorder );
253 Main.debug("FileDrop: normal border restored." );
254 } // end if: JComponent
255 } // end dragExit
256
257 @Override
258 public void dropActionChanged( DropTargetDragEvent evt )
259 { Main.debug("FileDrop: dropActionChanged event." );
260 // Is this an acceptable drag event?
261 if( isDragOk( evt ) )
262 {
263 evt.acceptDrag( DnDConstants.ACTION_COPY );
264 Main.debug("FileDrop: event accepted." );
265 } // end if: drag ok
266 else
267 { evt.rejectDrag();
268 Main.debug("FileDrop: event rejected." );
269 } // end else: drag not ok
270 } // end dropActionChanged
271 }; // end DropTargetListener
272
273 // Make the component (and possibly children) drop targets
274 makeDropTarget( c, recursive );
275 } // end if: supports dnd
276 else
277 { Main.info("FileDrop: Drag and drop is not supported with this JVM" );
278 } // end else: does not support DnD
279 } // end constructor
280
281 private static synchronized boolean supportsDnD()
282 { // Static Boolean
283 if( supportsDnD == null )
284 {
285 boolean support = false;
286 try {
287 Class.forName( "java.awt.dnd.DnDConstants" );
288 support = true;
289 } catch( Exception e ) {
290 support = false;
291 }
292 supportsDnD = support;
293 } // end if: first time through
294 return supportsDnD.booleanValue();
295 } // end supportsDnD
296
297 // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
298 private static final String ZERO_CHAR_STRING = "" + (char)0;
299 private static File[] createFileArray(BufferedReader bReader)
300 {
301 try {
302 List<File> list = new ArrayList<>();
303 String line = null;
304 while ((line = bReader.readLine()) != null) {
305 try {
306 // kde seems to append a 0 char to the end of the reader
307 if (ZERO_CHAR_STRING.equals(line)) {
308 continue;
309 }
310
311 File file = new File(new URI(line));
312 list.add(file);
313 } catch (Exception ex) {
314 Main.warn("Error with " + line + ": " + ex.getMessage());
315 }
316 }
317
318 return list.toArray(new File[list.size()]);
319 } catch (IOException ex) {
320 Main.warn("FileDrop: IOException");
321 }
322 return new File[0];
323 }
324 // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
325
326 private void makeDropTarget( final Component c, boolean recursive )
327 {
328 // Make drop target
329 final DropTarget dt = new DropTarget();
330 try
331 { dt.addDropTargetListener( dropListener );
332 } // end try
333 catch( TooManyListenersException e )
334 { Main.error(e);
335 Main.warn("FileDrop: Drop will not work due to previous error. Do you have another listener attached?" );
336 } // end catch
337
338 // Listen for hierarchy changes and remove the drop target when the parent gets cleared out.
339 c.addHierarchyListener( new HierarchyListener()
340 { @Override
341 public void hierarchyChanged( HierarchyEvent evt )
342 { Main.trace("FileDrop: Hierarchy changed." );
343 Component parent = c.getParent();
344 if( parent == null )
345 { c.setDropTarget( null );
346 Main.trace("FileDrop: Drop target cleared from component." );
347 } // end if: null parent
348 else
349 { new DropTarget(c, dropListener);
350 Main.trace("FileDrop: Drop target added to component." );
351 } // end else: parent not null
352 } // end hierarchyChanged
353 }); // end hierarchy listener
354 if( c.getParent() != null ) {
355 new DropTarget(c, dropListener);
356 }
357
358 if( recursive && (c instanceof Container ) )
359 {
360 // Get the container
361 Container cont = (Container) c;
362
363 // Get it's components
364 Component[] comps = cont.getComponents();
365
366 // Set it's components as listeners also
367 for (Component comp : comps) {
368 makeDropTarget( comp, recursive);
369 }
370 } // end if: recursively set components as listener
371 } // end dropListener
372
373 /** Determine if the dragged data is a file list. */
374 private boolean isDragOk( final DropTargetDragEvent evt )
375 { boolean ok = false;
376
377 // Get data flavors being dragged
378 DataFlavor[] flavors = evt.getCurrentDataFlavors();
379
380 // See if any of the flavors are a file list
381 int i = 0;
382 while( !ok && i < flavors.length )
383 {
384 // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
385 // Is the flavor a file list?
386 final DataFlavor curFlavor = flavors[i];
387 if( curFlavor.equals( DataFlavor.javaFileListFlavor ) ||
388 curFlavor.isRepresentationClassReader()){
389 ok = true;
390 }
391 // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
392 i++;
393 } // end while: through flavors
394
395 // show data flavors
396 if( flavors.length == 0 ) {
397 Main.trace("FileDrop: no data flavors." );
398 }
399 for( i = 0; i < flavors.length; i++ ) {
400 Main.trace(flavors[i].toString() );
401 }
402
403 return ok;
404 } // end isDragOk
405
406 /**
407 * Removes the drag-and-drop hooks from the component and optionally
408 * from the all children. You should call this if you add and remove
409 * components after you've set up the drag-and-drop.
410 * This will recursively unregister all components contained within
411 * <var>c</var> if <var>c</var> is a {@link java.awt.Container}.
412 *
413 * @param c The component to unregister as a drop target
414 * @return {@code true} if at least one item has been removed, {@code false} otherwise
415 */
416 public static boolean remove( Component c)
417 { return remove( c, true );
418 } // end remove
419
420 /**
421 * Removes the drag-and-drop hooks from the component and optionally
422 * from the all children. You should call this if you add and remove
423 * components after you've set up the drag-and-drop.
424 *
425 * @param c The component to unregister
426 * @param recursive Recursively unregister components within a container
427 * @return {@code true} if at least one item has been removed, {@code false} otherwise
428 */
429 public static boolean remove( Component c, boolean recursive )
430 { // Make sure we support dnd.
431 if (supportsDnD()) {
432 Main.trace("FileDrop: Removing drag-and-drop hooks.");
433 c.setDropTarget(null);
434 if (recursive && (c instanceof Container)) {
435 for (Component comp : ((Container) c).getComponents()) {
436 remove(comp, recursive);
437 }
438 return true;
439 } // end if: recursive
440 else return false;
441 } // end if: supports DnD
442 else return false;
443 } // end remove
444
445 /* ******** I N N E R I N T E R F A C E L I S T E N E R ******** */
446
447 /**
448 * Implement this inner interface to listen for when files are dropped. For example
449 * your class declaration may begin like this:
450 * <code>
451 * public class MyClass implements FileDrop.Listener
452 * ...
453 * public void filesDropped( java.io.File[] files )
454 * {
455 * ...
456 * } // end filesDropped
457 * ...
458 * </code>
459 */
460 public static interface Listener {
461
462 /**
463 * This method is called when files have been successfully dropped.
464 *
465 * @param files An array of <tt>File</tt>s that were dropped.
466 */
467 public abstract void filesDropped( File[] files );
468
469 } // end inner-interface Listener
470
471 /* ******** I N N E R C L A S S ******** */
472
473 /**
474 * At last an easy way to encapsulate your custom objects for dragging and dropping
475 * in your Java programs!
476 * When you need to create a {@link java.awt.datatransfer.Transferable} object,
477 * use this class to wrap your object.
478 * For example:
479 * <pre><code>
480 * ...
481 * MyCoolClass myObj = new MyCoolClass();
482 * Transferable xfer = new TransferableObject( myObj );
483 * ...
484 * </code></pre>
485 * Or if you need to know when the data was actually dropped, like when you're
486 * moving data out of a list, say, you can use the {@link TransferableObject.Fetcher}
487 * inner class to return your object Just in Time.
488 * For example:
489 * <pre><code>
490 * ...
491 * final MyCoolClass myObj = new MyCoolClass();
492 *
493 * TransferableObject.Fetcher fetcher = new TransferableObject.Fetcher()
494 * { public Object getObject(){ return myObj; }
495 * }; // end fetcher
496 *
497 * Transferable xfer = new TransferableObject( fetcher );
498 * ...
499 * </code></pre>
500 *
501 * The {@link java.awt.datatransfer.DataFlavor} associated with
502 * {@link TransferableObject} has the representation class
503 * <tt>net.iharder.dnd.TransferableObject.class</tt> and MIME type
504 * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
505 * This data flavor is accessible via the static
506 * {@link #DATA_FLAVOR} property.
507 *
508 *
509 * <p>I'm releasing this code into the Public Domain. Enjoy.</p>
510 *
511 * @author Robert Harder
512 * @author rob@iharder.net
513 * @version 1.2
514 */
515 public static class TransferableObject implements Transferable {
516
517 /**
518 * The MIME type for {@link #DATA_FLAVOR} is
519 * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
520 */
521 public static final String MIME_TYPE = "application/x-net.iharder.dnd.TransferableObject";
522
523 /**
524 * The default {@link java.awt.datatransfer.DataFlavor} for
525 * {@link TransferableObject} has the representation class
526 * <tt>net.iharder.dnd.TransferableObject.class</tt>
527 * and the MIME type
528 * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
529 */
530 public static final DataFlavor DATA_FLAVOR =
531 new DataFlavor( FileDrop.TransferableObject.class, MIME_TYPE );
532
533 private Fetcher fetcher;
534 private Object data;
535
536 private DataFlavor customFlavor;
537
538 /**
539 * Creates a new {@link TransferableObject} that wraps <var>data</var>.
540 * Along with the {@link #DATA_FLAVOR} associated with this class,
541 * this creates a custom data flavor with a representation class
542 * determined from <code>data.getClass()</code> and the MIME type
543 * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
544 *
545 * @param data The data to transfer
546 */
547 public TransferableObject( Object data )
548 { this.data = data;
549 this.customFlavor = new DataFlavor( data.getClass(), MIME_TYPE );
550 } // end constructor
551
552 /**
553 * Creates a new {@link TransferableObject} that will return the
554 * object that is returned by <var>fetcher</var>.
555 * No custom data flavor is set other than the default
556 * {@link #DATA_FLAVOR}.
557 *
558 * @see Fetcher
559 * @param fetcher The {@link Fetcher} that will return the data object
560 */
561 public TransferableObject( Fetcher fetcher )
562 { this.fetcher = fetcher;
563 } // end constructor
564
565 /**
566 * Creates a new {@link TransferableObject} that will return the
567 * object that is returned by <var>fetcher</var>.
568 * Along with the {@link #DATA_FLAVOR} associated with this class,
569 * this creates a custom data flavor with a representation class <var>dataClass</var>
570 * and the MIME type
571 * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
572 *
573 * @see Fetcher
574 * @param dataClass The {@link java.lang.Class} to use in the custom data flavor
575 * @param fetcher The {@link Fetcher} that will return the data object
576 */
577 public TransferableObject(Class<?> dataClass, Fetcher fetcher )
578 { this.fetcher = fetcher;
579 this.customFlavor = new DataFlavor( dataClass, MIME_TYPE );
580 } // end constructor
581
582 /**
583 * Returns the custom {@link java.awt.datatransfer.DataFlavor} associated
584 * with the encapsulated object or <tt>null</tt> if the {@link Fetcher}
585 * constructor was used without passing a {@link java.lang.Class}.
586 *
587 * @return The custom data flavor for the encapsulated object
588 */
589 public DataFlavor getCustomDataFlavor()
590 { return customFlavor;
591 } // end getCustomDataFlavor
592
593 /* ******** T R A N S F E R A B L E M E T H O D S ******** */
594
595 /**
596 * Returns a two- or three-element array containing first
597 * the custom data flavor, if one was created in the constructors,
598 * second the default {@link #DATA_FLAVOR} associated with
599 * {@link TransferableObject}, and third the
600 * {@link java.awt.datatransfer.DataFlavor#stringFlavor}.
601 *
602 * @return An array of supported data flavors
603 */
604 @Override
605 public DataFlavor[] getTransferDataFlavors()
606 {
607 if( customFlavor != null )
608 return new DataFlavor[]
609 { customFlavor,
610 DATA_FLAVOR,
611 DataFlavor.stringFlavor
612 }; // end flavors array
613 else
614 return new DataFlavor[]
615 { DATA_FLAVOR,
616 DataFlavor.stringFlavor
617 }; // end flavors array
618 } // end getTransferDataFlavors
619
620 /**
621 * Returns the data encapsulated in this {@link TransferableObject}.
622 * If the {@link Fetcher} constructor was used, then this is when
623 * the {@link Fetcher#getObject getObject()} method will be called.
624 * If the requested data flavor is not supported, then the
625 * {@link Fetcher#getObject getObject()} method will not be called.
626 *
627 * @param flavor The data flavor for the data to return
628 * @return The dropped data
629 */
630 @Override
631 public Object getTransferData( DataFlavor flavor )
632 throws UnsupportedFlavorException, IOException
633 {
634 // Native object
635 if( flavor.equals( DATA_FLAVOR ) )
636 return fetcher == null ? data : fetcher.getObject();
637
638 // String
639 if( flavor.equals( DataFlavor.stringFlavor ) )
640 return fetcher == null ? data.toString() : fetcher.getObject().toString();
641
642 // We can't do anything else
643 throw new UnsupportedFlavorException(flavor);
644 } // end getTransferData
645
646 /**
647 * Returns <tt>true</tt> if <var>flavor</var> is one of the supported
648 * flavors. Flavors are supported using the <code>equals(...)</code> method.
649 *
650 * @param flavor The data flavor to check
651 * @return Whether or not the flavor is supported
652 */
653 @Override
654 public boolean isDataFlavorSupported( DataFlavor flavor )
655 {
656 // Native object
657 if( flavor.equals( DATA_FLAVOR ) )
658 return true;
659
660 // String
661 if( flavor.equals( DataFlavor.stringFlavor ) )
662 return true;
663
664 // We can't do anything else
665 return false;
666 } // end isDataFlavorSupported
667
668 /* ******** I N N E R I N T E R F A C E F E T C H E R ******** */
669
670 /**
671 * Instead of passing your data directly to the {@link TransferableObject}
672 * constructor, you may want to know exactly when your data was received
673 * in case you need to remove it from its source (or do anyting else to it).
674 * When the {@link #getTransferData getTransferData(...)} method is called
675 * on the {@link TransferableObject}, the {@link Fetcher}'s
676 * {@link #getObject getObject()} method will be called.
677 *
678 * @author Robert Harder
679 */
680 public static interface Fetcher
681 {
682 /**
683 * Return the object being encapsulated in the
684 * {@link TransferableObject}.
685 *
686 * @return The dropped object
687 */
688 public abstract Object getObject();
689 } // end inner interface Fetcher
690
691 } // end class TransferableObject
692
693} // end class FileDrop
Note: See TracBrowser for help on using the repository browser.