From 46b3a0bbc9133ce21d4ef8a4b7f4f664bb7361fc Mon Sep 17 00:00:00 2001 From: faysou Date: Tue, 24 Nov 2026 19:40:24 +0000 Subject: [PATCH] feat(plugins): support ranged reads in binary web editors (#4914) A web custom editor declared with `binary = true` (API 1.16, web page with `layout = "tab"`) opens a file without creating a text document. Its page reads the file's size with `document.size()` and byte ranges of at most 1 MiB with `document.readRange(offset, length)`, so large binary formats such as Parquet can be read piece by piece. The path is always the editor's own file, never one the page supplies, and messages from the page to the plugin's code carry that file as the editor context. The manifest field is rejected below API 1.16 and only allowed on tab-layout web editors; the docs and the API 1.16 notes list the new bridge methods. Co-authored-by: faysou <893862+faysou@users.noreply.github.com> --- crates/ide-host/src/plugins/ui_points.rs | 42 +++++++++++++ docs/en/plugins/guides/views.mdx | 9 +++ docs/zh/plugins/guides/views.mdx | 6 ++ plugins/README.md | 6 +- .../plugins/__tests__/webViews.test.tsx | 60 +++++++++++++++++-- src/features/plugins/backend.ts | 14 ++++- src/features/plugins/views/WebView.tsx | 35 ++++++++++- src/features/plugins/views/customEditor.tsx | 40 ++++++++++++- src/features/plugins/views/frame-bridge.js | 2 + 9 files changed, 201 insertions(+), 13 deletions(-) diff --git a/crates/ide-host/src/plugins/ui_points.rs b/crates/ide-host/src/plugins/ui_points.rs index 069b82ca16..1824ba670d 100644 --- a/crates/ide-host/src/plugins/ui_points.rs +++ b/crates/ide-host/src/plugins/ui_points.rs @@ -798,6 +798,8 @@ struct CustomEditorDecl { /// Origins the web page may embed (API 1.16). #[serde(default, skip_serializing_if = "Vec::is_empty")] frames: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + binary: Option, } fn default_priority() -> String { @@ -835,6 +837,12 @@ pub(super) fn custom_editor(pkg: &Package, decl: toml::Value) -> Result Result< It needs `editor.read` and `editor.write`. +For large binary files, use `binary = true` on a web custom editor with +`layout = "tab"` and `engines.openidea = "^1.16"`. The IDE opens the file +without creating a text document. The page gets a read-only document with +its filename and can read the file through the web view bridge. + +Messages from a binary editor carry the open file as the editor in the plugin invocation. + ## HTML bodies `Body::Html` runs in a sandboxed frame: an opaque origin under a CSP that allows only its @@ -247,6 +254,8 @@ web = "web/index.html" # the page; its directory is what it can load | `window.openidea` | What it does | | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------- | | `document.get()` | `{ version, text, readOnly, name }` of the custom editor's document (none in a tool window) | +| `document.size()` | Size in bytes of the file open in a binary custom editor | +| `document.readRange(offset, length)` | Bytes from the open binary file as a `Uint8Array`. Each call reads at most 1 MiB and may return fewer bytes at EOF | | `document.edit(version, edits)` | Applies `[{ from, to, insert }]` (UTF-16 offsets) as one undoable change; rejects with `stale` when not at `version` | | `document.replace(version, text)` | The same with the whole text | | `document.onChange(fn)` | `{ version, text }` after changes made elsewhere (text editor, Undo, another window) | diff --git a/docs/zh/plugins/guides/views.mdx b/docs/zh/plugins/guides/views.mdx index f962378526..6ccd02da27 100644 --- a/docs/zh/plugins/guides/views.mdx +++ b/docs/zh/plugins/guides/views.mdx @@ -178,6 +178,10 @@ fn handle(&mut self, _view: &str, event: ViewEvent, ctx: &Invocation) -> Result< 它需要 `editor.read` 和 `editor.write`。 +处理大型二进制文件时,在网页自定义编辑器中设置 `binary = true`、`layout = "tab"`,并在清单中声明 +`engines.openidea = "^1.16"`。IDE 打开文件时无需创建文本文档。页面可以访问只读文档的文件名,并通过网页视图桥接 +API 分段读取文件。插件代码收到此编辑器的消息时,编辑器上下文指向当前打开的二进制文件。 + ## HTML 主体 `Body::Html` 在沙箱 frame 中运行:不透明源(opaque origin),CSP 只允许其内联脚本、内联样式和 `data:` 图片, @@ -221,6 +225,8 @@ web = "web/index.html" # 页面;它所在的目录就是它能加载的范 | `window.openidea` | 作用 | | ------------------------------------ | ------------------------------------------------------------------------------------------- | | `document.get()` | 自定义编辑器文档的 `{ version, text, readOnly, name }`(工具窗口中没有) | +| `document.size()` | 当前二进制文件的字节数 | +| `document.readRange(offset, length)` | 从当前二进制文件的字节偏移处读取最多 1 MiB,返回 `Uint8Array`;到达文件末尾时可能更短 | | `document.edit(version, edits)` | 把 `[{ from, to, insert }]`(UTF-16 偏移)作为一次可撤销修改应用;版本不符时以 `stale` 拒绝 | | `document.replace(version, text)` | 同上,但替换整个文本 | | `document.onChange(fn)` | 其他地方(文本编辑器、撤销、另一个窗口)修改后收到 `{ version, text }` | diff --git a/plugins/README.md b/plugins/README.md index 3278ce73bf..573e446bce 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -155,7 +155,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK. | `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | | `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no | | `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `frames?` (API 1.16), `group?`, `when?` (API 1.3) | without `web` | -| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?`, `frames?` (API 1.16) | without `web` | +| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?`, `frames?`, `binary?` (API 1.16) | without `web` | | `editorPanels` | `id`, `web`, `width` (pixels, 40–400), `when?`, `frames?` (API 1.16) — needs `editor.read` (API 1.9; _Editor panels_) | no | | `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no | | `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables = [{ name, prompt }]` — New menu | no | @@ -432,6 +432,10 @@ are always available. Calling a gated function without its capability returns API 1.16.0 is in development on `main`. Use `engines.openidea = "^1.16"` and the matching SDK. Plugins for 1.15 and earlier keep working. New in 1.16: +- A tab-layout web custom editor can declare `binary = true` to open a file without loading it + into a text document. Its page can call `document.size()` and `document.readRange(offset, length)` + to read up to 1 MiB at a time. Messages to the plugin carry the open file as their editor context. + - **Incomplete completion lists.** The optional `completion-list-provider` export (world `plugin-completion-list`, SDK `Providers::completion_list`, registration diff --git a/src/features/plugins/__tests__/webViews.test.tsx b/src/features/plugins/__tests__/webViews.test.tsx index 26148b8999..cf994fda31 100644 --- a/src/features/plugins/__tests__/webViews.test.tsx +++ b/src/features/plugins/__tests__/webViews.test.tsx @@ -183,19 +183,28 @@ describe("frame bridge", () => { }); describe("WebView", () => { - function setup(hasCode: boolean) { + function setup(hasCode: boolean, doc = memoryDocument("hello world"), binaryPath?: string) { const events: ViewEvent[] = []; + const viewEvent = vi.fn(async (_p: string, _v: string, e: ViewEvent) => void events.push(e)); setPluginsBackend({ ...createMemoryPluginsBackend([]), webPageUrl: async () => "about:blank", - viewEvent: vi.fn(async (_p: string, _v: string, e: ViewEvent) => void events.push(e)), + viewEvent, }); usePlugins.setState({ plugins: [{ id: "acme.draw", hasCode, enabled: true, capabilities: [] } as unknown as PluginInfo], }); - const doc = memoryDocument("hello world"); - const view = render(); - return { events, doc, view }; + const view = render( + , + ); + return { events, doc, view, viewEvent }; } async function frameOf(container: HTMLElement) { @@ -221,6 +230,47 @@ describe("WebView", () => { expect(frame.getAttribute("allow")).toBeNull(); }); + it("uses the binary editor's own path for messages to plugin code", async () => { + const { view, viewEvent } = setup(true, undefined, "/project/open.parquet"); + const { send } = await frameOf(view.container); + send({ text: "query", path: "/ignored.parquet" }); + await waitFor(() => + expect(viewEvent.mock.calls).toEqual([ + [ + "acme.draw", + "draw", + { kind: "message", text: "query" }, + null, + { path: "/project/open.parquet", language: "binary", selections: [] }, + ], + ]), + ); + }); + + it("reads only bounded ranges from a binary editor's document", async () => { + const readRange = vi.fn(async () => Uint8Array.of(80, 65, 82, 49)); + const doc = { + ...memoryDocument(""), + read: () => ({ version: 0, text: "", readOnly: true, name: "data.parquet" }), + size: async () => 536870924, + readRange, + }; + const { view } = setup(false, doc); + const { posted, send } = await frameOf(view.container); + send({ call: 1, op: "document.size" }); + send({ call: 2, op: "document.readRange", args: { offset: 536870920, length: 4, path: "/ignored" } }); + send({ call: 3, op: "document.readRange", args: { offset: 0, length: 1048577 } }); + send({ call: 4, op: "document.readRange", args: { offset: Number.MAX_SAFE_INTEGER, length: 4 } }); + send({ call: 5, op: "document.replace", args: { version: 0, text: "changed" } }); + await waitFor(() => expect(posted.filter((event) => event.reply)).toHaveLength(5)); + expect(posted.find((event) => event.reply === 1)?.value).toBe(536870924); + expect(posted.find((event) => event.reply === 2)?.value).toEqual(Uint8Array.of(80, 65, 82, 49)); + expect(posted.find((event) => event.reply === 3)?.error).toBe("invalid byte range (at most 1 MiB per read)"); + expect(posted.find((event) => event.reply === 4)?.error).toBe("invalid byte range (at most 1 MiB per read)"); + expect(posted.find((event) => event.reply === 5)?.error).toBe("the document is read-only"); + expect(readRange.mock.calls).toEqual([[536870920, 4]]); + }); + it("serves the document to the page: versioned edits, replace, stale versions, outside changes", async () => { const { view, doc } = setup(false); const { posted, send } = await frameOf(view.container); diff --git a/src/features/plugins/backend.ts b/src/features/plugins/backend.ts index f6b037fe3b..364c14a4c8 100644 --- a/src/features/plugins/backend.ts +++ b/src/features/plugins/backend.ts @@ -134,7 +134,7 @@ export interface PluginsBackend { stagePackage(name: string, files: { path: string; text: string }[]): Promise; /** Content of a plugin view (`doc`: the document of a custom editor). */ renderView(pluginId: string, view: string, viewport: Viewport | null, doc: number | null): Promise; - viewEvent(pluginId: string, view: string, event: ViewEvent, doc: number | null): Promise; + viewEvent(pluginId: string, view: string, event: ViewEvent, doc: number | null, editor?: PluginEditor): Promise; /** The detail tabs of item `key` in a Services or `detail = true` view. */ serviceDetail(pluginId: string, view: string, key: string): Promise; /** The HTTP routes a plugin reports for this window's project (`[[contributes.endpoints]]`). */ @@ -170,6 +170,7 @@ export interface PluginsBackend { openWebFile(filters: FileFilter[] | undefined): Promise<{ name: string; data: Uint8Array } | null>; /** The bytes of a file on this machine, at most 64 MiB (a web custom editor's `document.bytes`). */ readFileBytes(path: string): Promise; + readFileRange(path: string, offset: number, length: number): Promise<{ total: number; data: Uint8Array }>; /** Which of a plugin's declared secrets are stored (values never come back). */ secrets(pluginId: string): Promise; /** Stores a secret (`null` removes it). */ @@ -336,8 +337,8 @@ export const tauriPluginsBackend: PluginsBackend = { // A tool window's calls (no `doc`) carry the window's active editor. renderView: (pluginId, view, viewport, doc) => call(commands.pluginViewRender(pluginId, view, viewport, doc, doc == null ? editorContext() : null)), - viewEvent: async (pluginId, view, event, doc) => { - await call(commands.pluginViewEvent(pluginId, view, event, doc, doc == null ? editorContext() : null)); + viewEvent: async (pluginId, view, event, doc, editor) => { + await call(commands.pluginViewEvent(pluginId, view, event, doc, doc == null ? (editor ?? editorContext()) : null)); }, serviceDetail: (pluginId, view, key) => call(commands.pluginServiceDetail(pluginId, view, key)), runTargets: () => call(commands.pluginRunTargets()), @@ -374,6 +375,10 @@ export const tauriPluginsBackend: PluginsBackend = { return { name: path.split(/[\\/]/).pop() ?? path, data }; }, readFileBytes: async (path) => fromBase64(await call(commands.pluginWebReadFile(path))), + readFileRange: async (path, offset, length) => { + const { total, data } = await call(commands.fsReadRange(path, offset, length)); + return { total, data: fromBase64(data) }; + }, secrets: (pluginId) => call(commands.pluginSecrets(pluginId)), setSecret: async (pluginId, name, value) => { await call(commands.pluginSetSecret(pluginId, name, value)); @@ -745,6 +750,9 @@ export function createMemoryPluginsBackend( readFileBytes: async () => { throw new IpcError({ kind: "unavailable", message: "reading the document needs the desktop app" }); }, + readFileRange: async () => { + throw new IpcError({ kind: "unavailable", message: "reading the document needs the desktop app" }); + }, secrets: async (pluginId) => [...secrets.entries()] .filter(([k]) => k.startsWith(`${pluginId}/`)) diff --git a/src/features/plugins/views/WebView.tsx b/src/features/plugins/views/WebView.tsx index 3da87c48ad..67355f5ae0 100644 --- a/src/features/plugins/views/WebView.tsx +++ b/src/features/plugins/views/WebView.tsx @@ -16,7 +16,7 @@ * - uses the clipboard, when the plugin was granted `clipboard`; * - passes on IDE shortcuts it doesn't handle itself (Save, Close…). */ -import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"; import { tx } from "@/platform/i18n"; import { dispatchForwardedKey } from "@/platform/keymap"; import { useProject } from "@/platform/project"; @@ -61,6 +61,8 @@ export interface FrameDocument { read(): DocumentState & { readOnly: boolean; name: string }; /** The bytes of the file on disk, for binary documents (read-only, so the disk is current). */ bytes(): Promise; + size?(): Promise; + readRange?(offset: number, length: number): Promise; /** Applies the frame's edits as one change; throws `stale` when not at `version`. Returns the new version. */ edit(version: number, changes: readonly TextChange[]): number; /** Changes made other than through `edit` (the text editor, Undo, other windows). */ @@ -258,6 +260,7 @@ export interface WebViewProps { document?: FrameDocument | null; /** The backend document, for messages to the plugin's code. */ doc?: number | null; + binaryPath?: string; /** The text editor an editor panel follows; none elsewhere. */ editor?: FrameEditor | null; } @@ -269,6 +272,7 @@ export function WebView({ header = "default", document = null, doc = null, + binaryPath, editor = null, }: WebViewProps) { const plugin = usePlugins((s) => s.plugins.find((p) => p.id === pluginId)); @@ -278,6 +282,10 @@ export function WebView({ const headless = ownHeader && page !== null && "url" in page && loadedPage === page; useOwnToolWindowHeader(headless); const hasCode = plugin?.hasCode ?? false; + const eventEditor = useMemo( + () => (binaryPath ? { path: binaryPath, language: "binary", selections: [] } : undefined), + [binaryPath], + ); const clipboard = plugin?.capabilities.some((c) => c.id === "clipboard" && c.granted) ?? false; const anyAction = plugin?.capabilities.some((c) => c.id === "ide.commands" && c.granted) ?? false; const anyActionRef = useRef(anyAction); @@ -409,6 +417,27 @@ export function WebView({ const bytes = await document.bytes(); return [bytes, [bytes.buffer]]; } + case "document.size": { + if (!document?.size) throw new Error("this view shows no binary document"); + return [await document.size()]; + } + case "document.readRange": { + if (!document?.readRange) throw new Error("this view shows no binary document"); + const { offset, length } = args; + if ( + typeof offset !== "number" || + !Number.isSafeInteger(offset) || + offset < 0 || + typeof length !== "number" || + !Number.isSafeInteger(length) || + length < 0 || + length > 1024 * 1024 || + !Number.isSafeInteger(offset + length) + ) + throw new Error("invalid byte range (at most 1 MiB per read)"); + const bytes = await document.readRange(offset, length); + return [bytes, [bytes.buffer]]; + } case "document.edit": case "document.replace": { if (!document) throw new Error("this view shows no document"); @@ -507,7 +536,7 @@ export function WebView({ if (ptys.handle(m.text)) return; if (hasCode) { pluginsBackend() - .viewEvent(pluginId, view, { kind: "message", text: m.text }, doc) + .viewEvent(pluginId, view, { kind: "message", text: m.text }, doc, eventEditor) .catch((err: unknown) => console.warn(`plugin ${pluginId}: ${errorText(err)}`)); } } @@ -524,7 +553,7 @@ export function WebView({ window.removeEventListener("pagehide", onUnload); currentFrame?.removeEventListener("load", onLoad); }; - }, [pluginId, view, document, doc, editor, hasCode, post, page]); + }, [pluginId, view, document, doc, eventEditor, editor, hasCode, post, page]); if (!page) return ( diff --git a/src/features/plugins/views/customEditor.tsx b/src/features/plugins/views/customEditor.tsx index 11e5bf95ad..0d5ca7a978 100644 --- a/src/features/plugins/views/customEditor.tsx +++ b/src/features/plugins/views/customEditor.tsx @@ -36,6 +36,7 @@ export interface CustomEditorData { title: string; /** A web page of the package (`web`) rather than content the code renders. */ web?: boolean; + binary?: boolean; } export interface CustomEditorDecl { @@ -46,10 +47,17 @@ export interface CustomEditorDecl { /** `tab`: its own tab; `split` / `preview`: beside the text editor, starting in that layout. */ layout?: "tab" | "split" | "preview"; web?: string; + binary?: boolean; } export function customEditorInput(pluginId: string, decl: CustomEditorDecl, path: string): EditorInput { - const data: CustomEditorData = { pluginId, editorId: decl.id, title: decl.title, web: !!decl.web }; + const data: CustomEditorData = { + pluginId, + editorId: decl.id, + title: decl.title, + web: !!decl.web, + ...(decl.binary ? { binary: true } : {}), + }; return { kind: CUSTOM_EDITOR_KIND, key: `${CUSTOM_EDITOR_KIND}:${pluginId}/${decl.id}:${path}`, path, data }; } @@ -283,6 +291,36 @@ function SessionBody({ } export function CustomEditor({ input }: { input: EditorInput }) { + return (input.data as CustomEditorData).binary ? ( + + ) : ( + + ); +} + +function BinaryCustomEditor({ input }: { input: EditorInput }) { + const { pluginId, editorId, title } = input.data as CustomEditorData; + const path = input.path!; + const name = basename(path); + const document = useMemo( + () => ({ + read: () => ({ version: 0, text: "", readOnly: true, name }), + bytes: () => pluginsBackend().readFileBytes(path), + size: async () => (await pluginsBackend().readFileRange(path, 0, 0)).total, + readRange: async (offset, length) => (await pluginsBackend().readFileRange(path, offset, length)).data, + edit: () => { + throw new Error("the document is read-only"); + }, + subscribe: () => () => {}, + }), + [path, name], + ); + return ( + + ); +} + +function DocumentCustomEditor({ input }: { input: EditorInput }) { const data = input.data as CustomEditorData; const state = useSession(input.key, input.path ?? "", false); diff --git a/src/features/plugins/views/frame-bridge.js b/src/features/plugins/views/frame-bridge.js index 425d0da515..cfdc452fda 100644 --- a/src/features/plugins/views/frame-bridge.js +++ b/src/features/plugins/views/frame-bridge.js @@ -123,6 +123,8 @@ get: () => call("document.get"), /** The bytes of the file the custom editor shows (read-only, so the disk is current). */ bytes: () => call("document.bytes"), + size: () => call("document.size"), + readRange: (offset, length) => call("document.readRange", { offset, length }), /** Called with `{ version, text }` when the document changes other than through this frame. */ onChange: (fn) => { if (typeof fn === "function") documentListeners.push(fn);