The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.
TypeScript code-editorcross-platformdapdatabase-clientdebuggerdesktop-appdeveloper-toolsgithttp-clientideintellijlsprusttauriterminal
fix(workbench): Open files dropped from the OS in the editor (#142)
l0ng-ai66c36a73611b
diff --git a/src/features/agents/Composer.tsx b/src/features/agents/Composer.tsxindex 287759354..a04c25099 100644--- a/src/features/agents/Composer.tsx+++ b/src/features/agents/Composer.tsx@@ -9,7 +9,7 @@ import type { AgentCommand, AgentConfigOption, AgentImage } from "@/bindings";import { call, commands, isTauri } from "@/platform/ipc";import { useTx } from "@/platform/i18n";import { basename } from "@/platform/project";-import { notifications } from "@/workbench/contributions";+import { notifications, OWNS_FILE_DROP } from "@/workbench/contributions";import { Icon, IconButton, fileIconName } from "@/ui";import {IMAGE_EXTENSIONS,@@ -275,7 +275,12 @@ export function Composer(props: ComposerProps) {};return (- <div ref={boxRef} className={clsx(styles.composer, props.className)} onClick={() => ref.current?.focus()}>+ <div+ ref={boxRef}+ className={clsx(styles.composer, props.className)}+ {...OWNS_FILE_DROP}+ onClick={() => ref.current?.focus()}+ >{open && (<div className={styles.popup} role="listbox" aria-label={tx(completion.kind === "file" ? "Files" : "Commands")}>{items.map((item, i) => (diff --git a/src/features/project-tree/ProjectView.tsx b/src/features/project-tree/ProjectView.tsxindex a0bf123ab..87b8b8bb3 100644--- a/src/features/project-tree/ProjectView.tsx+++ b/src/features/project-tree/ProjectView.tsx@@ -26,7 +26,7 @@ import { isTauri } from "@/platform/ipc";import type { RootFolder } from "@/platform/languageSettings";import { useEffectiveRoots } from "@/platform/projectRoots";import { macStroke, strokeOf } from "@/platform/keymap";-import { prepareMenuGroups, useFileDecoration } from "@/workbench/contributions";+import { OWNS_FILE_DROP, prepareMenuGroups, useFileDecoration } from "@/workbench/contributions";import {FILES_DRAG,HighlightedText,@@ -630,6 +630,7 @@ export function ProjectView() {<divref={containerRef}className={styles.view}+ {...OWNS_FILE_DROP}onKeyDown={onKeyDown}// The native Edit menu may take ⌘C/⌘X/⌘V before the keymap sees them; it then sends DOM clipboard events.onCopy={(e) => onClipboard(e, "project.copy")}diff --git a/src/workbench/activate.ts b/src/workbench/activate.tsindex ed1c3bf56..2c109e83c 100644--- a/src/workbench/activate.ts+++ b/src/workbench/activate.ts@@ -13,6 +13,7 @@ import {} from "./contributions";import { installBrowserGuards } from "./browserGuards";import { installDistractionFree } from "./distractionFree";+import { installFileDrop } from "./fileDrop";import { installFocusTracking } from "./focus";import { clearNotifications, installNotifyEvents, notificationServiceImpl } from "./notificationStore";import {@@ -62,6 +63,7 @@ export function activateWorkbench(): () => void {installTaskEvents(),installNotifyEvents(),installBrowserGuards(),+ installFileDrop(),registerOverlay({ id: "workbench.customizeToolbar", component: MainToolbarDialogHost }),registerStatusItem({ id: "workbench.tasks", align: "right", priority: 0, component: TaskStatus }),registerStatusItem({ id: "workbench.info", align: "left", priority: 5, component: StatusInfo }),diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.tsindex ff8d4e2f7..713796a4f 100644--- a/src/workbench/contributions.ts+++ b/src/workbench/contributions.ts@@ -368,6 +368,13 @@ export function textEditorWrapperFor(return undefined;}+/**+ * Spread on an element that handles files dropped from the OS itself (copy into+ * a folder, attach to a prompt); the window-wide drop (open in the editor)+ * leaves drops over it alone.+ */+export const OWNS_FILE_DROP = { "data-owns-file-drop": "" } as const;+// ---------------------------------------------------------------------------// Services implemented by one feature and consumed by others. The provider// calls `provide*` during activation; consumers call through the accessor.diff --git a/src/workbench/fileDrop.test.ts b/src/workbench/fileDrop.test.tsnew file mode 100644index 000000000..5059827be--- /dev/null+++ b/src/workbench/fileDrop.test.ts@@ -0,0 +1,94 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useProject } from "@/platform/project";+import { useRemote } from "@/platform/remote";+import type { RemoteSession } from "@/platform/ipc";+import { handleFileDrop, type FileDropDeps } from "./fileDrop";++function deps(dirs: string[] = []) {+ const calls: string[] = [];+ const d: FileDropDeps = {+ isDir: async (p) => dirs.includes(p),+ openFile: async (p, focus) => void calls.push(`file ${p}${focus ? " (focus)" : ""}`),+ openProject: async (p) => void calls.push(`project ${p}`),+ };+ return { d, calls };+}++/** A window with the editor, a Project view (owns drops) with a row, and the prompt box (owns drops). */+function mountWindow() {+ document.body.innerHTML = `+ <main id="editor"><div id="tabs"></div></main>+ <div id="project" data-owns-file-drop><div id="row"><span>src</span></div></div>+ <div id="composer" data-owns-file-drop><textarea id="prompt"></textarea></div>`;+ const at: Record<string, string> = { "1,1": "tabs", "2,2": "row", "3,3": "prompt", "4,4": "project" };+ document.elementFromPoint = (x: number, y: number) => {+ const id = at[`${x},${y}`];+ return id ? document.getElementById(id) : null;+ };+}++describe("files dropped from the OS", () => {+ beforeEach(() => {+ mountWindow();+ useProject.setState({ project: { root: "/p", name: "p" } } as never);+ });+ afterEach(() => {+ useProject.setState({ project: null } as never);+ useRemote.setState({ session: null });+ document.body.innerHTML = "";+ });++ it("opens each dropped file in its own tab, focusing the last; works for files outside the project", async () => {+ const { d, calls } = deps();+ await handleFileDrop(["/p/a.ts", "/elsewhere/notes.md"], 1, 1, d);+ expect(calls).toEqual(["file /p/a.ts", "file /elsewhere/notes.md (focus)"]);+ });++ it("opens a dropped folder as a project, after the files", async () => {+ const { d, calls } = deps(["/work/other", "/work/third"]);+ await handleFileDrop(["/work/other", "/x/readme.txt", "/work/third"], 1, 1, d);+ expect(calls).toEqual(["file /x/readme.txt (focus)", "project /work/other"]);+ });++ it("opens a path it cannot classify as a file", async () => {+ const { d, calls } = deps();+ d.isDir = () => Promise.reject(new Error("gone"));+ await handleFileDrop(["/gone.txt"], 1, 1, d);+ expect(calls).toEqual(["file /gone.txt (focus)"]);+ });++ it("keeps opening the rest when one file fails", async () => {+ vi.spyOn(console, "warn").mockImplementation(() => {});+ const { d, calls } = deps();+ const open = d.openFile;+ d.openFile = (p, f) => (p === "/bad" ? Promise.reject(new Error("denied")) : open(p, f));+ await handleFileDrop(["/bad", "/good"], 1, 1, d);+ expect(calls).toEqual(["file /good (focus)"]);+ });++ it.each([+ ["a Project view row", 2, 2],+ ["the Project view background", 4, 4],+ ["the prompt box", 3, 3],+ ])("leaves drops over %s to that region", (_, x, y) => {+ const { d, calls } = deps(["/dir"]);+ expect(handleFileDrop(["/a.ts", "/dir"], x, y, d)).toBeNull();+ expect(calls).toEqual([]);+ });++ it("acts on drops outside any element (window chrome)", async () => {+ const { d, calls } = deps();+ await handleFileDrop(["/a.ts"], 9, 9, d);+ expect(calls).toEqual(["file /a.ts (focus)"]);+ });++ it("leaves drops to the Welcome screen when no project is open, and ignores remote windows", () => {+ const { d } = deps();+ useProject.setState({ project: null } as never);+ expect(handleFileDrop(["/a.ts"], 1, 1, d)).toBeNull();+ useProject.setState({ project: { root: "/p", name: "p" } } as never);+ useRemote.setState({ session: {} as RemoteSession });+ expect(handleFileDrop(["/a.ts"], 1, 1, d)).toBeNull();+ expect(handleFileDrop([], 1, 1, d)).toBeNull();+ });+});diff --git a/src/workbench/fileDrop.ts b/src/workbench/fileDrop.tsnew file mode 100644index 000000000..58c20f3a7--- /dev/null+++ b/src/workbench/fileDrop.ts@@ -0,0 +1,74 @@+/**+ * Files dropped from the OS onto the project window open in the editor, one+ * tab each; a dropped folder opens as a project (the "Open project in" policy+ * applies). Regions marked with `OWNS_FILE_DROP` (Project view, prompt box)+ * handle their drops themselves.+ */+import { executeAction } from "@/platform/actions";+import { call, commands, isTauri } from "@/platform/ipc";+import { useProject } from "@/platform/project";+import { isRemoteWindow } from "@/platform/remote";+import { editorService, OWNS_FILE_DROP } from "./contributions";++const OWNER_ATTR = Object.keys(OWNS_FILE_DROP)[0]!;++export interface FileDropDeps {+ isDir(path: string): Promise<boolean>;+ openFile(path: string, focus: boolean): Promise<void>;+ openProject(path: string): Promise<void>;+}++/** Whether a drop at CSS pixel (x, y) lands on a region that handles OS drops itself. */+export function dropOwnedAt(x: number, y: number): boolean {+ return !!document.elementFromPoint(x, y)?.closest(`[${OWNER_ATTR}]`);+}++/** Opens the dropped files (the last one focused), then the first dropped folder as a project. */+export async function openDropped(paths: readonly string[], deps: FileDropDeps): Promise<void> {+ const kinds = await Promise.all(paths.map((p) => deps.isDir(p).catch(() => false)));+ const files = paths.filter((_, i) => !kinds[i]);+ const dir = paths.find((_, i) => kinds[i]);+ for (const [i, path] of files.entries())+ await deps.openFile(path, i === files.length - 1).catch((e) => console.warn(`could not open ${path}`, e));+ if (dir) await deps.openProject(dir);+}++const defaultDeps: FileDropDeps = {+ isDir: (path) => call(commands.fsReadDir(path)).then(() => true),+ openFile: (path, focus) => editorService().openFile(path, { focus }),+ openProject: async (path) => void (await executeAction("file.openProjectPath", path)),+};++/** Handles one drop; null when it is left to another handler (no local project: the Welcome screen). */+export function handleFileDrop(+ paths: readonly string[],+ x: number,+ y: number,+ deps: FileDropDeps = defaultDeps,+): Promise<void> | null {+ if (!paths.length || !useProject.getState().project || isRemoteWindow() || dropOwnedAt(x, y)) return null;+ return openDropped(paths, deps);+}++export function installFileDrop(): () => void {+ if (!isTauri()) return () => {};+ let unlisten: (() => void) | undefined;+ let disposed = false;+ void import("@tauri-apps/api/webview").then(({ getCurrentWebview }) =>+ getCurrentWebview()+ .onDragDropEvent((event) => {+ const p = event.payload;+ if (p.type !== "drop") return;+ const ratio = window.devicePixelRatio || 1;+ void handleFileDrop(p.paths, p.position.x / ratio, p.position.y / ratio);+ })+ .then((u) => {+ if (disposed) u();+ else unlisten = u;+ }),+ );+ return () => {+ disposed = true;+ unlisten?.();+ };+}