diff --git a/Cargo.lock b/Cargo.lock index f907ce3c20..fbe6413f72 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4261,6 +4261,7 @@ dependencies = [ name = "ide-clipboard" version = "0.1.40" dependencies = [ + "gtk", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", diff --git a/crates/ide-clipboard/Cargo.toml b/crates/ide-clipboard/Cargo.toml index fddf9fecc1..4211138a8d 100644 --- a/crates/ide-clipboard/Cargo.toml +++ b/crates/ide-clipboard/Cargo.toml @@ -11,3 +11,6 @@ license.workspace = true objc2 = { version = "0.6", default-features = false, features = ["std"] } objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] } objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard"] } + +[target.'cfg(target_os = "linux")'.dependencies] +gtk = "0.18" diff --git a/crates/ide-clipboard/src/lib.rs b/crates/ide-clipboard/src/lib.rs index 1bf899a178..ff2ef5110c 100644 --- a/crates/ide-clipboard/src/lib.rs +++ b/crates/ide-clipboard/src/lib.rs @@ -21,6 +21,12 @@ use std::path::PathBuf; +/// Replaces every clipboard flavor with plain text. `owner` is the calling window +/// handle on Windows, ignored elsewhere. Call on the main thread on macOS and Linux. +pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> { + imp::set_text(text, owner) +} + /// Size of `DROPFILES`: `pFiles`, `pt` (two `LONG`s), `fNC`, `fWide`. const HEADER: usize = 20; @@ -165,8 +171,12 @@ mod imp { /// Opens the clipboard as its owner: the list is written in full, so no /// owning window is needed. fn open() -> bool { + open_for(ptr::null_mut()) + } + + fn open_for(owner: Handle) -> bool { for _ in 0..OPEN_ATTEMPTS { - if unsafe { OpenClipboard(ptr::null_mut()) } != 0 { + if unsafe { OpenClipboard(owner) } != 0 { return true; } std::thread::sleep(OPEN_RETRY); @@ -230,6 +240,29 @@ mod imp { } } + pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> { + let (memory, _) = global_text(text); + if memory.is_null() { + return Err(std::io::Error::last_os_error()); + } + // SAFETY: ownership transfers only on success; otherwise we free the allocation. + unsafe { + if !open_for(owner as Handle) { + GlobalFree(memory); + return Err(std::io::Error::last_os_error()); + } + let taken = EmptyClipboard() != 0 && !SetClipboardData(CF_UNICODETEXT, memory).is_null(); + let error = std::io::Error::last_os_error(); + CloseClipboard(); + if taken { + Ok(()) + } else { + GlobalFree(memory); + Err(error) + } + } + } + pub fn set_files(paths: &[PathBuf]) -> bool { let bytes = encode(paths); if bytes.len() <= HEADER { @@ -340,6 +373,19 @@ mod imp { }) } + pub fn set_text(text: &str, _owner: usize) -> std::io::Result<()> { + debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread"); + autoreleasepool(|_| { + let board = NSPasteboard::generalPasteboard(); + board.clearContents(); + if board.setString_forType(&NSString::from_str(text), unsafe { NSPasteboardTypeString }) { + Ok(()) + } else { + Err(std::io::Error::other("Cannot write clipboard text")) + } + }) + } + pub fn set_files(paths: &[PathBuf]) -> bool { debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread"); autoreleasepool(|_| { @@ -370,6 +416,19 @@ mod imp { mod imp { use std::path::PathBuf; + pub fn set_text(text: &str, _owner: usize) -> std::io::Result<()> { + #[cfg(target_os = "linux")] + { + gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).set_text(text); + Ok(()) + } + #[cfg(not(target_os = "linux"))] + { + let _ = text; + Err(std::io::Error::other("Clipboard text is unavailable on this platform")) + } + } + pub fn has_files() -> bool { false } diff --git a/crates/ide-host/src/trust.rs b/crates/ide-host/src/trust.rs index 22e41f1338..b9d22e2472 100644 --- a/crates/ide-host/src/trust.rs +++ b/crates/ide-host/src/trust.rs @@ -247,6 +247,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool { | "clipboard_has_files" | "clipboard_image" | "clipboard_set_file_list" + | "clipboard_write_text" | "jdk_download_vendors" | "jdk_download_releases" | "jdk_download_location" @@ -454,3 +455,11 @@ impl TrustStore { Ok(TrustStatus { decided: trusted || state.restricted.contains(&root), root: root.into(), trusted }) } } + +#[cfg(test)] +mod tests { + #[test] + fn restricted_mode_allows_clipboard_write_text() { + assert!(super::restricted_command_allowed("clipboard_write_text")); + } +} diff --git a/crates/ide-host/tests/trust.rs b/crates/ide-host/tests/trust.rs index 595402627f..3d52993a08 100644 --- a/crates/ide-host/tests/trust.rs +++ b/crates/ide-host/tests/trust.rs @@ -48,6 +48,7 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project( "clipboard_has_files", "clipboard_image", "clipboard_set_file_list", + "clipboard_write_text", "jdk_download_vendors", "jdk_download_releases", "jdk_download_location", diff --git a/e2e/dialogFocus.spec.ts b/e2e/dialogFocus.spec.ts new file mode 100644 index 0000000000..be89be5187 --- /dev/null +++ b/e2e/dialogFocus.spec.ts @@ -0,0 +1,29 @@ +import { expect, openFromTree, test } from "./fixtures"; + +for (const key of ["Enter", "Escape"]) { + test(`confirmation keeps focus across a deferred editor focus until ${key}`, async ({ workbench: page }) => { + const editor = await openFromTree(page, "README.md"); + const content = editor.locator(".cm-content"); + await content.click(); + const before = await content.innerText(); + await page.evaluate(async () => { + const messages = "/src/workbench/messages.tsx"; + const { confirm } = await import(/* @vite-ignore */ messages); + const content = document.querySelector(".cm-content")!; + void confirm({ title: "Add File to Git", message: "Add README.md?", ok: "Add" }).then((accepted: boolean) => { + document.body.dataset.confirmed = String(accepted); + }); + requestAnimationFrame(() => { + content.focus(); + document.body.dataset.focusAttempted = "true"; + }); + }); + await expect(page.locator("body")).toHaveAttribute("data-focus-attempted", "true"); + await expect(page.getByRole("button", { name: "Add", exact: true })).toBeFocused(); + await page.keyboard.press(key); + await expect(page.getByRole("dialog", { name: "Add File to Git" })).toBeHidden(); + await expect(page.locator("body")).toHaveAttribute("data-confirmed", String(key === "Enter")); + await expect(content).toBeFocused(); + await expect(content).toHaveText(before!); + }); +} diff --git a/src-tauri/src/commands/clipboard.rs b/src-tauri/src/commands/clipboard.rs index b3c5c75e70..b9157bd7e1 100644 --- a/src-tauri/src/commands/clipboard.rs +++ b/src-tauri/src/commands/clipboard.rs @@ -1,12 +1,26 @@ //! The OS clipboard's file list, so the project view and Explorer exchange files. -#[cfg(not(target_os = "macos"))] +#[cfg(not(any(target_os = "macos", target_os = "linux")))] use crate::commands::doc::blocking; -#[cfg(target_os = "macos")] +#[cfg(any(target_os = "macos", target_os = "linux"))] use ide_core::IdeError; use ide_core::IdeResult; use std::path::{Path, PathBuf}; -use tauri::AppHandle; +use tauri::{AppHandle, WebviewWindow}; + +/// Writes text locally, without WebView user-activation requirements. +#[tauri::command] +#[specta::specta] +pub async fn clipboard_write_text(app: AppHandle, window: WebviewWindow, text: String) -> IdeResult<()> { + #[cfg(windows)] + let owner = window.hwnd().map_err(|error| ide_core::IdeError::internal(error.to_string()))?.0 as usize; + #[cfg(not(windows))] + let owner = { + let _ = window; + 0 + }; + with_clipboard(app, move || ide_clipboard::set_text(&text, owner).map_err(ide_core::IdeError::from)).await +} /// Absolute paths on the clipboard, empty when it holds no file list. #[tauri::command] @@ -70,7 +84,7 @@ async fn with_clipboard( app: AppHandle, f: impl FnOnce() -> IdeResult + Send + 'static, ) -> IdeResult { - #[cfg(target_os = "macos")] + #[cfg(any(target_os = "macos", target_os = "linux"))] { let (tx, rx) = tokio::sync::oneshot::channel(); app.run_on_main_thread(move || { @@ -79,7 +93,7 @@ async fn with_clipboard( .map_err(|error| IdeError::internal(format!("Cannot dispatch clipboard access to the main thread: {error}")))?; rx.await.map_err(|error| IdeError::internal(format!("Clipboard main-thread task was dropped: {error}")))? } - #[cfg(not(target_os = "macos"))] + #[cfg(not(any(target_os = "macos", target_os = "linux")))] { let _ = app; blocking(f).await diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index ab33584712..17c38cb222 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -164,6 +164,7 @@ pub fn builder() -> tauri_specta::Builder { fs::fs_copy_merge, fs::fs_compare_directories, fs::fs_read_text, + clipboard::clipboard_write_text, clipboard::clipboard_file_list, clipboard::clipboard_has_files, clipboard::clipboard_image, diff --git a/src/bindings.ts b/src/bindings.ts index ab1dc840d1..e81452648c 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -223,6 +223,8 @@ export const commands = { * definition). Prefers the unsaved buffer when the file is open. */ fsReadText: (path: string) => typedError(__TAURI_INVOKE("fs_read_text", { path })), + /** Writes text locally, without WebView user-activation requirements. */ + clipboardWriteText: (text: string) => typedError(__TAURI_INVOKE("clipboard_write_text", { text })), /** Absolute paths on the clipboard, empty when it holds no file list. */ clipboardFileList: () => typedError(__TAURI_INVOKE("clipboard_file_list")), /** Whether the clipboard holds files: cheap, for the Paste item's enabled state. */ diff --git a/src/editor/core/actions.ts b/src/editor/core/actions.ts index a3d8458129..cf42655f5c 100644 --- a/src/editor/core/actions.ts +++ b/src/editor/core/actions.ts @@ -1,4 +1,5 @@ /** Editor actions (ids from keymaps/intellij-macos.ts). */ +import { writeClipboardText } from "@/platform/clipboard"; import { EditorSelection, type EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { indentSelection, moveLineDown, moveLineUp } from "@codemirror/commands"; @@ -593,8 +594,7 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) { } function copyEditorPath(text: string) { - void navigator.clipboard - .writeText(text) + void writeClipboardText(text) .then(() => { recordClipboard(text); void executeAction("editor.showHint", { text: tx`Copied ${text}` }); diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index 4b685db221..21bcb9436a 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -3,6 +3,7 @@ * status, navigation history, autosave. The React views and actions talk to * this singleton; other features use the EditorService and editor/api. */ +import { writeClipboardText } from "@/platform/clipboard"; import { pasteEditorClipboard } from "./cm/clipboard"; import { EditorSelection } from "@codemirror/state"; import { create } from "zustand"; @@ -862,7 +863,7 @@ export class EditorController implements SlotHost { ...(slot.model.virtual ? ([ { kind: "separator" }, - { label: "Copy Reference", run: () => void navigator.clipboard?.writeText(slot.model.path) }, + { label: "Copy Reference", run: () => void writeClipboardText(slot.model.path) }, ] as MenuItem[]) : ([ { kind: "separator" }, diff --git a/src/editor/core/copyReference.ts b/src/editor/core/copyReference.ts index 160ac3ee3d..66d9b1586f 100644 --- a/src/editor/core/copyReference.ts +++ b/src/editor/core/copyReference.ts @@ -3,6 +3,7 @@ * fully qualified name, built from the file's outline and the language's module * conventions; anywhere else `path:line`, as in IDEA. */ +import { writeClipboardText } from "@/platform/clipboard"; export interface ReferenceInput { /** Backend language id (`java`, `rust`…). */ @@ -17,19 +18,8 @@ export interface ReferenceInput { line: number; } -/** - * Start the write during the user gesture, while the reference is still being resolved. - * Without `ClipboardItem`, the text is written once it is known. - */ -export function copyReferenceToClipboard( - reference: Promise, - clipboard: Clipboard = navigator.clipboard, - Item: typeof ClipboardItem | null = globalThis.ClipboardItem ?? null, -): Promise { - if (!Item || typeof clipboard.write !== "function") return reference.then((text) => clipboard.writeText(text)); - return clipboard.write([ - new Item({ "text/plain": reference.then((text) => new Blob([text], { type: "text/plain" })) }), - ]); +export function copyReferenceToClipboard(reference: Promise): Promise { + return reference.then(writeClipboardText); } /** Position inside a selected identifier or the identifier under the caret. */ diff --git a/src/editor/core/editingExtras.test.ts b/src/editor/core/editingExtras.test.ts index ab0542a10a..e03b7dc6da 100644 --- a/src/editor/core/editingExtras.test.ts +++ b/src/editor/core/editingExtras.test.ts @@ -12,8 +12,11 @@ import { rustImplType, rustModulePath, } from "./copyReference"; +import { writeClipboardText } from "@/platform/clipboard"; import { declarationChain } from "./view/outline"; +vi.mock("@/platform/clipboard", () => ({ writeClipboardText: vi.fn(async () => {}) })); + describe("cyclic expand word", () => { const text = "alphaOne x alphaTwo y al| alphaThree alphaOne"; const caret = text.indexOf("|"); @@ -60,37 +63,23 @@ describe("cyclic expand word", () => { describe("copy reference", () => { const base = { root: "/p", line: 4 }; - it("starts the clipboard write before asynchronous symbol resolution completes", async () => { + it("writes the resolved reference through the shared clipboard helper", async () => { + vi.mocked(writeClipboardText).mockClear(); let finish!: (value: string) => void; const reference = new Promise((resolve) => { finish = resolve; }); - let content: Promise | undefined; - class Item { - constructor(data: Record>) { - content = data["text/plain"]; - } - } - let writes = 0; - const write = () => { - writes++; - return Promise.resolve(); - }; - const result = copyReferenceToClipboard( - reference, - { write } as unknown as Clipboard, - Item as unknown as typeof ClipboardItem, - ); - expect(writes).toBe(1); + const result = copyReferenceToClipboard(reference); + expect(writeClipboardText).not.toHaveBeenCalled(); finish("coordination_layer.db.key_scope.load_scoped"); - expect(await (await content!).text()).toBe("coordination_layer.db.key_scope.load_scoped"); await result; + expect(writeClipboardText).toHaveBeenCalledExactlyOnceWith("coordination_layer.db.key_scope.load_scoped"); }); - it("writes the resolved text where ClipboardItem is unavailable", async () => { - const writeText = vi.fn(() => Promise.resolve()); - await copyReferenceToClipboard(Promise.resolve("pkg.mod.f"), { writeText } as unknown as Clipboard, null); - expect(writeText).toHaveBeenCalledExactlyOnceWith("pkg.mod.f"); + it("does not overwrite the clipboard when reference resolution fails", async () => { + vi.mocked(writeClipboardText).mockClear(); + await expect(copyReferenceToClipboard(Promise.reject(new Error("no symbol")))).rejects.toThrow("no symbol"); + expect(writeClipboardText).not.toHaveBeenCalled(); }); it("qualifies Java members with the package", () => { diff --git a/src/editor/core/extras.ts b/src/editor/core/extras.ts index 0c46fe72a3..931bbd9ddf 100644 --- a/src/editor/core/extras.ts +++ b/src/editor/core/extras.ts @@ -1,4 +1,5 @@ /** Edit › Paste from History and Code › Unwrap/Remove: the parts that need popups or the backend. */ +import { writeClipboardText } from "@/platform/clipboard"; import { EditorSelection } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; import { structure } from "@/editor/structure"; @@ -28,7 +29,7 @@ export function pasteFromHistory(view: EditorView) { } openPasteHistory(view, (text, linewise) => { recordClipboard(text, linewise); - void navigator.clipboard?.writeText(text).catch(() => {}); + void writeClipboardText(text).catch(() => {}); pasteText(view, text); }); } diff --git a/src/features/agents/replyActions.ts b/src/features/agents/replyActions.ts index 69cadfa95b..7811a17c49 100644 --- a/src/features/agents/replyActions.ts +++ b/src/features/agents/replyActions.ts @@ -1,3 +1,4 @@ +import { writeClipboardText } from "@/platform/clipboard"; import type { Action } from "@/platform/actions"; import { tx } from "@/platform/i18n"; import { confirm } from "@/workbench/messages"; @@ -20,7 +21,7 @@ export const copyReplyAction: Action = { const reply = arg as CopyReply | undefined; if (!reply || typeof reply.text !== "string" || !reply.text.trim()) return; try { - await navigator.clipboard.writeText(reply.text); + await writeClipboardText(reply.text); reply.onCopied?.(); } catch (e) { notifications().notify({ level: "error", title: "Couldn't copy the reply", body: String(e) }); diff --git a/src/features/app/AboutDialog.tsx b/src/features/app/AboutDialog.tsx index 0ea3660c3f..e5e9f74000 100644 --- a/src/features/app/AboutDialog.tsx +++ b/src/features/app/AboutDialog.tsx @@ -1,3 +1,4 @@ +import { writeClipboardText } from "@/platform/clipboard"; import { useEffect, useState } from "react"; import { create } from "zustand"; import { executeAction } from "@/platform/actions"; @@ -61,7 +62,7 @@ function AboutDialog({ onClose }: { onClose: () => void }) { const rows = aboutRows(build, app?.configDir ?? null); const copy = () => { const text = [t("app.about.title"), ...rows.map(([k, v]) => `${k}: ${v}`)].join("\n"); - void navigator.clipboard?.writeText(text).then(() => setCopied(true)); + void writeClipboardText(text).then(() => setCopied(true)); }; const run = (id: string) => { onClose(); diff --git a/src/features/build-tools/BuildToolView.tsx b/src/features/build-tools/BuildToolView.tsx index 0fe43f20b0..9f8cc95e7e 100644 --- a/src/features/build-tools/BuildToolView.tsx +++ b/src/features/build-tools/BuildToolView.tsx @@ -1,4 +1,5 @@ /** The Maven and Gradle tool windows: toolbar, status banner and the project tree. */ +import { writeClipboardText } from "@/platform/clipboard"; import { useCallback, useEffect, useMemo, useState, type MouseEvent } from "react"; import clsx from "clsx"; import type { BuildTool, GradleModel, MavenModel, RunConfig } from "@/platform/ipc"; @@ -377,7 +378,7 @@ function BuildToolView({ tool }: { tool: BuildTool }) { if (node.kind === "dependency") { const d = node.dependency; const coords = [d.groupId, d.artifactId, d.version].filter(Boolean).join(":"); - items.push({ label: "Copy Coordinates", icon: "copy", run: () => void navigator.clipboard?.writeText(coords) }); + items.push({ label: "Copy Coordinates", icon: "copy", run: () => void writeClipboardText(coords) }); } if (items.length) showContextMenu({ x: e.clientX, y: e.clientY }, items); }; diff --git a/src/features/code-insight/ProblemsView.tsx b/src/features/code-insight/ProblemsView.tsx index 924368e143..f5c1a5945c 100644 --- a/src/features/code-insight/ProblemsView.tsx +++ b/src/features/code-insight/ProblemsView.tsx @@ -1,3 +1,4 @@ +import { writeClipboardText } from "@/platform/clipboard"; import { menuGroupItems } from "@/workbench/contributions"; /** Problems tool window: "File" (current editor) and "Project Errors" tabs. */ import { useCallback, useMemo, useRef, useState, type KeyboardEvent } from "react"; @@ -267,7 +268,7 @@ export function ProblemsView() { const target = (n: Node | null) => n?.kind === "diag" ? { path: n.path, d: n.d } : n?.items[0] ? { path: n.path, d: n.items[0] } : null; const copy = (n: Node | null) => { - if (n?.kind === "diag") void navigator.clipboard?.writeText(problemText(n.d)); + if (n?.kind === "diag") void writeClipboardText(problemText(n.d)); }; const onKeyDownCapture = (e: KeyboardEvent) => { const t = target(lead); diff --git a/src/features/database/DataView.tsx b/src/features/database/DataView.tsx index d1a7ee8f11..8c4a41e4f4 100644 --- a/src/features/database/DataView.tsx +++ b/src/features/database/DataView.tsx @@ -4,6 +4,7 @@ * client-side sorting when the caller does not sort on the server, and the * Record / Value / Aggregates side panel following the selection. */ +import { writeClipboardText } from "@/platform/clipboard"; import { useMemo, useRef, useState, type KeyboardEvent, type RefObject } from "react"; import clsx from "clsx"; import { Button, Checkbox, Icon, IconButton, Input, Popup, SearchField, Select, Tabs, T, type MenuItem } from "@/ui"; @@ -38,7 +39,7 @@ export function exportMenu(data: ExportData, source: string, format?: ExportForm ...EXPORT_FORMATS.map((f): MenuItem => ({ label: tx`Copy as ${f.label}`, icon: "copy", - run: () => void navigator.clipboard?.writeText(exportData(f.id, data)), + run: () => void writeClipboardText(exportData(f.id, data)), })), ]; } diff --git a/src/features/database/ExportDialog.tsx b/src/features/database/ExportDialog.tsx index b8d9b014b7..350b3532f6 100644 --- a/src/features/database/ExportDialog.tsx +++ b/src/features/database/ExportDialog.tsx @@ -2,6 +2,7 @@ * IDEA's Export Data dialog: extractor (format) and its options on the left, * a live preview on the right; copies to the clipboard or writes a file. */ +import { writeClipboardText } from "@/platform/clipboard"; import { useEffect, useMemo, useState } from "react"; import { call, commands } from "@/platform/ipc"; import { Checkbox, Dialog, IconButton, Input, Select, T } from "@/ui"; @@ -118,7 +119,7 @@ export function ExportDialog({ { label: "Copy to Clipboard", onClick: () => { - void navigator.clipboard?.writeText(text()); + void writeClipboardText(text()); closeDialog(); }, }, diff --git a/src/features/database/Grid.tsx b/src/features/database/Grid.tsx index d9d8375b26..a1645500fe 100644 --- a/src/features/database/Grid.tsx +++ b/src/features/database/Grid.tsx @@ -3,6 +3,7 @@ * cell selection (click, ⇧-click, arrows, ⌘A), copy as TSV / CSV / One-Row, * `` rendering, sortable headers and in-place editing (table editor). */ +import { writeClipboardText } from "@/platform/clipboard"; import { useEffect, useMemo, useRef, useState, type ClipboardEvent, type KeyboardEvent, type MouseEvent } from "react"; import { useVirtualizer } from "@tanstack/react-virtual"; import clsx from "clsx"; @@ -238,7 +239,7 @@ export function Grid(props: GridProps) { : format === "tsv" ? toTsv(head, rows) : toCsv(head, rows); - void navigator.clipboard?.writeText(text); + void writeClipboardText(text); }; const commit = () => { diff --git a/src/features/database/treeActions.ts b/src/features/database/treeActions.ts index 7a43da172e..5a5907b175 100644 --- a/src/features/database/treeActions.ts +++ b/src/features/database/treeActions.ts @@ -3,6 +3,7 @@ * act on the node passed as the argument (context menus) or on the tree's * lead node (toolbar, shortcuts while the tree has focus). */ +import { writeClipboardText } from "@/platform/clipboard"; import { call, commands, type DataSource, type DbDriver, type DbTableInfo } from "@/platform/ipc"; import { registerActions, type Action } from "@/platform/actions"; import { editorService, notifications, showServiceView, toolWindowService } from "@/workbench/contributions"; @@ -62,7 +63,7 @@ function sourceOf(n: DbNode | null): DataSource | undefined { /** Copies `text`; `failure` is the notification title when the clipboard refuses it. */ async function copy(text: string, failure: string) { try { - await navigator.clipboard.writeText(text); + await writeClipboardText(text); } catch { notifications().notify({ level: "error", title: failure }); } diff --git a/src/features/debugger/ui/DebugToolWindow.tsx b/src/features/debugger/ui/DebugToolWindow.tsx index 3faa48e2ad..a1256e8520 100644 --- a/src/features/debugger/ui/DebugToolWindow.tsx +++ b/src/features/debugger/ui/DebugToolWindow.tsx @@ -1,4 +1,5 @@ /** Debug tool window: toolbar, Threads & Variables (frames + variables), Console. */ +import { writeClipboardText } from "@/platform/clipboard"; import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react"; import clsx from "clsx"; import { executeAction, getAction } from "@/platform/actions"; @@ -358,7 +359,7 @@ function FramesPane({ session }: { session: DebugSession }) { label: "Copy Stack", icon: "copy", run: () => - void navigator.clipboard?.writeText( + void writeClipboardText( session.frames .map((f) => `${frameLabel(f)}${f.path ? `, ${basename(f.path)}` : ""}`) .join("\n"), diff --git a/src/features/debugger/ui/VariablesView.tsx b/src/features/debugger/ui/VariablesView.tsx index 5aef503b13..2f76fa12dc 100644 --- a/src/features/debugger/ui/VariablesView.tsx +++ b/src/features/debugger/ui/VariablesView.tsx @@ -1,4 +1,5 @@ /** Lazy variables tree (scopes, locals, watches, evaluation results). */ +import { writeClipboardText } from "@/platform/clipboard"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react"; import clsx from "clsx"; import { call, commands, type DebugSessionId, type Variable } from "@/platform/ipc"; @@ -287,7 +288,7 @@ export function VariablesView({ return; } } - await navigator.clipboard?.writeText(text); + await writeClipboardText(text); }; const onContextMenu = (node: VarNode | null, _sel: Set, e: React.MouseEvent) => { @@ -302,7 +303,7 @@ export function VariablesView({ if (node.kind === "watch") items.push({ label: "Remove Watch", icon: "minus", run: () => removeWatch(node.name) }); if (node.kind !== "scope") { items.push({ label: "Copy Value", icon: "copy", run: () => void copyValue(node) }); - items.push({ label: "Copy Name", run: () => void navigator.clipboard?.writeText(node.name) }); + items.push({ label: "Copy Name", run: () => void writeClipboardText(node.name) }); if (node.kind === "var" && node.evaluateName) items.push({ label: "Add to Watches", icon: "eye", run: () => addWatch(node.evaluateName!) }); if (canWatch(node)) diff --git a/src/features/github/data/local.ts b/src/features/github/data/local.ts index 4d056e80cd..cb71b955e7 100644 --- a/src/features/github/data/local.ts +++ b/src/features/github/data/local.ts @@ -4,6 +4,7 @@ * the diff viewer (`vcs.openDiff`; `diff/` shows its review threads). Long operations run * one at a time and are shown in the tool window's banner (`useGhBusy`), cancellable. */ +import { writeClipboardText } from "@/platform/clipboard"; import { Channel } from "@tauri-apps/api/core"; import { create } from "zustand"; import { withChain, type DiffData } from "@/features/vcs/diffInput"; @@ -178,7 +179,7 @@ export function openInBrowser(url: string): Promise { /** "Copy Pull Request URL". */ export async function copyUrl(url: string): Promise { - await navigator.clipboard?.writeText(url); + await writeClipboardText(url); } /** diff --git a/src/features/github/details/flow.ts b/src/features/github/details/flow.ts index 3fe655e3a0..54e4a618a7 100644 --- a/src/features/github/details/flow.ts +++ b/src/features/github/details/flow.ts @@ -4,6 +4,7 @@ * request (`isBusy` disables the others), mutations go through `data/operations.ts`, local * git through `data/local.ts` and the vcs feature. Failures are reported as notifications. */ +import { writeClipboardText } from "@/platform/clipboard"; import { create } from "zustand"; import type { DiffData } from "@/features/vcs/diffInput"; import { mergeIntoCurrent } from "@/features/vcs/branchOps"; @@ -105,7 +106,7 @@ export async function showInGitLog(pr: GHPullRequest, headRemote: string | null) /** "Copy Branch Name". */ export async function copyBranchName(name: string) { - await navigator.clipboard?.writeText(name); + await writeClipboardText(name); } /** diff --git a/src/features/plugins/runtimeUi.tsx b/src/features/plugins/runtimeUi.tsx index 13ee3d46ce..062951d40d 100644 --- a/src/features/plugins/runtimeUi.tsx +++ b/src/features/plugins/runtimeUi.tsx @@ -4,6 +4,7 @@ * workbench events it subscribed to (`events.subscribe`), reported in * batches. */ +import { writeClipboardText } from "@/platform/clipboard"; import { providePluginTestParser, providePluginTestSelector } from "@/workbench/contributions"; import { contentTabData, @@ -589,7 +590,7 @@ export function handleRuntimeEvent(e: PluginEvent): boolean { void maybeEditorService()?.openFile(e.path, { selection: { line: e.line, col: e.column }, focus: true }); return true; case "copyToClipboard": - void navigator.clipboard?.writeText(e.text); + void writeClipboardText(e.text); return true; case "openProject": void executeAction("file.openProjectPath", { path: e.path, newWindow: e.newWindow }); diff --git a/src/features/project-tree/operations.ts b/src/features/project-tree/operations.ts index b58c4e96a0..7e2a3c0b28 100644 --- a/src/features/project-tree/operations.ts +++ b/src/features/project-tree/operations.ts @@ -2,6 +2,7 @@ * File operations behind the project view's actions: new / rename / delete, * internal copy-cut-paste, drag & drop moves and OS file imports. */ +import { writeClipboardText } from "@/platform/clipboard"; import { createElement, Fragment } from "react"; import { askUsagesDetected, fileUsages, viewUsages } from "@/editor/refactor"; import { executeAction, getAction } from "@/platform/actions"; @@ -566,7 +567,7 @@ export function copySelection(cut: boolean) { const remote = isRemoteWindow(); const osWrite = (async () => { if (!remote) return osClipboard().setFiles(paths); - await navigator.clipboard.writeText(paths.join("\n")); + await writeClipboardText(paths.join("\n")); return true; })().catch(() => false); setClipboard({ paths, cut, remote, osWrite }); @@ -817,7 +818,7 @@ export async function copyPaths(kind: PathKind, nodes: ProjectNode[] = selectedN const text = pathsFor(kind, nodes).join("\n"); if (!text) return; try { - await navigator.clipboard.writeText(text); + await writeClipboardText(text); void executeAction("editor.showHint", { text: tx`Copied ${text}` }); } catch (e) { fail(tx("Cannot access the clipboard"), e); diff --git a/src/features/run/ConfigForm.tsx b/src/features/run/ConfigForm.tsx index 526dc760e2..f07e3e42fc 100644 --- a/src/features/run/ConfigForm.tsx +++ b/src/features/run/ConfigForm.tsx @@ -3,6 +3,7 @@ * common ones, the options added through "Modify options" (⌥M) and the * Before launch list. */ +import { writeClipboardText } from "@/platform/clipboard"; import { isJvmApplication, parseJavaArgs } from "@/platform/javaLaunch"; import { useRunTargets } from "@/platform/pluginRunTargets"; import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode, type RefObject } from "react"; @@ -887,8 +888,7 @@ function OutputField({ label, text }: { label: string; text: string }) { const tx = useTx(); const [copied, setCopied] = useState(false); const copy = () => { - void navigator.clipboard - ?.writeText(text) + void writeClipboardText(text) .then(() => setCopied(true)) .catch(() => undefined); }; diff --git a/src/features/run/ConsoleView.tsx b/src/features/run/ConsoleView.tsx index 4493beae5c..dd06437d27 100644 --- a/src/features/run/ConsoleView.tsx +++ b/src/features/run/ConsoleView.tsx @@ -1,3 +1,4 @@ +import { writeClipboardText } from "@/platform/clipboard"; import { copySelectionOnKeyDown } from "@/ui/selectableText"; import { memo, @@ -408,10 +409,10 @@ export function ConsoleView({ icon: "copy", shortcut: formatBinding(hostBinding("Meta+C")), disabled: !selection, - run: () => void navigator.clipboard?.writeText(selection).catch(() => undefined), + run: () => void writeClipboardText(selection).catch(() => undefined), }, { label: "Select All", shortcut: formatBinding(hostBinding("Meta+A")), run: selectAll }, - { label: "Copy All", run: () => void navigator.clipboard?.writeText(model.text()).catch(() => undefined) }, + { label: "Copy All", run: () => void writeClipboardText(model.text()).catch(() => undefined) }, { label: "Find…", icon: "search", diff --git a/src/features/run/EnvDialog.tsx b/src/features/run/EnvDialog.tsx index a389c36511..6141fca9a0 100644 --- a/src/features/run/EnvDialog.tsx +++ b/src/features/run/EnvDialog.tsx @@ -1,3 +1,4 @@ +import { writeClipboardText } from "@/platform/clipboard"; import { useEffect, useState } from "react"; import clsx from "clsx"; import { commands, isTauri, type RunConfig } from "@/platform/ipc"; @@ -42,7 +43,7 @@ export function pasteRows(rows: readonly EnvRow[], text: string): EnvRow[] { async function writeClipboard(text: string) { try { - await navigator.clipboard.writeText(text); + await writeClipboardText(text); } catch { /* clipboard unavailable */ } diff --git a/src/features/run/TomcatSettings.tsx b/src/features/run/TomcatSettings.tsx index 3b93aa63a9..cda15e0769 100644 --- a/src/features/run/TomcatSettings.tsx +++ b/src/features/run/TomcatSettings.tsx @@ -1,3 +1,4 @@ +import { writeClipboardText } from "@/platform/clipboard"; import { useEffect, useRef, useState } from "react"; import clsx from "clsx"; import { call, commands, isTauri, type RunConfig, type TomcatInstallation, type WebArtifact } from "@/platform/ipc"; @@ -889,7 +890,7 @@ export function TomcatSettings({ config, onChange }: { config: RunConfig; onChan disabled={envRows.length === 0} onClick={() => { const row = envRows[selectedEnvIdx]; - if (row) void navigator.clipboard?.writeText(`${row.name}=${row.value}`); + if (row) void writeClipboardText(`${row.name}=${row.value}`); }} /> void navigator.clipboard?.writeText(text).catch(() => {}); + const copy = (text: string) => void writeClipboardText(text).catch(() => {}); const items: MenuItem[] = row.kind === "setting" ? [{ label: "Open Settings Page", run: () => activate(row) }] diff --git a/src/features/services/dashboard.tsx b/src/features/services/dashboard.tsx index b66bd000f9..0a486062a7 100644 --- a/src/features/services/dashboard.tsx +++ b/src/features/services/dashboard.tsx @@ -6,6 +6,7 @@ * `LineProgress`) and binary/SI unit & system-local timezone formatters * proven in `openidea-kubernetes` (`ResourceDetails.tsx`). */ +import { writeClipboardText } from "@/platform/clipboard"; import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"; import clsx from "clsx"; import type { @@ -520,7 +521,7 @@ export function parseNetworkInspect(raw: string | null): ParsedNetworkInspect | // --------------------------------------------------------------------------- // Shared UI primitives (adapted from openidea-kubernetes ResourceDetails.tsx) -const copyText = (text: string) => void navigator.clipboard?.writeText(text); +const copyText = (text: string) => void writeClipboardText(text); async function openExternalUrl(url: string): Promise { try { diff --git a/src/features/services/docker.tsx b/src/features/services/docker.tsx index 737e4a7772..e2b1354ffa 100644 --- a/src/features/services/docker.tsx +++ b/src/features/services/docker.tsx @@ -3,6 +3,7 @@ * grouped by Compose project, images, volumes, networks) and one per registry; * log / inspect of the selection in the detail pane. */ +import { writeClipboardText } from "@/platform/clipboard"; import { copySelectionOnKeyDown } from "@/ui/selectableText"; import { useEffect, useMemo, useState } from "react"; import clsx from "clsx"; @@ -359,7 +360,7 @@ function InspectView({ text, error }: { text: string | null; error: string | nul size="small" title="Copy" disabled={!text} - onClick={() => text && void navigator.clipboard?.writeText(text)} + onClick={() => text && void writeClipboardText(text)} />
 ({ label, run: () => void prunePrompt(conn, target) }));
 }
 
-const copy = (text: string) => void navigator.clipboard?.writeText(text);
+const copy = (text: string) => void writeClipboardText(text);
 
 export function showDetail(tab: DetailTab) {
   useServices.setState({ detailTab: tab });
diff --git a/src/features/terminal/embedded.ts b/src/features/terminal/embedded.ts
index 3a841cb0ad..ab70586b78 100644
--- a/src/features/terminal/embedded.ts
+++ b/src/features/terminal/embedded.ts
@@ -4,6 +4,7 @@
  * and size go to the owner instead of a terminal PTY (a Run console emulating
  * a terminal feeds its process).
  */
+import { writeClipboardText } from "@/platform/clipboard";
 import { installTerminalDrop } from "./drop";
 import { installDomRowCache } from "./domRowCache";
 import { installTerminalPaste } from "./paste";
@@ -62,7 +63,7 @@ export function createEmbeddedTerminal(host: HTMLElement, opts: EmbeddedTerminal
     if (action.kind === "send" && e.key === "Enter") {
       if (e.type === "keydown") term.input(action.data);
     } else if (action.kind === "copy") {
-      if (e.type === "keydown") void navigator.clipboard?.writeText(term.getSelection()).catch(() => undefined);
+      if (e.type === "keydown") void writeClipboardText(term.getSelection()).catch(() => undefined);
     } else {
       return true;
     }
diff --git a/src/features/terminal/session.ts b/src/features/terminal/session.ts
index d27d64e14a..bb8b3a9653 100644
--- a/src/features/terminal/session.ts
+++ b/src/features/terminal/session.ts
@@ -3,6 +3,7 @@
  * lives in a detached host element owned by the session (not by React), so a
  * session survives its tool window being hidden or its pane being re-mounted.
  */
+import { writeClipboardText } from "@/platform/clipboard";
 import { Terminal, type IDisposable, type ILink, type ILinkHandler } from "@xterm/xterm";
 import { FitAddon } from "@xterm/addon-fit";
 import { SearchAddon, type ISearchOptions } from "@xterm/addon-search";
@@ -710,7 +711,7 @@ export class TerminalSession {
   copySelection(): boolean {
     const text = this.term.getSelection();
     if (!text) return false;
-    void navigator.clipboard?.writeText(text).catch(() => undefined);
+    void writeClipboardText(text).catch(() => undefined);
     return true;
   }
 
diff --git a/src/features/vcs/CommitView.tsx b/src/features/vcs/CommitView.tsx
index 64214b4bfb..44f3fef0f8 100644
--- a/src/features/vcs/CommitView.tsx
+++ b/src/features/vcs/CommitView.tsx
@@ -2,6 +2,7 @@
  * Commit tool window: change list with inclusion checkboxes, message, stashes. Its
  * parts also make the Git window's Local Changes / Stash tabs and the Commit dialog.
  */
+import { writeClipboardText } from "@/platform/clipboard";
 import { useWorkflowSettings } from "@/platform/workflowSettings";
 import { formatBinding, isMacHost, macStroke, normalizeBinding, shortcutLabel, strokeOf } from "@/platform/keymap";
 import {
@@ -268,7 +269,7 @@ export function copyChangePaths(nodes: ChangeNode[], kind: "absolute" | "name")
   const text = filesOf(nodes)
     .map((f) => (kind === "name" ? basename(f.path) : f.path))
     .join("\n");
-  if (text) void navigator.clipboard?.writeText(text);
+  if (text) void writeClipboardText(text);
 }
 
 export function nodeMenu(
diff --git a/src/features/vcs/GitLog.tsx b/src/features/vcs/GitLog.tsx
index a57db1c841..e2598eb1fd 100644
--- a/src/features/vcs/GitLog.tsx
+++ b/src/features/vcs/GitLog.tsx
@@ -1,3 +1,4 @@
+import { writeClipboardText } from "@/platform/clipboard";
 import { useBookmarkPopups } from "@/features/search/bookmarks/store";
 import { commitBookmarkPath } from "./logBookmarks";
 import { copySelectionOnKeyDown } from "@/ui/selectableText";
@@ -2785,7 +2786,7 @@ function CommitMessage({ commit, compact = false }: { commit: Commit; compact?:
           type="button"
           className={clsx(styles.linkButton, styles.hash)}
           title={tx("Copy revision number")}
-          onClick={() => void navigator.clipboard?.writeText(commit.id)}
+          onClick={() => void writeClipboardText(commit.id)}
         >
           {commit.shortId}
         {" "}
diff --git a/src/features/vcs/HunkPopup.tsx b/src/features/vcs/HunkPopup.tsx
index e71c8736d2..0e7bbc7884 100644
--- a/src/features/vcs/HunkPopup.tsx
+++ b/src/features/vcs/HunkPopup.tsx
@@ -1,4 +1,5 @@
 /** Inline change popup shown when clicking a gutter change marker. */
+import { writeClipboardText } from "@/platform/clipboard";
 import { useState } from "react";
 import { createRoot, type Root } from "react-dom/client";
 import type { EditorView } from "@codemirror/view";
@@ -142,7 +143,7 @@ function HunkPopupView({ state }: { state: PopupState }) {
           size="small"
           disabled={!hunk.oldText}
           onClick={() => {
-            void navigator.clipboard?.writeText(hunk.oldText).then(() => setCopied(true));
+            void writeClipboardText(hunk.oldText).then(() => setCopied(true));
           }}
         />
         
diff --git a/src/features/vcs/blame.ts b/src/features/vcs/blame.ts
index d7f2839e77..4fd0c401a2 100644
--- a/src/features/vcs/blame.ts
+++ b/src/features/vcs/blame.ts
@@ -1,4 +1,5 @@
 /** Annotate (git blame) gutter left of the line numbers. */
+import { writeClipboardText } from "@/platform/clipboard";
 import { Compartment, Prec, RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
 import { EditorView, GutterMarker, ViewPlugin, gutter, type PluginValue, type ViewUpdate } from "@codemirror/view";
 import type { BlameLine } from "@/bindings";
@@ -181,7 +182,7 @@ function blameExtension(lines: BlameLine[], path: string, live: boolean): Extens
                     {
                       label: "Copy Revision Number",
                       icon: "copy",
-                      run: () => void navigator.clipboard?.writeText(l.commit),
+                      run: () => void writeClipboardText(l.commit),
                     },
                     { kind: "separator" as const },
                   ]
diff --git a/src/features/vcs/historyActions.tsx b/src/features/vcs/historyActions.tsx
index 6de2a6f8da..99acf9cd1e 100644
--- a/src/features/vcs/historyActions.tsx
+++ b/src/features/vcs/historyActions.tsx
@@ -1,3 +1,4 @@
+import { writeClipboardText } from "@/platform/clipboard";
 import { parseCommitBookmark } from "./logBookmarks";
 import { commitKey, commitRepo } from "./multiRoot";
 /**
@@ -281,7 +282,7 @@ export function registerHistoryActions(): () => void {
       icon: "copy",
       when: "vcsAvailable || projectOpen || vcsLogFocus",
       keyWhen: IN_GIT_LOG,
-      run: withCommits((cs) => navigator.clipboard?.writeText(cs.map((c) => c.id).join(" ")), true),
+      run: withCommits((cs) => writeClipboardText(cs.map((c) => c.id).join(" ")), true),
     },
     {
       id: "vcs.log.createPatch",
diff --git a/src/features/vcs/patches.tsx b/src/features/vcs/patches.tsx
index b269fddef0..32bad54d24 100644
--- a/src/features/vcs/patches.tsx
+++ b/src/features/vcs/patches.tsx
@@ -1,3 +1,4 @@
+import { writeClipboardText } from "@/platform/clipboard";
 import { commitRepo } from "./multiRoot";
 /** Create Patch… (from local changes or commits) and Apply Patch… (file or clipboard, with a preview). */
 import { useEffect, useState } from "react";
@@ -58,7 +59,7 @@ export async function copyChangesAsPatch(paths: readonly string[]) {
     tx("Create patch"),
     async () => {
       const source: PatchSource = { from: "changes", paths: files.map((f) => stripSlash(f.path)), reverse: false };
-      await navigator.clipboard.writeText(await call(commands.vcsCreatePatch(currentRepoRoot(), source)));
+      await writeClipboardText(await call(commands.vcsCreatePatch(currentRepoRoot(), source)));
     },
     { success: "Patch copied to the clipboard", refresh: false },
   );
@@ -149,7 +150,7 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose:
             ? await call(commands.vcsShelfPatch(origin.entry.id, origin.path ?? null))
             : await call(commands.vcsCreatePatch(repo, source!));
         if (toFile) await call(commands.vcsWritePatch(file.trim(), patch));
-        else await navigator.clipboard.writeText(patch);
+        else await writeClipboardText(patch);
         return true;
       },
       { success: toFile ? `Patch saved to ${baseName(file.trim())}` : "Patch copied to the clipboard", refresh: false },
diff --git a/src/features/vcs/shelf.tsx b/src/features/vcs/shelf.tsx
index a6607984be..f27b5d8be7 100644
--- a/src/features/vcs/shelf.tsx
+++ b/src/features/vcs/shelf.tsx
@@ -3,6 +3,7 @@
  * the Shelf tab of the Commit tool window, Unshelve (3-way, conflicts go to the
  * merge UI), rename and delete.
  */
+import { writeClipboardText } from "@/platform/clipboard";
 import { useEffect, useMemo, useState, type MouseEvent } from "react";
 import { create } from "zustand";
 import type { ApplyOutcome, FileStatus, ShelvedChangeList, ShelfDiffFile } from "@/bindings";
@@ -292,7 +293,7 @@ export async function renameShelf(entry: ShelvedChangeList) {
 
 export async function copyShelfPatch(entry: ShelvedChangeList, path?: string) {
   try {
-    await navigator.clipboard.writeText(await call(commands.vcsShelfPatch(entry.id, path ?? null)));
+    await writeClipboardText(await call(commands.vcsShelfPatch(entry.id, path ?? null)));
     notifications().notify({ group: "vcs", level: "info", title: "Patch copied to the clipboard" });
   } catch (e) {
     logConsole("err", errorMessage(e));
diff --git a/src/features/welcome/RecentList.tsx b/src/features/welcome/RecentList.tsx
index 35626fd0c8..403c263c74 100644
--- a/src/features/welcome/RecentList.tsx
+++ b/src/features/welcome/RecentList.tsx
@@ -1,3 +1,4 @@
+import { writeClipboardText } from "@/platform/clipboard";
 import { useMemo, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from "react";
 import clsx from "clsx";
 import { call, commands, type RecentProject, type RecentProjectGroup } from "@/platform/ipc";
@@ -145,7 +146,7 @@ export function recentMenu(project: RecentProject, onOpened?: () => void, onRemo
       id: "copy",
       label: "Copy Path",
       icon: "copy",
-      run: () => void navigator.clipboard?.writeText(project.path).catch(() => undefined),
+      run: () => void writeClipboardText(project.path).catch(() => undefined),
     },
     { kind: "separator" },
     // Groups hold local projects (remote ones live in this window's own list).
diff --git a/src/platform/clipboard.test.ts b/src/platform/clipboard.test.ts
index 9f19f74149..5f055c930f 100644
--- a/src/platform/clipboard.test.ts
+++ b/src/platform/clipboard.test.ts
@@ -1,6 +1,6 @@
 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
 import { commands } from "./ipc";
-import { pasteClipboardFiles, readClipboardText } from "./clipboard";
+import { pasteClipboardFiles, readClipboardText, writeClipboardText } from "./clipboard";
 
 beforeEach(() => vi.stubGlobal("__TAURI_INTERNALS__", {}));
 afterEach(() => {
@@ -60,3 +60,43 @@ describe("clipboard text", () => {
     expect(paste).not.toHaveBeenCalled();
   });
 });
+
+describe("clipboard writes", () => {
+  it.each(["com.acme.A#run", "/p/src/A.java:5", "中文\n😀", ""])(
+    "writes %j natively without browser activation",
+    async (text) => {
+      const native = vi.spyOn(commands, "clipboardWriteText").mockResolvedValue({ status: "ok", data: null });
+      const browser = vi
+        .fn()
+        .mockRejectedValue(
+          new DOMException(
+            "The request is not allowed by the user agent or the platform in the current context",
+            "NotAllowedError",
+          ),
+        );
+      Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText: browser } });
+      await Promise.resolve();
+      await writeClipboardText(text);
+      expect(native).toHaveBeenCalledExactlyOnceWith(text);
+      expect(browser).not.toHaveBeenCalled();
+    },
+  );
+
+  it("reports native errors instead of claiming success", async () => {
+    vi.spyOn(commands, "clipboardWriteText").mockResolvedValue({
+      status: "error",
+      error: { kind: "internal", message: "busy", data: null },
+    });
+    await expect(writeClipboardText("text")).rejects.toThrow("busy");
+  });
+
+  it("uses the browser clipboard outside Tauri", async () => {
+    vi.unstubAllGlobals();
+    const native = vi.spyOn(commands, "clipboardWriteText");
+    const browser = vi.fn().mockResolvedValue(undefined);
+    Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText: browser } });
+    await writeClipboardText("web preview");
+    expect(browser).toHaveBeenCalledExactlyOnceWith("web preview");
+    expect(native).not.toHaveBeenCalled();
+  });
+});
diff --git a/src/platform/clipboard.ts b/src/platform/clipboard.ts
index f3b25716fc..c4f8c00245 100644
--- a/src/platform/clipboard.ts
+++ b/src/platform/clipboard.ts
@@ -1,6 +1,12 @@
 import { call, commands, isTauri } from "./ipc";
 import { ipcPath } from "./paths";
 
+/** Native menu actions and async work can outlive WebKit's user activation. */
+export async function writeClipboardText(text: string): Promise {
+  if (isTauri()) await call(commands.clipboardWriteText(text));
+  else await navigator.clipboard.writeText(text);
+}
+
 type FormatFiles = (paths: string[]) => string;
 const rawPaths: FormatFiles = (paths) => paths.join("\n");
 
diff --git a/src/ui/Dialog.test.tsx b/src/ui/Dialog.test.tsx
index 3a986495f4..01911d0187 100644
--- a/src/ui/Dialog.test.tsx
+++ b/src/ui/Dialog.test.tsx
@@ -1,5 +1,9 @@
 import { afterEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, render, screen, within } from "@testing-library/react";
+import { act, fireEvent, render, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { useLayoutEffect, useRef } from "react";
+import { Popup } from "./Popup";
+import { openLayer } from "./popupState";
 import { usePlatform } from "@/platform/platformInfo";
 import { Dialog, dialogPlatformOf, orderDialogButtons, type DialogButton, type DialogPlatform } from "./Dialog";
 
@@ -305,3 +309,121 @@ describe("Dialog keyboard", () => {
     expect(document.activeElement).toBe(screen.getByRole("button", { name: "Cancel" }));
   });
 });
+
+describe("Dialog focus containment", () => {
+  it.each(["Enter", "Escape"])("keeps deferred editor focus out and restores it after %s", async (key) => {
+    const editor = document.createElement("textarea");
+    document.body.append(editor);
+    editor.focus();
+    const accepted = vi.fn();
+    const cancelled = vi.fn();
+    const { rerender, unmount } = render(
+      
+        

Do you want to add the following file to Git?

+
, + ); + await act(async () => { + await Promise.resolve(); + editor.focus(); + }); + expect(document.activeElement).toBe(screen.getByRole("button", { name: "Add" })); + await userEvent.keyboard(`{${key}}`); + expect(accepted).toHaveBeenCalledTimes(key === "Enter" ? 1 : 0); + expect(cancelled).toHaveBeenCalledTimes(key === "Escape" ? 1 : 0); + rerender( + +

closed

+
, + ); + expect(document.activeElement).toBe(editor); + unmount(); + editor.remove(); + }); + + it("lets nested dialogs own focus, then restores the last field in the parent", () => { + const { rerender } = render( + {}}> + + + , + ); + screen.getByLabelText("Last").focus(); + const content = (child: boolean) => ( + <> + {}}> + + + + {child && ( + {}}> + + + )} + + ); + rerender(content(true)); + expect(document.activeElement).toBe(screen.getByLabelText("Child field")); + rerender(content(false)); + expect(document.activeElement).toBe(screen.getByLabelText("Last")); + }); +}); + +it("allows a menu above a dialog and remembers its last focused control", () => { + const { unmount } = render( + {}}> + + + , + ); + const last = screen.getByLabelText("Last"); + last.focus(); + const menu = document.createElement("button"); + document.body.append(menu); + const layer = openLayer(() => menu); + menu.focus(); + expect(document.activeElement).toBe(menu); + layer.release(); + last.focus(); + document.body.focus(); + const outside = document.createElement("input"); + document.body.append(outside); + outside.focus(); + expect(document.activeElement).toBe(last); + unmount(); + menu.remove(); + outside.remove(); +}); + +it("allows a newly mounted menu to focus before its popup layer registers", () => { + function MenuItem() { + const ref = useRef(null); + useLayoutEffect(() => { + ref.current?.focus(); + }, []); + return ; + } + const show = (menu: boolean) => ( + <> + {}}> + + + {menu && ( + {}} autoFocus={false}> + + + )} + + ); + const { rerender } = render(show(false)); + rerender(show(true)); + expect(document.activeElement).toBe(screen.getByRole("button", { name: "Menu item" })); +}); diff --git a/src/ui/Dialog.tsx b/src/ui/Dialog.tsx index 03e757e2a8..4a2c27cbd2 100644 --- a/src/ui/Dialog.tsx +++ b/src/ui/Dialog.tsx @@ -271,7 +271,7 @@ function DialogInner({ useEffect(() => { const layer = openLayer(() => ref.current); - const previous = document.activeElement as HTMLElement | null; + let previous = document.activeElement as HTMLElement | null; const el = ref.current; // Content first (an alert's checkbox is not content), then the default button; never the title bar's close button. const target = @@ -282,6 +282,22 @@ function DialogInner({ el?.querySelector("[data-dialog-footer] [data-dialog-default]:not([disabled])") ?? el?.querySelector(`[data-dialog-footer] :is(${FOCUSABLE})`) ?? el; + let lastFocused = target; + const onFocusIn = (e: FocusEvent) => { + const focused = e.target; + if (!(focused instanceof HTMLElement)) return; + if (el?.contains(focused)) lastFocused = focused; + else if (!layer.containsFromHere(focused) && layer.isTop()) { + // A newly mounted portal can focus before its layer's effect registers it. + const overlay = focused.closest('[data-popup], [role="dialog"]'); + if (overlay && el && el.compareDocumentPosition(overlay) & Node.DOCUMENT_POSITION_FOLLOWING) return; + // An editor opened behind this dialog may finish mounting on a later frame. + previous = focused; + (lastFocused?.isConnected ? lastFocused : target)?.focus({ preventScroll: true }); + if (el && !el.contains(document.activeElement)) el.focus({ preventScroll: true }); + } + }; + document.addEventListener("focusin", onFocusIn); target?.focus({ preventScroll: true }); const onKey = (e: KeyboardEvent) => { if (!layer.isTop() || !ref.current) return; @@ -306,6 +322,7 @@ function DialogInner({ document.addEventListener("keydown", onKey); return () => { document.removeEventListener("keydown", onKey); + document.removeEventListener("focusin", onFocusIn); layer.release(); if (previous?.isConnected && restoreFocusRef.current?.() !== false) previous.focus({ preventScroll: true }); }; diff --git a/src/ui/selectableText.ts b/src/ui/selectableText.ts index e8489a48ed..b4055bc162 100644 --- a/src/ui/selectableText.ts +++ b/src/ui/selectableText.ts @@ -4,6 +4,8 @@ * (chrome); content opts back in with `selectableText`. A right-click on a * selection, or anywhere in such content, offers Copy (`copyMenuFor`). */ +import { writeClipboardText } from "@/platform/clipboard"; +import { isTauri } from "@/platform/ipc"; import type { KeyboardEvent } from "react"; import { hasPrimaryModifier, formatBinding } from "@/platform/keymap"; import type { MenuItem } from "./Menu"; @@ -44,8 +46,8 @@ export function copyMenuFor(target: EventTarget | null): MenuItem[] | null { /** Writes `text` to the clipboard; falls back to copying the live selection. */ export async function copyText(text: string): Promise { try { - if (navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(text); + if (isTauri() || typeof navigator.clipboard?.writeText === "function") { + await writeClipboardText(text); return; } } catch {