diff --git a/packages/app/src/composer/attachments/attachments.ts b/packages/app/src/composer/attachments/attachments.ts index 6547a9aed3de..de2bc08badab 100644 --- a/packages/app/src/composer/attachments/attachments.ts +++ b/packages/app/src/composer/attachments/attachments.ts @@ -1,6 +1,7 @@ import { onCleanup, onMount } from "solid-js" import { makeEventListener } from "@solid-primitives/event-listener" import { createBlobReference } from "@/runtime/persistence/drafts" +import { dragOutText, draggingOut } from "@/runtime/platform/drag-out" import { uuid } from "@opencode/util/uuid" import type { ComposerPrompt } from "../types" import type { ImageAttachmentPart, PathAttachmentPart } from "../state" @@ -212,7 +213,10 @@ export function createComposerAttachments( if (input.isDialogActive()) return event.preventDefault() clearDrag() - const plainText = event.dataTransfer?.getData("text/plain") + + const plainText = + event.dataTransfer?.getData("text/plain") || + dragOutText(Array.from(event.dataTransfer?.files ?? []).map((file) => input.getPathForFile?.(file) ?? "")) if (plainText?.startsWith("file:")) { const path = plainText.slice("file:".length) @@ -270,6 +274,8 @@ export function createComposerAttachments( // Files from the system and file rows from the workspace tree (which also carry a file URL) drop as attachments. // A text selection carries neither, so dragging it shows no dropzone. function dragType(data: DataTransfer | null) { + if (draggingOut()) return "@mention" + if (data?.types.includes("Files")) return "image" if (data?.types.includes("text/uri-list")) return "@mention" diff --git a/packages/app/src/runtime/platform/drag-out.test.ts b/packages/app/src/runtime/platform/drag-out.test.ts new file mode 100644 index 000000000000..7f24c99ae5fb --- /dev/null +++ b/packages/app/src/runtime/platform/drag-out.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, test } from "bun:test" +import { dragOutText, draggingOut, startDragOut } from "./drag-out" + +const path = "C:\\repo\\src\\index.ts" + +// A file row inside a shadow root, as the file tree renders it, whose `dragstart` is handled on the host outside it. +function rowDrag(platform: Parameters[0]) { + const host = document.createElement("div") + const row = document.createElement("button") + host.attachShadow({ mode: "open" }).append(row) + document.body.append(host) + const handled = { started: false, event: undefined as DragEvent | undefined } + host.addEventListener("dragstart", (event) => { + handled.event = event + handled.started = startDragOut(platform, event, path) + }) + + const dataTransfer = new DataTransfer() + dataTransfer.setData("text/plain", "file:src/index.ts") + const event = new DragEvent("dragstart", { dataTransfer, bubbles: true, composed: true, cancelable: true }) + // happy-dom drops `dataTransfer` from the init dictionary; a browser keeps it. + Object.defineProperty(event, "dataTransfer", { value: dataTransfer }) + row.dispatchEvent(event) + + return { ...handled, row } +} + +describe("drag out", () => { + test("a drop of the dragged-out file reads as the row's drag until the system drag ends, which ends the row's drag", async () => { + const ended = Promise.withResolvers() + const drag = rowDrag({ startFileDrag: () => ended.promise }) + const ends: string[] = [] + drag.row.addEventListener("dragend", () => ends.push("row")) + window.addEventListener("dragend", () => ends.push("window"), { once: true }) + + expect(drag.started).toBe(true) + expect(drag.event?.defaultPrevented).toBe(true) + expect(draggingOut()).toBe(true) + expect(dragOutText([path])).toBe("file:src/index.ts") + // Windows paths ignore case and take either separator. + expect(dragOutText(["c:/repo/src/INDEX.ts"])).toBe("file:src/index.ts") + expect(dragOutText(["C:\\repo\\other.ts"])).toBeUndefined() + expect(dragOutText([path, "C:\\repo\\other.ts"])).toBeUndefined() + + ended.resolve(true) + await ended.promise + await Promise.resolve() + + expect(draggingOut()).toBe(false) + expect(dragOutText([path])).toBeUndefined() + expect(ends).toEqual(["row", "window"]) + }) + + test("without a system drag the row keeps its own drag", () => { + const drag = rowDrag({}) + + expect(drag.started).toBe(false) + expect(drag.event?.defaultPrevented).toBe(false) + expect(draggingOut()).toBe(false) + }) +}) diff --git a/packages/app/src/runtime/platform/drag-out.ts b/packages/app/src/runtime/platform/drag-out.ts new file mode 100644 index 000000000000..cbcffcf13d3e --- /dev/null +++ b/packages/app/src/runtime/platform/drag-out.ts @@ -0,0 +1,53 @@ +import type { Platform } from "./platform" + +type DragOut = { readonly path: string; readonly text: string } + +type DragOutState = { current: DragOut | undefined } + +// The file drag handed to the system, with the `text/plain` the app's own drag carried, until the drag ends. A drop +// back into the app then reads as that drag did, not as a file from another app. +const state: DragOutState = { current: undefined } + +/** + * Hands a file row's `dragstart` to the system's drag, so the file drops into other apps as the file itself. False + * when the platform has no system drag; the event's own drag goes on then. When the system drag ends, the row gets + * the `dragend` its cancelled drag never fired, so whatever started dragging it can finish. + */ +export function startDragOut(platform: Pick, event: DragEvent, path: string) { + if (!platform.startFileDrag || !event.dataTransfer) return false + const drag = { path, text: event.dataTransfer.getData("text/plain") } + // The row may sit in a shadow root (the file tree's does), where `target` is retargeted to its host. + const source = event.composedPath()[0] ?? event.target + event.preventDefault() + state.current = drag + + const end = () => { + if (state.current === drag) state.current = undefined + source?.dispatchEvent(new DragEvent("dragend", { bubbles: true, composed: true })) + } + + void platform.startFileDrag(path).then(end, end) + + return true +} + +/** Whether a drag handed to the system is under way. */ +export function draggingOut() { + return state.current !== undefined +} + +/** The text the app's own drag carried, when the dropped files are the drag handed to the system. */ +export function dragOutText(paths: readonly string[]) { + const drag = state.current + + if (!drag || paths.length !== 1 || !sameFile(paths[0] ?? "", drag.path)) return + + return drag.text +} + +// The system drag is Windows-only, where paths ignore case, take either separator and may end in one. +function sameFile(a: string, b: string) { + const key = (value: string) => value.replaceAll("/", "\\").replace(/\\+$/, "").toLowerCase() + + return key(a) === key(b) +} diff --git a/packages/app/src/runtime/platform/platform.tsx b/packages/app/src/runtime/platform/platform.tsx index d0a8b168f6cb..a324ae4b0c9f 100644 --- a/packages/app/src/runtime/platform/platform.tsx +++ b/packages/app/src/runtime/platform/platform.tsx @@ -69,6 +69,12 @@ type PlatformBase = { /** Resolve the native source path for a desktop File. */ getPathForFile?(file: File): string + /** + * Start a system drag of a local file, so it drops into other apps as the file itself (Windows desktop only). + * Resolves once the drag ends; false when none started. + */ + startFileDrag?(path: string): Promise + /** Observe native drag cancellation that does not reach the renderer event loop. */ onDragCancel?(callback: () => void): () => void diff --git a/packages/app/src/runtime/plugin/host-apis.tsx b/packages/app/src/runtime/plugin/host-apis.tsx index 4c377ba13a50..7fd232817020 100644 --- a/packages/app/src/runtime/plugin/host-apis.tsx +++ b/packages/app/src/runtime/plugin/host-apis.tsx @@ -37,6 +37,7 @@ import { } from "@opencode/plugin/gui" import { BuiltinPanel, BuiltinPromptGate, type BuiltinOpenOptions, type BuiltinStoreFrom, type BuiltinStoreOptions } from "@opencode/plugin/gui/builtin" import { usePlatform } from "@/runtime/platform/platform" +import { startDragOut } from "@/runtime/platform/drag-out" import { same } from "@/runtime/persistence/equality" import { Persist, persisted, removePersisted } from "@/runtime/persistence/storage" import { useGlobal, type ServerCtx } from "@/runtime/server/runtime" @@ -327,6 +328,7 @@ export function createHostApis() { reveal: (path) => platform.revealPath?.(path) ?? Promise.resolve(false), installed: (app) => platform.checkAppExists?.(app) ?? Promise.resolve(false), forceFocus: (enabled) => platform.setForceFocus?.(enabled) ?? Promise.resolve(), + dragOut: (event, path) => startDragOut(platform, event, path), async pick(options) { if (options?.directory) { const picked = await platform.openDirectoryPickerDialog({ diff --git a/packages/desktop/src/main/files/index.ts b/packages/desktop/src/main/files/index.ts index 8cd3ee661871..bc1ec2e8ee71 100644 --- a/packages/desktop/src/main/files/index.ts +++ b/packages/desktop/src/main/files/index.ts @@ -186,6 +186,22 @@ function make( return true }), + // Windows runs the drag in a nested loop, so this returns once the file was dropped or the drag was cancelled. + startDrag: Effect.fn("DesktopFiles.startDrag")(function* (contents: Electron.WebContents, target: string) { + if (process.platform !== "win32" || !path.isAbsolute(target)) return false + const exists = yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false)) + + if (!exists) return false + + const icon = yield* Effect.promise(() => + app.getFileIcon(target, { size: "normal" }).catch(() => nativeImage.createEmpty()), + ) + + if (contents.isDestroyed()) return false + contents.startDrag({ file: target, icon }) + + return true + }), readClipboardImage: Effect.fn("DesktopFiles.readClipboardImage")(function* () { const items = yield* Effect.promise(() => clipboard.read()) diff --git a/packages/desktop/src/main/ipc-handlers/files.ts b/packages/desktop/src/main/ipc-handlers/files.ts index 7b0840b324bd..947508fe4fb9 100644 --- a/packages/desktop/src/main/ipc-handlers/files.ts +++ b/packages/desktop/src/main/ipc-handlers/files.ts @@ -33,6 +33,7 @@ export const fileHandlers = FileRpcs.toLayer( Effect.orDie, ), FilesRevealPath: ({ path }) => files.revealPath(path), + FilesStartDrag: ({ path }, context) => files.startDrag(sender(handoff, context), path), FilesReadClipboardImage: () => files.readClipboardImage(), FilesWriteClipboardText: ({ text }) => files.writeClipboardText(text), }) diff --git a/packages/desktop/src/renderer/api-types.ts b/packages/desktop/src/renderer/api-types.ts index 4d142497d3dc..3e3f6354302a 100644 --- a/packages/desktop/src/renderer/api-types.ts +++ b/packages/desktop/src/renderer/api-types.ts @@ -52,6 +52,7 @@ export type ElectronAPI = { openBrowser(url: string): Promise openPath(path: string, app?: string): Promise revealPath(path: string): Promise + startFileDrag(path: string): Promise readClipboardImage(): Promise writeClipboardText(text: string): Promise getWindowFocused(): Promise diff --git a/packages/desktop/src/renderer/api.ts b/packages/desktop/src/renderer/api.ts index 25e65ac4d7e7..52f54efdd68f 100644 --- a/packages/desktop/src/renderer/api.ts +++ b/packages/desktop/src/renderer/api.ts @@ -56,6 +56,7 @@ export const api: ElectronAPI = { openBrowser: (url) => invoke("FilesOpenBrowser", { url }), openPath: (path, app) => invoke("FilesOpenPath", { path, application: app }).then((value) => value ?? undefined), revealPath: (path) => invoke("FilesRevealPath", { path }), + startFileDrag: (path) => invoke("FilesStartDrag", { path }), readClipboardImage: () => invoke("FilesReadClipboardImage").then((image) => image ? { ...image, buffer: toArrayBuffer(image.buffer) } : null, diff --git a/packages/desktop/src/renderer/platform/files.ts b/packages/desktop/src/renderer/platform/files.ts index 36635a7da7e2..c996b8d3e323 100644 --- a/packages/desktop/src/renderer/platform/files.ts +++ b/packages/desktop/src/renderer/platform/files.ts @@ -16,6 +16,7 @@ type DesktopFileAPI = Pick< | "resolveAppPath" | "openPath" | "revealPath" + | "startFileDrag" | "readClipboardImage" | "writeClipboardText" > @@ -89,6 +90,8 @@ export function createDesktopFiles(api: DesktopFileAPI, os: DesktopOS) { async revealPath(path: string) { return api.revealPath(path) }, + // Only Windows hands a file row's drag to the system, so macOS and Linux keep the page's own drag. + startFileDrag: os === "windows" ? (path: string) => api.startFileDrag(path) : undefined, async readClipboardImage() { const image = await api.readClipboardImage().catch(() => null) diff --git a/packages/desktop/src/shared/ipc-rpc/files.ts b/packages/desktop/src/shared/ipc-rpc/files.ts index ea535d6a3aa5..ce0275433b28 100644 --- a/packages/desktop/src/shared/ipc-rpc/files.ts +++ b/packages/desktop/src/shared/ipc-rpc/files.ts @@ -69,6 +69,13 @@ export const FilesRevealPath = Rpc.make("FilesRevealPath", { success: Schema.Boolean, }) +// Starts a Windows system drag of a local file for a renderer that cancelled its own `dragstart`. Answers once the drag +// ends; false when none started. +export const FilesStartDrag = Rpc.make("FilesStartDrag", { + payload: { path: Schema.String }, + success: Schema.Boolean, +}) + export const FilesReadClipboardImage = Rpc.make("FilesReadClipboardImage", { success: Schema.NullOr(ClipboardImage), }) @@ -87,6 +94,7 @@ export const FileRpcs = RpcGroup.make( FilesOpenBrowser, FilesOpenPath, FilesRevealPath, + FilesStartDrag, FilesReadClipboardImage, FilesWriteClipboardText, ) diff --git a/packages/gui-plugins/src/file/pierre-tree.tsx b/packages/gui-plugins/src/file/pierre-tree.tsx index 713ba02abb72..7542519e3f62 100644 --- a/packages/gui-plugins/src/file/pierre-tree.tsx +++ b/packages/gui-plugins/src/file/pierre-tree.tsx @@ -2,6 +2,7 @@ import "@pierre/trees/web-components" import { FileTree, type FileTreeDirectoryHandle, type FileTreeItemHandle } from "@pierre/trees" import { getIcon } from "@opencode/ui/icons/catalog" import { createMemo, createSignal, onCleanup, onMount, untrack } from "solid-js" +import { builtinContext } from "@opencode/plugin/gui/builtin" import type { ChangeKind } from "@opencode/plugin/gui/review" import { createKeyed, usePlugin, type FileNode, type MountedSession, type SessionScreen } from "@opencode/plugin/gui" import { startFileDrag } from "./drag" @@ -488,7 +489,13 @@ export default function PierreFileTree(props: { if (!draggable()) return const button = findTreeItemButton(event) - if (button?.dataset.itemPath) startFileDrag(event, pierreTreeOriginalPath(machine(), button.dataset.itemPath)) + if (!button?.dataset.itemPath) return + startFileDrag(event, pierreTreeOriginalPath(machine(), button.dataset.itemPath)) + + // A file of this computer drags out to other apps as the file itself. + if (!openIn?.canOpen()) return + const node = pierreTreeFileNode(machine(), button.dataset.itemPath) + builtinContext(ctx).desktop?.dragOut(event, resolveOpenInAppPath(file.root, node.absolute || node.path)) }} /> diff --git a/packages/plugin/src/gui/builtin.ts b/packages/plugin/src/gui/builtin.ts index 1a4aa1d87cc2..28cc60085e9a 100644 --- a/packages/plugin/src/gui/builtin.ts +++ b/packages/plugin/src/gui/builtin.ts @@ -312,6 +312,18 @@ export interface BuiltinDesktop extends Desktop { * @param enabled - Turns it on or off. */ forceFocus(enabled: boolean): Promise + /** + * Hands a file row's drag to the system, so the file drops into other apps (a file manager, a browser, a chat app) + * as the file itself. Call it from `dragstart` after setting the drag's data: a drop back into the app reads as + * that data, as the row's own drag would. The host cancels the event's drag when it hands it over; when the file is + * gone by then, nothing is dragged. When the system drag ends, the event's target gets the `dragend` its cancelled drag + * never fired. Windows desktop only: returns false elsewhere, and the event's own drag goes on. + * + * @param event - The row's `dragstart`. + * @param path - The file's absolute path on this computer. + * @returns Whether the system drag started in place of the event's. + */ + dragOut(event: DragEvent, path: string): boolean } /** `OpenOptions` with the placement only built-ins use. */