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

Last change on this file since 9997 was 9992, checked in by Don-vip, 8 years ago

sonar - fix more issues

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