diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 17a5855..dbac882 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -2029,19 +2029,27 @@ pub fn copy_text_to_clipboard(_text: String) -> Result<(), String> { Err("Text clipboard copy is only supported on desktop".to_string()) } -/// Read text from the system clipboard through the native backend. +/// Text and HTML on the system clipboard, read through the native backend. +#[derive(Debug, Default, Clone, serde::Serialize)] +pub struct ClipboardContents { + pub text: Option, + pub html: Option, +} + +/// Read text and HTML from the system clipboard through the native backend. /// Works around the WebKitGTK clipboard bug where the async `navigator.clipboard` -/// API returns empty for text copied from external applications. +/// API returns nothing, or only plain text, for content copied from external +/// applications. Each format is optional; a missing one is not an error. #[cfg(desktop)] #[tauri::command] -pub async fn read_clipboard_text() -> Result { +pub async fn read_clipboard_contents() -> Result { // Reading the clipboard can block while the owning application answers, like the image read below. tauri::async_runtime::spawn_blocking(move || { let mut clipboard = arboard::Clipboard::new().map_err(|e| format!("Clipboard init failed: {}", e))?; - clipboard - .get_text() - .map_err(|e| format!("Failed to read text from clipboard: {}", e)) + let text = clipboard.get_text().ok().filter(|text| !text.is_empty()); + let html = clipboard.get().html().ok().filter(|html| !html.is_empty()); + Ok(ClipboardContents { text, html }) }) .await .map_err(|error| error.to_string())? @@ -2049,8 +2057,8 @@ pub async fn read_clipboard_text() -> Result { #[cfg(mobile)] #[tauri::command] -pub async fn read_clipboard_text() -> Result { - Err("Text clipboard read is only supported on desktop".to_string()) +pub async fn read_clipboard_contents() -> Result { + Err("Native clipboard read is only supported on desktop".to_string()) } /// Read image from system clipboard (bypasses WebKitGTK clipboard bug). diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index aa8ac26..77a0e02 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -212,7 +212,7 @@ pub fn run() { commands::load_vault_state, commands::save_vault_state, commands::copy_text_to_clipboard, - commands::read_clipboard_text, + commands::read_clipboard_contents, commands::read_clipboard_image, commands::copy_image_to_clipboard, commands::save_image, diff --git a/src/lib/api.ts b/src/lib/api.ts index c7947f0..ec8d860 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -280,8 +280,13 @@ export async function readClipboardImage(): Promise { return invoke("read_clipboard_image"); } -export async function readClipboardText(): Promise { - return invoke("read_clipboard_text"); +export interface ClipboardContents { + text: string | null; + html: string | null; +} + +export async function readClipboardContents(): Promise { + return invoke("read_clipboard_contents"); } export async function copyImageToClipboard(path: string): Promise { diff --git a/src/lib/components/Editor.svelte b/src/lib/components/Editor.svelte index 830ac94..56356c6 100644 --- a/src/lib/components/Editor.svelte +++ b/src/lib/components/Editor.svelte @@ -35,7 +35,7 @@ import { openFile, openUrl, copyFileTo, copyImageToClipboard as copyImageToClipboardCmd, writeBytesTo, copyPngToClipboard, copyTextToClipboard } from '$lib/api'; import { save as saveDialog } from '@tauri-apps/plugin-dialog'; import { activeNote, activeNotePath, appConfig, editorDirty, sourceMode, focusMode, readOnly, quickAccessPaths, notes, navHistory, canGoBack, canGoForward, viewerNote, viewMode, notebooks, outlineWidth } from '$lib/stores/app'; - import { saveNote, importNote, createNote, saveImage, saveAttachment, readClipboardImage, readClipboardText, addQuickAccess, removeQuickAccess, getQuickAccess, getNoteVersions, getNoteVersionContent, createVersion, aiAsk, getAllNoteTitles, readNote, renameNote, setToolbarLayout } from '$lib/api'; + import { saveNote, importNote, createNote, saveImage, saveAttachment, readClipboardImage, readClipboardContents, addQuickAccess, removeQuickAccess, getQuickAccess, getNoteVersions, getNoteVersionContent, createVersion, aiAsk, getAllNoteTitles, readNote, renameNote, setToolbarLayout } from '$lib/api'; import type { NoteContent, VersionEntry, AiStreamEvent, NoteTitleEntry, TaskItem as TaskRecord, FileEvent, SearchTarget, ToolbarLayout } from '$lib/types'; import { listen } from '@tauri-apps/api/event'; import { debounce } from '$lib/utils/debounce'; @@ -62,7 +62,7 @@ import { restoreTitleHeading, stripTitleHeading, type HiddenTitleHeading } from '$lib/editor/titleVisibility'; import { documentHeadings, sourceHeadings, activeHeadingIndex, mapDocumentHeadings, mapSourceHeadings, type OutlineHeading } from '$lib/editor/outline'; import { createEditorMarkdownParser } from '$lib/editor/markdownParser'; - import { collectClipboardPayload, isEmptyPayload, type ClipboardPastePayload } from '$lib/utils/clipboard-paste'; + import { collectClipboardPayload, isEmptyPayload, needsNativeClipboard, withNativeClipboard, type ClipboardPastePayload } from '$lib/utils/clipboard-paste'; import { externalNoteReferences } from '$lib/editor/externalNote'; import { tagIterationKey } from '$lib/utils/tag-styles'; import { replaceWithWikiLink } from '$lib/editor/wikiLinks'; @@ -5880,31 +5880,37 @@ } } + async function readNativeClipboard(): Promise<{ text?: string | null; html?: string | null }> { + try { + return await readClipboardContents(); + } catch (e) { + console.error('Native clipboard read failed:', e); + return {}; + } + } + async function ctxPaste() { // insertClipboardImage() saves the attachment before inserting it, so an // unguarded paste here would leave an orphan file behind when the editor // cannot accept the insertion. if (!editor || $readOnly || $viewerNote) { closeTextContextMenu(); return; } const origin = captureOrigin(); - const payload = await readWebClipboard(); + let payload = await readWebClipboard(); if (!canInsert(origin) || !editor) return; - if (payload && replayPaste(payload)) { + // WebKitGTK (bug #218519) often gives nothing, or only plain text, for content from other + // apps. Fill in text and HTML from the native clipboard so formatting survives like Ctrl+V. + if (needsNativeClipboard(payload)) { + payload = withNativeClipboard(payload, await readNativeClipboard()); + if (!canInsert(origin) || !editor) return; + } + // Replaying the event runs Ctrl+V's handlers, including the WebKitGTK image fallback for a + // clipboard holding only an image (or a bare ). + if (payload && !isEmptyPayload(payload) && replayPaste(payload)) { closeTextContextMenu(); return; } - // Native fallback when the web clipboard is unavailable or empty. An image comes first, so a - // browser "Copy image" pastes the bitmap rather than the image URL that may come with it. - if (await insertClipboardImage(origin)) { - if (isOriginCurrent(origin)) closeTextContextMenu(); - return; - } - try { - const text = await readClipboardText(); - if (!canInsert(origin) || !editor) return; - if (text) replayPaste({ text, html: '', strings: [], files: [] }); - } catch (e) { - console.error('Native clipboard read failed:', e); - } + // Nothing textual at all: the clipboard may still hold a bitmap only the native reader sees. + await insertClipboardImage(origin); if (isOriginCurrent(origin)) closeTextContextMenu(); } diff --git a/src/lib/utils/clipboard-paste.test.mjs b/src/lib/utils/clipboard-paste.test.mjs index 4c8272c..5d9cd16 100644 --- a/src/lib/utils/clipboard-paste.test.mjs +++ b/src/lib/utils/clipboard-paste.test.mjs @@ -4,8 +4,10 @@ import { classifyClipboardType, collectClipboardPayload, isEmptyPayload, + needsNativeClipboard, pastedFileName, - plainTextFromUriList + plainTextFromUriList, + withNativeClipboard } from './clipboard-paste.ts'; const item = entries => ({ @@ -79,3 +81,23 @@ test('pasted file names use friendly extensions', () => { assert.equal(pastedFileName('image/svg+xml', 1), 'pasted-image-2.svg'); assert.equal(pastedFileName('application/pdf', 0), 'pasted-file.pdf'); }); + +test('formatting from other apps survives when the web clipboard only offers plain text (P6)', async () => { + // WebKitGTK: navigator.clipboard.read() gives just text/plain for a web page copied in a browser. + const web = await collectClipboardPayload([item({ 'text/plain': 'Bold link' })]); + assert.equal(needsNativeClipboard(web), true); + const merged = withNativeClipboard(web, { text: 'Bold link (native)', html: 'Bold link' }); + assert.equal(merged.html, 'Bold link'); + assert.equal(merged.text, 'Bold link', 'web text is kept when present'); +}); + +test('a failed web clipboard read falls back to native text and HTML entirely', () => { + assert.equal(needsNativeClipboard(null), true); + assert.deepEqual(withNativeClipboard(null, { text: 'plain', html: null }), { text: 'plain', html: '', strings: [], files: [] }); + assert.equal(isEmptyPayload(withNativeClipboard(null, {})), true, 'nothing textual: the native image read comes next'); +}); + +test('the native clipboard is not consulted when the web clipboard already has HTML or files', async () => { + assert.equal(needsNativeClipboard(await collectClipboardPayload([item({ 'text/html': 'x' })])), false); + assert.equal(needsNativeClipboard(await collectClipboardPayload([item({ 'image/png': png })])), false); +}); diff --git a/src/lib/utils/clipboard-paste.ts b/src/lib/utils/clipboard-paste.ts index 52d932c..e75e87b 100644 --- a/src/lib/utils/clipboard-paste.ts +++ b/src/lib/utils/clipboard-paste.ts @@ -62,6 +62,28 @@ export interface ClipboardPastePayload { files: File[]; } +/** Web clipboard data still missing formats a keyboard paste would carry, so the native clipboard is needed. */ +export function needsNativeClipboard(payload: ClipboardPastePayload | null): boolean { + return !payload || (!payload.html && payload.files.length === 0); +} + +/** + * Fill in what the web clipboard didn't provide from the native clipboard. WebKitGTK often returns + * nothing, or only `text/plain`, for content copied from other applications; Ctrl+V would still + * have received the HTML (formatting, links), so a paste without it is not the same paste. + */ +export function withNativeClipboard( + payload: ClipboardPastePayload | null, + native: { text?: string | null; html?: string | null }, +): ClipboardPastePayload { + return { + text: payload?.text || native.text || '', + html: payload?.html || native.html || '', + strings: payload?.strings ?? [], + files: payload?.files ?? [], + }; +} + export function isEmptyPayload(payload: ClipboardPastePayload): boolean { return !payload.text && !payload.html && payload.files.length === 0; }