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);
}
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);
}
}
}
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);
}
}
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;
}
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;
}
Aggregations