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

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

minor code style issues

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