Search in sources :

Example 6 with UnsupportedFlavorException

use of java.awt.datatransfer.UnsupportedFlavorException in project frostwire by frostwire.

the class TransferVisualizer method getImage.

Image getImage() {
    if (!t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
        return null;
    List<?> l = null;
    try {
        l = (List<?>) t.getTransferData(DataFlavor.javaFileListFlavor);
    } catch (UnsupportedFlavorException ufe) {
        return null;
    } catch (IOException ioe) {
        return null;
    }
    // if no data, there's nothing to draw.
    if (l.size() == 0)
        return null;
    int height = IMAGE_ROW_HEIGHT * l.size();
    BufferedImage buffer = new BufferedImage(IMAGE_WIDTH, height, BufferedImage.TYPE_INT_ARGB);
    Graphics g = buffer.getGraphics();
    JLabel label = new JLabel();
    label.setVerticalAlignment(SwingConstants.TOP);
    label.setOpaque(false);
    int y = 0;
    for (Iterator<?> i = l.iterator(); i.hasNext(); ) {
        File f = (File) i.next();
        Icon icon = IconManager.instance().getIconForFile(f);
        label.setIcon(icon);
        label.setText(f.getName());
        PANE.paintComponent(g, label, null, 0, y, IMAGE_WIDTH, height - y);
        y += IMAGE_ROW_HEIGHT;
    }
    g.dispose();
    return buffer;
}
Also used : IOException(java.io.IOException) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) File(java.io.File) BufferedImage(java.awt.image.BufferedImage)

Example 7 with UnsupportedFlavorException

use of java.awt.datatransfer.UnsupportedFlavorException in project jabref by JabRef.

the class ClipBoardManager method extractBibEntriesFromClipboard.

public List<BibEntry> extractBibEntriesFromClipboard() {
    // Get clipboard contents, and see if TransferableBibtexEntry is among the content flavors offered
    Transferable content = CLIPBOARD.getContents(null);
    List<BibEntry> result = new ArrayList<>();
    if (content.isDataFlavorSupported(TransferableBibtexEntry.entryFlavor)) {
        // We have determined that the clipboard data is a set of entries.
        try {
            @SuppressWarnings("unchecked") List<BibEntry> contents = (List<BibEntry>) content.getTransferData(TransferableBibtexEntry.entryFlavor);
            result = contents;
        } catch (UnsupportedFlavorException | ClassCastException ex) {
            LOGGER.warn("Could not paste this type", ex);
        } catch (IOException ex) {
            LOGGER.warn("Could not paste", ex);
        }
    } else if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        try {
            String data = (String) content.getTransferData(DataFlavor.stringFlavor);
            // fetch from doi
            if (DOI.parse(data).isPresent()) {
                LOGGER.info("Found DOI in clipboard");
                Optional<BibEntry> entry = new DoiFetcher(Globals.prefs.getImportFormatPreferences()).performSearchById(new DOI(data).getDOI());
                entry.ifPresent(result::add);
            } else {
                // parse bibtex string
                BibtexParser bp = new BibtexParser(Globals.prefs.getImportFormatPreferences());
                BibDatabase db = bp.parse(new StringReader(data)).getDatabase();
                LOGGER.info("Parsed " + db.getEntryCount() + " entries from clipboard text");
                if (db.hasEntries()) {
                    result = db.getEntries();
                }
            }
        } catch (UnsupportedFlavorException ex) {
            LOGGER.warn("Could not parse this type", ex);
        } catch (IOException ex) {
            LOGGER.warn("Data is no longer available in the requested flavor", ex);
        } catch (FetcherException ex) {
            LOGGER.error("Error while fetching", ex);
        }
    }
    return result;
}
Also used : BibEntry(org.jabref.model.entry.BibEntry) DoiFetcher(org.jabref.logic.importer.fetcher.DoiFetcher) Optional(java.util.Optional) BibtexParser(org.jabref.logic.importer.fileformat.BibtexParser) Transferable(java.awt.datatransfer.Transferable) ArrayList(java.util.ArrayList) IOException(java.io.IOException) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) FetcherException(org.jabref.logic.importer.FetcherException) StringReader(java.io.StringReader) ArrayList(java.util.ArrayList) List(java.util.List) BibDatabase(org.jabref.model.database.BibDatabase) DOI(org.jabref.model.entry.identifier.DOI)

Example 8 with UnsupportedFlavorException

use of java.awt.datatransfer.UnsupportedFlavorException in project jabref by JabRef.

the class FileListEditorTransferHandler method importData.

@Override
public boolean importData(JComponent comp, Transferable t) {
    try {
        List<Path> files = new ArrayList<>();
        // This flavor is used for dragged file links in Windows:
        if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            @SuppressWarnings("unchecked") List<Path> transferedFiles = (List<Path>) t.getTransferData(DataFlavor.javaFileListFlavor);
            files.addAll(transferedFiles);
        }
        if (t.isDataFlavorSupported(urlFlavor)) {
            URL dropLink = (URL) t.getTransferData(urlFlavor);
            LOGGER.debug("URL: " + dropLink);
        }
        // under Gnome. The data consists of the file paths, one file per line:
        if (t.isDataFlavorSupported(stringFlavor)) {
            String dropStr = (String) t.getTransferData(stringFlavor);
            files.addAll(EntryTableTransferHandler.getFilesFromDraggedFilesString(dropStr));
        }
        SwingUtilities.invokeLater(() -> {
            for (Path file : files) {
                // Find the file's extension, if any:
                String name = file.toAbsolutePath().toString();
                FileHelper.getFileExtension(name).ifPresent(extension -> ExternalFileTypes.getInstance().getExternalFileTypeByExt(extension).ifPresent(fileType -> {
                    if (droppedFileHandler == null) {
                        droppedFileHandler = new DroppedFileHandler(frame, frame.getCurrentBasePanel());
                    }
                    droppedFileHandler.handleDroppedfile(name, fileType, entryContainer.getEntry());
                }));
            }
        });
        if (!files.isEmpty()) {
            // Found some files, return
            return true;
        }
    } catch (IOException ioe) {
        LOGGER.warn("Failed to read dropped data. ", ioe);
    } catch (UnsupportedFlavorException | ClassCastException ufe) {
        LOGGER.warn("Drop type error. ", ufe);
    }
    // all supported flavors failed
    StringBuilder logMessage = new StringBuilder("Cannot transfer input:");
    DataFlavor[] inflavs = t.getTransferDataFlavors();
    for (DataFlavor inflav : inflavs) {
        logMessage.append(' ').append(inflav);
    }
    LOGGER.warn(logMessage.toString());
    return false;
}
Also used : Path(java.nio.file.Path) Clipboard(java.awt.datatransfer.Clipboard) JComponent(javax.swing.JComponent) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) DataFlavor(java.awt.datatransfer.DataFlavor) URL(java.net.URL) Transferable(java.awt.datatransfer.Transferable) DnDConstants(java.awt.dnd.DnDConstants) IOException(java.io.IOException) EntryTableTransferHandler(org.jabref.gui.groups.EntryTableTransferHandler) ArrayList(java.util.ArrayList) FileHelper(org.jabref.model.util.FileHelper) List(java.util.List) SwingUtilities(javax.swing.SwingUtilities) DroppedFileHandler(org.jabref.gui.externalfiles.DroppedFileHandler) JabRefFrame(org.jabref.gui.JabRefFrame) TransferHandler(javax.swing.TransferHandler) Log(org.apache.commons.logging.Log) ExternalFileTypes(org.jabref.gui.externalfiletype.ExternalFileTypes) LogFactory(org.apache.commons.logging.LogFactory) Path(java.nio.file.Path) EntryContainer(org.jabref.gui.EntryContainer) ArrayList(java.util.ArrayList) IOException(java.io.IOException) DroppedFileHandler(org.jabref.gui.externalfiles.DroppedFileHandler) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) URL(java.net.URL) DataFlavor(java.awt.datatransfer.DataFlavor) ArrayList(java.util.ArrayList) List(java.util.List)

Example 9 with UnsupportedFlavorException

use of java.awt.datatransfer.UnsupportedFlavorException in project JMRI by JMRI.

the class ControlPanelEditor method drop.

@SuppressWarnings("unchecked")
@Override
public void drop(DropTargetDropEvent evt) {
    try {
        //Point pt = evt.getLocation(); coords relative to entire window
        Point pt = _targetPanel.getMousePosition(true);
        Transferable tr = evt.getTransferable();
        if (log.isDebugEnabled()) {
            // avoid string building if not debug
            DataFlavor[] flavors = tr.getTransferDataFlavors();
            StringBuilder flavor = new StringBuilder();
            for (DataFlavor flavor1 : flavors) {
                flavor.append(flavor1.getRepresentationClass().getName()).append(", ");
            }
            log.debug("Editor Drop: flavor classes={}", flavor);
        }
        if (tr.isDataFlavorSupported(_positionableDataFlavor)) {
            Positionable item = (Positionable) tr.getTransferData(_positionableDataFlavor);
            if (item == null) {
                return;
            }
            item.setLocation(pt.x, pt.y);
            // now set display level in the pane.
            item.setDisplayLevel(item.getDisplayLevel());
            item.setEditor(this);
            putItem(item);
            item.updateSize();
            //if (_debug) log.debug("Drop positionable "+item.getNameString()+
            //                                    " as "+item.getClass().getName()+
            //                                    ", w= "+item.maxWidth()+", h= "+item.maxHeight());
            evt.dropComplete(true);
            return;
        } else if (tr.isDataFlavorSupported(_namedIconDataFlavor)) {
            NamedIcon newIcon = new NamedIcon((NamedIcon) tr.getTransferData(_namedIconDataFlavor));
            String url = newIcon.getURL();
            NamedIcon icon = NamedIcon.getIconByName(url);
            PositionableLabel ni = new PositionableLabel(icon, this);
            // infer a background icon from the size
            if (icon.getIconHeight() > 500 || icon.getIconWidth() > 600) {
                ni.setDisplayLevel(BKG);
            } else {
                ni.setDisplayLevel(ICONS);
            }
            ni.setLocation(pt.x, pt.y);
            ni.setEditor(this);
            putItem(ni);
            ni.updateSize();
            evt.dropComplete(true);
            return;
        } else if (tr.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            String text = (String) tr.getTransferData(DataFlavor.stringFlavor);
            PositionableLabel l = new PositionableLabel(text, this);
            l.setSize(l.getPreferredSize().width, l.getPreferredSize().height);
            l.setDisplayLevel(LABELS);
            l.setLocation(pt.x, pt.y);
            l.setEditor(this);
            putItem(l);
            evt.dropComplete(true);
        } else if (tr.isDataFlavorSupported(_positionableListDataFlavor)) {
            List<Positionable> dragGroup = (List<Positionable>) tr.getTransferData(_positionableListDataFlavor);
            for (Positionable pos : dragGroup) {
                pos.setEditor(this);
                putItem(pos);
                pos.updateSize();
                log.debug("DnD Add {}", pos.getNameString());
            }
        } else {
            log.warn("Editor DropTargetListener  supported DataFlavors not avaialable at drop from " + tr.getClass().getName());
        }
    } catch (IOException ioe) {
        log.warn("Editor DropTarget caught IOException", ioe);
    } catch (UnsupportedFlavorException ufe) {
        log.warn("Editor DropTarget caught UnsupportedFlavorException", ufe);
    }
    log.debug("Editor DropTargetListener drop REJECTED!");
    evt.rejectDrop();
}
Also used : NamedIcon(jmri.jmrit.catalog.NamedIcon) Transferable(java.awt.datatransfer.Transferable) PositionableLabel(jmri.jmrit.display.PositionableLabel) List(java.util.List) ArrayList(java.util.ArrayList) Point(java.awt.Point) Positionable(jmri.jmrit.display.Positionable) IOException(java.io.IOException) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) DataFlavor(java.awt.datatransfer.DataFlavor)

Example 10 with UnsupportedFlavorException

use of java.awt.datatransfer.UnsupportedFlavorException in project JMRI by JMRI.

the class ControlPanelEditor method pasteFromClipboard.

private void pasteFromClipboard() {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    DataFlavor[] flavors = clipboard.getAvailableDataFlavors();
    for (DataFlavor flavor : flavors) {
        if (_positionableListDataFlavor.equals(flavor)) {
            try {
                @SuppressWarnings("unchecked") List<Positionable> clipGroup = (List<Positionable>) clipboard.getData(_positionableListDataFlavor);
                if (clipGroup != null && clipGroup.size() > 0) {
                    Positionable pos = clipGroup.get(0);
                    int minX = pos.getLocation().x;
                    int minY = pos.getLocation().y;
                    // locate group at mouse point
                    for (int i = 1; i < clipGroup.size(); i++) {
                        pos = clipGroup.get(i);
                        minX = Math.min(minX, pos.getLocation().x);
                        minY = Math.min(minY, pos.getLocation().y);
                    }
                    if (_pastePending) {
                        abortPasteItems();
                    }
                    _selectionGroup = new ArrayList<Positionable>();
                    for (int i = 0; i < clipGroup.size(); i++) {
                        pos = clipGroup.get(i);
                        // make positionable belong to this editor
                        pos.setEditor(this);
                        pos.setLocation(pos.getLocation().x + _anchorX - minX, pos.getLocation().y + _anchorY - minY);
                        // now set display level in the pane.
                        pos.setDisplayLevel(pos.getDisplayLevel());
                        putItem(pos);
                        pos.updateSize();
                        pos.setVisible(true);
                        _selectionGroup.add(pos);
                        if (pos instanceof PositionableIcon) {
                            jmri.NamedBean bean = pos.getNamedBean();
                            if (bean != null) {
                                ((PositionableIcon) pos).displayState(bean.getState());
                            }
                        } else if (pos instanceof MemoryIcon) {
                            ((MemoryIcon) pos).displayState();
                        } else if (pos instanceof PositionableJComponent) {
                            ((PositionableJComponent) pos).displayState();
                        }
                        log.debug("Paste Added at ({}, {})", pos.getLocation().x, pos.getLocation().y);
                    }
                }
                return;
            } catch (IOException ioe) {
                log.warn("Editor Paste caught IOException", ioe);
            } catch (UnsupportedFlavorException ufe) {
                log.warn("Editor Paste caught UnsupportedFlavorException", ufe);
            }
        }
    }
}
Also used : MemoryIcon(jmri.jmrit.display.MemoryIcon) PositionableIcon(jmri.jmrit.display.PositionableIcon) IOException(java.io.IOException) UnsupportedFlavorException(java.awt.datatransfer.UnsupportedFlavorException) Point(java.awt.Point) DataFlavor(java.awt.datatransfer.DataFlavor) PositionableJComponent(jmri.jmrit.display.PositionableJComponent) List(java.util.List) ArrayList(java.util.ArrayList) Clipboard(java.awt.datatransfer.Clipboard) Positionable(jmri.jmrit.display.Positionable)

Aggregations

UnsupportedFlavorException (java.awt.datatransfer.UnsupportedFlavorException)106 IOException (java.io.IOException)92 Transferable (java.awt.datatransfer.Transferable)55 List (java.util.List)32 DataFlavor (java.awt.datatransfer.DataFlavor)26 File (java.io.File)25 Point (java.awt.Point)18 ArrayList (java.util.ArrayList)15 Clipboard (java.awt.datatransfer.Clipboard)14 JTree (javax.swing.JTree)9 TreePath (javax.swing.tree.TreePath)9 JComponent (javax.swing.JComponent)7 TransferHandler (javax.swing.TransferHandler)7 DropTargetContext (java.awt.dnd.DropTargetContext)6 URL (java.net.URL)5 DefaultTableModel (javax.swing.table.DefaultTableModel)5 Image (java.awt.Image)4 ActionEvent (java.awt.event.ActionEvent)4 MouseEvent (java.awt.event.MouseEvent)4 NodeInterface (com.sldeditor.common.NodeInterface)3