Search in sources :

Example 36 with Transferable

use of java.awt.datatransfer.Transferable in project intellij-community by JetBrains.

the class EditorModificationUtil method pasteTransferableAsBlock.

public static void pasteTransferableAsBlock(Editor editor, @Nullable Producer<Transferable> producer) {
    Transferable content = getTransferable(producer);
    if (content == null)
        return;
    String text = getStringContent(content);
    if (text == null)
        return;
    int caretLine = editor.getCaretModel().getLogicalPosition().line;
    LogicalPosition caretToRestore = editor.getCaretModel().getLogicalPosition();
    String[] lines = LineTokenizer.tokenize(text.toCharArray(), false);
    int longestLineLength = 0;
    for (int i = 0; i < lines.length; i++) {
        String line = lines[i];
        longestLineLength = Math.max(longestLineLength, line.length());
        editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(caretLine + i, caretToRestore.column));
        insertStringAtCaret(editor, line, false, true);
    }
    caretToRestore = new LogicalPosition(caretLine, caretToRestore.column + longestLineLength);
    editor.getCaretModel().moveToLogicalPosition(caretToRestore);
    zeroWidthBlockSelectionAtCaretColumn(editor, caretLine, caretLine);
}
Also used : Transferable(java.awt.datatransfer.Transferable)

Example 37 with Transferable

use of java.awt.datatransfer.Transferable in project intellij-community by JetBrains.

the class CopyHandler method doExecute.

@Override
public void doExecute(final Editor editor, Caret caret, final DataContext dataContext) {
    assert caret == null : "Invocation of 'copy' operation for specific caret is not supported";
    final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(editor.getComponent()));
    if (project == null) {
        if (myOriginalAction != null) {
            myOriginalAction.execute(editor, null, dataContext);
        }
        return;
    }
    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null) {
        if (myOriginalAction != null) {
            myOriginalAction.execute(editor, null, dataContext);
        }
        return;
    }
    final SelectionModel selectionModel = editor.getSelectionModel();
    if (!selectionModel.hasSelection(true)) {
        if (Registry.is(CopyAction.SKIP_COPY_AND_CUT_FOR_EMPTY_SELECTION_KEY)) {
            return;
        }
        editor.getCaretModel().runForEachCaret(new CaretAction() {

            @Override
            public void perform(Caret caret) {
                selectionModel.selectLineAtCaret();
            }
        });
        if (!selectionModel.hasSelection(true))
            return;
        editor.getCaretModel().runForEachCaret(new CaretAction() {

            @Override
            public void perform(Caret caret) {
                EditorActionUtil.moveCaretToLineStartIgnoringSoftWraps(editor);
            }
        });
    }
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    final int[] startOffsets = selectionModel.getBlockSelectionStarts();
    final int[] endOffsets = selectionModel.getBlockSelectionEnds();
    final List<TextBlockTransferableData> transferableDatas = new ArrayList<>();
    DumbService.getInstance(project).withAlternativeResolveEnabled(() -> {
        for (CopyPastePostProcessor<? extends TextBlockTransferableData> processor : Extensions.getExtensions(CopyPastePostProcessor.EP_NAME)) {
            transferableDatas.addAll(processor.collectTransferableData(file, editor, startOffsets, endOffsets));
        }
    });
    String text = editor.getCaretModel().supportsMultipleCarets() ? EditorCopyPasteHelperImpl.getSelectedTextForClipboard(editor, transferableDatas) : selectionModel.getSelectedText();
    String rawText = TextBlockTransferable.convertLineSeparators(text, "\n", transferableDatas);
    String escapedText = null;
    for (CopyPastePreProcessor processor : Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
        escapedText = processor.preprocessOnCopy(file, startOffsets, endOffsets, rawText);
        if (escapedText != null) {
            break;
        }
    }
    final Transferable transferable = new TextBlockTransferable(escapedText != null ? escapedText : rawText, transferableDatas, escapedText != null ? new RawText(rawText) : null);
    CopyPasteManager.getInstance().setContents(transferable);
    if (editor instanceof EditorEx) {
        EditorEx ex = (EditorEx) editor;
        if (ex.isStickySelection()) {
            ex.setStickySelection(false);
        }
    }
}
Also used : EditorEx(com.intellij.openapi.editor.ex.EditorEx) ArrayList(java.util.ArrayList) Transferable(java.awt.datatransfer.Transferable) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile)

Example 38 with Transferable

use of java.awt.datatransfer.Transferable in project intellij-community by JetBrains.

the class PasteHandler method execute.

@Override
public void execute(final Editor editor, final DataContext dataContext, @Nullable final Producer<Transferable> producer) {
    final Transferable transferable = EditorModificationUtil.getContentsToPasteToEditor(producer);
    if (transferable == null)
        return;
    if (!EditorModificationUtil.checkModificationAllowed(editor))
        return;
    final Document document = editor.getDocument();
    if (!EditorModificationUtil.requestWriting(editor)) {
        return;
    }
    DataContext context = new DataContext() {

        @Override
        public Object getData(@NonNls String dataId) {
            return PasteAction.TRANSFERABLE_PROVIDER.is(dataId) ? (Producer<Transferable>) () -> transferable : dataContext.getData(dataId);
        }
    };
    final Project project = editor.getProject();
    if (project == null || editor.isColumnMode() || editor.getCaretModel().getCaretCount() > 1) {
        if (myOriginalHandler != null) {
            myOriginalHandler.execute(editor, null, context);
        }
        return;
    }
    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (file == null) {
        if (myOriginalHandler != null) {
            myOriginalHandler.execute(editor, null, context);
        }
        return;
    }
    DumbService.getInstance(project).setAlternativeResolveEnabled(true);
    document.startGuardedBlockChecking();
    try {
        for (PasteProvider provider : Extensions.getExtensions(EP_NAME)) {
            if (provider.isPasteEnabled(context)) {
                provider.performPaste(context);
                return;
            }
        }
        doPaste(editor, project, file, document, transferable);
    } catch (ReadOnlyFragmentModificationException e) {
        EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(e);
    } finally {
        document.stopGuardedBlockChecking();
        DumbService.getInstance(project).setAlternativeResolveEnabled(false);
    }
}
Also used : NonNls(org.jetbrains.annotations.NonNls) Project(com.intellij.openapi.project.Project) DataContext(com.intellij.openapi.actionSystem.DataContext) PasteProvider(com.intellij.ide.PasteProvider) Transferable(java.awt.datatransfer.Transferable) PsiFile(com.intellij.psi.PsiFile)

Example 39 with Transferable

use of java.awt.datatransfer.Transferable 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 40 with Transferable

use of java.awt.datatransfer.Transferable 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)

Aggregations

Transferable (java.awt.datatransfer.Transferable)96 UnsupportedFlavorException (java.awt.datatransfer.UnsupportedFlavorException)30 IOException (java.io.IOException)30 List (java.util.List)18 DataFlavor (java.awt.datatransfer.DataFlavor)14 ArrayList (java.util.ArrayList)14 File (java.io.File)13 Clipboard (java.awt.datatransfer.Clipboard)12 Point (java.awt.Point)9 StringSelection (java.awt.datatransfer.StringSelection)5 Project (com.intellij.openapi.project.Project)4 ClipboardOwner (java.awt.datatransfer.ClipboardOwner)4 TransferHandler (javax.swing.TransferHandler)4 Editor (com.intellij.openapi.editor.Editor)3 ActionEvent (java.awt.event.ActionEvent)3 JComponent (javax.swing.JComponent)3 TreePath (javax.swing.tree.TreePath)3 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)2 DataContext (com.intellij.openapi.actionSystem.DataContext)2 PsiElement (com.intellij.psi.PsiElement)2