Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion packages/app/src/composer/attachments/attachments.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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"
Expand Down
52 changes: 52 additions & 0 deletions packages/app/src/runtime/platform/drag-out.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { describe, expect, test } from "bun:test"
import { dragOutText, draggingOut, startDragOut } from "./drag-out"

const path = "C:\\repo\\src\\index.ts"

function rowDrag(row = document.createElement("button")) {
const dataTransfer = new DataTransfer()
dataTransfer.setData("text/plain", "file:src/index.ts")

const event = new DragEvent("dragstart", { dataTransfer, cancelable: true })
// happy-dom drops `dataTransfer` from the init dictionary; a browser keeps it.
Object.defineProperty(event, "dataTransfer", { value: dataTransfer })

row.dispatchEvent(event)

return event
}

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<boolean>()
const row = document.createElement("button")
const ends: string[] = []
row.addEventListener("dragend", (end) => ends.push(end.type))
const event = rowDrag(row)

expect(startDragOut({ startFileDrag: () => ended.promise }, event, path)).toBe(true)
expect(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(["dragend"])
})

test("without a system drag the row keeps its own drag", () => {
const event = rowDrag()

expect(startDragOut({}, event, path)).toBe(false)
expect(event.defaultPrevented).toBe(false)
expect(draggingOut()).toBe(false)
})
})
52 changes: 52 additions & 0 deletions packages/app/src/runtime/platform/drag-out.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
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<Platform, "startFileDrag">, event: DragEvent, path: string) {
if (!platform.startFileDrag || !event.dataTransfer) return false
const drag = { path, text: event.dataTransfer.getData("text/plain") }
const source = event.target
event.preventDefault()
state.current = drag

const end = () => {
if (state.current === drag) state.current = undefined
source?.dispatchEvent(new DragEvent("dragend", { bubbles: 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 and take either separator.
function sameFile(a: string, b: string) {
const key = (value: string) => value.replaceAll("/", "\\").toLowerCase()

return key(a) === key(b)
}
6 changes: 6 additions & 0 deletions packages/app/src/runtime/platform/platform.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean>

/** Observe native drag cancellation that does not reach the renderer event loop. */
onDragCancel?(callback: () => void): () => void

Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/runtime/plugin/host-apis.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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({
Expand Down
16 changes: 16 additions & 0 deletions packages/desktop/src/main/files/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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())

Expand Down
1 change: 1 addition & 0 deletions packages/desktop/src/main/ipc-handlers/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
})
Expand Down
1 change: 1 addition & 0 deletions packages/desktop/src/renderer/api-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export type ElectronAPI = {
openBrowser(url: string): Promise<boolean>
openPath(path: string, app?: string): Promise<string | undefined>
revealPath(path: string): Promise<boolean>
startFileDrag(path: string): Promise<boolean>
readClipboardImage(): Promise<ClipboardImage | null>
writeClipboardText(text: string): Promise<void>
getWindowFocused(): Promise<boolean>
Expand Down
1 change: 1 addition & 0 deletions packages/desktop/src/renderer/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions packages/desktop/src/renderer/platform/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type DesktopFileAPI = Pick<
| "resolveAppPath"
| "openPath"
| "revealPath"
| "startFileDrag"
| "readClipboardImage"
| "writeClipboardText"
>
Expand Down Expand Up @@ -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)

Expand Down
8 changes: 8 additions & 0 deletions packages/desktop/src/shared/ipc-rpc/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
})
Expand All @@ -87,6 +94,7 @@ export const FileRpcs = RpcGroup.make(
FilesOpenBrowser,
FilesOpenPath,
FilesRevealPath,
FilesStartDrag,
FilesReadClipboardImage,
FilesWriteClipboardText,
)
9 changes: 8 additions & 1 deletion packages/gui-plugins/src/file/pierre-tree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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))
Comment thread
Hona marked this conversation as resolved.
Resolved
}}
/>
</OpenInAppContextMenuV2>
Expand Down
12 changes: 12 additions & 0 deletions packages/plugin/src/gui/builtin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,18 @@ export interface BuiltinDesktop extends Desktop {
* @param enabled - Turns it on or off.
*/
forceFocus(enabled: boolean): Promise<void>
/**
* 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. */
Expand Down
Loading