package ij.io;
import ij.*;
import ij.gui.*;
import ij.plugin.frame.Recorder;
import ij.util.Java2;
import java.awt.*;
import java.io.*;
import java.util.ArrayList; import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.awt.datatransfer.*;
public class DragAndDropHandler extends TransferHandler {
private JFileChooser jFileChooser;
public DragAndDropHandler(JFileChooser jFileChooser) {
super();
this.jFileChooser = jFileChooser;
}
public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
for (DataFlavor dataFlavor : transferFlavors) {
if (isSupportedTransferFlavor(dataFlavor))
return true;
}
return false;
}
public boolean importData(JComponent comp, Transferable t) {
DataFlavor[] transferFlavors = t.getTransferDataFlavors();
for (DataFlavor dataFlavor : transferFlavors) {
try {
java.util.List<File> fileList = null;
if (dataFlavor.isFlavorJavaFileListType()) {
fileList = (java.util.List<File>)t.getTransferData(DataFlavor.javaFileListFlavor);
if (IJ.debugMode) IJ.log("dragAndDrop FileList size="+fileList.size()+" first: "+fileList.get(0));
} else if (isSupportedTransferFlavor(dataFlavor)) {
String str = (String)t.getTransferData(dataFlavor);
if (IJ.debugMode) IJ.log("dragAndDrop str="+str);
String[] strs = str.split("[\n\r]+"); fileList = new ArrayList<File>(strs.length);
for (String s : strs) {
if (s.length() > 0) {
File file = new File(s); if (!file.exists()) try {
file = new File(new URI(s)); } catch (URISyntaxException e) {continue;}
if (file.exists()) fileList.add(file);
}
}
}
if (fileList == null || fileList.size() ==0) continue;
File firstFile = fileList.get(0);
if (jFileChooser.isMultiSelectionEnabled()) { File dir = firstFile.getParentFile();
jFileChooser.setCurrentDirectory(dir);
File[] files = fileList.toArray(new File[0]);
jFileChooser.setSelectedFiles(files);
} else {
File file = firstFile; if (jFileChooser.getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY && !file.isDirectory())
file = file.getParentFile(); if (jFileChooser.getDialogType() == JFileChooser.SAVE_DIALOG && file.isDirectory())
jFileChooser.setCurrentDirectory(file); else
jFileChooser.setSelectedFile(file);
}
jFileChooser.rescanCurrentDirectory();
return true;
} catch (Exception e) {if (IJ.debugMode) IJ.handleException(e);}
}
return false;
}
public boolean isSupportedTransferFlavor(DataFlavor flavor) {
return flavor.isFlavorJavaFileListType() ||
(flavor.getRepresentationClass() == String.class &&
(flavor.getMimeType().startsWith("text/uri-list") || flavor.getMimeType().startsWith("text/plain")));
}
}