From 04880ebb9f682d76335e12d55b2fe3e1ff813753 Mon Sep 17 00:00:00 2001 From: l0ng-ai <24760907+l0ng-ai@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:20:43 +0800 Subject: [PATCH] fix(remote): use the correct filesystem for file dialogs --- src/editor/core/controller.ts | 5 +- src/editor/core/librarySources.test.tsx | 1 + src/editor/core/librarySources.ts | 5 +- src/features/agents/AgentList.tsx | 2 +- src/features/agents/registry.ts | 9 +- src/features/analysis/dialogs.tsx | 7 +- src/features/build-tools/store.ts | 18 +-- src/features/coverage/reports.tsx | 6 +- src/features/database/DataDialogs.tsx | 3 +- src/features/database/JdbcDriverProfiles.tsx | 7 +- .../database/JdbcSourceDialog.test.tsx | 1 + src/features/database/SourceDialog.tsx | 5 +- src/features/database/treeActions.ts | 3 +- src/features/database/treeMenu.ts | 4 +- src/features/deployment/remoteHost.test.ts | 5 +- src/features/deployment/remoteHost.ts | 5 +- .../plugins/__tests__/projectUi.test.tsx | 1 + src/features/plugins/backend.ts | 7 +- src/features/plugins/runtimeUi.tsx | 14 +-- .../run/ExportTestResultsDialog.test.tsx | 61 ++++++++- src/features/run/ExportTestResultsDialog.tsx | 17 +++ src/features/search/find/FindInFiles.tsx | 13 +- src/features/settings/keymap/KeymapPage.tsx | 9 +- .../settings/pages/editor/ColorSchemeBody.tsx | 10 +- .../settings/pages/editor/codeStyle.tsx | 6 +- src/features/settings/pages/tools.tsx | 5 +- src/features/tools/backend.ts | 7 +- src/features/vcs/RevisionBrowser.tsx | 9 +- src/features/vcs/clone.tsx | 9 +- src/features/vcs/compare.tsx | 10 +- src/features/vcs/createRepository.ts | 4 +- src/features/vcs/patches.tsx | 10 +- src/features/vcs/shelf.tsx | 9 +- src/platform/choosePath.ts | 42 +++++-- src/platform/desktopFiles.test.ts | 40 ++++++ src/platform/desktopFiles.ts | 24 ++++ src/platform/ipc.ts | 12 ++ src/workbench/inputDialogs.tsx | 117 +++++++++++++----- src/workbench/pathChooser.test.tsx | 63 +++++++++- 39 files changed, 416 insertions(+), 169 deletions(-) create mode 100644 src/platform/desktopFiles.test.ts create mode 100644 src/platform/desktopFiles.ts diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index 97b830d3c6..d0df959d71 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -52,7 +52,8 @@ import { call, commands, isErrorKind, isTauri } from "@/platform/ipc"; import { openLightweightEditor } from "./openLightweightEditor"; import { windowBackgroundHex } from "@/workbench/theme"; import { hoverActionsAt } from "@/platform/hoverActions"; -import { save as saveFileDialog, type DialogFilter as SaveDialogFilter } from "@/platform/dialog"; +import { chooseSavePath } from "@/platform/choosePath"; +import type { DialogFilter as SaveDialogFilter } from "@/platform/dialog"; import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs"; import { isRemoteWindow } from "@/platform/remote"; import { auxiliaryWindow } from "@/platform/auxWindow"; @@ -1299,7 +1300,7 @@ export class EditorController implements SlotHost { * every tab showing it becomes a file tab. */ private async saveUntitled(model: import("./model/document").DocModel): Promise { - const path = await saveFileDialog({ + const path = await chooseSavePath({ title: tx("Save As"), defaultPath: this.saveAsSuggestion(model), filters: await languageFilters(), diff --git a/src/editor/core/librarySources.test.tsx b/src/editor/core/librarySources.test.tsx index 5dd4001524..bd07efca40 100644 --- a/src/editor/core/librarySources.test.tsx +++ b/src/editor/core/librarySources.test.tsx @@ -11,6 +11,7 @@ import { VirtualBanner } from "./view/Banner"; const ipc = vi.hoisted(() => ({ support: vi.fn(), sources: vi.fn(), cancel: vi.fn(), choose: vi.fn() })); vi.mock("@/platform/ipc", async (original) => ({ ...(await original()), + isTauri: () => true, commands: { lspCanDownloadSources: ipc.support, lspLibrarySources: ipc.sources, cancelRequest: ipc.cancel }, })); vi.mock("@tauri-apps/plugin-dialog", () => ({ open: ipc.choose })); diff --git a/src/editor/core/librarySources.ts b/src/editor/core/librarySources.ts index 93bf8f5f8f..54efc0d638 100644 --- a/src/editor/core/librarySources.ts +++ b/src/editor/core/librarySources.ts @@ -1,6 +1,7 @@ import { useEffect, useState } from "react"; import { create } from "zustand"; import { registerActions } from "@/platform/actions"; +import { choosePath } from "@/platform/choosePath"; import { call, commands, isCancelled, nextRequestId, onIdeEvent, type RequestId } from "@/platform/ipc"; import { tx } from "@/platform/i18n"; import { useProject } from "@/platform/project"; @@ -26,8 +27,8 @@ async function retrieve(path: string, choose: boolean) { try { let sources: string | null = null; if (choose) { - const { open } = await import("@/platform/dialog"); - const selected = await open({ + const selected = await choosePath({ + directory: false, title: tx("Choose Sources…"), filters: [{ name: tx("Source archives"), extensions: ["jar", "zip"] }], }); diff --git a/src/features/agents/AgentList.tsx b/src/features/agents/AgentList.tsx index 53c088e64a..74670950b1 100644 --- a/src/features/agents/AgentList.tsx +++ b/src/features/agents/AgentList.tsx @@ -679,7 +679,7 @@ function CustomAgentModal({ try { const trimmed = name.trim(); const title = trimmed ? tx`Select ${trimmed}` : tx("Select executable"); - const path = await backend.chooseExecutable(title, command); + const path = await backend.chooseExecutable(title, command, "desktop"); if (path) setCommand(path); setError(null); } catch (e) { diff --git a/src/features/agents/registry.ts b/src/features/agents/registry.ts index 16410c04c4..71eb4bedd1 100644 --- a/src/features/agents/registry.ts +++ b/src/features/agents/registry.ts @@ -1,5 +1,7 @@ /** Agents of the ACP Registry: listing, install / update / remove (`agent_registry_*`). */ import { open } from "@/platform/dialog"; +import { choosePath } from "@/platform/choosePath"; +import { readDesktopText } from "@/platform/desktopFiles"; import { Channel } from "@tauri-apps/api/core"; import type { AcpImportOutcome, @@ -31,7 +33,7 @@ export interface CommandsBackend { providers(): Promise; set(id: string, command: string | null): Promise; setEnv(id: string, env: Record): Promise; - chooseExecutable(title: string, current?: string): Promise; + chooseExecutable(title: string, current?: string, location?: "desktop"): Promise; saveCustom(input: CustomAgentInput): Promise; removeCustom(id: string): Promise; importAcp(text: string): Promise; @@ -56,7 +58,8 @@ export const tauriCommands: CommandsBackend = { updateCli: (id, offer, request) => call(commands.agentCliUpdate(id, offer, request)), cancel: tauriRegistry.cancel, providers: () => call(commands.agentProviders()), - chooseExecutable: async (title, current) => { + chooseExecutable: async (title, current, location) => { + if (location !== "desktop") return choosePath({ title, defaultPath: current, directory: false }); const picked = await open({ title, defaultPath: current || undefined, directory: false, multiple: false }); return typeof picked === "string" ? picked : null; }, @@ -81,7 +84,7 @@ export const tauriCommands: CommandsBackend = { filters: [{ name: tx("ACP config"), extensions: ["json"] }], }); if (typeof picked !== "string") return null; - return call(commands.fsReadText(picked)); + return readDesktopText(picked); }, }; diff --git a/src/features/analysis/dialogs.tsx b/src/features/analysis/dialogs.tsx index 1c5e14b17d..22255b1f26 100644 --- a/src/features/analysis/dialogs.tsx +++ b/src/features/analysis/dialogs.tsx @@ -4,7 +4,7 @@ import clsx from "clsx"; import { create } from "zustand"; import { executeAction } from "@/platform/actions"; import { tx } from "@/platform/i18n"; -import { isTauri } from "@/platform/ipc"; +import { choosePath } from "@/platform/choosePath"; import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search"; import { Button, IconButton, Input, Radio, Select, T } from "@/ui"; import { SCOPE_LABELS, currentFile, type ScopeChoice, type ScopeKind } from "./scope"; @@ -40,10 +40,7 @@ export function AnalysisDialogHost() { } async function browseDirectory(initial: string): Promise { - if (!isTauri()) return null; - const { open } = await import("@/platform/dialog"); - const picked = await open({ directory: true, multiple: false, defaultPath: initial || undefined }); - return typeof picked === "string" ? picked : null; + return choosePath({ directory: true, defaultPath: initial }); } const KINDS: ScopeKind[] = ["project", "directory", "file", "changed", "custom"]; diff --git a/src/features/build-tools/store.ts b/src/features/build-tools/store.ts index 8545c9409f..822bdc4832 100644 --- a/src/features/build-tools/store.ts +++ b/src/features/build-tools/store.ts @@ -10,6 +10,7 @@ import { tx } from "@/platform/i18n"; import { create } from "zustand"; import { Channel } from "@tauri-apps/api/core"; import { executeAction } from "@/platform/actions"; +import { choosePath, choosePaths } from "@/platform/choosePath"; import { call, commands, @@ -427,15 +428,12 @@ export function classifyPickedPoms(root: string, picked: readonly string[]): { l export async function addProjects(dialogTitle?: string) { const root = useProject.getState().project?.root; if (!root || useProject.getState().project?.workspace || !isTauri()) return; - const { open } = await import("@/platform/dialog"); - const picked = await open({ + const paths = await choosePaths({ title: dialogTitle ?? tx`Add Maven Projects`, directory: false, - multiple: true, defaultPath: root, filters: [{ name: "pom.xml", extensions: ["xml"] }], }); - const paths = typeof picked === "string" ? [picked] : (picked ?? []); if (!paths.length) return; const { link, rejected } = classifyPickedPoms(root, paths); if (link.length) await setLinked(root, link, true); @@ -470,14 +468,11 @@ export async function importModuleFromExistingSources() { } catch { /* Tests and hosts without the tool-window service still link the POM. */ } - const { open } = await import("@/platform/dialog"); - const picked = await open({ + const path = await choosePath({ title: tx`Import Module from Existing Sources`, directory: true, - multiple: false, defaultPath: root, }); - const path = typeof picked === "string" ? picked : picked?.[0]; if (!path) return; const pom = mavenPomForImport(path); if (!(await directoryListsPom(pom))) { @@ -532,16 +527,13 @@ export async function linkGradleProjects() { !isTauri() ) return; - const { open } = await import("@/platform/dialog"); - const picked = await open({ + const paths = await choosePaths({ title: tx`Link Gradle Projects`, directory: false, - multiple: true, defaultPath: root, filters: [{ name: "Gradle build files", extensions: ["gradle", "kts"] }], }); - const paths = typeof picked === "string" ? [picked] : picked; - if (!paths?.length || useProject.getState().project?.root !== root || gen !== generation) return; + if (!paths.length || useProject.getState().project?.root !== root || gen !== generation) return; const model = await call(commands.gradleLinkProjects(paths)); if (useProject.getState().project?.root !== root || gen !== generation) return; const configs = await call(commands.runConfigs()).catch(() => useBuild.getState().configs); diff --git a/src/features/coverage/reports.tsx b/src/features/coverage/reports.tsx index b18c5b0e26..f07fa10c97 100644 --- a/src/features/coverage/reports.tsx +++ b/src/features/coverage/reports.tsx @@ -5,6 +5,7 @@ */ import { useMemo, useState } from "react"; import { create } from "zustand"; +import { choosePath } from "@/platform/choosePath"; import { call, commands, isTauri } from "@/platform/ipc"; import { basename } from "@/platform/project"; import { Dialog, Icon, List, T } from "@/ui"; @@ -28,9 +29,7 @@ import styles from "./Coverage.module.css"; const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e)); async function pickReport(): Promise { - const { open } = await import("@/platform/dialog"); - const file = await open({ - multiple: false, + return choosePath({ directory: false, title: "Import Coverage Report", filters: [ @@ -41,7 +40,6 @@ async function pickReport(): Promise { { name: "All files", extensions: ["*"] }, ], }); - return typeof file === "string" ? file : null; } /** Imports `path` (asks for a file without one) and shows it like a run's suite. */ diff --git a/src/features/database/DataDialogs.tsx b/src/features/database/DataDialogs.tsx index 281f5140bc..b5920dbd69 100644 --- a/src/features/database/DataDialogs.tsx +++ b/src/features/database/DataDialogs.tsx @@ -1,6 +1,7 @@ /** Query History (browse / paste / delete) and Import Data from File dialogs. */ import { useEffect, useMemo, useState } from "react"; import { call, commands, type DbHistoryEntry } from "@/platform/ipc"; +import { readDesktopText } from "@/platform/desktopFiles"; import { editorsFor } from "@/editor/api"; import { Checkbox, Dialog, EmptyState, IconButton, Input, List, Select, T } from "@/ui"; import { notifications } from "@/workbench/contributions"; @@ -157,7 +158,7 @@ export function ImportDialog({ id, schema, table }: { id: string; schema: string filters: [{ name: "CSV / TSV", extensions: ["csv", "tsv", "txt"] }], }); if (typeof f !== "string") return; - const content = await call(commands.fsReadText(f)); + const content = await readDesktopText(f); setFile(f); setText(content); setSep(guessSeparator(content)); diff --git a/src/features/database/JdbcDriverProfiles.tsx b/src/features/database/JdbcDriverProfiles.tsx index f093c619ac..7982f45e34 100644 --- a/src/features/database/JdbcDriverProfiles.tsx +++ b/src/features/database/JdbcDriverProfiles.tsx @@ -1,4 +1,5 @@ import { useEffect, useState } from "react"; +import { choosePaths } from "@/platform/choosePath"; import { call, commands, type DbJdbcDriver } from "@/platform/ipc"; import { useTx } from "@/platform/i18n"; import { Button, Dialog, IconButton, Input, Select, T } from "@/ui"; @@ -85,14 +86,12 @@ export function JdbcDriverProfiles({ setBusy(true); setError(null); try { - const { open } = await import("@/platform/dialog"); - const files = await open({ + const files = await choosePaths({ title: tx("Choose JDBC Driver and Dependency JARs"), - multiple: true, directory: false, filters: [{ name: tx("Java archives"), extensions: ["jar"] }], }); - if (files && draft) { + if (files.length && draft) { const jars = [...new Set([...draft.jars, ...files])]; set({ jars }); const names = await call(commands.dbJdbcDriverClasses(jars)); diff --git a/src/features/database/JdbcSourceDialog.test.tsx b/src/features/database/JdbcSourceDialog.test.tsx index ff5793ef56..915bd59e23 100644 --- a/src/features/database/JdbcSourceDialog.test.tsx +++ b/src/features/database/JdbcSourceDialog.test.tsx @@ -16,6 +16,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => { (...args: unknown[]) => [name, ...args]; return { ...real, + isTauri: () => true, call: backend.call, commands: { ...real.commands, diff --git a/src/features/database/SourceDialog.tsx b/src/features/database/SourceDialog.tsx index e683f3d93a..c68037fd51 100644 --- a/src/features/database/SourceDialog.tsx +++ b/src/features/database/SourceDialog.tsx @@ -21,6 +21,7 @@ import { type DbTxMode, } from "@/platform/ipc"; import { executeAction } from "@/platform/actions"; +import { choosePath } from "@/platform/choosePath"; import { tx, txPart, useTx, useTxTemplate } from "@/platform/i18n"; import { useProject } from "@/platform/project"; import { sshLabel as configLabel } from "@/platform/remoteSettings"; @@ -259,9 +260,7 @@ function blank(): DataSource { } async function pickFile(title: string): Promise { - const { open } = await import("@/platform/dialog"); - const file = await open({ multiple: false, directory: false, title }); - return typeof file === "string" ? file : null; + return choosePath({ directory: false, title }); } /** A path field with Browse…. */ diff --git a/src/features/database/treeActions.ts b/src/features/database/treeActions.ts index 135b110122..579700afcb 100644 --- a/src/features/database/treeActions.ts +++ b/src/features/database/treeActions.ts @@ -6,6 +6,7 @@ import { introspectSource } from "./introspection"; import { writeClipboardText } from "@/platform/clipboard"; import { call, commands, type DataSource, type DbDriver, type DbTableInfo } from "@/platform/ipc"; +import { readDesktopText } from "@/platform/desktopFiles"; import { registerActions, type Action } from "@/platform/actions"; import { editorService, notifications, showServiceView, toolWindowService } from "@/workbench/contributions"; import { splitTarget } from "./model"; @@ -200,7 +201,7 @@ async function runScriptFile(id: string) { }); if (typeof file !== "string") return; try { - const text = await call(commands.fsReadText(file)); + const text = await readDesktopText(file); const statements = await call(commands.dbStatements(id, text, 0, text.length)); useDatabase.setState({ activeResult: OUTPUT_TAB }); showServiceView(RESULTS_VIEW, false); diff --git a/src/features/database/treeMenu.ts b/src/features/database/treeMenu.ts index d8e047cf57..55eabd541e 100644 --- a/src/features/database/treeMenu.ts +++ b/src/features/database/treeMenu.ts @@ -1,4 +1,5 @@ /** Menus of the Database tool window, laid out like IDEA's (New ▸, Copy/Paste ▸, SQL Scripts ▸ …). */ +import { choosePath } from "@/platform/choosePath"; import type { MenuItem } from "@/ui"; import { notifications } from "@/workbench/contributions"; import { fileSourceName, parseSourceUrl } from "./model"; @@ -32,8 +33,7 @@ const act = ( const sep: MenuItem = { kind: "separator" }; async function sqliteFromFile() { - const { open } = await import("@/platform/dialog"); - const file = await open({ multiple: false, directory: false, title: "SQLite Database File" }); + const file = await choosePath({ directory: false, title: "SQLite Database File" }); if (typeof file === "string") openSourceDialog(null, { driver: "sqlite", file, name: fileSourceName(file) }); } diff --git a/src/features/deployment/remoteHost.test.ts b/src/features/deployment/remoteHost.test.ts index 1d59feb677..022ee7aec1 100644 --- a/src/features/deployment/remoteHost.test.ts +++ b/src/features/deployment/remoteHost.test.ts @@ -19,7 +19,9 @@ vi.mock("@/ui", () => ({ copyText: vi.fn() })); vi.mock("@/workbench/inputDialogs", () => ({ promptInput: vi.fn() })); vi.mock("@/workbench/messages", () => ({ confirm: vi.fn() })); vi.mock("@/platform/dialog", () => ({ open: (...args: unknown[]) => ipc.openDialog(...args) })); -vi.mock("@/platform/project", () => ({ useProject: { getState: () => ({ project: { root: "/project" } }) } })); +vi.mock("@/platform/project", () => ({ + useProject: { getState: () => ({ project: { root: "/project" } }), subscribe: vi.fn() }, +})); vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify: ipc.notify }), projectViewSelection: () => ipc.selection(), @@ -27,6 +29,7 @@ vi.mock("@/workbench/contributions", () => ({ })); vi.mock("@/platform/ipc", async (original) => ({ ...(await original()), + isTauri: () => true, commands: { deployServerRoot: ipc.root, remoteList: ipc.list, diff --git a/src/features/deployment/remoteHost.ts b/src/features/deployment/remoteHost.ts index 410566b54b..b23534c42c 100644 --- a/src/features/deployment/remoteHost.ts +++ b/src/features/deployment/remoteHost.ts @@ -1,5 +1,6 @@ /** Remote Host tool window operations: list, open, create, rename, delete and download remote files. */ import { tx, txTemplate } from "@/platform/i18n"; +import { choosePath } from "@/platform/choosePath"; import { call, commands, type RemoteEntry } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { deploymentConnection, deploymentSecretKey, type DeploymentServerValid } from "@/platform/remoteSettings"; @@ -183,10 +184,8 @@ export async function downloadToProject(server: DeploymentServerValid, entries: * the project root, preselected), without the server path above them. */ export async function downloadTo(server: DeploymentServerValid, entries: RemoteEntry[]) { if (!entries.length) return; - const { open } = await import("@/platform/dialog"); - const target = await open({ + const target = await choosePath({ directory: true, - multiple: false, title: tx("Download to"), defaultPath: (await defaultDownloadFolder()) ?? undefined, }); diff --git a/src/features/plugins/__tests__/projectUi.test.tsx b/src/features/plugins/__tests__/projectUi.test.tsx index 83e44bbb78..00c8fb7291 100644 --- a/src/features/plugins/__tests__/projectUi.test.tsx +++ b/src/features/plugins/__tests__/projectUi.test.tsx @@ -7,6 +7,7 @@ import { handleRuntimeEvent } from "../runtimeUi"; const nativeOpen = vi.hoisted(() => vi.fn()); vi.mock("@tauri-apps/plugin-dialog", () => ({ open: nativeOpen })); +vi.mock("@/platform/ipc", async (original) => ({ ...(await original()), isTauri: () => true })); const answerPrompt = vi.fn().mockResolvedValue(undefined); let notes: Parameters[0][]; let dispose: (() => void) | undefined; diff --git a/src/features/plugins/backend.ts b/src/features/plugins/backend.ts index 5d06636c8d..f6b037fe3b 100644 --- a/src/features/plugins/backend.ts +++ b/src/features/plugins/backend.ts @@ -40,6 +40,7 @@ import type { WorkbenchEvent, } from "@/bindings"; import { toBase64 } from "@/platform/base64"; +import { choosePath } from "@/platform/choosePath"; import { tx } from "@/platform/i18n"; import { useRemote } from "@/platform/remote"; import { call, commands, IpcError, isCancelled, isTauri, nextRequestId } from "@/platform/ipc"; @@ -222,11 +223,7 @@ export const tauriPluginsBackend: PluginsBackend = { return chosen; }, program: (id, program, scope) => call(commands.pluginProgram(id, program, scope)), - pickProgram: async () => { - const { open } = await import("@/platform/dialog"); - const picked = await open({ directory: false, multiple: false, title: tx("Choose plugin executable") }); - return (Array.isArray(picked) ? picked[0] : picked) ?? null; - }, + pickProgram: () => choosePath({ directory: false, title: tx("Choose plugin executable") }), setCapability: (id, capability, granted) => call(commands.pluginSetCapability(id, capability, granted)), revokeNetHost: (id, host) => call(commands.pluginRevokeNetHost(id, host)), assets: (pluginId, prefix) => call(commands.pluginAssets(pluginId, prefix)), diff --git a/src/features/plugins/runtimeUi.tsx b/src/features/plugins/runtimeUi.tsx index 86d77cffb5..b8eb43b2c6 100644 --- a/src/features/plugins/runtimeUi.tsx +++ b/src/features/plugins/runtimeUi.tsx @@ -5,6 +5,7 @@ * batches. */ import { readClipboardPlainText, readClipboardPng, writeClipboardText } from "@/platform/clipboard"; +import { choosePath } from "@/platform/choosePath"; import { providePluginTestParser, providePluginTestSelector } from "@/workbench/contributions"; import { contentTabData, @@ -512,16 +513,11 @@ async function askUser(prompt: Prompt, signal: AbortSignal): Promise ({ confirm: vi.fn(async () => true) })); vi.mock("@/workbench/messages", async (orig) => ({ ...(await orig()), confirm: messages.confirm })); const dialog = vi.hoisted(() => ({ save: vi.fn(async (): Promise => null) })); vi.mock("@/platform/dialog", () => dialog); +vi.mock("@/platform/ipc", async (orig) => ({ ...(await orig()), isTauri: () => true })); const ok = { status: "ok", data: null } as const; let onDisk: Record = {}; @@ -39,7 +42,10 @@ beforeEach(() => { return ok; }); }); -afterEach(() => vi.restoreAllMocks()); +afterEach(() => { + useRemote.setState({ session: null }); + vi.restoreAllMocks(); +}); function results() { const r = new TestResults(); @@ -164,6 +170,59 @@ describe("ExportTestResultsDialog", () => { expect(written.map((w) => w.path)).toEqual([path]); }); + it.each(["html", "xml"] as const)( + "browses the remote folder for a %s report and confirms replacement", + async (format) => { + useRemote.setState({ session: { root: "/work/app", os: "linux" } as never }); + const choose = vi.fn(async () => ["/srv/reports"]); + const unregister = registerHostPathChooser(choose); + try { + const onClose = open(); + if (format === "xml") fireEvent.click(screen.getByRole("radio", { name: "XML" })); + const name = `Test Results - go test _calc.${format}`; + const path = `/srv/reports/${name}`; + onDisk[path] = "file"; + press("Browse…"); + await waitFor(() => expect(folder()).toHaveValue("/srv/reports")); + expect(choose).toHaveBeenCalledWith(expect.objectContaining({ directory: true, defaultPath: "/work/app/" })); + expect(dialog.save).not.toHaveBeenCalled(); + expect(file()).toHaveValue(name); + + messages.confirm.mockResolvedValueOnce(false); + press("OK"); + await waitFor(() => expect(messages.confirm).toHaveBeenCalledOnce()); + await waitFor(() => expect(screen.getByRole("button", { name: "OK" })).toBeEnabled()); + expect(commands.fsDelete).not.toHaveBeenCalled(); + expect(written).toHaveLength(0); + + press("OK"); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + expect(written.map((w) => w.path)).toEqual([path]); + } finally { + unregister(); + } + }, + ); + + it("moves an absolute report path to the browsed remote folder", async () => { + useRemote.setState({ session: { root: "/work/app", os: "linux" } as never }); + const choose = vi.fn(async () => ["/srv/reports"]); + const unregister = registerHostPathChooser(choose); + try { + const onClose = open(); + fireEvent.change(file(), { target: { value: "/tmp/custom.html" } }); + press("Browse…"); + await waitFor(() => expect(file()).toHaveValue("custom.html")); + expect(choose).toHaveBeenCalledWith(expect.objectContaining({ defaultPath: "/tmp/" })); + fireEvent.click(screen.getByRole("checkbox", { name: "Open exported file in browser" })); + press("OK"); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + expect(written.map((w) => w.path)).toEqual(["/srv/reports/custom.html"]); + } finally { + unregister(); + } + }); + it("confirms again when the destination changes after using the save dialog", async () => { dialog.save.mockResolvedValueOnce("/tmp/picked.html"); onDisk["/work/app/reports/picked.html"] = "file"; diff --git a/src/features/run/ExportTestResultsDialog.tsx b/src/features/run/ExportTestResultsDialog.tsx index f922a82a34..76d8507a3e 100644 --- a/src/features/run/ExportTestResultsDialog.tsx +++ b/src/features/run/ExportTestResultsDialog.tsx @@ -5,8 +5,10 @@ import { useId, useState } from "react"; import { executeAction } from "@/platform/actions"; import { toBase64 } from "@/platform/base64"; +import { choosePath } from "@/platform/choosePath"; import { tx } from "@/platform/i18n"; import { call, commands } from "@/platform/ipc"; +import { isRemoteWindow } from "@/platform/remote"; import { Checkbox, Dialog, IconButton, Input, Radio, T } from "@/ui"; import { notifications } from "@/workbench/contributions"; import { confirm } from "@/workbench/messages"; @@ -159,6 +161,21 @@ export function ExportTestResultsDialog({ const browse = async () => { try { + if (isRemoteWindow()) { + const current = isAbsolutePath(fileName.trim()) ? destinationFromPicker(fileName.trim()) : destination; + const initial = current.folder.trim(); + const chosen = await choosePath({ + directory: true, + title: "Choose Directory…", + defaultPath: !initial + ? cwd + : isAbsolutePath(initial) + ? initial + : resolveDestination({ folder: cwd, fileName: initial }, cwd), + }); + if (chosen) setDestination({ folder: chosen, fileName: current.fileName }); + return; + } const { save } = await import("@/platform/dialog"); const chosen = await save({ defaultPath: target || folder || cwd, diff --git a/src/features/search/find/FindInFiles.tsx b/src/features/search/find/FindInFiles.tsx index 47f71005cd..a48714aba5 100644 --- a/src/features/search/find/FindInFiles.tsx +++ b/src/features/search/find/FindInFiles.tsx @@ -12,10 +12,11 @@ import { import clsx from "clsx"; import { openEditorPaths, useEditorRegistry } from "@/editor/api"; import { executeAction } from "@/platform/actions"; +import { choosePath } from "@/platform/choosePath"; import { setContext } from "@/platform/context"; import { t, useTxTemplate, tx, txPart } from "@/platform/i18n"; import { formatBinding, hostBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap"; -import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc"; +import { call, commands, onIdeEvent } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { useProjectModules } from "@/platform/projectRoots"; import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search"; @@ -98,15 +99,7 @@ import styles from "./FindInFiles.module.css"; /** The Directory scope's browse button: a folder chooser opened at the current directory. */ async function chooseDirectory(current: string): Promise { - if (!isTauri()) return null; - const { open } = await import("@/platform/dialog"); - const picked = await open({ - directory: true, - multiple: false, - title: tx("Select Search Directory"), - defaultPath: current || undefined, - }); - return (Array.isArray(picked) ? picked[0] : picked) ?? null; + return choosePath({ directory: true, title: tx("Select Search Directory"), defaultPath: current }); } const POPUP_MAX_MATCHES = 2000; diff --git a/src/features/settings/keymap/KeymapPage.tsx b/src/features/settings/keymap/KeymapPage.tsx index 5474d1f510..c76a53e60e 100644 --- a/src/features/settings/keymap/KeymapPage.tsx +++ b/src/features/settings/keymap/KeymapPage.tsx @@ -9,9 +9,8 @@ import { useMemo, useRef, useState, type MouseEvent } from "react"; import clsx from "clsx"; import { allActions, useActions, type Action } from "@/platform/actions"; -import { toBase64 } from "@/platform/base64"; import { defaultPreset, formatBinding, type Keymap, PRESET_TITLES, PRESETS } from "@/platform/keymap"; -import { call, commands } from "@/platform/ipc"; +import { readDesktopText, writeDesktopText } from "@/platform/desktopFiles"; import { notifications } from "@/workbench/contributions"; import { ask, confirm, showError } from "@/workbench/messages"; import { @@ -258,7 +257,7 @@ export function KeymapPage() { if (!path) return; let parsed; try { - parsed = parseIdeaKeymap(await call(commands.fsReadText(path))); + parsed = parseIdeaKeymap(await readDesktopText(path)); } catch (e) { await showError(tx("Import Keymap"), e instanceof Error ? e.message : String(e)); return; @@ -299,9 +298,7 @@ export function KeymapPage() { draft, ); try { - // The save dialog already confirmed replacing an existing file. - await call(commands.fsDelete(path)).catch(() => {}); - await call(commands.fsCreateFileBytes(path, toBase64(new TextEncoder().encode(json)))); + await writeDesktopText(path, json); notifications().notify({ level: "info", title: tx("Keymap exported"), diff --git a/src/features/settings/pages/editor/ColorSchemeBody.tsx b/src/features/settings/pages/editor/ColorSchemeBody.tsx index 551222d9ea..71a17a0098 100644 --- a/src/features/settings/pages/editor/ColorSchemeBody.tsx +++ b/src/features/settings/pages/editor/ColorSchemeBody.tsx @@ -46,8 +46,7 @@ import { Row, Select } from "../../components/Form"; import { useSetting } from "../../components/context"; import styles from "./Editor.module.css"; import { executeAction, registerActions } from "@/platform/actions"; -import { toBase64 } from "@/platform/base64"; -import { call, commands } from "@/platform/ipc"; +import { readDesktopText, writeDesktopText } from "@/platform/desktopFiles"; import { ask, confirm, showError } from "@/workbench/messages"; import { useContributions } from "@/workbench/contributions"; import { parseIcls, SchemeParseError, importScheme, deleteScheme, exportIcls } from "@/platform/icls"; @@ -1728,7 +1727,7 @@ export function ColorSchemePage({ .split(/[\\/]/) .at(-1) ?.replace(/\.[^.]+$/, "") || "Imported scheme"; - const parsed = parseIcls(await call(commands.fsReadText(path)), fallbackName); + const parsed = parseIcls(await readDesktopText(path), fallbackName); let overwrite = false; if (schemes.some((s) => s.name === parsed.scheme.name)) { const canOverwrite = Object.values(customs).some((s) => s.name === parsed.scheme.name); @@ -1759,10 +1758,7 @@ export function ColorSchemePage({ filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls"] }], })); if (!path) return; - const bytes = toBase64(new TextEncoder().encode(exportIcls(id, customs, mine))); - // The save dialog already confirmed replacing an existing file. - await call(commands.fsDelete(path)).catch(() => {}); - await call(commands.fsCreateFileBytes(path, bytes)); + await writeDesktopText(path, exportIcls(id, customs, mine)); setReport(tx("Scheme exported.")); }, delete: async () => { diff --git a/src/features/settings/pages/editor/codeStyle.tsx b/src/features/settings/pages/editor/codeStyle.tsx index 7cab5d5cd0..7c15c6a67d 100644 --- a/src/features/settings/pages/editor/codeStyle.tsx +++ b/src/features/settings/pages/editor/codeStyle.tsx @@ -10,6 +10,7 @@ import { useId, useState } from "react"; import { Button, Checkbox, Input, type SelectOption, T } from "@/ui"; import { commands, isTauri, type LanguageInfo_Serialize as LanguageInfo } from "@/platform/ipc"; +import { choosePath } from "@/platform/choosePath"; import { ENCODING_CHOICES, lineCommentDefaults, type LanguageCodeStyle } from "@/platform/editorSettings"; import { NATIVE_TO_ASCII_ACTION } from "../../nativeToAscii"; import { FormGroup, NumberInput, Row, Select, Toggle } from "../../components/Form"; @@ -300,9 +301,8 @@ function JavaFormatter({ }) { const id = useId(); const browse = async () => { - const { open } = await import("@/platform/dialog"); - const path = await open({ - multiple: false, + const path = await choosePath({ + directory: false, title: tx("Eclipse formatter XML"), filters: [{ name: "XML", extensions: ["xml"] }], }); diff --git a/src/features/settings/pages/tools.tsx b/src/features/settings/pages/tools.tsx index 7582e7e351..9dd83ba0d3 100644 --- a/src/features/settings/pages/tools.tsx +++ b/src/features/settings/pages/tools.tsx @@ -8,6 +8,7 @@ import { FontPicker } from "../components/FontPicker"; import { useEffect, useId, useRef, useState, type ReactNode } from "react"; import clsx from "clsx"; import { quotePath } from "@/platform/commandLine"; +import { choosePath } from "@/platform/choosePath"; import { commands, isTauri } from "@/platform/ipc"; import { DEFAULT_EXTERNAL_TOOL, @@ -137,9 +138,7 @@ function ShellPathRow() { void commands.termAvailableShells().then(setShells, () => undefined); }, []); const browse = async () => { - const { open: pick } = await import("@/platform/dialog"); - const picked = await pick({ multiple: false, title: "Shell Path" }); - const path = Array.isArray(picked) ? picked[0] : picked; + const path = await choosePath({ directory: false, title: "Shell Path" }); if (path) set(quotePath(path)); }; return ( diff --git a/src/features/tools/backend.ts b/src/features/tools/backend.ts index 288f0e8d9b..17cceb8f4f 100644 --- a/src/features/tools/backend.ts +++ b/src/features/tools/backend.ts @@ -5,6 +5,7 @@ import { Channel } from "@tauri-apps/api/core"; import type { InstallEvent, RequestId, ToolInfo, ToolUpdate } from "@/bindings"; import { call, commands, IpcError, isTauri } from "@/platform/ipc"; +import { choosePath } from "@/platform/choosePath"; export interface LanguageChoice { id: string; @@ -43,11 +44,7 @@ export const tauriToolsBackend: ToolsBackend = { restartServers: async (name) => { await call(commands.lspRestartNamed(name)); }, - chooseExecutable: async (title, defaultPath) => { - const { open } = await import("@/platform/dialog"); - const picked = await open({ directory: false, multiple: false, title, defaultPath: defaultPath || undefined }); - return (Array.isArray(picked) ? picked[0] : picked) ?? null; - }, + chooseExecutable: (title, defaultPath) => choosePath({ directory: false, title, defaultPath }), languages: async () => (await commands.languages()) .map((l) => ({ id: l.id, name: l.name, extensions: l.extensions, filenames: l.filenames })) diff --git a/src/features/vcs/RevisionBrowser.tsx b/src/features/vcs/RevisionBrowser.tsx index 9de60718ee..ae78aa015a 100644 --- a/src/features/vcs/RevisionBrowser.tsx +++ b/src/features/vcs/RevisionBrowser.tsx @@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import type { Commit } from "@/bindings"; -import { call, commands, isTauri } from "@/platform/ipc"; +import { call, commands } from "@/platform/ipc"; import { tx } from "@/platform/i18n"; import { notifications, type EditorInput } from "@/workbench/contributions"; import { @@ -26,15 +26,12 @@ import { currentRepoRoot } from "./store"; import { repositoryPath } from "./repositoryPaths"; import { firstLineOf, languageFor, viewerBase } from "./cm"; import styles from "./GitLog.module.css"; -import { choosePath } from "@/platform/choosePath"; +import { choosePaths } from "@/platform/choosePath"; import { openLogTab } from "./logStore"; import { openRevisionFile, type RevisionData } from "./revisionInput"; export async function openExternalLog() { - const picked = isTauri() - ? await (await import("@/platform/dialog")).open({ title: tx("Open Git Log"), directory: true, multiple: true }) - : await choosePath({ title: "Open Git Log", directory: true }); - const paths = Array.isArray(picked) ? picked : picked ? [picked] : []; + const paths = await choosePaths({ title: tx("Open Git Log"), directory: true }); if (!paths.length) return; try { const roots = await Promise.all(paths.map((path) => call(commands.vcsOpenExternalLog(path)))); diff --git a/src/features/vcs/clone.tsx b/src/features/vcs/clone.tsx index bbd9da4a52..ecca909918 100644 --- a/src/features/vcs/clone.tsx +++ b/src/features/vcs/clone.tsx @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from "react"; import { Channel } from "@tauri-apps/api/core"; import { tx } from "@/platform/i18n"; -import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc"; +import { callDesktop, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc"; import { openProject } from "@/platform/project"; import { Checkbox, Dialog, Icon, IconButton, Input, ProgressBar, Select, T, showContextMenu } from "@/ui"; import { cloneSourceList, notifications, useCloneSources } from "@/workbench/contributions"; @@ -183,8 +183,9 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl: }; const cancel = () => { - if (request.current !== null) void commands.cancelRequest(request.current); - else onClose(); + const id = request.current; + if (id === null) onClose(); + else void callDesktop("cancel_request", { id }); }; const clone = async (picked?: string) => { @@ -201,7 +202,7 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl: if (text) setProgress({ line: text, fraction: progressFraction(text) }); }; try { - await call(commands.vcsClone(id, cloneUrl.trim(), target, depth, channel)); + await callDesktop("vcs_clone", { request: id, url: cloneUrl.trim(), dest: target, depth, onOutput: channel }); writeParent(parentOf(target)); rememberUrl(cloneUrl.trim()); onClose(); diff --git a/src/features/vcs/compare.tsx b/src/features/vcs/compare.tsx index 8d648b534b..5216547412 100644 --- a/src/features/vcs/compare.tsx +++ b/src/features/vcs/compare.tsx @@ -4,6 +4,7 @@ */ import { activeEditor } from "@/editor/api"; import { registerActions } from "@/platform/actions"; +import { choosePath } from "@/platform/choosePath"; import { call, commands, isTauri } from "@/platform/ipc"; import { isRemoteWindow } from "@/platform/remote"; import { maybeEditorService, notifications, projectViewSelection } from "@/workbench/contributions"; @@ -97,16 +98,13 @@ function info(title: string) { } async function pickFile(near: string): Promise { - if (!isTauri()) return null; - const { open } = await import("@/platform/dialog"); const dir = near.slice(0, near.lastIndexOf("/")) || undefined; - const picked = await open({ multiple: false, directory: false, title: "Compare With", defaultPath: dir }); - return (Array.isArray(picked) ? picked[0] : picked) ?? null; + return choosePath({ directory: false, title: tx("Compare With"), defaultPath: dir }); } /** - * The file to compare `path` against: the OS file dialog on the desktop; a - * browser file picker's contents elsewhere (remote development / `pnpm dev`), + * The file to compare `path` against: a project-host path in the app; a + * browser file picker's contents in the browser build, * compared as text since no absolute path is available to the backend. */ async function pickComparison( diff --git a/src/features/vcs/createRepository.ts b/src/features/vcs/createRepository.ts index bfe0340f66..9f1db412b4 100644 --- a/src/features/vcs/createRepository.ts +++ b/src/features/vcs/createRepository.ts @@ -1,5 +1,5 @@ /** VCS › Create Git Repository…: `git init` in a folder chosen under the project. */ -import { open } from "@/platform/dialog"; +import { choosePath } from "@/platform/choosePath"; import { tx } from "@/platform/i18n"; import { call, commands } from "@/platform/ipc"; import { useProject } from "@/platform/project"; @@ -8,7 +8,7 @@ import { discoverRoots } from "./store"; export async function createRepository() { const root = useProject.getState().project?.root; - const dir = await open({ title: tx("Select Directory for Git Init"), directory: true, defaultPath: root }); + const dir = await choosePath({ title: tx("Select Directory for Git Init"), directory: true, defaultPath: root }); if (typeof dir !== "string") return; try { await call(commands.vcsInit(dir)); diff --git a/src/features/vcs/patches.tsx b/src/features/vcs/patches.tsx index 95600e0e26..bce3089967 100644 --- a/src/features/vcs/patches.tsx +++ b/src/features/vcs/patches.tsx @@ -35,7 +35,7 @@ import { } from "@/ui"; import { executeAction } from "@/platform/actions"; import { bindingsFor, normalizeBinding, registerKeyClaim, shortcutLabel } from "@/platform/keymap"; -import { choosePath } from "@/platform/choosePath"; +import { choosePath, chooseSavePath } from "@/platform/choosePath"; import { workflowSettings } from "@/platform/workflowSettings"; import { notifications } from "@/workbench/contributions"; import { ask } from "@/workbench/messages"; @@ -165,8 +165,7 @@ export function showCreatePatchForShelf(entry: ShelvedChangeList, path?: string) async function browseSave(current: string): Promise { try { - const { save } = await import("@/platform/dialog"); - return (await save({ defaultPath: current, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] })) ?? null; + return await chooseSavePath({ defaultPath: current, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] }); } catch { return null; } @@ -414,14 +413,11 @@ export async function showApplyPatch(from: "file" | "clipboard", path?: string) } else { let file = path ?? null; if (!file) { - const { open } = await import("@/platform/dialog"); - const picked = await open({ - multiple: false, + file = await choosePath({ directory: false, defaultPath: useVcs.getState().root ?? undefined, filters: [{ name: "Patch", extensions: ["patch", "diff"] }], }); - file = typeof picked === "string" ? picked : null; } if (!file) return; sourcePath = file; diff --git a/src/features/vcs/shelf.tsx b/src/features/vcs/shelf.tsx index d960784b54..84a7cb90d2 100644 --- a/src/features/vcs/shelf.tsx +++ b/src/features/vcs/shelf.tsx @@ -4,6 +4,7 @@ * merge UI), rename and delete. */ import { writeClipboardText } from "@/platform/clipboard"; +import { choosePaths } from "@/platform/choosePath"; import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react"; import clsx from "clsx"; import { create } from "zustand"; @@ -581,12 +582,8 @@ export async function showShelfDiff(arg?: unknown, local = false, newTab = false export async function importShelfPatches(paths?: string[]) { const repo = currentRepo(); const picked = - paths ?? - (await import("@/platform/dialog").then(({ open }) => - open({ multiple: true, directory: false, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] }), - )); - if (!picked) return; - for (const path of typeof picked === "string" ? [picked] : picked) { + paths ?? (await choosePaths({ directory: false, filters: [{ name: "Patch", extensions: ["patch", "diff"] }] })); + for (const path of picked) { await runOp( tx("Import patches"), async () => call(commands.vcsShelfImport(repo, baseName(path), await call(commands.fsReadText(path)))), diff --git a/src/platform/choosePath.ts b/src/platform/choosePath.ts index fe888a5219..04a03fa566 100644 --- a/src/platform/choosePath.ts +++ b/src/platform/choosePath.ts @@ -1,13 +1,21 @@ import { isTauri } from "@/platform/ipc"; import { isRemoteWindow } from "@/platform/remote"; +import type { DialogFilter, SaveDialogOptions } from "@/platform/dialog"; export interface ChoosePathOptions { directory: boolean; - title: string; + title?: string; defaultPath?: string; + filters?: DialogFilter[]; } -type HostChooser = (opts: ChoosePathOptions) => Promise; +export interface HostPathOptions extends ChoosePathOptions { + multiple?: boolean; + save?: boolean; + signal?: AbortSignal; +} + +type HostChooser = (opts: HostPathOptions) => Promise; let hostChooser: HostChooser | null = null; /** @@ -25,16 +33,28 @@ export function registerHostPathChooser(chooser: HostChooser): () => void { * File / folder chooser for a path on the host this window's commands run on: the desktop's dialog * locally, the in-app chooser in a remote window. Null when cancelled or outside Tauri. */ -export async function choosePath(opts: ChoosePathOptions): Promise { - if (!isTauri()) return null; - if (isRemoteWindow() && hostChooser) return hostChooser(opts); +export async function choosePath(opts: ChoosePathOptions, signal?: AbortSignal): Promise { + if (!isTauri() || signal?.aborted) return null; + if (isRemoteWindow()) return (await hostChooser?.({ ...opts, signal }))?.[0] ?? null; // Lazy on purpose: loading platform/dialog starts its GTK capability probe at module load. const { open } = await import("@/platform/dialog"); - const picked = await open({ - directory: opts.directory, - multiple: false, - title: opts.title, - defaultPath: opts.defaultPath || undefined, - }); + if (signal?.aborted) return null; + const picked = await open({ ...opts, multiple: false, defaultPath: opts.defaultPath || undefined }); return (Array.isArray(picked) ? picked[0] : picked) ?? null; } + +/** Pick multiple existing paths on the project host. */ +export async function choosePaths(opts: ChoosePathOptions): Promise { + if (!isTauri()) return []; + if (isRemoteWindow()) return (await hostChooser?.({ ...opts, multiple: true })) ?? []; + const { open } = await import("@/platform/dialog"); + const picked = await open({ ...opts, multiple: true }); + return typeof picked === "string" ? [picked] : (picked ?? []); +} + +/** Choose a destination on the project host and confirm replacement if it exists. */ +export async function chooseSavePath(opts: SaveDialogOptions): Promise { + if (isRemoteWindow()) return (await hostChooser?.({ ...opts, directory: false, save: true }))?.[0] ?? null; + const { save } = await import("@/platform/dialog"); + return save(opts); +} diff --git a/src/platform/desktopFiles.test.ts b/src/platform/desktopFiles.test.ts new file mode 100644 index 0000000000..38fdad17a7 --- /dev/null +++ b/src/platform/desktopFiles.test.ts @@ -0,0 +1,40 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { readDesktopText, writeDesktopText } from "./desktopFiles"; +import { useRemote } from "./remote"; +import { setInvokeRoute } from "./tauriCore"; + +const invoke = vi.fn(); +const remoteInvoke = vi.fn(); + +beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("__TAURI_INTERNALS__", { invoke }); + useRemote.setState({ session: { root: "/srv/project", os: "linux" } as never }); + setInvokeRoute(remoteInvoke); +}); + +afterEach(() => { + setInvokeRoute(null); + useRemote.setState({ session: null }); + vi.unstubAllGlobals(); +}); + +it("reads desktop settings or import files even when project IPC is remote", async () => { + const path = "C:\\Users\\me\\settings.xml"; + invoke.mockResolvedValueOnce(""); + await expect(readDesktopText(path)).resolves.toBe(""); + expect(invoke.mock.calls[0]?.slice(0, 2)).toEqual(["fs_read_text", { path }]); + expect(remoteInvoke).not.toHaveBeenCalled(); +}); + +it("checks and replaces an existing desktop file on the desktop", async () => { + const path = "C:\\Users\\me\\scheme.icls"; + invoke.mockResolvedValueOnce("file").mockResolvedValueOnce(null).mockResolvedValueOnce(null); + await writeDesktopText(path, "é"); + expect(invoke.mock.calls.map((args) => args.slice(0, 2))).toEqual([ + ["fs_entry_kind", { path }], + ["fs_delete", { path }], + ["fs_create_file_bytes", { path, data: "w6k=" }], + ]); + expect(remoteInvoke).not.toHaveBeenCalled(); +}); diff --git a/src/platform/desktopFiles.ts b/src/platform/desktopFiles.ts new file mode 100644 index 0000000000..2000062501 --- /dev/null +++ b/src/platform/desktopFiles.ts @@ -0,0 +1,24 @@ +import { toBase64 } from "./base64"; +import { call, callDesktop, commands, isErrorKind } from "./ipc"; +import { isRemoteWindow } from "./remote"; + +/** Text selected in the desktop's file dialog, including in a remote window. */ +export function readDesktopText(path: string): Promise { + return isRemoteWindow() ? callDesktop("fs_read_text", { path }) : call(commands.fsReadText(path)); +} + +/** Write UTF-8 to a path already confirmed in the desktop's save dialog. */ +export async function writeDesktopText(path: string, text: string): Promise { + const data = toBase64(new TextEncoder().encode(text)); + if (!isRemoteWindow()) { + await call(commands.fsDelete(path)).catch(() => {}); + await call(commands.fsCreateFileBytes(path, data)); + return; + } + const kind = await callDesktop("fs_entry_kind", { path }).catch((e: unknown) => { + if (!isErrorKind(e, "notFound")) throw e; + return null; + }); + if (kind === "file") await callDesktop("fs_delete", { path }); + await callDesktop("fs_create_file_bytes", { path, data }); +} diff --git a/src/platform/ipc.ts b/src/platform/ipc.ts index cdf68bf4e4..792efa857d 100644 --- a/src/platform/ipc.ts +++ b/src/platform/ipc.ts @@ -9,6 +9,8 @@ import type { UnlistenFn } from "@tauri-apps/api/event"; import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"; import { commands, type IdeError, type IdeEvent, type RequestId } from "@/bindings"; import { notifyEach } from "./listeners"; +import { invokeLocal } from "./tauriCore"; +import type { InvokeArgs } from "@tauri-apps/api/core"; export { commands }; export type * from "@/bindings"; @@ -43,6 +45,16 @@ export async function call(result: Promise>): Promise { return r.data; } +/** Run a command in the desktop process when its path came from that machine. */ +export async function callDesktop(command: string, args: InvokeArgs): Promise { + try { + return await invokeLocal(command, args); + } catch (e) { + if (e && typeof e === "object" && "kind" in e && "message" in e) throw new IpcError(e as IdeError); + throw e; + } +} + export function isCancelled(e: unknown): boolean { return e instanceof IpcError && e.kind === "cancelled"; } diff --git a/src/workbench/inputDialogs.tsx b/src/workbench/inputDialogs.tsx index 349f9272e8..d2392744a7 100644 --- a/src/workbench/inputDialogs.tsx +++ b/src/workbench/inputDialogs.tsx @@ -9,11 +9,13 @@ */ import { useEffect, useRef, useState, type ReactNode } from "react"; import { create } from "zustand"; -import { registerHostPathChooser, type ChoosePathOptions } from "@/platform/choosePath"; +import { registerHostPathChooser, type HostPathOptions } from "@/platform/choosePath"; import { t, tx, VerbatimTextContext } from "@/platform/i18n"; -import { call, commands, type FileEntry } from "@/platform/ipc"; +import { call, commands, isErrorKind, type FileEntry } from "@/platform/ipc"; +import { ipcPath } from "@/platform/paths"; import { useProject } from "@/platform/project"; import { Checkbox, Dialog, Given, Icon, IconButton, Input, List, T } from "@/ui"; +import { confirm } from "./messages"; import styles from "./inputDialogs.module.css"; export interface PromptInputOptions { @@ -63,7 +65,7 @@ type Request = | { kind: "prompt"; id: number; options: PromptInputOptions; resolve: (v: string | null) => void } | { kind: "choose"; id: number; options: ChooseItemOptions; resolve: (v: string | null) => void } | { kind: "pick"; id: number; options: PickItemsOptions; resolve: (v: string[] | null) => void } - | { kind: "path"; id: number; options: ChoosePathOptions; resolve: (v: string | null) => void }; + | { kind: "path"; id: number; options: HostPathOptions; resolve: (v: string[] | null) => void }; const useInputDialogs = create<{ stack: Request[] }>(() => ({ stack: [] })); let seq = 0; @@ -102,8 +104,8 @@ export function pickItems(options: PickItemsOptions): Promise { } /** A file or folder on the host this window's commands run on, browsed in the IDE (a remote window's chooser). */ -export function choosePathOnHost(options: ChoosePathOptions): Promise { - return open((id, resolve) => ({ kind: "path", id, options, resolve })); +function choosePathOnHost(options: HostPathOptions): Promise { + return open((id, resolve) => ({ kind: "path", id, options, resolve }), options.signal); } registerHostPathChooser(choosePathOnHost); @@ -351,8 +353,10 @@ function PickDialog({ options, done }: { options: PickItemsOptions; done: (v: st /** The folder that holds `path` (either separator), or null at a root. */ export function parentPath(path: string): string | null { if (/^(?:[\\/]+|[A-Za-z]:[\\/]*)$/.test(path)) return null; - const trimmed = path.length > 1 ? path.replace(/[\\/]+$/, "") : path; - const cut = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\")); + const posix = path.startsWith("/") && !path.startsWith("//"); + const trimmed = path.replace(posix ? /\/+$/ : /[\\/]+$/, ""); + const slash = trimmed.lastIndexOf("/"); + const cut = posix ? slash : Math.max(slash, trimmed.lastIndexOf("\\")); if (cut < 0) return null; const parent = trimmed.slice(0, cut); // `/a` → `/`; `C:\a` → `C:\`. @@ -360,30 +364,44 @@ export function parentPath(path: string): string | null { return parent === trimmed ? null : parent; } -function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: string | null) => void }) { +function PathDialog({ options, done }: { options: HostPathOptions; done: (v: string[] | null) => void }) { const root = useProject((s) => s.project?.root ?? null); + const title = + options.title ?? (options.save ? tx("Save As") : options.directory ? tx("Choose Directory…") : tx("Choose File…")); const [dir, setDir] = useState(null); const [entries, setEntries] = useState([]); const [active, setActive] = useState(-1); const [value, setValue] = useState(options.defaultPath || root || ""); + const [selected, setSelected] = useState([]); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); + const [submitting, setSubmitting] = useState(false); const request = useRef(0); + const inDir = (dir: string, name: string) => `${ipcPath(dir).replace(/\/$/, "")}/${name}`; + const isAbsolute = (path: string) => /^(?:\/|[A-Za-z]:\/)/.test(ipcPath(path)); const isDir = (e: FileEntry) => e.kind === "dir" || (e.kind === "symlink" && e.targetKind === "dir"); - const visit = async (path: string) => { + const nameOf = (path: string) => ipcPath(path).split("/").at(-1) ?? ""; + const accepts = (entry: FileEntry) => + isDir(entry) || + (!options.directory && + (!options.filters?.length || + options.filters.some(({ extensions }) => + extensions.some((ext) => ext === "*" || entry.name.toLowerCase().endsWith(`.${ext.toLowerCase()}`)), + ))); + const visit = async (path: string, filename = "") => { const id = ++request.current; setLoading(true); try { const listed = await call(commands.fsReadDir(path)); if (id !== request.current) return true; const shown = listed - .filter((e) => !options.directory || isDir(e)) + .filter(accepts) .sort((a, b) => Number(isDir(b)) - Number(isDir(a)) || a.name.localeCompare(b.name)); setDir(path); setEntries(shown); setActive(-1); - setValue(path); + setValue(filename ? inDir(path, filename) : path); setError(null); return true; } catch (e) { @@ -395,7 +413,12 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s }; useEffect(() => { - const start = options.defaultPath || root || "/"; + const initial = options.defaultPath || root || "/"; + const start = root && !isAbsolute(initial) ? inDir(root, initial) : initial; + if (options.save) { + void visit(parentPath(start) ?? root ?? "/", nameOf(start)); + return; + } // A file path starts in its folder, with the file in the field. void visit(start).then((ok) => { const parent = parentPath(start); @@ -404,23 +427,42 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + const move = (path: string) => visit(path, options.save && value !== dir ? nameOf(value) : ""); + const toggle = (path: string) => + setSelected((paths) => (paths.includes(path) ? paths.filter((p) => p !== path) : [...paths, path])); const choose = (entry: FileEntry) => { - if (isDir(entry)) void visit(entry.path); - else done(entry.path); + if (isDir(entry)) void move(entry.path); + else if (options.multiple) toggle(entry.path); + else if (options.save) setValue(entry.path); + else done([entry.path]); }; const submit = async () => { - const path = value.trim(); - if (!path) return; - let kind: string; + const input = value.trim(); + if (loading || submitting) return; + if (options.multiple && selected.length) return done(selected); + if (!input) return; + const path = dir && !isAbsolute(input) ? inDir(dir, input) : input; + setSubmitting(true); try { - kind = await call(commands.fsEntryKind(path)); - } catch { - return setError(tx("No such file or folder")); + const kind = await call(commands.fsEntryKind(path)); + const folder = kind === "dir"; + if (options.directory) return folder ? done([path]) : setError(tx("Choose a folder")); + if (folder) return void visit(path); + if ( + !options.save || + (await confirm({ + title, + message: tx`File '${nameOf(path)}' already exists. Do you want to overwrite it?`, + ok: "Overwrite", + })) + ) + done([path]); + } catch (e) { + if (options.save && isErrorKind(e, "notFound")) done([path]); + else setError(options.save && e instanceof Error ? e.message : tx("No such file or folder")); + } finally { + setSubmitting(false); } - const folder = kind === "dir"; - if (options.directory) return folder ? done(path) : setError(tx("Choose a folder")); - if (folder) return void visit(path); - done(path); }; const up = dir === null ? null : parentPath(dir); @@ -428,11 +470,16 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s done(null)} width={520} buttons={[ - { label: tx("OK"), role: "default", disabled: !value.trim(), onClick: () => void submit() }, + { + label: tx("OK"), + role: "default", + disabled: loading || submitting || (!value.trim() && !selected.length), + onClick: () => void submit(), + }, { label: t("common.cancel"), role: "cancel" }, ]} > @@ -448,12 +495,12 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s icon="arrow-up" title={tx("Parent Folder")} disabled={!up || loading} - onClick={() => up && void visit(up)} + onClick={() => up && void move(up)} /> { @@ -469,12 +516,12 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s onActiveChange={(i) => { setActive(i); const entry = entries[i]; - if (entry) setValue(entry.path); + if (entry && (!options.save || !isDir(entry))) setValue(entry.path); }} // A click selects; a double click or Enter opens the folder or chooses the file. onActivate={(entry, _i, e) => (e.type !== "click" || e.detail > 1) && choose(entry)} className={styles.pathList} - aria-label={dir ?? options.title} + aria-label={dir ?? title} empty={
{loading ? "Loading…" : "Empty folder"} @@ -483,7 +530,15 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s renderItem={(entry, state) => (
- {entry.name} + {options.multiple && (options.directory || !isDir(entry)) ? ( + {entry.name}} + checked={selected.includes(entry.path)} + onChange={() => toggle(entry.path)} + /> + ) : ( + {entry.name} + )}
)} /> diff --git a/src/workbench/pathChooser.test.tsx b/src/workbench/pathChooser.test.tsx index 9ea9094eb6..991455387b 100644 --- a/src/workbench/pathChooser.test.tsx +++ b/src/workbench/pathChooser.test.tsx @@ -6,6 +6,8 @@ const mocks = vi.hoisted(() => ({ readDir: vi.fn(), entryKind: vi.fn(), nativeOpen: vi.fn(), + nativeSave: vi.fn(), + confirm: vi.fn(), })); vi.mock("@/platform/ipc", async (importOriginal) => { @@ -16,9 +18,10 @@ vi.mock("@/platform/ipc", async (importOriginal) => { commands: { ...real.commands, fsReadDir: mocks.readDir, fsEntryKind: mocks.entryKind }, }; }); -vi.mock("@tauri-apps/plugin-dialog", () => ({ open: mocks.nativeOpen, save: vi.fn() })); +vi.mock("@tauri-apps/plugin-dialog", () => ({ open: mocks.nativeOpen, save: mocks.nativeSave })); +vi.mock("./messages", async (original) => ({ ...(await original()), confirm: mocks.confirm })); -import { choosePath } from "@/platform/choosePath"; +import { choosePath, choosePaths, chooseSavePath } from "@/platform/choosePath"; import { useRemote } from "@/platform/remote"; import { InputDialogsHost, parentPath } from "./inputDialogs"; @@ -26,6 +29,8 @@ const tree: Record = { "/srv/app": [ ["runner", "dir"], ["pom.xml", "file"], + ["build.xml", "file"], + ["README.txt", "file"], ], "/srv/app/runner": [ ["plugins", "dir"], @@ -119,6 +124,58 @@ describe("choosePath in a remote window", () => { fireEvent.click(dialog().getByRole("button", { name: "Cancel" })); await expect(result).resolves.toBeNull(); }); + + it("selects multiple matching files on the host", async () => { + let result!: Promise; + act(() => { + result = choosePaths({ + directory: false, + title: "Add Maven Projects", + defaultPath: "/srv/app", + filters: [{ name: "XML", extensions: ["xml"] }], + }); + }); + fireEvent.click(await dialog().findByRole("checkbox", { name: "pom.xml" })); + fireEvent.click(dialog().getByRole("checkbox", { name: "build.xml" })); + expect(dialog().queryByText("README.txt")).toBeNull(); + fireEvent.click(dialog().getByRole("button", { name: "OK" })); + await expect(result).resolves.toEqual(["/srv/app/pom.xml", "/srv/app/build.xml"]); + expect(mocks.nativeOpen).not.toHaveBeenCalled(); + }); + + it("keeps a proposed name while browsing to a new save destination", async () => { + let result!: Promise; + act(() => { + result = chooseSavePath({ title: "Save As", defaultPath: "/srv/app/new.txt" }); + }); + await dialog().findByText("runner"); + expect(dialog().getByRole("textbox")).toHaveValue("/srv/app/new.txt"); + fireEvent.click(dialog().getByText("runner"), { detail: 2 }); + await dialog().findByText("plugins"); + expect(dialog().getByRole("textbox")).toHaveValue("/srv/app/runner/new.txt"); + fireEvent.click(dialog().getByRole("button", { name: "OK" })); + await expect(result).resolves.toBe("/srv/app/runner/new.txt"); + expect(mocks.nativeSave).not.toHaveBeenCalled(); + expect(mocks.confirm).not.toHaveBeenCalled(); + }); + + it("asks before accepting an existing save destination", async () => { + mocks.confirm.mockResolvedValueOnce(false).mockResolvedValueOnce(true); + let result!: Promise; + act(() => { + result = chooseSavePath({ title: "Save As", defaultPath: "/srv/app/pom.xml" }); + }); + await dialog().findByText("runner"); + const ok = dialog().getByRole("button", { name: "OK" }); + fireEvent.click(ok); + await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(ok).toBeEnabled()); + fireEvent.click(ok); + await expect(result).resolves.toBe("/srv/app/pom.xml"); + expect(mocks.confirm).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining("pom.xml") }), + ); + }); }); describe("parentPath", () => { @@ -127,8 +184,10 @@ describe("parentPath", () => { expect(parentPath("/srv")).toBe("/"); expect(parentPath("/")).toBeNull(); expect(parentPath("C:\\Users\\me")).toBe("C:\\Users"); + expect(parentPath("C:/Users\\me")).toBe("C:/Users"); expect(parentPath("C:\\Users")).toBe("C:\\"); expect(parentPath("C:\\")).toBeNull(); expect(parentPath("/srv/app/")).toBe("/srv"); + expect(parentPath("/srv/app/file\\name")).toBe("/srv/app"); }); });