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

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

fix remaining checkstyle issues

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