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

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

remove extra whitespaces

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