From dadc97e4b200c03ab1498dc570ffad719efa4838 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:17:41 +0000 Subject: [PATCH] IDE: PDF and image viewer tabs on a generic custom-editor seam (#256) - editorGroup.openCustom / registerCustomEditor: a tab whose content is a DOM element of its own, with preview, close, drag, split and session restore like a file tab (agent chat tabs will use it too) - PDF viewer on pdf.js (lazy chunk, bundled worker, CSP unchanged): lazy page drawing, text layer, find with highlights, zoom, fit width - Image viewer: fit, zoom steps, actual size, dimensions and size - Workspace.readDocument: PDF bytes, inside the folder, 64 MB cap --- .claude/docs/V1.2.1_STATUS.md | 11 + apps/ide/README.md | 30 ++ apps/ide/THIRD_PARTY_NOTICES.md | 13 + apps/ide/package.json | 1 + apps/ide/src/main/ipc.ts | 1 + apps/ide/src/main/workspace/workspace.ts | 27 +- apps/ide/src/preload/index.ts | 1 + .../renderer/commands/workbenchCommands.ts | 18 +- apps/ide/src/renderer/editor/customEditor.ts | 58 ++ .../renderer/editor/customEditorRegistry.ts | 46 ++ apps/ide/src/renderer/editor/editorGroup.ts | 176 ++++++- apps/ide/src/renderer/main.ts | 7 +- apps/ide/src/renderer/styles.css | 4 + apps/ide/src/renderer/viewers/fileViewers.ts | 65 +++ apps/ide/src/renderer/viewers/imageViewer.ts | 134 +++++ apps/ide/src/renderer/viewers/pdfViewer.ts | 498 ++++++++++++++++++ apps/ide/src/renderer/viewers/viewerChrome.ts | 24 + apps/ide/src/renderer/viewers/viewerModel.ts | 98 ++++ apps/ide/src/renderer/viewers/viewers.css | 110 ++++ apps/ide/src/shared/api.ts | 5 +- apps/ide/test/viewers.test.ts | 110 ++++ package-lock.json | 291 ++++++++++ 22 files changed, 1698 insertions(+), 30 deletions(-) create mode 100644 apps/ide/src/renderer/editor/customEditor.ts create mode 100644 apps/ide/src/renderer/editor/customEditorRegistry.ts create mode 100644 apps/ide/src/renderer/viewers/fileViewers.ts create mode 100644 apps/ide/src/renderer/viewers/imageViewer.ts create mode 100644 apps/ide/src/renderer/viewers/pdfViewer.ts create mode 100644 apps/ide/src/renderer/viewers/viewerChrome.ts create mode 100644 apps/ide/src/renderer/viewers/viewerModel.ts create mode 100644 apps/ide/src/renderer/viewers/viewers.css create mode 100644 apps/ide/test/viewers.test.ts diff --git a/.claude/docs/V1.2.1_STATUS.md b/.claude/docs/V1.2.1_STATUS.md index 83b7a427a..45c8afeda 100644 --- a/.claude/docs/V1.2.1_STATUS.md +++ b/.claude/docs/V1.2.1_STATUS.md @@ -643,6 +643,17 @@ Then pushed `v1.2.1` to `origin` at the maintainer's request. **No merge and no **#180 (IDE), eighteenth PR of epic #163: debugger (DAP) for Python and Node.js** [confirmed: unit tests (`debug.test.ts`: `launch.json` parsing with aliases and errors, the template, variables on POSIX and Windows, DAP framing split anywhere including inside a UTF-8 character, the client's responses, error formats, reverse requests, timeouts and close, the Node adapter's helpers, and two end-to-end sessions: a Node.js program through the IDE's adapter on every run, a Python one through debugpy when it is installed (run locally with it)), `smoke.test.ts`, the gate, the smoke run (debugging refused in Restricted Mode), Playwright on Linux in both themes: a breakpoint set from the glyph margin, F5 on a `.py` file offered "Install debugpy", installing it into the IDE's environment and starting stopped on the breakpoint with the locals shown, F10 stepped, a watch and a console expression evaluated, Shift+F5 stopped; the same on a `.js` file with Shift+F11 and continuing to the end with the output in the Debug Console]. Main: `main/debug/dapClient.ts` (DAP over a byte stream), `debugSession.ts` (start-up sequence, events, path mapping), `debugHost.ts` (IPC `codexr:debug:*`, one session per window, trust-gated), `nodeAdapter.ts` (DAP to the V8 inspector, `node --inspect-brk` + WebSocket); `PythonEnvironmentService.debugAdapterCommand`/`installDebugpy` (pinned `debugpy==1.8.22`, installed only after consent); Output channel `debug`. Renderer: `renderer/debug/` (controller, view, console, CSS), `renderer/editor/debugDecorations.ts` (glyph margin, `glyphMargin` on), activity item `debug`, panel view `debug`, commands `workbench.action.debug.*`, `editor.debug.action.toggleBreakpoint`, `workbench.view.debug`. Windows and macOS: the Node adapter's breakpoint regex is caseless and slash-agnostic on Windows (unit-tested), the rest is the same spawn/stdio code as the tested path, run by CI on Linux only. Plugin: nothing to do, VS Code has its own debugger. Not done: attach requests, conditional breakpoints and logpoints, exception breakpoints, multi-thread and child-process debugging. +**#256 (IDE), epic #253 (classic gaps after #163): PDF and image viewer tabs on a generic custom-editor seam** [confirmed: unit tests (`viewers.test.ts`: zoom steps and fit, find across pages and its item mapping, sizes, the resolver registry, `readDocument` limited to PDFs inside the folder including through a symlink), the gate, the smoke run, Playwright on Linux in both themes. That run covered a 12-page PDF drawn lazily with its text layer, Ctrl+F finding and highlighting "lazy" on page 3, zoom, an image with its size, a broken PDF reported, the split showing the PDF in both groups, a session restored with both, an external overwrite re-rendered (12 then 3 pages), a deletion shown in the tab, and Close Editor from the palette on an image tab.] +- Main: `Workspace.readDocument` (PDF only, 64 MB cap, real path inside the folder) over IPC `codexr:workspace:read-document`; `readImage` also serves ICO and AVIF. +- Renderer: + - `editor/customEditor.ts` (types), `editor/customEditorRegistry.ts` (DOM-free registry), and `editorGroup.openCustom` / `registerCustomEditor`. A custom tab is a document with an empty placeholder model under the `codexr-custom:` scheme plus one view per tab; text commands see no active document. + - `viewers/` (pdf.js viewer loaded lazily, image viewer, resolver). + - New command target `hasActiveTab` for close, split, keep, copy path and reveal. +- Dependency: `pdfjs-dist` 6.5.438 (Apache-2.0, notice added). +- Plugin: nothing to do, VS Code has its own viewers. +- The agent-first layout thread builds its chat tabs on the same seam. +- Not done: password-protected PDFs, the outline/thumbnails sidebar, printing, CJK PDFs without embedded fonts (no CMaps bundled). + **#176 (IDE), sixteenth PR of epic #163: tasks and Run Current File** [confirmed: unit tests (`tasks.test.ts`: package.json scripts and hooks, package manager by lock file, Makefile targets, `.codexr/tasks.json` with comments, matchers by command, interpreters by extension, PATH and PATHEXT lookup, quoting for bash/PowerShell/cmd, tsc and ESLint matchers, a command terminal's output and exit code), the smoke run (an untrusted folder lists its tasks as not trusted and refuses a run), Playwright on Linux: Run Task in Restricted Mode shows the explanation with Manage Workspace Trust; once trusted the picker lists the user task, `npm: hello` and `make: build`; each ran in its own tab with its exit code; the user task's tsc-shaped line reached the Problems panel; Run Current File ran `run me.py` (a space in the name) with python3]. `shared/tasks.ts` (pure), `main/tasks/taskHost.ts` + `problemMatchers.ts`, `TerminalService.createCommand` (the default profile's shell with `-c` or its equivalent, `shellInvocation` from the agents' command tool), `Workspace.runnableFile`, settings `run.pythonInterpreter` / `run.nodeInterpreter`, commands `workbench.action.tasks.runTask`, `workbench.action.tasks.configureTaskRunner`, `workbench.action.runCurrentFile` (`Ctrl/Cmd+F5`). Core: `ProblemOrigin` gains `task` (type only; the plugin never produces it). The user tasks file is `.codexr/tasks.json`, next to `.codexr/settings.json`, not the `.code-xr/` the issue wrote. Windows and macOS not run by hand: the quoting and PATHEXT paths are unit-tested and CI runs the gate on all three. Plugin: nothing to do, VS Code has tasks natively. **#177 (IDE), fifteenth PR of epic #163: workspace trust** [confirmed: unit tests (`trust.test.ts`: parent trusts children, a sibling with the same prefix is not, Restricted Mode inside a trusted parent, case rules per platform, bounded storage; the choices offered), the smoke run (new folder unknown, shield shown, Git `restricted`, then trusted and Git on), Playwright on Linux: the question on a new folder, the XR deep analysis ran to a scene while restricted, Trust Folder turned Git on and hid the shield, the answer survived a restart, Manage Workspace Trust from the palette restricted it again, "Trust every folder in ol" trusted it through the parent]. Main: `main/trust/trustModel.ts` (pure), `main/trust/workspaceTrust.ts` (decisions in `userData/workspace-trust.json`, in memory for the smoke run; `isWorkspaceTrusted(contents)` for #176), IPC `codexr:workspace:trust` / `set-trust` and event `trust-changed`. Gated: Git (`GitRepoState` `restricted`, status and every operation), the Python language server (pyright runs a project-configured interpreter); a trust change stops the window's language servers and the renderer re-sends its documents (`reopenLanguageDocuments`). Not gated: the IDE's own TypeScript server (no local tsserver plugins), the terminal, the analysis. Renderer: `trustView.ts` + `trustChoices.ts`, status-bar shield, command `workbench.trust.manage`. Acceptance "Run Task is disabled with an explanation" lands with #176, which does not exist yet; this PR provides the gate. Plugin: nothing to do, VS Code has Workspace Trust natively. diff --git a/apps/ide/README.md b/apps/ide/README.md index 752e7b244..7bfcac728 100644 --- a/apps/ide/README.md +++ b/apps/ide/README.md @@ -202,6 +202,36 @@ Each run gets a terminal tab of its own, in the folder, started with the shell o The renderer names a task only by the id the main process listed, or a file by its workspace path; the main process re-reads the folder, builds the command line (quoted for bash/zsh/fish, PowerShell or cmd), checks the trust and starts the terminal (`shared/tasks.ts`, pure and unit-tested; `main/tasks/`; `renderer/taskRunner.ts`). The smoke run checks that a task is refused in an untrusted folder. +## PDF and image viewers (#256) + +PDFs and images open in an editor tab instead of being refused as binary files. This covers the explorer, Quick Open, search results and links in the Markdown preview. The tabs behave like file tabs: +- a single click opens a preview tab; +- they can be dragged to the other group or split with `Ctrl/Cmd+\`; +- they are restored with the folder's session; +- they follow the file on disk. + +- **PDF** + - Drawn by [PDF.js](https://github.com/mozilla/pdf.js), fitted to the width by default. + - Pages are drawn as they come near the viewport, and give their memory back when they are far away. + - Text can be selected and copied. + - The toolbar has the page number (type one and press Enter), previous and next page, zoom in and out (also `Ctrl/Cmd+=` / `Ctrl/Cmd+-` and `Ctrl/Cmd`+wheel), fit width (`Ctrl/Cmd+0`) and actual size. + - It also has a find box (`Ctrl/Cmd+F`, Enter and Shift+Enter step through the matches, Escape clears them) that highlights the match on the page. + - Up to 64 MB. Password-protected PDFs are not supported yet. +- **Images** (PNG, JPEG, GIF, WebP, BMP, ICO, AVIF, up to 8 MB) + - Fitted to the tab over a checkerboard. + - Zoom in steps, to actual size or back to fit, with the same keys. + - The size in pixels and bytes is shown in the toolbar. + - SVG stays a text file: it is a document that can carry script. +- **Security** + - The bytes come from the main process through a read that stays inside the folder and is size-capped (`workspace.readDocument` / `readImage`). + - PDF.js parses them in its own worker, bundled with the app. + - The CSP is unchanged: no frames, no objects, no remote fetches. + - Viewing is read-only, so it works in Restricted Mode. +- **Custom editor tabs** + - The viewers are the first users of a generic seam in `renderer/editor/customEditor.ts`. `editorGroup.openCustom(input)` opens a tab whose content is a DOM element of its own, and `registerCustomEditor(resolver)` turns an id (a file being opened, or a tab of a saved session) into such a tab. + - A tab's id is a workspace path for a file viewer, and carries a prefix of its own otherwise (`chat:`). + - Text commands (save, format, go to line) leave custom tabs alone; close, split, keep and copy path work on them. + ## Debugger (#180) **Run and Debug** (activity bar, `Ctrl/Cmd+Shift+D`) debugs Python and Node.js programs over the Debug Adapter Protocol. Click left of a line number (or press `F9`) to set a breakpoint; breakpoints follow the text as you edit, are listed in the view and are kept per folder. **F5** starts the configuration picked in the view, by default the active file with its language's debugger, and continues once paused. While paused, the line is highlighted, and the view shows **Variables** (expanded on demand, open nodes stay open from one stop to the next), **Watch** expressions, the **Call Stack** (click a frame to inspect it) and **Breakpoints**. A floating toolbar over the editors and the usual keys drive it: Continue `F5`, Pause `F6`, Step Over `F10`, Step Into `F11`, Step Out `Shift+F11`, Restart `Ctrl/Cmd+Shift+F5`, Stop `Shift+F5`. The **Debug Console** (panel, `Ctrl/Cmd+Shift+Y`) shows the program's output and evaluates expressions in the selected frame. The status bar turns orange while a session runs. diff --git a/apps/ide/THIRD_PARTY_NOTICES.md b/apps/ide/THIRD_PARTY_NOTICES.md index 54429476e..4125f8e02 100644 --- a/apps/ide/THIRD_PARTY_NOTICES.md +++ b/apps/ide/THIRD_PARTY_NOTICES.md @@ -83,3 +83,16 @@ Usage in this package: Usage in this package: - Bundled into the renderer by Vite: sanitises the Markdown preview's HTML before it reaches the page (#179, `src/renderer/editor/markdownPreview.ts`). The same version Monaco already depends on. + +## PDF.js (PDF viewer) + +- Project: `pdfjs-dist` on npm, 6.5.438, by Mozilla and the PDF.js contributors +- Source: https://github.com/mozilla/pdf.js +- License: Apache-2.0 + +Usage in this package: + +- Bundled into the renderer by Vite: draws PDFs in the PDF viewer tab (#256, `src/renderer/viewers/pdfViewer.ts`). The library is a chunk loaded on the first PDF only. +- Its worker (`pdfjs-dist/build/pdf.worker.mjs`) is bundled the same way and served from the app's origin, so the CSP's `worker-src 'self'` covers it. +- The text-layer rules in `src/renderer/viewers/viewers.css` are a trimmed copy of the `.textLayer` block of its `web/pdf_viewer.css`. +- The optional `@napi-rs/canvas` dependency is only used by PDF.js under Node and is not bundled. diff --git a/apps/ide/package.json b/apps/ide/package.json index b66d4e531..8936cced6 100644 --- a/apps/ide/package.json +++ b/apps/ide/package.json @@ -30,6 +30,7 @@ "marked": "14.0.0", "material-icon-theme": "^5.40.0", "monaco-editor": "0.57.0", + "pdfjs-dist": "6.5.438", "vite": "^8.3.8", "vscode-jsonrpc": "9.0.3", "vscode-languageserver-types": "3.18.4" diff --git a/apps/ide/src/main/ipc.ts b/apps/ide/src/main/ipc.ts index cfc9fbfd1..0f268a720 100644 --- a/apps/ide/src/main/ipc.ts +++ b/apps/ide/src/main/ipc.ts @@ -145,6 +145,7 @@ export function registerIpcHandlers(origins: ReadonlySet, isDevelopment: handle(IPC_CHANNELS.workspaceTrust, (event) => trustInfoOf(event.sender)); handle(IPC_CHANNELS.workspaceSetTrust, (event, choice) => setWorkspaceTrust(event.sender, choice)); handle(IPC_CHANNELS.workspaceReadImage, (event, path) => workspaceOf(event.sender).readImage(path)); + handle(IPC_CHANNELS.workspaceReadDocument, (event, path) => workspaceOf(event.sender).readDocument(path)); handle(IPC_CHANNELS.workspaceOpenExternalLink, async (_event, url) => { if (!isOpenableExternalLink(url)) { throw new Error('Only http, https and mailto links open outside the IDE.'); diff --git a/apps/ide/src/main/workspace/workspace.ts b/apps/ide/src/main/workspace/workspace.ts index c538fa342..0813a77bf 100644 --- a/apps/ide/src/main/workspace/workspace.ts +++ b/apps/ide/src/main/workspace/workspace.ts @@ -18,7 +18,14 @@ export const MAX_PREVIEW_IMAGE_BYTES = 8 * 1024 * 1024; * Raster images only: an SVG is a document that can carry script and * external references, and the preview has no reason to take that on. */ -const IMAGE_TYPES: Record = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', bmp: 'image/bmp' }; +const IMAGE_TYPES: Record = { + png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', bmp: 'image/bmp', + ico: 'image/x-icon', avif: 'image/avif', +}; +/** #256: the largest document the PDF viewer reads (pdf.js keeps it in memory). */ +export const MAX_DOCUMENT_BYTES = 64 * 1024 * 1024; +/** #256: the documents a viewer tab may read whole, by extension. */ +const DOCUMENT_TYPES = new Set(['pdf']); export function imageMimeType(path: string): string | null { const dot = path.lastIndexOf('.'); @@ -173,6 +180,24 @@ export class Workspace { return `data:${mime};base64,${(await fs.readFile(absolute)).toString('base64')}`; } + /** + * #256: a document of the folder (a PDF) as bytes, for a viewer tab. Null + * for another kind of file or one over `MAX_DOCUMENT_BYTES`. + */ + async readDocument(relativePath: unknown): Promise { + const name = parseWorkspacePath(relativePath).join('/'); + const dot = name.lastIndexOf('.'); + if (dot <= name.lastIndexOf('/') || !DOCUMENT_TYPES.has(name.slice(dot + 1).toLowerCase())) { + return null; + } + const absolute = await this.realPathInside(relativePath); + const stat = await fs.stat(absolute); + if (!stat.isFile() || stat.size > MAX_DOCUMENT_BYTES) { + return null; + } + return new Uint8Array(await fs.readFile(absolute)); + } + /** * Overwrites an existing file with `text` (UTF-8). Refuses a folder, a text * over the editor limit, and, when `expectedMtimeMs` is given, a file whose diff --git a/apps/ide/src/preload/index.ts b/apps/ide/src/preload/index.ts index f677aeb96..5627a8b8d 100644 --- a/apps/ide/src/preload/index.ts +++ b/apps/ide/src/preload/index.ts @@ -173,6 +173,7 @@ const api: CodeXRApi = Object.freeze({ rename: (path: string, newName: string) => ipcRenderer.invoke(IPC_CHANNELS.workspaceRename, path, newName), copyPath: (path: string, kind: 'absolute' | 'relative') => ipcRenderer.invoke(IPC_CHANNELS.workspaceCopyPath, path, kind), readImage: (path: string) => ipcRenderer.invoke(IPC_CHANNELS.workspaceReadImage, path), + readDocument: (path: string) => ipcRenderer.invoke(IPC_CHANNELS.workspaceReadDocument, path), trust: () => ipcRenderer.invoke(IPC_CHANNELS.workspaceTrust), setTrust: (choice: 'folder' | 'parent' | 'restrict') => ipcRenderer.invoke(IPC_CHANNELS.workspaceSetTrust, choice), onDidChangeTrust: (listener: (trust: WorkspaceTrustInfo) => void) => subscribe(IPC_EVENTS.workspaceTrustChanged, listener), diff --git a/apps/ide/src/renderer/commands/workbenchCommands.ts b/apps/ide/src/renderer/commands/workbenchCommands.ts index ecd0392a5..b37a7e445 100644 --- a/apps/ide/src/renderer/commands/workbenchCommands.ts +++ b/apps/ide/src/renderer/commands/workbenchCommands.ts @@ -18,6 +18,8 @@ export interface WorkbenchCommandTargets { quickOpen(): void; goToSymbol(): void; hasActiveEditor(): boolean; + /** #256: any tab is active, a text editor or a custom one (a PDF, an image). */ + hasActiveTab(): boolean; changeIndentation(): void; changeEndOfLine(): void; changeLanguageMode(): void; @@ -97,22 +99,22 @@ export function workbenchCommands(targets: WorkbenchCommandTargets): CommandDefi { id: 'file.newFolder', category: 'File', title: 'New Folder…', enabled: targets.hasFolder, run: targets.newFolder }, { id: 'file.save', category: 'File', title: 'Save', ...menu('file.save'), enabled: targets.hasActiveEditor, run: targets.save }, { id: 'file.saveAll', category: 'File', title: 'Save All', ...menu('file.saveAll'), run: targets.saveAll }, - { id: 'editor.close', category: 'View', title: 'Close Editor', ...menu('editor.close'), enabled: targets.hasActiveEditor, run: targets.closeEditor }, - { id: 'editor.closeOthers', category: 'View', title: 'Close Other Editors', enabled: targets.hasActiveEditor, run: () => targets.closeEditors('others') }, - { id: 'editor.closeToTheRight', category: 'View', title: 'Close Editors to the Right', enabled: targets.hasActiveEditor, run: () => targets.closeEditors('right') }, + { id: 'editor.close', category: 'View', title: 'Close Editor', ...menu('editor.close'), enabled: targets.hasActiveTab, run: targets.closeEditor }, + { id: 'editor.closeOthers', category: 'View', title: 'Close Other Editors', enabled: targets.hasActiveTab, run: () => targets.closeEditors('others') }, + { id: 'editor.closeToTheRight', category: 'View', title: 'Close Editors to the Right', enabled: targets.hasActiveTab, run: () => targets.closeEditors('right') }, { id: 'editor.closeSaved', category: 'View', title: 'Close Saved Editors', keybinding: 'CmdOrCtrl+K U', enabled: targets.hasEditors, run: () => targets.closeEditors('saved') }, { id: 'editor.closeAll', category: 'View', title: 'Close All Editors', keybinding: 'CmdOrCtrl+K W', enabled: targets.hasEditors, run: () => targets.closeEditors('all') }, { id: 'editor.next', category: 'View', title: 'Open Next Editor', keybinding: 'Ctrl+PageDown', secondaryKeybindings: ['Ctrl+Tab'], enabled: targets.hasEditors, recordRecent: false, run: () => targets.cycleEditor(1) }, { id: 'editor.previous', category: 'View', title: 'Open Previous Editor', keybinding: 'Ctrl+PageUp', secondaryKeybindings: ['Ctrl+Shift+Tab'], enabled: targets.hasEditors, recordRecent: false, run: () => targets.cycleEditor(-1) }, - { id: 'editor.splitRight', category: 'View', title: 'Split Editor Right', keybinding: 'CmdOrCtrl+\\', enabled: targets.hasActiveEditor, run: targets.splitEditor }, + { id: 'editor.splitRight', category: 'View', title: 'Split Editor Right', keybinding: 'CmdOrCtrl+\\', enabled: targets.hasActiveTab, run: targets.splitEditor }, { id: 'workbench.focusFirstEditorGroup', category: 'View', title: 'Focus First Editor Group', keybinding: 'CmdOrCtrl+1', recordRecent: false, run: () => { targets.focusEditorGroup(0); } }, { id: 'workbench.focusSecondEditorGroup', category: 'View', title: 'Focus Second Editor Group', keybinding: 'CmdOrCtrl+2', recordRecent: false, run: () => { if (!targets.focusEditorGroup(1)) { targets.splitEditor(); } } }, { id: 'workbench.trust.manage', category: 'Workspaces', title: 'Manage Workspace Trust', enabled: targets.hasFolder, run: targets.manageWorkspaceTrust }, { id: 'markdown.showPreviewToSide', category: 'Markdown', title: 'Open Preview to the Side', keybinding: 'CmdOrCtrl+K V', enabled: targets.canPreviewMarkdown, run: targets.openMarkdownPreview }, - { id: 'editor.keep', category: 'View', title: 'Keep Editor', keybinding: 'CmdOrCtrl+K Enter', enabled: targets.hasActiveEditor, run: targets.keepEditor }, - { id: 'file.copyPath', category: 'File', title: 'Copy Path of Active File', enabled: targets.hasActiveEditor, run: () => targets.copyActivePath('absolute') }, - { id: 'file.copyRelativePath', category: 'File', title: 'Copy Relative Path of Active File', enabled: targets.hasActiveEditor, run: () => targets.copyActivePath('relative') }, - { id: 'file.revealInExplorer', category: 'File', title: 'Reveal Active File in Explorer', enabled: targets.hasActiveEditor, run: targets.revealActiveFile }, + { id: 'editor.keep', category: 'View', title: 'Keep Editor', keybinding: 'CmdOrCtrl+K Enter', enabled: targets.hasActiveTab, run: targets.keepEditor }, + { id: 'file.copyPath', category: 'File', title: 'Copy Path of Active File', enabled: targets.hasActiveTab, run: () => targets.copyActivePath('absolute') }, + { id: 'file.copyRelativePath', category: 'File', title: 'Copy Relative Path of Active File', enabled: targets.hasActiveTab, run: () => targets.copyActivePath('relative') }, + { id: 'file.revealInExplorer', category: 'File', title: 'Reveal Active File in Explorer', enabled: targets.hasActiveTab, run: targets.revealActiveFile }, { id: 'workbench.action.tasks.runTask', category: 'Tasks', title: 'Run Task', enabled: targets.hasFolder, run: targets.runTask }, { id: 'workbench.action.tasks.configureTaskRunner', category: 'Tasks', title: 'Configure Tasks', enabled: targets.hasFolder, run: targets.configureTasks }, { id: 'workbench.action.runCurrentFile', category: 'Run', title: 'Run Current File', keybinding: 'CmdOrCtrl+F5', enabled: targets.hasActiveEditor, run: targets.runCurrentFile }, diff --git a/apps/ide/src/renderer/editor/customEditor.ts b/apps/ide/src/renderer/editor/customEditor.ts new file mode 100644 index 000000000..fcd000340 --- /dev/null +++ b/apps/ide/src/renderer/editor/customEditor.ts @@ -0,0 +1,58 @@ +/** + * #256: custom editor tabs. A custom tab sits in a group's tab strip like a + * file tab (preview, keep, close, drag to the other group, split, session + * restore) but shows a DOM element of its own instead of a Monaco editor. + * The PDF and image viewers are custom tabs over a file; the agent-first + * layout opens its chats through the same seam. + * + * A tab's id is its key everywhere a file tab uses its path: a file viewer's + * id is the file's workspace path, any other id carries a prefix of its own + * (`chat:`), so it never collides with a file. Each tab gets its own + * view: a document open in both groups is two views over the same input. + */ + +/** What a view can ask of the tab that holds it. */ +export interface CustomEditorContext { + /** The tab's id. */ + readonly id: string; + /** Renames the tab (a chat that got its title). */ + setTitle(title: string): void; + /** Shows the tab's dot. It is only a mark: Save does not reach a custom tab, so `canClose` must ask on its own. */ + setDirty(dirty: boolean): void; + /** Closes this tab (after `canClose`). */ + close(): void; + /** A one-line message for the status bar. */ + status(message: string): void; +} + +/** One tab's view of a custom input. */ +export interface CustomEditorView { + /** Placed in the group while its tab is active, removed (not destroyed) while another tab is. */ + readonly element: HTMLElement; + /** The tab became the visible one of its group (after the element is in the document). */ + onShow?(): void; + /** Another tab of the group became visible (before the element leaves the document). */ + onHide?(): void; + /** Takes the keyboard focus when the tab is activated by the person. */ + focus?(): void; + /** False keeps the tab open; asked once per close, never for a close the workspace forces. */ + canClose?(): boolean; + /** A file viewer's file changed on disk, or is gone. */ + fileChanged?(state: 'changed' | 'deleted'): void; + /** The tab closed for good. */ + dispose?(): void; +} + +/** What `openCustom` takes, and what a resolver hands back for a saved id. */ +export interface CustomEditorInput { + readonly id: string; + readonly title: string; + /** The file name whose icon the tab shows (the title when absent). */ + readonly iconName?: string; + /** Set for a viewer of a workspace file (the id is then that path): the tab follows the file on disk and is watched. */ + readonly filePath?: string; + create(context: CustomEditorContext): CustomEditorView; +} + +/** Turns an id (a saved tab, a file being opened) into an input, or null when it is not this resolver's. */ +export type CustomEditorResolver = (id: string) => CustomEditorInput | null; diff --git a/apps/ide/src/renderer/editor/customEditorRegistry.ts b/apps/ide/src/renderer/editor/customEditorRegistry.ts new file mode 100644 index 000000000..20ce30262 --- /dev/null +++ b/apps/ide/src/renderer/editor/customEditorRegistry.ts @@ -0,0 +1,46 @@ +/** + * #256: the DOM-free half of the custom editor seam (editor/customEditor.ts): + * the resolver registry and the file-type helpers, which the unit tests run + * under Node. + */ + +/** The resolvers in registration order: the first one that answers wins. */ +export class CustomEditorRegistry { + private readonly resolvers: ((id: string) => T | null)[] = []; + + /** Adds a resolver; the returned function removes it. */ + register(resolver: (id: string) => T | null): () => void { + this.resolvers.push(resolver); + return () => { + const index = this.resolvers.indexOf(resolver); + if (index >= 0) { + this.resolvers.splice(index, 1); + } + }; + } + + resolve(id: string): T | null { + for (const resolver of this.resolvers) { + const input = resolver(id); + if (input) { + return input; + } + } + return null; + } +} + +/** The extension of a workspace path, lower case, without the dot ('' when it has none). */ +export function extensionOf(path: string): string { + const name = path.slice(path.lastIndexOf('/') + 1); + const dot = name.lastIndexOf('.'); + return dot > 0 ? name.slice(dot + 1).toLowerCase() : ''; +} + +/** #256: the images the image viewer shows (the ones `workspace.readImage` serves). SVG opens as text. */ +export const VIEWER_IMAGE_EXTENSIONS: ReadonlySet = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'avif']); + +/** True for an id that names another kind of tab (`chat:...`) rather than a workspace path. */ +export function isSchemeId(id: string): boolean { + return /^[a-z][a-z0-9-]*:/i.test(id); +} diff --git a/apps/ide/src/renderer/editor/editorGroup.ts b/apps/ide/src/renderer/editor/editorGroup.ts index b973134bf..4d3eb2a25 100644 --- a/apps/ide/src/renderer/editor/editorGroup.ts +++ b/apps/ide/src/renderer/editor/editorGroup.ts @@ -9,6 +9,8 @@ import { installGitDecorations, type GitDecorationsHooks } from './gitDecoration import { installDebugDecorations, type DebugDecorationsHooks } from './debugDecorations.ts'; import { createMarkdownPreview, type MarkdownPreview } from './markdownPreview.ts'; import { isMarkdownPath } from './markdownPath.ts'; +import type { CustomEditorContext, CustomEditorInput, CustomEditorResolver, CustomEditorView } from './customEditor.ts'; +import { CustomEditorRegistry } from './customEditorRegistry.ts'; import { clampSplit, closeTargets, cycleTab, DEFAULT_SPLIT, discardQuestion, moveTab, type CloseKind, type GroupSession, type TabSession, @@ -72,6 +74,10 @@ interface Doc { /** #170: a save is being written (an auto save does not start a second one). */ saving: boolean; readonly listener: monaco.IDisposable; + /** #256: a custom tab's input (its model is an empty placeholder, never shown); null for a text file. */ + readonly custom: CustomEditorInput | null; + /** #256: the dot a custom view asked for. */ + customDirty: boolean; } /** A document's tab in one group. */ @@ -83,6 +89,9 @@ interface Tab { viewState: monaco.editor.ICodeEditorViewState | null; /** #167: a preview tab, replaced by the next preview of its group until it is kept. */ preview: boolean; + /** #256: this tab's view of a custom input (null for a text file). */ + readonly view: CustomEditorView | null; + readonly label: HTMLElement; } /** An editor group (#168): a tab strip over a Monaco editor. */ @@ -91,6 +100,8 @@ interface Group { readonly strip: HTMLElement; readonly host: HTMLElement; readonly placeholder: HTMLElement; + /** #256: where the active custom tab's element goes, in place of the editor. */ + readonly customHost: HTMLElement; readonly editor: monaco.editor.IStandaloneCodeEditor; readonly sceneShown: monaco.editor.IContextKey; readonly tabs: Map; @@ -105,6 +116,8 @@ export interface OpenOptions { /** #173: Monaco's resources for workspace files, and the owner of the Code-XR metric markers. */ const FILE_SCHEME = 'codexr-file'; +/** #256: the placeholder models of custom tabs; nothing (languages, lenses, markers) follows this scheme. */ +const CUSTOM_SCHEME = 'codexr-custom'; const METRIC_OWNER = 'codexr-metrics'; const MARKER_SEVERITY: Record = { error: monaco.MarkerSeverity.Error, @@ -193,6 +206,17 @@ export interface EditorGroup { closeMarkdownPreview(): void; canPreviewMarkdown(): boolean; markdownPreviewOpen(): boolean; + /** + * #256: opens a custom tab (a view of its own instead of a text editor) + * in the active group, or activates the one with the same id. + */ + openCustom(input: CustomEditorInput, options?: OpenOptions): void; + /** + * #256: adds a resolver that turns an id into a custom input: a file being + * opened (the PDF and image viewers) or a tab of a saved session. The + * returned function removes it. + */ + registerCustomEditor(resolver: CustomEditorResolver): () => void; /** #18: applies the editor settings in force. */ applySettings(settings: SettingValues): void; /** #170: formats the active file with its language's formatter; false when it has none. */ @@ -294,7 +318,12 @@ export function createEditorGroup( /** The active tab of the active group. */ const activeTab = (): Tab | null => current.active; - const activeDoc = (): Doc | null => current.active?.doc ?? null; + /** The active text document: null when the active tab is a custom one (#256), so text commands leave it alone. */ + const activeDoc = (): Doc | null => { + const doc = current.active?.doc ?? null; + return doc?.custom ? null : doc; + }; + const customEditors = new CustomEditorRegistry(); const tabsOf = (doc: Doc): Tab[] => groups.flatMap((group) => { const tab = group.tabs.get(doc.path); return tab?.doc === doc ? [tab] : []; @@ -388,7 +417,7 @@ export function createEditorGroup( /** Draws a document's state on every tab that shows it. */ function refreshDoc(doc: Doc): void { - const dirty = isDirty(doc); + const dirty = isDirty(doc) || doc.customDirty; const title = doc.diskState === 'deleted' ? 'Deleted on disk' : doc.diskState === 'changed' ? 'Changed on disk; your version is unsaved' : dirty ? 'Unsaved changes' : ''; @@ -431,16 +460,33 @@ export function createEditorGroup( } } + /** #256: takes the shown custom view out of `group` (another tab, or none, takes its place). */ + function hideCustomView(group: Group): void { + const shown = group.customHost.firstElementChild; + if (!shown) { + return; + } + const owner = [...group.tabs.values()].find((candidate) => candidate.view?.element === shown); + owner?.view?.onHide?.(); + shown.remove(); + } + function activate(group: Group, tab: Tab | null, focus = true): void { const previous = group.active; if (previous && previous !== tab) { - previous.viewState = group.editor.saveViewState(); + if (!previous.view) { + previous.viewState = group.editor.saveViewState(); + } previous.element.setAttribute('aria-selected', 'false'); previous.element.tabIndex = -1; } group.active = tab; const wasCurrent = current === group; focusGroupInternal(group, false); + if (group.customHost.firstElementChild !== (tab?.view?.element ?? null)) { + hideCustomView(group); + } + group.customHost.hidden = !tab?.view; if (!tab) { group.editor.setModel(null); showPlaceholder(group, docs.size === 0 ? 'Open a file from the explorer.' : null); @@ -448,7 +494,14 @@ export function createEditorGroup( return; } showPlaceholder(group, null); - if (group.editor.getModel() !== tab.doc.model) { + if (tab.view) { + group.host.hidden = true; + group.editor.setModel(null); + if (!tab.view.element.isConnected) { + group.customHost.append(tab.view.element); + tab.view.onShow?.(); + } + } else if (group.editor.getModel() !== tab.doc.model) { group.editor.setModel(tab.doc.model); if (tab.viewState) { group.editor.restoreViewState(tab.viewState); @@ -458,7 +511,11 @@ export function createEditorGroup( tab.element.tabIndex = 0; tab.element.scrollIntoView({ block: 'nearest', inline: 'nearest' }); if (focus) { - group.editor.focus(); + if (tab.view) { + tab.view.focus?.(); + } else { + group.editor.focus(); + } } callbacks.onActiveChange(tab.doc.path); followPreview(tab.doc); @@ -484,6 +541,7 @@ export function createEditorGroup( const doc: Doc = { path: content.path, model, savedVersion: model.getAlternativeVersionId(), mtimeMs: content.mtimeMs, diskState: 'same', bom: content.text.startsWith(BOM), config: {}, autoSaveTimer: undefined, saving: false, lensStale: false, + custom: null, customDirty: false, listener: model.onDidChangeContent(() => { refreshDoc(doc); scheduleAutoSave(doc); @@ -506,6 +564,30 @@ export function createEditorGroup( return doc; } + /** #256: a custom tab's document: an empty placeholder model under its own scheme, never shown or saved. */ + function createCustomDoc(input: CustomEditorInput): Doc { + const uri = monaco.Uri.from({ scheme: CUSTOM_SCHEME, path: `/${input.id}` }); + const model = monaco.editor.getModel(uri) ?? monaco.editor.createModel('', 'plaintext', uri); + const doc: Doc = { + path: input.id, model, savedVersion: model.getAlternativeVersionId(), mtimeMs: 0, + diskState: 'same', bom: false, config: {}, autoSaveTimer: undefined, saving: false, lensStale: false, + listener: { dispose: () => undefined }, custom: input, customDirty: false, + }; + docs.set(doc.path, doc); + callbacks.onOpenFilesChange?.(); + return doc; + } + + /** #256: the document for a custom input, or for a file a resolver claims; null when nothing claims `id`. */ + function customDocFor(id: string): Doc | null { + const known = docs.get(id); + if (known) { + return known.custom ? known : null; + } + const input = customEditors.resolve(id); + return input && input.id === id ? createCustomDoc(input) : null; + } + function disposeDoc(doc: Doc): void { clearTimeout(doc.autoSaveTimer); docs.delete(doc.path); @@ -521,14 +603,35 @@ export function createEditorGroup( } function addTab(group: Group, doc: Doc, preview = false, before: Element | null = null): Tab { - const name = doc.path.split('/').pop() ?? doc.path; + const name = doc.custom ? doc.custom.title : doc.path.split('/').pop() ?? doc.path; const dirtyMark = el('span', { className: 'tab-dirty', attrs: { 'aria-hidden': 'true' } }); const close = el('button', { className: 'tab-close', attrs: { type: 'button', title: 'Close', 'aria-label': `Close ${name}`, tabindex: '-1' } }, [icon(CLOSE)]); + const label = el('span', { className: 'tab-label', text: name }); const element = el('div', { className: 'editor-tab', - attrs: { role: 'tab', 'aria-selected': 'false', tabindex: '-1', title: doc.path, 'data-path': doc.path, draggable: 'true' }, - }, [fileIcon(name, 'file'), el('span', { className: 'tab-label', text: name }), dirtyMark, close]); - const tab: Tab = { doc, group, element, dirtyMark, viewState: null, preview: false }; + attrs: { role: 'tab', 'aria-selected': 'false', tabindex: '-1', title: doc.custom?.filePath ?? doc.custom?.title ?? doc.path, 'data-path': doc.path, draggable: 'true' }, + }, [fileIcon(doc.custom?.iconName ?? name, 'file'), label, dirtyMark, close]); + let view: CustomEditorView | null = null; + if (doc.custom) { + const context: CustomEditorContext = { + id: doc.path, + setTitle: (title) => { + label.textContent = title; + close.setAttribute('aria-label', `Close ${title}`); + if (!doc.custom?.filePath) { element.title = title; } + }, + setDirty: (dirty) => { + doc.customDirty = dirty; + refreshDoc(doc); + }, + close: () => { + if (tab.group.tabs.get(doc.path) === tab) { closeTabs(tab.group, [tab]); } + }, + status: (message) => callbacks.onStatus(message), + }; + view = doc.custom.create(context); + } + const tab: Tab = { doc, group, element, dirtyMark, viewState: null, preview: false, view, label }; setPreview(tab, preview); element.addEventListener('click', (event) => { if ((event.target as Element).closest('.tab-close')) { @@ -625,6 +728,10 @@ export function createEditorGroup( } const closing = new Set(targets); const leaving = targets.filter((tab) => tabsOf(tab.doc).every((other) => closing.has(other))); + // #256: a custom view may keep its tab open (it asks its own question). + if (ask && targets.some((tab) => tab.view?.canClose?.() === false)) { + return false; + } const question = ask ? discardQuestion(targets.map((tab) => tab.doc.path), new Set(leaving.filter((tab) => isDirty(tab.doc)).map((tab) => tab.doc.path))) : null; if (question !== null && !window.confirm(question)) { return false; @@ -634,6 +741,7 @@ export function createEditorGroup( for (const tab of targets) { group.tabs.delete(tab.doc.path); tab.element.remove(); + disposeView(tab); } for (const tab of leaving) { disposeDoc(tab.doc); @@ -659,6 +767,18 @@ export function createEditorGroup( return true; } + /** #256: a closing tab's custom view leaves its group for good. */ + function disposeView(tab: Tab): void { + if (!tab.view) { + return; + } + if (tab.view.element.isConnected) { + tab.view.onHide?.(); + tab.view.element.remove(); + } + tab.view.dispose?.(); + } + /** #168: a group left without tabs goes, as long as another one stays. */ function collapseEmptyGroups(): void { for (const group of [...groups]) { @@ -780,6 +900,13 @@ export function createEditorGroup( /** Re-reads one open file after the watcher reported it. */ async function followDisk(doc: Doc): Promise { + if (doc.custom) { + // #256: a file viewer reads its file again (or finds it gone) on its own. + for (const tab of tabsOf(doc)) { + tab.view?.fileChanged?.('changed'); + } + return; + } let content: FileContent; try { content = await api.readFile(doc.path); @@ -855,10 +982,11 @@ export function createEditorGroup( const strip = el('div', { className: 'editor-tabs', attrs: { role: 'tablist', 'aria-label': 'Open editors', 'data-testid': 'editor-tabs' } }); const host = el('div', { className: 'editor-host', attrs: { 'data-testid': 'editor-host' } }); const placeholder = el('div', { className: 'editor-placeholder muted' }); - const root = el('div', { className: 'editor-group', attrs: { 'data-testid': 'editor-group' } }, [strip, host, placeholder]); + const customHost = el('div', { className: 'editor-custom-host', attrs: { 'data-testid': 'editor-custom-host', hidden: '' } }); + const root = el('div', { className: 'editor-group', attrs: { 'data-testid': 'editor-group' } }, [strip, host, customHost, placeholder]); const editor = monaco.editor.create(host, { ...editorOptions, model: null }); const sceneShown = editor.createContextKey('codexrSceneShown', sceneIsShown); - const group: Group = { root, strip, host, placeholder, editor, sceneShown, tabs: new Map(), active: null, disposables: [] }; + const group: Group = { root, strip, host, placeholder, customHost, editor, sceneShown, tabs: new Map(), active: null, disposables: [] }; const ifCurrent = (listener: () => void) => () => { if (current === group) { listener(); } }; group.disposables.push( editor.onDidChangeCursorSelection(ifCurrent(scheduleStatus)), @@ -1017,7 +1145,7 @@ export function createEditorGroup( /** #168: a tab dropped on the other group moves there (the file's model goes with it, unchanged). */ function moveTabToGroup(tab: Tab, target: Group, before: Element | null): void { - const viewState = tab.group.active === tab ? tab.group.editor.saveViewState() : tab.viewState; + const viewState = tab.group.active === tab && !tab.view ? tab.group.editor.saveViewState() : tab.viewState; const preview = tab.preview; showDoc(target, tab.doc, { before: target.tabs.has(tab.doc.path) ? null : before, viewState, preview }); closeTabs(tab.group, [tab], false); @@ -1169,7 +1297,7 @@ export function createEditorGroup( /** Opens `path` in `group`: the document if it is already open (in either group), else read from disk. */ async function openIn(group: Group, path: string, options: OpenOptions & { viewState?: monaco.editor.ICodeEditorViewState | null; focus?: boolean } = {}): Promise { - const known = docs.get(path); + const known = docs.get(path) ?? customDocFor(path); if (known) { return showDoc(group, known, options); } @@ -1199,7 +1327,7 @@ export function createEditorGroup( if (group.tabs.has(entry.path)) { continue; } - let doc = docs.get(entry.path); + let doc = docs.get(entry.path) ?? customDocFor(entry.path) ?? undefined; if (!doc) { let content: FileContent; try { @@ -1222,7 +1350,7 @@ export function createEditorGroup( } function groupSession(group: Group): GroupSession { - if (group.active) { + if (group.active && !group.active.view) { group.active.viewState = group.editor.saveViewState(); } const tabs = ordered(group); @@ -1257,7 +1385,7 @@ export function createEditorGroup( let replacements = 0; for (const path of paths) { const doc = docs.get(path); - if (!doc) { + if (!doc || doc.custom) { continue; } handled.push(path); @@ -1279,7 +1407,7 @@ export function createEditorGroup( }, async applyAgentEdit(path, expected, text) { const doc = docs.get(path); - if (!doc) { + if (!doc || doc.custom) { return 'not-open'; } if (fileText(doc) !== expected) { @@ -1371,6 +1499,15 @@ export function createEditorGroup( return true; }, groupCount: () => groups.length, + openCustom(input: CustomEditorInput, options: OpenOptions = {}): void { + const doc = docs.get(input.id) ?? createCustomDoc(input); + if (!doc.custom) { + callbacks.onStatus(`${input.id} is already open as a file.`); + return; + } + showDoc(current, doc, options); + }, + registerCustomEditor: (resolver: CustomEditorResolver) => customEditors.register(resolver), openMarkdownPreview: () => openPreview(), closeMarkdownPreview: () => closePreview(), canPreviewMarkdown: () => { @@ -1543,6 +1680,7 @@ export function createEditorGroup( for (const group of [...groups].reverse()) { for (const tab of group.tabs.values()) { tab.element.remove(); + disposeView(tab); } group.tabs.clear(); group.active = null; @@ -1560,7 +1698,7 @@ export function createEditorGroup( callbacks.onOpenFilesChange?.(); }, dirtyPaths: () => [...docs.values()].filter(isDirty).map((doc) => doc.path), - openPaths: () => [...docs.keys()], + openPaths: () => [...docs.values()].filter((doc) => !doc.custom || doc.custom.filePath !== undefined).map((doc) => doc.path), async entryMoved(from: string, to: string | null): Promise { const affected = [...docs.values()].filter((doc) => doc.path === from || doc.path.startsWith(`${from}/`)); const reopen: { group: Group; path: string; active: boolean }[] = []; @@ -1599,7 +1737,7 @@ export function createEditorGroup( // #170: an .editorconfig changed: read them again and re-apply them to every open file. if (paths.some((path) => path === EDITORCONFIG_NAME || path.endsWith(`/${EDITORCONFIG_NAME}`))) { editorConfigs = new Map(); - await Promise.all([...docs.values()].map(applyEditorConfig)); + await Promise.all([...docs.values()].filter((doc) => !doc.custom).map(applyEditorConfig)); } await Promise.all([...docs.values()].filter((doc) => changed.has(doc.path)).map(followDisk)); }, diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index 7d6f851b4..225983609 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -85,7 +85,9 @@ const outlineView = createOutlineView(workbench.outlineView, { let outline: OutlineController | null = null; let outlineLanguage: string | null = null; function editorGroup(): Promise { - editorsLoading ??= Promise.all([import('./editor/editorGroup.ts'), import('./lsp/languageClient.ts'), import('./editor/outlineController.ts')]).then(([{ createEditorGroup }, { installLanguageClient }, { createOutlineController }]) => { + editorsLoading ??= Promise.all([ + import('./editor/editorGroup.ts'), import('./lsp/languageClient.ts'), import('./editor/outlineController.ts'), import('./viewers/fileViewers.ts'), + ]).then(([{ createEditorGroup }, { installLanguageClient }, { createOutlineController }, { fileViewerResolver }]) => { // #21: before any model exists (lsp/languageClient.ts); go to definition opens tabs here. installLanguageClient(api.lsp, { openAt: (path, line, column, length) => editorGroup().then((group) => group.openAt(path, line, column, length)) }); editors = createEditorGroup(workbench.editorArea, api.workspace, { @@ -119,6 +121,8 @@ function editorGroup(): Promise { revealInScene: (path) => revealInScene(path), }); editors.setSceneShown(!workbench.sceneArea.hidden); + // #256: PDFs and images open in viewer tabs. + editors.registerCustomEditor(fileViewerResolver(api.workspace)); outline = createOutlineController({ editors, view: outlineView, @@ -654,6 +658,7 @@ registerWorkbenchCommands(registry, { }, goToSymbol: () => editors?.showSymbols(), hasActiveEditor: () => (editors?.activeLineCount() ?? null) !== null, + hasActiveTab: () => activeFile !== null, changeIndentation: pickIndentation, changeEndOfLine: pickEndOfLine, changeLanguageMode: pickLanguage, diff --git a/apps/ide/src/renderer/styles.css b/apps/ide/src/renderer/styles.css index f6d301857..c752a825a 100644 --- a/apps/ide/src/renderer/styles.css +++ b/apps/ide/src/renderer/styles.css @@ -428,6 +428,10 @@ body { .editor-host { flex: 1; min-height: 0; } .editor-placeholder { flex: 1; display: grid; place-items: center; } .editor-host[hidden], .editor-placeholder[hidden] { display: none; } +/* #256: a custom tab's view (PDF, image, chat) in place of the editor. */ +.editor-custom-host { flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: hidden; } +.editor-custom-host[hidden] { display: none; } +.editor-custom-host > * { flex: 1; min-height: 0; } .welcome-title { font-size: clamp(28px, 4vw, 40px); diff --git a/apps/ide/src/renderer/viewers/fileViewers.ts b/apps/ide/src/renderer/viewers/fileViewers.ts new file mode 100644 index 000000000..4b253804d --- /dev/null +++ b/apps/ide/src/renderer/viewers/fileViewers.ts @@ -0,0 +1,65 @@ +import type { CodeXRApi } from '../../shared/api.ts'; +import { el } from '../dom.ts'; +import type { CustomEditorResolver, CustomEditorView } from '../editor/customEditor.ts'; +import { extensionOf, isSchemeId, VIEWER_IMAGE_EXTENSIONS } from '../editor/customEditorRegistry.ts'; +import { createImageView } from './imageViewer.ts'; + +/** + * #256: the built-in file viewers as a custom-editor resolver: a `.pdf` opens + * in the PDF viewer, a raster image in the image viewer, anything else is + * left to the text editor. The id of a viewer tab is the file's path, so a + * saved session and a rename treat it like any file. pdf.js is loaded on the + * first PDF only, so a window that never opens one never pays for it. + */ +export function fileViewerResolver(workspace: Pick): CustomEditorResolver { + return (id) => { + if (isSchemeId(id)) { + return null; // another kind of tab (chat:...), not a workspace path + } + const extension = extensionOf(id); + const title = id.slice(id.lastIndexOf('/') + 1); + if (extension === 'pdf') { + return { + id, title, filePath: id, + create: () => lazyView(import('./pdfViewer.ts').then((module) => module.createPdfView(id, (path) => workspace.readDocument(path)))), + }; + } + if (VIEWER_IMAGE_EXTENSIONS.has(extension)) { + return { id, title, filePath: id, create: () => createImageView(id, (path) => workspace.readImage(path)) }; + } + return null; + }; +} + +/** A view whose module is still loading: a holder element now, the real view inside it once it arrives. */ +function lazyView(loading: Promise): CustomEditorView { + const element = el('div', { className: 'viewer-lazy' }); + let view: CustomEditorView | null = null; + let shown = false; + let disposed = false; + let wantsFocus = false; + loading.then((loaded) => { + if (disposed) { + loaded.dispose?.(); + return; + } + view = loaded; + element.replaceChildren(loaded.element); + if (shown) { + loaded.onShow?.(); + } + if (wantsFocus) { + loaded.focus?.(); + } + }).catch((error: unknown) => { + element.replaceChildren(el('div', { className: 'viewer-message muted', text: `The viewer could not start: ${error instanceof Error ? error.message : String(error)}` })); + }); + return { + element, + onShow: () => { shown = true; view?.onShow?.(); }, + onHide: () => { shown = false; view?.onHide?.(); }, + focus: () => { wantsFocus = true; view?.focus?.(); }, + fileChanged: (state) => view?.fileChanged?.(state), + dispose: () => { disposed = true; view?.dispose?.(); }, + }; +} diff --git a/apps/ide/src/renderer/viewers/imageViewer.ts b/apps/ide/src/renderer/viewers/imageViewer.ts new file mode 100644 index 000000000..f2069ce9e --- /dev/null +++ b/apps/ide/src/renderer/viewers/imageViewer.ts @@ -0,0 +1,134 @@ +import { el } from '../dom.ts'; +import type { CustomEditorView } from '../editor/customEditor.ts'; +import { clampZoom, dataUrlBytes, formatBytes, stepZoom, zoomLabel } from './viewerModel.ts'; +import { VIEWER_ICONS, viewerButton } from './viewerChrome.ts'; + +/** + * #256: an image of the folder in an editor tab. The bytes come from the + * main process as a `data:` URL (the only images the CSP lets the window + * load), the image starts fitted to the tab, and the toolbar zooms it in + * steps, to its actual size, or back to fit (Ctrl + wheel works too). + */ +export function createImageView(path: string, readImage: (path: string) => Promise): CustomEditorView { + const image = el('img', { className: 'image-viewer-image', attrs: { alt: path, draggable: 'false', 'data-testid': 'image-viewer-image' } }); + const stage = el('div', { className: 'viewer-scroll image-viewer-stage is-fit', attrs: { tabindex: '0', 'data-testid': 'image-viewer-stage' } }, [image]); + const message = el('div', { className: 'viewer-message muted', attrs: { hidden: '' } }); + const zoomText = el('span', { className: 'viewer-zoom', attrs: { 'data-testid': 'viewer-zoom' } }); + const info = el('span', { className: 'viewer-info muted', attrs: { 'data-testid': 'image-viewer-info' } }); + const fitButton = viewerButton('Fit to the tab', VIEWER_ICONS.fit, 'viewer-fit', () => setFit(true)); + const toolbar = el('div', { className: 'viewer-toolbar', attrs: { role: 'toolbar', 'aria-label': 'Image' } }, [ + viewerButton('Zoom out (Ctrl+-)', VIEWER_ICONS.zoomOut, 'viewer-zoom-out', () => zoomBy(-1)), + zoomText, + viewerButton('Zoom in (Ctrl+=)', VIEWER_ICONS.zoomIn, 'viewer-zoom-in', () => zoomBy(1)), + fitButton, + viewerButton('Actual size', VIEWER_ICONS.actualSize, 'viewer-actual-size', () => setZoom(1)), + el('span', { className: 'viewer-spacer' }), + info, + ]); + const element = el('div', { className: 'viewer image-viewer', attrs: { 'data-testid': 'image-viewer' } }, [toolbar, stage, message]); + + let fit = true; + let zoom = 1; + let bytes = 0; + let disposed = false; + + /** The zoom the fitted image is shown at (for the label, and as the start of a step). */ + function fittedZoom(): number { + if (!image.naturalWidth || !image.naturalHeight) { + return 1; + } + const width = stage.clientWidth - 32; + const height = stage.clientHeight - 32; + return Math.min(1, width / image.naturalWidth, height / image.naturalHeight); + } + + function render(): void { + stage.classList.toggle('is-fit', fit); + fitButton.setAttribute('aria-pressed', String(fit)); + if (fit) { + image.style.width = ''; + image.style.height = ''; + } else { + image.style.width = `${image.naturalWidth * zoom}px`; + image.style.height = `${image.naturalHeight * zoom}px`; + } + zoomText.textContent = zoomLabel(fit ? fittedZoom() : zoom); + info.textContent = image.naturalWidth ? `${image.naturalWidth} x ${image.naturalHeight} px, ${formatBytes(bytes)}` : ''; + } + + function setFit(value: boolean): void { + fit = value; + render(); + } + + function setZoom(value: number): void { + fit = false; + zoom = clampZoom(value); + render(); + } + + function zoomBy(direction: 1 | -1): void { + setZoom(stepZoom(fit ? fittedZoom() : zoom, direction)); + } + + function showMessage(text: string | null): void { + message.textContent = text ?? ''; + message.hidden = text === null; + stage.hidden = text !== null; + } + + async function load(): Promise { + let url: string | null; + try { + url = await readImage(path); + } catch { + url = null; + } + if (disposed) { + return; + } + if (!url) { + showMessage(`${path} cannot be shown: it is gone, over 8 MB, or not an image the viewer reads.`); + return; + } + bytes = dataUrlBytes(url); + showMessage(null); + image.src = url; + } + + image.addEventListener('load', render); + image.addEventListener('error', () => showMessage(`${path} is not an image the viewer can decode.`)); + stage.addEventListener('wheel', (event) => { + if (event.ctrlKey || event.metaKey) { + event.preventDefault(); + zoomBy(event.deltaY < 0 ? 1 : -1); + } + }, { passive: false }); + element.addEventListener('keydown', (event) => { + const mod = event.ctrlKey || event.metaKey; + if (mod && (event.key === '=' || event.key === '+')) { + zoomBy(1); + } else if (mod && event.key === '-') { + zoomBy(-1); + } else if (mod && event.key === '0') { + setFit(true); + } else { + return; + } + event.preventDefault(); + event.stopPropagation(); + }); + const resize = new ResizeObserver(() => { if (fit) { render(); } }); + resize.observe(stage); + void load(); + + return { + element, + focus: () => stage.focus(), + fileChanged: () => void load(), + dispose: () => { + disposed = true; + resize.disconnect(); + }, + }; +} diff --git a/apps/ide/src/renderer/viewers/pdfViewer.ts b/apps/ide/src/renderer/viewers/pdfViewer.ts new file mode 100644 index 000000000..80a40cb1a --- /dev/null +++ b/apps/ide/src/renderer/viewers/pdfViewer.ts @@ -0,0 +1,498 @@ +import { getDocument, GlobalWorkerOptions, PasswordException, PixelsPerInch, TextLayer, type PDFDocumentLoadingTask, type PDFDocumentProxy, type PDFPageProxy, type RenderTask } from 'pdfjs-dist'; +import PdfWorker from 'pdfjs-dist/build/pdf.worker.mjs?worker'; +import { el } from '../dom.ts'; +import type { CustomEditorView } from '../editor/customEditor.ts'; +import { fitZoom, findInPages, itemsInRange, stepZoom, clampZoom, zoomLabel, type PageMatch } from './viewerModel.ts'; +import { VIEWER_ICONS, viewerButton } from './viewerChrome.ts'; + +/** + * #256: a PDF of the folder in an editor tab, drawn by pdf.js. The bytes come + * from the main process (a size-capped read inside the folder); pdf.js parses + * them in its own worker, bundled by Vite and served from the app's origin, + * so the CSP stays as it is (`worker-src 'self'`, no frames, no objects). + * + * Pages are placeholders of the right size until they come near the + * viewport; only then is a page drawn on a canvas (at the screen's pixel + * ratio) with its text layer over it, so text selects and copies. Pages far + * from the viewport give their canvas back. The find (Ctrl+F) reads each + * page's text once, lists the matches, and highlights the current one. + */ + +let workerStarted = false; +/** One pdf.js worker for every PDF tab of the window. */ +function ensureWorker(): void { + if (!workerStarted) { + GlobalWorkerOptions.workerPort = new PdfWorker(); + workerStarted = true; + } +} + +/** CSS pixels per PDF point at 100 % (pdf.js's own viewer uses the same, 96/72). */ +const CSS_UNITS = PixelsPerInch.PDF_TO_CSS_UNITS; +/** Pages within this distance of the viewport are drawn. */ +const RENDER_MARGIN = '150% 0px'; + +interface PageSlot { + readonly index: number; + readonly element: HTMLElement; + /** The page's size at 100 %, in CSS pixels (the first page's until its own is known). */ + width: number; + height: number; + page: PDFPageProxy | null; + /** The zoom it is drawn at (0: not drawn). */ + drawnAt: number; + renderTask: RenderTask | null; + textLayer: TextLayer | null; + visible: boolean; +} + +export function createPdfView(path: string, readDocument: (path: string) => Promise): CustomEditorView { + const pages = el('div', { className: 'pdf-pages' }); + const scroll = el('div', { className: 'viewer-scroll pdf-scroll', attrs: { tabindex: '0', 'data-testid': 'pdf-scroll' } }, [pages]); + const message = el('div', { className: 'viewer-message muted', attrs: { hidden: '' } }); + const pageInput = el('input', { className: 'pdf-page-input', attrs: { type: 'text', inputmode: 'numeric', 'aria-label': 'Page number', 'data-testid': 'pdf-page-input', value: '1' } }); + const pageCount = el('span', { className: 'muted', attrs: { 'data-testid': 'pdf-page-count' } }); + const zoomText = el('span', { className: 'viewer-zoom', attrs: { 'data-testid': 'viewer-zoom' } }); + const findInput = el('input', { className: 'viewer-find-input', attrs: { type: 'search', placeholder: 'Find', 'aria-label': 'Find in the document', 'data-testid': 'pdf-find-input' } }); + const findCount = el('span', { className: 'viewer-find-count muted', attrs: { 'aria-live': 'polite', 'data-testid': 'pdf-find-count' } }); + const fitWidthButton = viewerButton('Fit width', VIEWER_ICONS.fitWidth, 'viewer-fit-width', () => setZoom('fit')); + const toolbar = el('div', { className: 'viewer-toolbar', attrs: { role: 'toolbar', 'aria-label': 'PDF' } }, [ + viewerButton('Previous page', VIEWER_ICONS.previous, 'pdf-previous-page', () => goToPage(currentPage - 1)), + viewerButton('Next page', VIEWER_ICONS.next, 'pdf-next-page', () => goToPage(currentPage + 1)), + pageInput, + pageCount, + el('span', { className: 'viewer-separator' }), + viewerButton('Zoom out (Ctrl+-)', VIEWER_ICONS.zoomOut, 'viewer-zoom-out', () => setZoom(stepZoom(zoom, -1))), + zoomText, + viewerButton('Zoom in (Ctrl+=)', VIEWER_ICONS.zoomIn, 'viewer-zoom-in', () => setZoom(stepZoom(zoom, 1))), + fitWidthButton, + viewerButton('Actual size', VIEWER_ICONS.actualSize, 'viewer-actual-size', () => setZoom(1)), + el('span', { className: 'viewer-spacer' }), + el('div', { className: 'viewer-find' }, [ + findInput, + findCount, + viewerButton('Previous match (Shift+Enter)', VIEWER_ICONS.previous, 'pdf-find-previous', () => stepMatch(-1)), + viewerButton('Next match (Enter)', VIEWER_ICONS.next, 'pdf-find-next', () => stepMatch(1)), + ]), + ]); + const element = el('div', { className: 'viewer pdf-viewer', attrs: { 'data-testid': 'pdf-viewer' } }, [toolbar, scroll, message]); + + let pdf: PDFDocumentProxy | null = null; + /** The loading task of `pdf`: destroying it frees the document in the worker. */ + let pdfTask: PDFDocumentLoadingTask | null = null; + let slots: PageSlot[] = []; + let zoom = 1; + let fitting = true; + let currentPage = 1; + let disposed = false; + /** Bumped on every (re)load: work of an older load stops when it sees another value. */ + let generation = 0; + let observer: IntersectionObserver | null = null; + // The find: each page's text items, read once per load, and the matches of the query. + let pageTexts: Promise | null = null; + let matches: PageMatch[] = []; + let matchIndex = -1; + let query = ''; + + function showMessage(text: string | null): void { + message.textContent = text ?? ''; + message.hidden = text === null; + scroll.hidden = text !== null; + } + + function sizeSlot(slot: PageSlot): void { + const width = Math.floor(slot.width * zoom); + const height = Math.floor(slot.height * zoom); + slot.element.style.width = `${width}px`; + slot.element.style.height = `${height}px`; + } + + function clearSlot(slot: PageSlot): void { + slot.renderTask?.cancel(); + slot.renderTask = null; + slot.textLayer?.cancel(); + slot.textLayer = null; + slot.drawnAt = 0; + slot.element.replaceChildren(); + } + + async function drawSlot(slot: PageSlot): Promise { + const doc = pdf; + const mine = generation; + if (!doc || slot.drawnAt === zoom) { + return; + } + clearSlot(slot); + const at = zoom; + slot.drawnAt = at; + const page = slot.page ?? await doc.getPage(slot.index + 1); + if (mine !== generation || slot.drawnAt !== at) { + return; + } + if (!slot.page) { + slot.page = page; + const natural = page.getViewport({ scale: CSS_UNITS }); + slot.width = natural.width; + slot.height = natural.height; + sizeSlot(slot); + } + const viewport = page.getViewport({ scale: at * CSS_UNITS }); + const ratio = window.devicePixelRatio || 1; + const canvas = el('canvas', { className: 'pdf-canvas' }); + canvas.width = Math.floor(viewport.width * ratio); + canvas.height = Math.floor(viewport.height * ratio); + canvas.style.width = `${Math.floor(viewport.width)}px`; + canvas.style.height = `${Math.floor(viewport.height)}px`; + const text = el('div', { className: 'textLayer' }); + slot.element.replaceChildren(canvas, text); + slot.element.style.setProperty('--total-scale-factor', String(viewport.scale)); + const task = page.render({ canvas, viewport, ...(ratio !== 1 ? { transform: [ratio, 0, 0, ratio, 0, 0] } : {}) }); + slot.renderTask = task; + const layer = new TextLayer({ textContentSource: page.streamTextContent(), container: text, viewport }); + slot.textLayer = layer; + try { + await Promise.all([task.promise, layer.render()]); + } catch { + return; // cancelled by a zoom, a scroll far away, or a reload + } + if (slot.renderTask === task) { + slot.renderTask = null; + markMatch(slot); + } + } + + function observe(): void { + observer?.disconnect(); + observer = new IntersectionObserver((entries) => { + for (const entry of entries) { + const slot = slots[Number((entry.target as HTMLElement).dataset['index'])]; + if (!slot) { + continue; + } + slot.visible = entry.isIntersecting; + if (entry.isIntersecting) { + void drawSlot(slot); + } else if (slot.drawnAt !== 0) { + clearSlot(slot); // its canvas memory goes back + } + } + }, { root: scroll, rootMargin: RENDER_MARGIN }); + for (const slot of slots) { + observer.observe(slot.element); + } + } + + function fitWidthZoom(): number { + const widest = slots.reduce((max, slot) => Math.max(max, slot.width), 0); + return fitZoom(widest, scroll.clientWidth - 16); + } + + /** Applies a zoom (a value, or 'fit' for the width), keeping the page in view. */ + function setZoom(value: number | 'fit'): void { + fitting = value === 'fit'; + const next = value === 'fit' ? fitWidthZoom() : clampZoom(value); + fitWidthButton.setAttribute('aria-pressed', String(fitting)); + zoomText.textContent = zoomLabel(next); + if (next === zoom || slots.length === 0) { + zoom = next; + return; + } + const slot = slots[currentPage - 1]; + const within = slot ? (scroll.scrollTop - slot.element.offsetTop) / Math.max(1, slot.element.offsetHeight) : 0; + zoom = next; + for (const each of slots) { + sizeSlot(each); + if (each.visible) { + void drawSlot(each); + } else { + clearSlot(each); + } + } + if (slot) { + scroll.scrollTop = slot.element.offsetTop + within * slot.element.offsetHeight; + } + } + + function goToPage(number: number): void { + const slot = slots[Math.min(Math.max(1, Math.round(number)), slots.length) - 1]; + if (slot) { + scroll.scrollTop = slot.element.offsetTop - 8; + setCurrentPage(slot.index + 1); + } + } + + function setCurrentPage(number: number): void { + currentPage = number; + if (document.activeElement !== pageInput) { + pageInput.value = String(number); + } + } + + /** The page under the middle of the viewport. */ + function pageAtScroll(): number { + const mark = scroll.scrollTop + scroll.clientHeight / 2; + let low = 0; + let high = slots.length - 1; + while (low < high) { + const middle = Math.ceil((low + high) / 2); + if ((slots[middle]?.element.offsetTop ?? 0) <= mark) { + low = middle; + } else { + high = middle - 1; + } + } + return low + 1; + } + + // The find. + function readTexts(): Promise { + const doc = pdf; + if (!doc) { + return Promise.resolve([]); + } + pageTexts ??= (async () => { + const texts: string[][] = []; + for (let number = 1; number <= doc.numPages; number++) { + const page = await doc.getPage(number); + const content = await page.getTextContent(); + texts.push(content.items.map((item) => ('str' in item ? item.str : ''))); + } + return texts; + })(); + return pageTexts; + } + + async function runFind(): Promise { + const wanted = findInput.value; + query = wanted; + const texts = await readTexts(); + if (query !== wanted) { + return; // typed on meanwhile + } + matches = findInPages(texts.map((items) => items.join('')), wanted); + matchIndex = matches.length > 0 ? 0 : -1; + showMatch(); + } + + function stepMatch(direction: 1 | -1): void { + if (matches.length === 0) { + void runFind(); + return; + } + matchIndex = (matchIndex + direction + matches.length) % matches.length; + showMatch(); + } + + function showMatch(): void { + findCount.textContent = query === '' ? '' : matches.length === 0 ? 'No results' : `${matchIndex + 1} of ${matches.length}`; + for (const slot of slots) { + markMatch(slot); + } + const match = matches[matchIndex]; + const slot = match ? slots[match.page] : undefined; + if (slot && match) { + const span = slot.element.querySelector('.highlight.selected'); + if (span) { + span.scrollIntoView({ block: 'center', inline: 'nearest' }); + } else { + goToPage(slot.index + 1); + } + } + } + + /** + * Highlights the current match on `slot` when it is the match's page and + * its text layer is drawn: the matched characters of each item it covers + * are wrapped in a mark, the rest of the item stays plain text. + */ + function markMatch(slot: PageSlot): void { + const layer = slot.textLayer; + if (!layer) { + return; + } + const strings = layer.textContentItemsStr; + const divs = layer.textDivs; + for (const div of slot.element.querySelectorAll('[data-marked]')) { + div.textContent = strings[Number(div.dataset['marked'])] ?? div.textContent; + delete div.dataset['marked']; + } + const match = matches[matchIndex]; + if (!match || match.page !== slot.index) { + return; + } + let start = 0; + const starts = strings.map((str) => { const at = start; start += str.length; return at; }); + const hit = itemsInRange(strings.map((str) => str.length), match.offset, query.length); + let first: HTMLElement | null = null; + for (const index of hit) { + const div = divs[index]; + const text = strings[index] ?? ''; + if (!div) { + continue; + } + const from = Math.max(0, match.offset - (starts[index] ?? 0)); + const to = Math.min(text.length, match.offset + query.length - (starts[index] ?? 0)); + const mark = el('span', { className: 'highlight selected', text: text.slice(from, to) }); + div.replaceChildren(text.slice(0, from), mark, text.slice(to)); + div.dataset['marked'] = String(index); + first ??= mark; + } + first?.scrollIntoView({ block: 'center', inline: 'nearest' }); + } + + async function load(): Promise { + const mine = ++generation; + const keepPage = currentPage; + let bytes: Uint8Array | null; + try { + bytes = await readDocument(path); + } catch { + bytes = null; + } + if (disposed || mine !== generation) { + return; + } + if (!bytes) { + showMessage(`${path} cannot be shown: it is gone, or over 64 MB.`); + return; + } + ensureWorker(); + let next: PDFDocumentProxy; + const task = getDocument({ data: bytes, useSystemFonts: true }); + try { + next = await task.promise; + } catch (error) { + if (!disposed && mine === generation) { + showMessage(error instanceof PasswordException + ? `${path} is protected by a password, which the viewer does not support yet.` + : `${path} is not a PDF the viewer can read: ${error instanceof Error ? error.message : String(error)}`); + } + return; + } + if (disposed || mine !== generation) { + void task.destroy(); + return; + } + // The new document replaces the old one only once it parsed. + for (const slot of slots) { + clearSlot(slot); + } + void pdfTask?.destroy(); + pdf = next; + pdfTask = task; + pageTexts = null; + matches = []; + matchIndex = -1; + const first = await next.getPage(1); + if (disposed || mine !== generation) { + return; + } + const size = first.getViewport({ scale: CSS_UNITS }); + slots = Array.from({ length: next.numPages }, (_, index) => ({ + index, + element: el('div', { className: 'pdf-page', attrs: { 'data-index': String(index), 'data-testid': 'pdf-page', 'aria-label': `Page ${index + 1}` } }), + width: size.width, + height: size.height, + page: index === 0 ? first : null, + drawnAt: 0, + renderTask: null, + textLayer: null, + visible: false, + })); + pages.replaceChildren(...slots.map((slot) => slot.element)); + pageCount.textContent = `of ${next.numPages}`; + showMessage(null); + const keepZoom = zoom; + zoom = 0; // forces the sizes below + setZoom(fitting ? 'fit' : keepZoom); + observe(); + goToPage(keepPage); + if (query !== '') { + void runFind(); + } + } + + scroll.addEventListener('scroll', () => setCurrentPage(pageAtScroll()), { passive: true }); + scroll.addEventListener('wheel', (event) => { + if (event.ctrlKey || event.metaKey) { + event.preventDefault(); + setZoom(stepZoom(zoom, event.deltaY < 0 ? 1 : -1)); + } + }, { passive: false }); + pageInput.addEventListener('keydown', (event) => { + if (event.key === 'Enter') { + goToPage(Number(pageInput.value)); + scroll.focus(); + event.preventDefault(); + } + }); + pageInput.addEventListener('blur', () => { pageInput.value = String(currentPage); }); + findInput.addEventListener('keydown', (event) => { + if (event.key === 'Enter') { + if (findInput.value !== query) { + void runFind(); + } else { + stepMatch(event.shiftKey ? -1 : 1); + } + event.preventDefault(); + } else if (event.key === 'Escape') { + findInput.value = ''; + query = ''; + matches = []; + matchIndex = -1; + showMatch(); + scroll.focus(); + event.preventDefault(); + } + }); + let findTimer: ReturnType | undefined; + findInput.addEventListener('input', () => { + clearTimeout(findTimer); + findTimer = setTimeout(() => void runFind(), 250); + }); + element.addEventListener('keydown', (event) => { + const mod = event.ctrlKey || event.metaKey; + const inField = event.target === findInput || event.target === pageInput; + if (mod && event.key.toLowerCase() === 'f') { + findInput.focus(); + findInput.select(); + } else if (mod && (event.key === '=' || event.key === '+')) { + setZoom(stepZoom(zoom, 1)); + } else if (mod && event.key === '-') { + setZoom(stepZoom(zoom, -1)); + } else if (mod && event.key === '0') { + setZoom('fit'); + } else if (!inField && (event.key === 'PageDown' || event.key === 'PageUp') && !mod) { + return; // the scroller handles them + } else if (!inField && !mod && (event.key === 'Home' || event.key === 'End')) { + goToPage(event.key === 'Home' ? 1 : slots.length); + } else { + return; + } + event.preventDefault(); + event.stopPropagation(); + }); + const resize = new ResizeObserver(() => { if (fitting && slots.length > 0) { setZoom('fit'); } }); + resize.observe(scroll); + zoomText.textContent = zoomLabel(1); + void load(); + + return { + element, + focus: () => scroll.focus(), + fileChanged: () => void load(), + dispose: () => { + disposed = true; + generation++; + clearTimeout(findTimer); + observer?.disconnect(); + resize.disconnect(); + for (const slot of slots) { + clearSlot(slot); + } + void pdfTask?.destroy(); + pdfTask = null; + pdf = null; + }, + }; +} diff --git a/apps/ide/src/renderer/viewers/viewerChrome.ts b/apps/ide/src/renderer/viewers/viewerChrome.ts new file mode 100644 index 000000000..6365865ef --- /dev/null +++ b/apps/ide/src/renderer/viewers/viewerChrome.ts @@ -0,0 +1,24 @@ +import { el, icon } from '../dom.ts'; +import './viewers.css'; + +/** #256: the toolbar icons of the PDF and image viewers (24x24 stroke paths). */ +export const VIEWER_ICONS = { + zoomIn: 'M11 4a7 7 0 1 0 0.01 0M16 16l5 5M8 11h6M11 8v6', + zoomOut: 'M11 4a7 7 0 1 0 0.01 0M16 16l5 5M8 11h6', + fit: 'M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5', + fitWidth: 'M3 12h18M7 8l-4 4 4 4M17 8l4 4-4 4', + actualSize: 'M5 6h2v12M15 6h2v12M11 9v0.01M11 15v0.01', + previous: 'M6 15l6-6 6 6', + next: 'M6 9l6 6 6-6', + search: 'M10 4a6 6 0 1 0 0.01 0M15 15l5 5', + close: 'M6 6l12 12M18 6L6 18', +} as const; + +export function viewerButton(label: string, path: string, testId: string, run: () => void): HTMLButtonElement { + const button = el('button', { className: 'icon-button', attrs: { type: 'button', title: label, 'aria-label': label, 'data-testid': testId } }, [icon(path)]); + button.addEventListener('click', (event) => { + event.stopPropagation(); + run(); + }); + return button; +} diff --git a/apps/ide/src/renderer/viewers/viewerModel.ts b/apps/ide/src/renderer/viewers/viewerModel.ts new file mode 100644 index 000000000..be09dc734 --- /dev/null +++ b/apps/ide/src/renderer/viewers/viewerModel.ts @@ -0,0 +1,98 @@ +/** + * #256: the pure parts of the PDF and image viewers: zoom steps, the matches + * of a find over page texts, and the size line. Kept free of the DOM so the + * unit tests run them under Node. + */ + +/** The zoom levels the + and - buttons step through (1 is 100 %). */ +export const ZOOM_STEPS: readonly number[] = [0.25, 0.33, 0.5, 0.67, 0.75, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5]; +export const MIN_ZOOM = ZOOM_STEPS[0] ?? 0.25; +export const MAX_ZOOM = ZOOM_STEPS[ZOOM_STEPS.length - 1] ?? 5; + +export function clampZoom(zoom: number): number { + return Number.isFinite(zoom) ? Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, zoom)) : 1; +} + +/** The next step above (`direction` 1) or below (-1) `zoom`, which need not be a step itself (a fit). */ +export function stepZoom(zoom: number, direction: 1 | -1): number { + const epsilon = 1e-6; + if (direction > 0) { + return ZOOM_STEPS.find((step) => step > zoom + epsilon) ?? MAX_ZOOM; + } + return [...ZOOM_STEPS].reverse().find((step) => step < zoom - epsilon) ?? MIN_ZOOM; +} + +/** The zoom that makes `contentWidth` fill `availableWidth` (a margin each side), within the limits. */ +export function fitZoom(contentWidth: number, availableWidth: number, margin = 16): number { + if (contentWidth <= 0 || availableWidth <= 2 * margin) { + return 1; + } + return clampZoom((availableWidth - 2 * margin) / contentWidth); +} + +export function zoomLabel(zoom: number): string { + return `${Math.round(zoom * 100)}%`; +} + +/** A match of the find: page index (from 0) and the character offset in that page's text. */ +export interface PageMatch { + readonly page: number; + readonly offset: number; +} + +/** At most this many matches are listed (a one-letter query on a book would list them all). */ +export const MAX_FIND_MATCHES = 1000; + +/** Every case-insensitive occurrence of `query` in `pages`, in reading order. */ +export function findInPages(pages: readonly string[], query: string): PageMatch[] { + const needle = query.toLocaleLowerCase(); + const matches: PageMatch[] = []; + if (needle.length === 0) { + return matches; + } + pages.forEach((text, page) => { + const haystack = text.toLocaleLowerCase(); + let offset = haystack.indexOf(needle); + while (offset >= 0 && matches.length < MAX_FIND_MATCHES) { + matches.push({ page, offset }); + offset = haystack.indexOf(needle, offset + needle.length); + } + }); + return matches; +} + +/** + * The items of a page's text that a match from `offset` spanning `length` + * characters touches, given each item's length in order (the page's text is + * the items joined). Returns item indexes. + */ +export function itemsInRange(itemLengths: readonly number[], offset: number, length: number): number[] { + const hit: number[] = []; + let start = 0; + itemLengths.forEach((itemLength, index) => { + const end = start + itemLength; + if (itemLength > 0 && end > offset && start < offset + length) { + hit.push(index); + } + start = end; + }); + return hit; +} + +export function formatBytes(bytes: number): string { + if (bytes < 1024) { + return `${bytes} B`; + } + if (bytes < 1024 * 1024) { + return `${(bytes / 1024).toFixed(1)} KB`; + } + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +/** The decoded size of a base64 `data:` URL's payload. */ +export function dataUrlBytes(url: string): number { + const comma = url.indexOf(','); + const payload = comma >= 0 ? url.slice(comma + 1) : ''; + const padding = payload.endsWith('==') ? 2 : payload.endsWith('=') ? 1 : 0; + return Math.max(0, Math.floor((payload.length * 3) / 4) - padding); +} diff --git a/apps/ide/src/renderer/viewers/viewers.css b/apps/ide/src/renderer/viewers/viewers.css new file mode 100644 index 000000000..35c61cdbf --- /dev/null +++ b/apps/ide/src/renderer/viewers/viewers.css @@ -0,0 +1,110 @@ +/* #256: the PDF and image viewer tabs. */ + +.viewer-lazy { display: flex; flex-direction: column; min-height: 0; } +.viewer-lazy > * { flex: 1; min-height: 0; } +.viewer { display: flex; flex-direction: column; min-height: 0; height: 100%; background: var(--editor); } +.viewer-toolbar { + flex: none; + display: flex; + align-items: center; + gap: 2px; + min-height: 32px; + padding: 2px 8px; + border-bottom: 1px solid var(--line); + background: var(--chrome); + font-size: 12px; + flex-wrap: wrap; + white-space: nowrap; +} +.viewer-toolbar .icon-button[aria-pressed='true'] { background: var(--hover); color: var(--fg); } +.viewer-spacer { flex: 1; min-width: 8px; } +.viewer-separator { width: 1px; height: 16px; margin: 0 6px; background: var(--line); } +.viewer-zoom { min-width: 40px; text-align: center; font-variant-numeric: tabular-nums; } +.viewer-info { font-variant-numeric: tabular-nums; } +.viewer-scroll { flex: 1; min-height: 0; overflow: auto; outline: none; } +.viewer-scroll[hidden], .viewer-message[hidden] { display: none; } +.viewer-message { flex: 1; display: grid; place-items: center; padding: 24px; text-align: center; } +.viewer-find { display: flex; align-items: center; gap: 2px; } +.viewer-find-input, .pdf-page-input { + height: 22px; + border: 1px solid var(--line); + border-radius: 3px; + background: var(--editor); + color: var(--fg); + font: inherit; +} +.viewer-find-input { width: 160px; padding: 0 6px; } +.viewer-find-input:focus, .pdf-page-input:focus { outline: 1px solid var(--accent); outline-offset: -1px; } +.viewer-find-count { min-width: 64px; margin: 0 4px; text-align: center; font-variant-numeric: tabular-nums; } +.pdf-page-input { width: 40px; margin: 0 4px; text-align: center; } + +/* The image: fitted by default, checkerboard behind transparency. */ +.image-viewer-stage { display: grid; place-items: center; padding: 16px; box-sizing: border-box; } +.image-viewer-image { + background-color: #fff; + background-image: + linear-gradient(45deg, #ddd 25%, transparent 25%), linear-gradient(-45deg, #ddd 25%, transparent 25%), + linear-gradient(45deg, transparent 75%, #ddd 75%), linear-gradient(-45deg, transparent 75%, #ddd 75%); + background-size: 16px 16px; + background-position: 0 0, 0 8px, 8px -8px, -8px 0; + box-shadow: 0 1px 6px rgba(0, 0, 0, 0.3); + image-rendering: auto; +} +.image-viewer-stage.is-fit { overflow: hidden; } +.image-viewer-stage.is-fit .image-viewer-image { max-width: 100%; max-height: 100%; object-fit: contain; } + +/* The PDF: pages down the middle, drawn white whatever the theme. */ +.pdf-scroll { position: relative; background: var(--panel); } +.pdf-pages { display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 12px 8px; width: max-content; min-width: 100%; box-sizing: border-box; } +.pdf-page { + position: relative; + flex: none; + background: #fff; + box-shadow: 0 1px 6px rgba(0, 0, 0, 0.35); + --scale-round-x: 1px; + --scale-round-y: 1px; +} +.pdf-canvas { display: block; } + +/* pdf.js's text layer (from its pdf_viewer.css, trimmed): transparent text over the canvas, for selection and find. */ +.pdf-page .textLayer { + color-scheme: only light; + position: absolute; + text-align: initial; + inset: 0; + overflow: clip; + opacity: 1; + line-height: 1; + letter-spacing: normal; + word-spacing: normal; + text-size-adjust: none; + forced-color-adjust: none; + transform-origin: 0 0; + z-index: 0; + --min-font-size: 1; + --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); + --min-font-size-inv: calc(1 / var(--min-font-size)); +} +.pdf-page .textLayer :is(span, br) { + color: transparent; + position: absolute; + white-space: pre; + cursor: text; + transform-origin: 0% 0%; + user-select: text; +} +.pdf-page .textLayer > :not(.markedContent), +.pdf-page .textLayer .markedContent span:not(.markedContent) { + z-index: 1; + --font-height: 0; + font-size: calc(var(--text-scale-factor) * var(--font-height)); + --scale-x: 1; + --rotate: 0deg; + transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv)); +} +.pdf-page .textLayer .markedContent { display: contents; } +.pdf-page .textLayer ::selection { background: rgba(0, 120, 215, 0.3); color: transparent; } +.pdf-page .textLayer br::selection { background: transparent; } +.pdf-page .textLayer .endOfContent { display: block; position: absolute; inset: 100% 0 0; z-index: 0; cursor: default; user-select: none; } +.pdf-page .textLayer.selecting .endOfContent { top: 0; } +.pdf-page .textLayer .highlight { position: static; margin: -1px; padding: 1px; border-radius: 3px; background-color: rgba(255, 140, 0, 0.5); } diff --git a/apps/ide/src/shared/api.ts b/apps/ide/src/shared/api.ts index 64113065d..5b54453c3 100644 --- a/apps/ide/src/shared/api.ts +++ b/apps/ide/src/shared/api.ts @@ -476,9 +476,11 @@ export interface CodeXRApi { /** * #179: an image of the open folder as a `data:` URL, for the Markdown * preview (the CSP lets the window load nothing else). Null for a file - * that is not a PNG, JPEG, GIF, WebP or BMP image, or over 8 MB. + * that is not a PNG, JPEG, GIF, WebP, BMP, ICO or AVIF image, or over 8 MB. */ readImage(path: string): Promise; + /** #256: a PDF of the open folder as bytes, for the PDF viewer tab; null for another file or one over 64 MB. */ + readDocument(path: string): Promise; /** #179: opens an http(s) or mailto link in the system's browser or mail app; any other URL is refused. */ openExternalLink(url: string): Promise; /** Recently opened folders, most recent first (absolute paths, for display and `openRecent`). */ @@ -614,6 +616,7 @@ export const IPC_CHANNELS = { workspaceRename: 'codexr:workspace:rename', workspaceCopyPath: 'codexr:workspace:copy-path', workspaceReadImage: 'codexr:workspace:read-image', + workspaceReadDocument: 'codexr:workspace:read-document', workspaceTrust: 'codexr:workspace:trust', workspaceSetTrust: 'codexr:workspace:set-trust', workspaceOpenExternalLink: 'codexr:workspace:open-external-link', diff --git a/apps/ide/test/viewers.test.ts b/apps/ide/test/viewers.test.ts new file mode 100644 index 000000000..7c8ded8c9 --- /dev/null +++ b/apps/ide/test/viewers.test.ts @@ -0,0 +1,110 @@ +import { after, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { clampZoom, dataUrlBytes, findInPages, fitZoom, formatBytes, itemsInRange, MAX_FIND_MATCHES, MAX_ZOOM, MIN_ZOOM, stepZoom, zoomLabel } from '../src/renderer/viewers/viewerModel.ts'; +import { CustomEditorRegistry, extensionOf, isSchemeId, VIEWER_IMAGE_EXTENSIONS } from '../src/renderer/editor/customEditorRegistry.ts'; +import { imageMimeType, MAX_DOCUMENT_BYTES, Workspace } from '../src/main/workspace/workspace.ts'; + +describe('Viewer model (#256)', () => { + it('steps the zoom through the fixed levels, from any value', () => { + assert.equal(stepZoom(1, 1), 1.1); + assert.equal(stepZoom(1, -1), 0.9); + assert.equal(stepZoom(1.03, 1), 1.1, 'a fitted zoom steps to the next level up'); + assert.equal(stepZoom(1.03, -1), 1); + assert.equal(stepZoom(MAX_ZOOM, 1), MAX_ZOOM); + assert.equal(stepZoom(MIN_ZOOM, -1), MIN_ZOOM); + assert.equal(clampZoom(100), MAX_ZOOM); + assert.equal(clampZoom(Number.NaN), 1); + assert.equal(zoomLabel(1.254), '125%'); + }); + + it('fits a width into the room left by the margins', () => { + assert.equal(fitZoom(500, 1032), 2); + assert.equal(fitZoom(0, 800), 1); + assert.equal(fitZoom(100_000, 800), MIN_ZOOM); + }); + + it('finds every case-insensitive match, page by page', () => { + assert.deepEqual(findInPages(['Abc abc', '', 'xABCx'], 'abc'), [{ page: 0, offset: 0 }, { page: 0, offset: 4 }, { page: 2, offset: 1 }]); + assert.deepEqual(findInPages(['aaaa'], 'aa'), [{ page: 0, offset: 0 }, { page: 0, offset: 2 }], 'matches do not overlap'); + assert.deepEqual(findInPages(['abc'], ''), []); + assert.equal(findInPages(['a'.repeat(5000)], 'a').length, MAX_FIND_MATCHES); + }); + + it('maps a match to the text items it covers', () => { + // Items "Hello ", "", "wor", "ld!": "o wo" starts at 4 and spans 4. + assert.deepEqual(itemsInRange([6, 0, 3, 4], 4, 4), [0, 2]); + assert.deepEqual(itemsInRange([6, 0, 3, 4], 9, 1), [3]); + assert.deepEqual(itemsInRange([3], 5, 1), []); + }); + + it('formats sizes and measures a data URL', () => { + assert.equal(formatBytes(512), '512 B'); + assert.equal(formatBytes(2048), '2.0 KB'); + assert.equal(formatBytes(3 * 1024 * 1024), '3.0 MB'); + assert.equal(dataUrlBytes('data:image/png;base64,iVBORw=='), 4); + assert.equal(dataUrlBytes('data:image/png;base64,'), 0); + }); +}); + +describe('Custom editor seam (#256)', () => { + const input = (id: string): { readonly id: string } => ({ id }); + + it('asks the resolvers in order and stops at the first answer', () => { + const registry = new CustomEditorRegistry<{ readonly id: string }>(); + const asked: string[] = []; + registry.register((id) => { asked.push(`a:${id}`); return id.startsWith('chat:') ? input(id) : null; }); + const remove = registry.register((id) => { asked.push(`b:${id}`); return input(`b-${id}`); }); + assert.equal(registry.resolve('chat:1')?.id, 'chat:1'); + assert.equal(registry.resolve('x.pdf')?.id, 'b-x.pdf'); + assert.deepEqual(asked, ['a:chat:1', 'a:x.pdf', 'b:x.pdf']); + remove(); + assert.equal(registry.resolve('x.pdf'), null); + }); + + it('reads extensions the way the viewers pick files', () => { + assert.equal(extensionOf('docs/Paper.PDF'), 'pdf'); + assert.equal(extensionOf('a.b/c'), ''); + assert.equal(extensionOf('.gitignore'), '', 'a dot file has no extension'); + for (const extension of VIEWER_IMAGE_EXTENSIONS) { + assert.ok(imageMimeType(`x.${extension}`), `the image viewer's ${extension} is one readImage serves`); + } + assert.equal(VIEWER_IMAGE_EXTENSIONS.has('svg'), false, 'SVG stays text'); + assert.equal(isSchemeId('chat:42'), true); + assert.equal(isSchemeId('docs/a.pdf'), false); + assert.equal(isSchemeId('C-1.pdf'), false); + }); +}); + +describe('Document reads, main process (#256)', () => { + const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-viewers-'))); + const root = path.join(base, 'project'); + fs.mkdirSync(path.join(root, 'docs'), { recursive: true }); + fs.writeFileSync(path.join(root, 'docs', 'paper.pdf'), Buffer.from('%PDF-1.7\n%âã\n', 'latin1')); + fs.writeFileSync(path.join(root, 'docs', 'notes.txt'), 'text'); + fs.writeFileSync(path.join(base, 'outside.pdf'), Buffer.from('%PDF')); + let linked = true; + try { + fs.symlinkSync(path.join(base, 'outside.pdf'), path.join(root, 'link.pdf')); + } catch { + linked = false; // Windows without the symlink privilege + } + after(() => fs.rmSync(base, { recursive: true, force: true })); + + it('reads PDFs of the folder only, as bytes', async () => { + const workspace = await Workspace.open(root); + const bytes = await workspace.readDocument('docs/paper.pdf'); + assert.ok(bytes instanceof Uint8Array); + assert.equal(Buffer.from(bytes).subarray(0, 8).toString('latin1'), '%PDF-1.7'); + assert.equal(await workspace.readDocument('docs/notes.txt'), null, 'not a document type'); + assert.equal(await workspace.readDocument('docs'), null, 'no extension'); + await assert.rejects(workspace.readDocument('../outside.pdf')); + if (linked) { + await assert.rejects(workspace.readDocument('link.pdf'), 'a symlink out of the folder'); + } + await assert.rejects(workspace.readDocument(42)); + assert.ok(MAX_DOCUMENT_BYTES >= 32 * 1024 * 1024); + }); +}); diff --git a/package-lock.json b/package-lock.json index 6c4dee0f9..89c841833 100644 --- a/package-lock.json +++ b/package-lock.json @@ -34,6 +34,7 @@ "marked": "14.0.0", "material-icon-theme": "^5.40.0", "monaco-editor": "0.57.0", + "pdfjs-dist": "6.5.438", "vite": "^8.3.8", "vscode-jsonrpc": "9.0.3", "vscode-languageserver-types": "3.18.4" @@ -1134,6 +1135,283 @@ "node": ">=10" } }, + "node_modules/@napi-rs/canvas": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.2.1.tgz", + "integrity": "sha512-dTFJYKi4eE9Yr9FlLi7hN/Q+15VVmpnA1HrKkTzGQuWiVw5MWBL2reLXAaXUMENmzKxtlqYCtCp1NIeQqx+uEA==", + "dev": true, + "license": "MIT", + "optional": true, + "workspaces": [ + "e2e/*" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "optionalDependencies": { + "@napi-rs/canvas-android-arm64": "1.2.1", + "@napi-rs/canvas-darwin-arm64": "1.2.1", + "@napi-rs/canvas-darwin-x64": "1.2.1", + "@napi-rs/canvas-linux-arm-gnueabihf": "1.2.1", + "@napi-rs/canvas-linux-arm64-gnu": "1.2.1", + "@napi-rs/canvas-linux-arm64-musl": "1.2.1", + "@napi-rs/canvas-linux-riscv64-gnu": "1.2.1", + "@napi-rs/canvas-linux-x64-gnu": "1.2.1", + "@napi-rs/canvas-linux-x64-musl": "1.2.1", + "@napi-rs/canvas-win32-arm64-msvc": "1.2.1", + "@napi-rs/canvas-win32-x64-msvc": "1.2.1" + } + }, + "node_modules/@napi-rs/canvas-android-arm64": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.2.1.tgz", + "integrity": "sha512-CtM+0Xieqc8jMyIm6sPLbnvDut4/BmSAP+HQnbbwPcw3ZG+bY1NhwndtpOzAPcNbIPyWuiShSF99/Ja7vYeXbw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-darwin-arm64": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.2.1.tgz", + "integrity": "sha512-DazlaWwTa1xIdROpA8e95ttU4yNedl6brXbqBm+upoQ/1WIpmDu4zwanYp6ftGIbrjMld/OjJK15kFrDPWLoEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-darwin-x64": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.2.1.tgz", + "integrity": "sha512-XU9zFjeRusfeP49/Dk4CNqvMzxOiBtrl6Qoyndp2Wxk0LhJxgiUhhSMGLIripipZZKfKJOo1h/k8FswMVk0PuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.2.1.tgz", + "integrity": "sha512-24R1MI8ZcWSrqU5rD+hRelWsoExMc4Bo8vRbIIge4f5X97P4pvrPMIMV0e5szSyU9y5aF8gA+CCXwWWRwFthYg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-arm64-gnu": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.2.1.tgz", + "integrity": "sha512-2pxxAlQ3wTYxqZnuqXhQbE4sTvLC1/dYkuPpudggCgvQXRb6KYm6K01UAL2kWqpkTqFmy6kHfIjLJ/86vQhOnQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-arm64-musl": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.2.1.tgz", + "integrity": "sha512-+Ksk8ilbmbA4oMu+BfOL/WZMeDY0Z40TblthqS8Ssr6K7MFXh9707O1H3uJcVx3H7plXWsDuycGai20FBRO0sg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-riscv64-gnu": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.2.1.tgz", + "integrity": "sha512-B7Y0cljUn/kTmDiSJ7q94axEvQMJLoJZX8FDf8+JdvAkQiUR2tHnDomGIxtHsvXGmzf3UE736YdtvNLEfCDjdg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-x64-gnu": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.2.1.tgz", + "integrity": "sha512-1/7y8Yx589PcQE8Xuvc0ZLRwEsjA1FonfV+ZWUS4s+pwI6Aa5i+VHUhAv+pR1692A+mIjuaH5FpH89+CFK0Nng==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-x64-musl": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.2.1.tgz", + "integrity": "sha512-fiO90vFdt9Kq3v+sPHSczzbpRi2CTMx6NQdfD31zfJFeouXVR8EeiGyHpXuV5wwE6ui7IQLmVTHq7Uz3V0xq/w==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-win32-arm64-msvc": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.2.1.tgz", + "integrity": "sha512-COZrzxhGGpWwP+3xMtppDz3J7ycLKsIZfClKxAmJRZFR5sVmiujy+ShnMyzmQtzTzpFInxkzQ35maAxYjR88kA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-win32-x64-msvc": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.2.1.tgz", + "integrity": "sha512-oPzPLrFlox/NAcqVVT8mHaXF0FsQ2XXX3nWy/l5yV/NksxBf9V/nnCes+O5fz+xzzwDNVjL5EOk7+siz5HmfCA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, "node_modules/@napi-rs/wasm-runtime": { "version": "1.2.6", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", @@ -7919,6 +8197,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/pdfjs-dist": { + "version": "6.5.438", + "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz", + "integrity": "sha512-vg8Pw1x+AFKy4AMDvhuWl5cOYV8d698UoEANoFFhc79hqXDnZQqnOXoxw3HG907WHOg1JYOvLhP756boddFxpA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=22.13.0 || >=24" + }, + "optionalDependencies": { + "@napi-rs/canvas": "^1.0.13" + } + }, "node_modules/pe-library": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/pe-library/-/pe-library-0.4.1.tgz",