@Override public boolean importData(JComponent comp, Transferable t) { DataFlavor htmlFlavor = DataFlavor.stringFlavor; if (canImport(comp, t.getTransferDataFlavors())) { try { String transferString = (String) t.getTransferData(htmlFlavor); EditorPane targetTextPane = (EditorPane) comp; for (Map.Entry<String, String> entry : _copiedImgs.entrySet()) { String imgName = entry.getKey(); String imgPath = entry.getValue(); File destFile = targetTextPane.copyFileToBundle(imgPath); String newName = destFile.getName(); if (!newName.equals(imgName)) { String ptnImgName = "\"" + imgName + "\""; newName = "\"" + newName + "\""; transferString = transferString.replaceAll(ptnImgName, newName); Debug.info(ptnImgName + " exists. Rename it to " + newName); } } targetTextPane.insertString(transferString); } catch (Exception e) { Debug.error(me + "importData: Problem pasting text\n%s", e.getMessage()); } return true; } return false; }
/** * Returns an object which represents the data to be transferred. The class of the object returned * is defined by the representation class of the flavor. * * @param flavor the requested flavor for the data * @see DataFlavor#getRepresentationClass * @exception IOException if the data is no longer available in the requested flavor. * @exception UnsupportedFlavorException if the requested data flavor is not supported. */ @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { Transferable t = (Transferable) transferables.get(flavor); if (t == null) { throw new UnsupportedFlavorException(flavor); } return t.getTransferData(flavor); }
public void drop(DropTargetDropEvent dtde) { dtde.acceptDrop(DnDConstants.ACTION_COPY); DataFlavor[] flavors = null; try { Transferable t = dtde.getTransferable(); iterator = null; flavors = t.getTransferDataFlavors(); if (IJ.debugMode) IJ.log("DragAndDrop.drop: " + flavors.length + " flavors"); for (int i = 0; i < flavors.length; i++) { if (IJ.debugMode) IJ.log(" flavor[" + i + "]: " + flavors[i].getMimeType()); if (flavors[i].isFlavorJavaFileListType()) { Object data = t.getTransferData(DataFlavor.javaFileListFlavor); iterator = ((List) data).iterator(); break; } else if (flavors[i].isFlavorTextType()) { Object ob = t.getTransferData(flavors[i]); if (!(ob instanceof String)) continue; String s = ob.toString().trim(); if (IJ.isLinux() && s.length() > 1 && (int) s.charAt(1) == 0) s = fixLinuxString(s); ArrayList list = new ArrayList(); if (s.indexOf("href=\"") != -1 || s.indexOf("src=\"") != -1) { s = parseHTML(s); if (IJ.debugMode) IJ.log(" url: " + s); list.add(s); this.iterator = list.iterator(); break; } BufferedReader br = new BufferedReader(new StringReader(s)); String tmp; while (null != (tmp = br.readLine())) { tmp = java.net.URLDecoder.decode(tmp.replaceAll("\\+", "%2b"), "UTF-8"); if (tmp.startsWith("file://")) tmp = tmp.substring(7); if (IJ.debugMode) IJ.log(" content: " + tmp); if (tmp.startsWith("http://")) list.add(s); else list.add(new File(tmp)); } this.iterator = list.iterator(); break; } } if (iterator != null) { Thread thread = new Thread(this, "DrawAndDrop"); thread.setPriority(Math.max(thread.getPriority() - 1, Thread.MIN_PRIORITY)); thread.start(); } } catch (Exception e) { dtde.dropComplete(false); return; } dtde.dropComplete(true); if (flavors == null || flavors.length == 0) { if (IJ.isMacOSX()) IJ.error( "First drag and drop ignored. Please try again. You can avoid this\n" + "problem by dragging to the toolbar instead of the status bar."); else IJ.error("Drag and drop failed"); } }
public StringBuffer getTransferData(Transferable t) { StringBuffer xferData = null; Object dropped; DataFlavor dtf; dtf = testAllFlavors(t); JConfig.log().logVerboseDebug("dtf == " + dtf); try { if (dtf == _htmlFlavor || dtf == _utf8HtmlFlavor || dtf == _thtmlFlavor) { /* * Annoying. */ if (JConfig.queryConfiguration("debug.uber", "false").equals("true") && JConfig.debugging) System.out.println("Ick: " + t.getTransferData(DataFlavor.getTextPlainUnicodeFlavor())); } dropped = t.getTransferData(dtf); } catch (IOException ioe) { try { dropped = t.getTransferData(DataFlavor.stringFlavor); } catch (Exception e) { JConfig.log().logDebug("I/O Exception: " + ioe); return null; } } catch (UnsupportedFlavorException ufe) { try { dropped = t.getTransferData(DataFlavor.stringFlavor); } catch (Exception e) { JConfig.log().logDebug("Unsupported flavor: " + dtf); return null; } } if (dropped != null) { if (dropped instanceof InputStream) { JConfig.log().logVerboseDebug("Dropped an InputStream"); xferData = getInputStreamData(t, dtf, (InputStream) dropped); } else if (dropped instanceof Reader) { JConfig.log().logVerboseDebug("Dropped a Reader"); xferData = getDataFromReader(new BufferedReader((Reader) dropped)); } else if (dropped instanceof java.net.URL) { JConfig.log().logVerboseDebug("Dropped a URL"); JConfig.log().logVerboseDebug("Got: " + dropped.toString()); xferData = new StringBuffer(dropped.toString()); } else if (dropped instanceof String) { JConfig.log().logVerboseDebug("Dropped a String"); xferData = new StringBuffer((String) dropped); } return (xferData); } return null; }
/** * Returns the contents of the specified transferable. * * @param tr transferable * @return contents */ @SuppressWarnings("unchecked") public static ArrayList<Object> contents(final Transferable tr) { final ArrayList<Object> list = new ArrayList<>(); try { if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { for (final File fl : (List<File>) tr.getTransferData(DataFlavor.javaFileListFlavor)) list.add(fl); } else if (tr.isDataFlavorSupported(DataFlavor.stringFlavor)) { list.add(tr.getTransferData(DataFlavor.stringFlavor)); } } catch (final Exception ex) { Util.stack(ex); } return list; }
private boolean testFlavor(DataFlavor inFlavor, Transferable t) { if (inFlavor != null) { if (t.isDataFlavorSupported(inFlavor)) { JConfig.log().logVerboseDebug("Accepting(2): " + inFlavor.getMimeType()); return true; } } return false; }
public void add(Transferable t) { DataFlavor[] f = t.getTransferDataFlavors(); for (int i = 0; i < f.length; i++) { if (!transferables.containsKey(f[i])) { flavors.add(f[i]); } transferables.put(f[i], t); } }
public void drop(DropTargetDropEvent evt) { try { Transferable t = evt.getTransferable(); if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) { evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); String s = (String) t.getTransferData(DataFlavor.stringFlavor); evt.getDropTargetContext().dropComplete(true); process(s); } else { evt.rejectDrop(); } } catch (IOException e) { evt.rejectDrop(); } catch (UnsupportedFlavorException e) { evt.rejectDrop(); } }
@Override public void drop(DropTargetDropEvent dtde) { try { if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { dtde.acceptDrop(DnDConstants.ACTION_COPY); Transferable t = dtde.getTransferable(); List list = (List) t.getTransferData(DataFlavor.javaFileListFlavor); for (Object o : list) { if (o instanceof File) { File f = (File) o; System.out.println(f.getAbsolutePath()); } } dtde.dropComplete(true); return; } } catch (UnsupportedFlavorException | IOException ex) { ex.printStackTrace(); } dtde.rejectDrop(); }
/** * Get the String residing on the clipboard. * * @return any text found on the Clipboard; if none found, return an empty String. */ public void openClipboardContents() { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // odd: the Object param of getContents is not currently used Transferable contents = clipboard.getContents(null); boolean hasTransferableText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor); if (hasTransferableText) { TextDocument entry_document = new TextDocument(); final InputStreamProgressListener progress_listener = getInputStreamProgressListener(); entry_document.addInputStreamProgressListener(progress_listener); final EntryInformation artemis_entry_information = Options.getArtemisEntryInformation(); final uk.ac.sanger.artemis.io.Entry new_embl_entry = EntryFileDialog.getEntryFromFile(this, entry_document, artemis_entry_information, false); if (new_embl_entry == null) // the read failed return; try { final Entry entry = new Entry(new_embl_entry); EntryEdit last_entry_edit = makeEntryEdit(entry); addEntryEdit(last_entry_edit); getStatusLabel().setText(""); last_entry_edit.setVisible(true); } catch (OutOfRangeException e) { new MessageDialog( this, "read failed: one of the features in " + " cut and paste has an out of range " + "location: " + e.getMessage()); } catch (NoSequenceException e) { new MessageDialog(this, "read failed: " + " cut and paste contains no sequence"); } } }
public boolean importData(JComponent comp, Transferable t) { ImageIcon icon = null; try { if (t.isDataFlavorSupported(flavors[0])) { image = (Image) t.getTransferData(flavors[0]); icon = new ImageIcon(image); } if (comp instanceof JLabel) { JLabel label = (JLabel) comp; label.setIcon(icon); return true; } else if (comp instanceof AbstractButton) { AbstractButton button = (AbstractButton) comp; button.setIcon(icon); return true; } } catch (UnsupportedFlavorException ignored) { } catch (IOException ignored) { } return false; }
/** * Gets a Reader for a text flavor, decoded, if necessary, for the expected charset (encoding). * The supported representation classes are <code>java.io.Reader</code>, <code>java.lang.String * </code>, <code>java.nio.CharBuffer</code>, <code>[C</code>, <code>java.io.InputStream</code>, * <code>java.nio.ByteBuffer</code>, and <code>[B</code>. * * <p>Because text flavors which do not support the charset parameter are encoded in a * non-standard format, this method should not be called for such flavors. However, in order to * maintain backward-compatibility, if this method is called for such a flavor, this method will * treat the flavor as though it supports the charset parameter and attempt to decode it * accordingly. See <code>selectBestTextFlavor</code> for a list of text flavors which do not * support the charset parameter. * * @param transferable the <code>Transferable</code> whose data will be requested in this flavor * @return a <code>Reader</code> to read the <code>Transferable</code>'s data * @exception IllegalArgumentException if the representation class is not one of the seven listed * above * @exception IllegalArgumentException if the <code>Transferable</code> has <code>null</code> data * @exception NullPointerException if the <code>Transferable</code> is <code>null</code> * @exception UnsupportedEncodingException if this flavor's representation is <code> * java.io.InputStream</code>, <code>java.nio.ByteBuffer</code>, or <code>[B</code> and this * flavor's encoding is not supported by this implementation of the Java platform * @exception UnsupportedFlavorException if the <code>Transferable</code> does not support this * flavor * @exception IOException if the data cannot be read because of an I/O error * @see #selectBestTextFlavor * @since 1.3 */ public Reader getReaderForText(Transferable transferable) throws UnsupportedFlavorException, IOException { Object transferObject = transferable.getTransferData(this); if (transferObject == null) { throw new IllegalArgumentException("getTransferData() returned null"); } if (transferObject instanceof Reader) { return (Reader) transferObject; } else if (transferObject instanceof String) { return new StringReader((String) transferObject); } else if (transferObject instanceof CharBuffer) { CharBuffer buffer = (CharBuffer) transferObject; int size = buffer.remaining(); char[] chars = new char[size]; buffer.get(chars, 0, size); return new CharArrayReader(chars); } else if (transferObject instanceof char[]) { return new CharArrayReader((char[]) transferObject); } InputStream stream = null; if (transferObject instanceof InputStream) { stream = (InputStream) transferObject; } else if (transferObject instanceof ByteBuffer) { ByteBuffer buffer = (ByteBuffer) transferObject; int size = buffer.remaining(); byte[] bytes = new byte[size]; buffer.get(bytes, 0, size); stream = new ByteArrayInputStream(bytes); } else if (transferObject instanceof byte[]) { stream = new ByteArrayInputStream((byte[]) transferObject); } if (stream == null) { throw new IllegalArgumentException( "transfer data is not Reader, String, CharBuffer, char array, InputStream, ByteBuffer, or byte array"); } String encoding = getParameter("charset"); return (encoding == null) ? new InputStreamReader(stream) : new InputStreamReader(stream, encoding); }
private void dumpFlavorsOld(Transferable t) { DataFlavor[] dfa = t.getTransferDataFlavors(); if (dfa != null) { if (dfa.length == 0) { JConfig.log().logVerboseDebug("Trying a second attack..."); try { Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable t2 = sysClip.getContents(null); StringBuffer stBuff; stBuff = getTransferData(t2); JConfig.log().logVerboseDebug("Check out: " + stBuff); } catch (Exception e) { JConfig.log().handleException("Caught: " + e, e); } JConfig.log().logVerboseDebug("Done trying a second attack..."); } } dumpDataFlavors(dfa); }
public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); StringBuffer dropData = null; DataFlavor dtf; JConfig.log().logVerboseDebug("Dropping!"); if (t.getTransferDataFlavors().length == 0) { Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable t2 = sysClip.getContents(null); DataFlavor[] dfa2; int j; JConfig.log().logDebug("Dropped 0 data flavors, trying clipboard."); dfa2 = null; if (t2 != null) { JConfig.log().logVerboseDebug("t2 is not null: " + t2); dfa2 = t2.getTransferDataFlavors(); JConfig.log().logVerboseDebug("Back from getTransferDataFlavors()!"); } else { JConfig.log().logVerboseDebug("t2 is null!"); } if (JConfig.queryConfiguration("debug.uber", "false").equals("true")) { if (dfa2 != null) { if (dfa2.length == 0) { JConfig.log().logVerboseDebug("Length is still zero!"); } for (j = 0; j < dfa2.length; j++) { JConfig.log() .logVerboseDebug("Flavah " + j + " == " + dfa2[j].getHumanPresentableName()); JConfig.log().logVerboseDebug("Flavah/mime " + j + " == " + dfa2[j].getMimeType()); } } else { JConfig.log().logVerboseDebug("Flavahs supported: none!\n"); } } } if (JConfig.queryConfiguration("debug.uber", "false").equals("true") && JConfig.debugging) dumpFlavorsOld(t); dtf = testAllFlavors(t); if (dtf != null) { JConfig.log().logVerboseDebug("Accepting!"); acceptDrop(dtde); dropData = getTransferData(t); dtde.dropComplete(true); dtde.getDropTargetContext().dropComplete(true); if (dropData != null) { if (handler != null) { handler.receiveDropString(dropData); } } } else { JConfig.log().logVerboseDebug("Rejecting!"); dtde.rejectDrop(); handler.receiveDropString(dropData); } }
/** * Paste the contents of the clipboard into the console buffer * * @return true if clipboard contents pasted */ public boolean paste() throws IOException { Clipboard clipboard; try { // May throw ugly exception on system without X clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); } catch (Exception e) { return false; } if (clipboard == null) { return false; } Transferable transferable = clipboard.getContents(null); if (transferable == null) { return false; } try { Object content = transferable.getTransferData(DataFlavor.plainTextFlavor); /* * This fix was suggested in bug #1060649 at * http://sourceforge.net/tracker/index.php?func=detail&aid=1060649&group_id=64033&atid=506056 * to get around the deprecated DataFlavor.plainTextFlavor, but it * raises a UnsupportedFlavorException on Mac OS X */ if (content == null) { try { content = new DataFlavor().getReaderForText(transferable); } catch (Exception e) { } } if (content == null) { return false; } String value; if (content instanceof Reader) { // TODO: we might want instead connect to the input stream // so we can interpret individual lines value = ""; String line = null; for (BufferedReader read = new BufferedReader((Reader) content); (line = read.readLine()) != null; ) { if (value.length() > 0) { value += "\n"; } value += line; } } else { value = content.toString(); } if (value == null) { return true; } putString(value); return true; } catch (UnsupportedFlavorException ufe) { if (debugger != null) debug(ufe + ""); return false; } }
public void run(String arg) { Frame[] niframes = WindowManager.getNonImageWindows(); String[] titles = new String[niframes.length + 1]; for (int i = 0; i < niframes.length; i++) { titles[i] = niframes[i].getTitle(); } titles[niframes.length] = "Clipboard"; GenericDialog gd = new GenericDialog("Windows"); boolean importfile = false; gd.addCheckbox("Import from file?", importfile); gd.addChoice("Windows", titles, titles[0]); boolean hasxvals = false; gd.addCheckbox("X Vals Column?", hasxvals); boolean multix = false; gd.addCheckbox("Multi_X_Columns?", multix); boolean skipendzeros = false; gd.addCheckbox("Skip_end_zeros?", skipendzeros); String[] delimiters = {"Tab", "Comma", "Space"}; gd.addChoice("Delimiter", delimiters, delimiters[0]); gd.showDialog(); if (gd.wasCanceled()) { return; } importfile = gd.getNextBoolean(); int index = gd.getNextChoiceIndex(); hasxvals = gd.getNextBoolean(); multix = gd.getNextBoolean(); skipendzeros = gd.getNextBoolean(); int delimindex = gd.getNextChoiceIndex(); if (multix) hasxvals = true; String textdata = ""; if (importfile) { OpenDialog od = new OpenDialog("Open File", "", ".txt"); String directory = od.getDirectory(); String name = od.getFileName(); if (name == null) { return; } try { File infile = new File(directory + name); BufferedReader b = new BufferedReader(new FileReader(infile)); textdata = (new jdataio()).readstringfile(b); b.close(); } catch (IOException e) { return; } } else { if (index == niframes.length) { // here we get the data from the clipboard Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); try { if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) { textdata = (String) t.getTransferData(DataFlavor.stringFlavor); } } catch (UnsupportedFlavorException e) { } catch (IOException e) { } if (textdata.equals("")) { IJ.error("Error copying from clipboard."); return; } } else { if (niframes[index] instanceof Editor) { Editor tw = (Editor) niframes[index]; textdata = tw.getText(); } else { if (niframes[index] instanceof TextWindow) { TextWindow tw = (TextWindow) niframes[index]; textdata = tw.getTextPanel().getText(); } else { IJ.showMessage("Not a valid text window"); return; } } } } if (textdata == null) { IJ.showMessage("Error in Obtaining String"); return; } if (textdata.indexOf("\r") >= 0) { textdata = textdata.replace('\r', '\n'); } char[] delims = {'\t', ',', ' '}; delimit_string ds = new delimit_string(delims[delimindex]); String[] rows = ds.getrows(textdata); int lines = rows.length; int columns = ds.getnumcolumns(rows[0]); int ycolumns = columns; if (hasxvals) { if (multix) { ycolumns /= 2; } else { ycolumns--; } } if (multix) { float[][] ydata = new float[ycolumns][lines]; float[][] xdata = new float[ycolumns][lines]; for (int i = 0; i < lines; i++) { float[] temp = ds.delim2float(rows[i], columns); for (int j = 0; j < ycolumns; j++) { ydata[j][i] = temp[2 * j + 1]; xdata[j][i] = temp[2 * j]; } } int[] npts = new int[ycolumns]; for (int i = 0; i < ycolumns; i++) { npts[i] = lines; } if (skipendzeros) { for (int i = 0; i < ycolumns; i++) { int counter = lines - 1; while ((xdata[i][counter] == 0.0f || Float.isNaN(xdata[i][counter])) && counter > 0) { xdata[i][counter] = 0.0f; ydata[i][counter] = 0.0f; npts[i]--; counter--; } } } (new PlotWindow4("Text Plot", "x", "y", xdata, ydata, npts)).draw(); } else { float[][] tempydata = new float[ycolumns][lines]; float[] tempxdata = new float[lines]; float[][] xdata = null; float[][] ydata = null; int startcolumn = 0; if (hasxvals) startcolumn = 1; for (int i = 0; i < lines; i++) { float[] temp = ds.delim2float(rows[i], columns); if (hasxvals) { tempxdata[i] = temp[0]; } else { tempxdata[i] = (float) (i + 1); } for (int j = 0; j < ycolumns; j++) { tempydata[j][i] = temp[j + startcolumn]; } } int[] npts = new int[ycolumns]; npts[0] = lines; if (skipendzeros) { int maxpts = 0; for (int i = 0; i < ycolumns; i++) { int counter = lines - 1; npts[i] = lines; while ((tempydata[i][counter] == 0.0f || Float.isNaN(tempydata[i][counter])) && counter > 0) { npts[i]--; counter--; } if (npts[i] > maxpts) maxpts = npts[i]; IJ.log("" + npts[i]); } ydata = new float[ycolumns][maxpts]; xdata = new float[ycolumns][maxpts]; for (int i = 0; i < ycolumns; i++) { // npts[i]=npts[0]; System.arraycopy(tempxdata, 0, xdata[i], 0, npts[i]); System.arraycopy(tempydata[i], 0, ydata[i], 0, npts[i]); } } else { ydata = tempydata; xdata = new float[ycolumns][]; for (int i = 0; i < ycolumns; i++) { npts[i] = npts[0]; xdata[i] = tempxdata.clone(); } } (new PlotWindow4("Text Plot", "x", "y", xdata, ydata, npts)).draw(); } }