Make PDF Viewer a native feature

- Move the PDF Viewer plugin into src/lib/features/pdf/ with pdfjs-dist 6.4.299 (minified builds).
- A static pdf document type marks PDF files and opens them as tabs. The first PDF tab loads the module.
- The worker, the character maps, the fonts, and the decoders come from the app. One worker for each tab.
- The toolbar uses IconButton and the shared tooltip, with the new zoom-in, zoom-out, fit-width, and rotate icons.
- Add THIRD_PARTY_NOTICES.md for PDF.js and xterm.
- Update the tests, the menu inventory, the docs, and UI-059.
This commit is contained in:
Knotty Wyvern
2026-10-29 19:41:17 -07:00
parent 833f793244
commit e6deecc092
35 changed files with 2101 additions and 49 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
RuneStone is a desktop workspace for Markdown notes, code, and project work in ordinary local files. RuneStone is a desktop workspace for Markdown notes, code, and project work in ordinary local files.
A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface (`src/`). A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface (`src/`).
Git, Background, and Terminal are native features with an off switch in Settings → Features (`src/lib/features/`). They do not use the plugin API. Git, Background, Terminal, and PDF Viewer are native features with an off switch in Settings → Features (`src/lib/features/`). They do not use the plugin API.
Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_CSV_Viewer`. Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_CSV_Viewer`.
The [development guide](docs/development.md#architecture) maps the source folders. The [development guide](docs/development.md#architecture) maps the source folders.
File diff suppressed because it is too large Load Diff
+15
View File
@@ -1076,3 +1076,18 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
- Evidence: `tests/smoke/features/terminal.smoke.mjs` and `tests/unit/features/terminal.spec.ts`, with screenshots in both themes and at 360 pixels in `output/smoke/features/terminal/`. - Evidence: `tests/smoke/features/terminal.smoke.mjs` and `tests/unit/features/terminal.spec.ts`, with screenshots in both themes and at 360 pixels in `output/smoke/features/terminal/`.
- Replaces / replaced by: The settings dialog and the ANSI color map of the Terminal plugin. The terminal roles of [UI-042](#ui-042--theme-file-format-3-and-terminal-colors) and the selection cap of [UI-029](#ui-029--text-selection-transparency) stay. - Replaces / replaced by: The settings dialog and the ANSI color map of the Terminal plugin. The terminal roles of [UI-042](#ui-042--theme-file-format-3-and-terminal-colors) and the selection cap of [UI-029](#ui-029--text-selection-transparency) stay.
- Limits: The smoke tests use mock shells. Real shells, dictation, and native desktop appearance need user review. The old package stays installed until the user removes it. - Limits: The smoke tests use mock shells. Real shells, dictation, and native desktop appearance need user review. The old package stays installed until the user removes it.
### UI-059 — The PDF toolbar on shared controls
- Type: Rule change
- Date: 2026-10-29
- Status: Implemented for user review
- Decision source: The owner decisions of Phase 7, stage 7-4 (2026-10-29), and decision 5C.
- Previous rule: The PDF Viewer plugin (`runestone.pdf-viewer` 0.0.5) drew its own toolbar buttons, tooltip spans, and `title` tooltips. **Fit width** and **Reload PDF** showed a caption. Disabled buttons faded with opacity. Rotation used an icon that the plugin drew. All strings were English only.
- New rule: PDF Viewer is a native feature with a switch in Settings → Features. Each PDF tab has one toolbar of shared `IconButton` controls with the shared tooltip: **Previous page**, the page field, the page count, **Next page**, **Zoom out**, the zoom percent, **Zoom in**, **Fit width**, **Rotate clockwise**, and **Reload PDF**. All buttons are icon only. **Fit width** is a toggle with the selection fill and the accent bar while the page fits the tab. Previous and next page use the `up` and `down` icons of the find panel. The new shared icons are `zoom-in`, `zoom-out`, `fit-width`, and `rotate`. The toolbar wraps in a narrow tab. The page is white paper in both themes. All strings come from the catalog.
- Reason: The owner chose response time and memory over the plugin API. The PDF toolbar is a compact toolbar of familiar actions, so it follows the icon rules of [Icons and labels](ui-design.md#icons-and-labels).
- Scope: The PDF tab, its toolbar, its password form, its status line, the file tree mark of PDF files, and Settings → Features.
- Shared implementation: `src/lib/features/pdf/`, `src/lib/features/pdfDocument.ts`, `src/lib/features/session.ts`, `src/lib/ui/Icon.svelte`, and `src/lib/ui/IconButton.svelte`.
- Evidence: `tests/smoke/features/pdf.smoke.mjs` and `tests/unit/features/pdf.spec.ts`, with screenshots in both themes, at 900 pixels, and with keyboard focus in `output/smoke/features/pdf/`.
- Replaces / replaced by: The toolbar of the PDF Viewer plugin.
- Limits: The tab shows one page at a time. The old package stays installed until the user removes it.
+6 -3
View File
@@ -209,16 +209,16 @@ Errors of the plugin API stay in English, because they are for plugin developers
## Native features ## Native features
Git, Background, and Terminal are native features: host code with an off switch in **Settings → Features**. They do not use the plugin API. Git, Background, Terminal, and PDF Viewer are native features: host code with an off switch in **Settings → Features**. They do not use the plugin API.
| Part | File | | Part | File |
| --- | --- | | --- | --- |
| The catalog: ID, old plugin ID, name, views, and commands | `src/lib/features/catalog.ts` | | The catalog: ID, old plugin ID, name, views, commands, and document types | `src/lib/features/catalog.ts` |
| The switches: the `features` settings section | `src/lib/features/state.ts` | | The switches: the `features` settings section | `src/lib/features/state.ts` |
| The first start: each switch takes the state of the old plugin package, or the default of the feature when `followsPackage` is false | `src/lib/features/migration.ts` and `src-tauri/src/features.rs` | | The first start: each switch takes the state of the old plugin package, or the default of the feature when `followsPackage` is false | `src/lib/features/migration.ts` and `src-tauri/src/features.rs` |
| One import at first need in each window | `src/lib/features/loader.ts` | | One import at first need in each window | `src/lib/features/loader.ts` |
| A start without a view: the launch rules, also the rule for browser windows | `src/lib/features/launch.ts` | | A start without a view: the launch rules, also the rule for browser windows | `src/lib/features/launch.ts` |
| Views and commands in the workbench | `src/lib/features/session.ts` and `src/lib/plugins/external.ts` | | Views, commands, and document tabs in the workbench | `src/lib/features/session.ts` and `src/lib/plugins/external.ts` |
| The feature code | `src/lib/features/<feature>/index.ts` and its components | | The feature code | `src/lib/features/<feature>/index.ts` and its components |
- The catalog holds only static data, so the main bundle stays small. The feature code loads when the user first opens a view, a tab, or a command of the feature. An off feature loads nothing. - The catalog holds only static data, so the main bundle stays small. The feature code loads when the user first opens a view, a tab, or a command of the feature. An off feature loads nothing.
@@ -227,6 +227,9 @@ Git, Background, and Terminal are native features: host code with an off switch
- The first start makes the `background` section from the kept settings of the Background Slideshow plugin and from the old background image. `background_migrate` copies the folder of the old plugin grant to the host only when the host has no folder. - The first start makes the `background` section from the kept settings of the Background Slideshow plugin and from the old background image. `background_migrate` copies the folder of the old plugin grant to the host only when the host has no folder.
- Terminal has no view and no launch rule. `TerminalHost.svelte` puts the panel in the workbench and in the terminal window, and the first use loads the module. `terminalKeys.ts` holds the shortcuts and the Help rows. Settings → Terminal (`TerminalSettings.svelte`) loads no xterm. - Terminal has no view and no launch rule. `TerminalHost.svelte` puts the panel in the workbench and in the terminal window, and the first use loads the module. `terminalKeys.ts` holds the shortcuts and the Help rows. Settings → Terminal (`TerminalSettings.svelte`) loads no xterm.
- `@xterm/xterm` and `@xterm/addon-fit` are host dependencies. `pnpm check:features` keeps them out of the start chunks. - `@xterm/xterm` and `@xterm/addon-fit` are host dependencies. `pnpm check:features` keeps them out of the start chunks.
- PDF Viewer has a document type and no view. The file tree marks PDF files through `identifyPdf` in `src/lib/features/pdfDocument.ts`, in the main bundle. The first PDF tab loads the module and calls `FeatureInstance.mountDocument`. Each tab reads its file with `workspace_read_bytes` and starts its own PDF.js worker. Closing the tab, or Off, stops the worker.
- `pdfjs-dist` is a host dependency. `src/lib/features/pdf/engine.ts` loads the minified build. The worker, the character maps, the standard fonts, and the image decoders are Vite assets of the app, so PDF.js makes no network request. `build.assetsInlineLimit` in `vite.config.js` keeps these files out of the code.
- [THIRD_PARTY_NOTICES.md](../THIRD_PARTY_NOTICES.md) gives the version, license, and source of each third-party package that a feature includes. Update it when you add or update such a package.
- The first start makes the `terminal` section from the `runestone.terminal` key of `localStorage`, which the Terminal plugin wrote. The old key stays. - The first start makes the `terminal` section from the `runestone.terminal` key of `localStorage`, which the Terminal plugin wrote. The old key stays.
- Before Terminal goes off, Settings asks `pty_running` for the shells of all windows. Off closes the sessions of each window. - Before Terminal goes off, Settings asks `pty_running` for the shells of all windows. Off closes the sessions of each window.
- Host code never imports a feature folder statically. `pnpm check:features` builds the app. It fails when a feature module, or a library that only a feature needs, is in a chunk that loads at start. - Host code never imports a feature folder statically. `pnpm check:features` builds the app. It fails when a feature module, or a library that only a feature needs, is in a chunk that loads at start.
-1
View File
@@ -5,7 +5,6 @@
"RuneStone_Project_Management", "RuneStone_Project_Management",
"RuneStone_Background_Slideshow", "RuneStone_Background_Slideshow",
"RuneStone_Local_Autocomplete", "RuneStone_Local_Autocomplete",
"RuneStone_PDF_Viewer",
"RuneStone_CSV_Viewer" "RuneStone_CSV_Viewer"
], ],
"limits": [ "limits": [
+1 -1
View File
@@ -422,7 +422,7 @@ Do not call `invoke`, `listen`, or other `@tauri-apps/api` functions from a plug
Use the `api` members of the [API reference](#api-reference). They check plugin shutdown, and they will stay available when a later host runs each plugin in its own isolated context. Use the `api` members of the [API reference](#api-reference). They check plugin shutdown, and they will stay available when a later host runs each plugin in its own isolated context.
Make sure that an optional member exists before you use it. Make sure that an optional member exists before you use it.
The Project Management, Local Autocomplete, PDF Viewer, and CSV Viewer plugins make no native calls. The Project Management, Local Autocomplete, and CSV Viewer plugins make no native calls.
Their test scripts replace `window.__TAURI_INTERNALS__` with a test double. That is test code and does not go into the package. Their test scripts replace `window.__TAURI_INTERNALS__` with a test double. That is test code and does not go into the package.
## Folder grants ## Folder grants
+5 -5
View File
@@ -33,7 +33,7 @@ The browser preview (`pnpm dev`) has no installed plugins unless a smoke test su
The built-in browser and the theme editor use the plugin API, but they are not packages. `builtInModules` in `src/lib/plugins/external.ts` lists them. The host starts them in each window, and the plugin menus do not list their tools. A browser window starts only the browser. The built-in browser and the theme editor use the plugin API, but they are not packages. `builtInModules` in `src/lib/plugins/external.ts` lists them. The host starts them in each window, and the plugin menus do not list their tools. A browser window starts only the browser.
`builtInPackages` lists the IDs of old packages for features that RuneStone now includes. The host never loads such a package. Settings → Plug-ins shows it as included with RuneStone, so that the user can remove it. `builtInPackages` lists the IDs of old packages for features that RuneStone now includes. The host never loads such a package. Settings → Plug-ins shows it as included with RuneStone, so that the user can remove it.
Native features, such as Git, Background, and Terminal, do not use the plugin API. `syncFeatures` in `external.ts` gives each feature that is on a feature session (`src/lib/features/session.ts`) under the ID of its old package, so that its views share the tab model of plugin views. A launch rule (`src/lib/features/launch.ts`) can start a feature at once: Background starts when a folder or an image is selected. Browser windows start only the features with a browser window rule, which is Background. See [Native features](development.md#native-features). Native features, such as Git, Background, Terminal, and PDF Viewer, do not use the plugin API. `syncFeatures` in `external.ts` gives each feature that is on a feature session (`src/lib/features/session.ts`) under the ID of its old package, so that its views and document types share the tab model of plugin views. The file tree identifies the files of a feature document type, such as PDF files, without the feature code. A launch rule (`src/lib/features/launch.ts`) can start a feature at once: Background starts when a folder or an image is selected. Browser windows start only the features with a browser window rule, which is Background. See [Native features](development.md#native-features).
`features_legacy` (`src-tauri/src/features.rs`) reads the catalog row and the kept `plugin-data/<id>/settings.json` of an old package. It accepts only the IDs of native features and changes no file. `features_legacy` (`src-tauri/src/features.rs`) reads the catalog row and the kept `plugin-data/<id>/settings.json` of an old package. It accepts only the IDs of native features and changes no file.
### Scans ### Scans
@@ -159,12 +159,12 @@ The policy stops a script that comes in through rendered content, for example a
| Directive | Sources | Reason | | Directive | Sources | Reason |
| --- | --- | --- | | --- | --- | --- |
| `default-src` | `'self'` | All other types come only from the app. | | `default-src` | `'self'` | All other types come only from the app. |
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: the PDF Viewer decodes JPEG 2000 and JBIG2 images and color profiles with WebAssembly in its worker. It does not permit `eval`. | | `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: PDF.js in the PDF Viewer feature decodes JPEG 2000 and JBIG2 images and compiles PostScript functions with WebAssembly. Its worker is a file of the app and gets no policy, so this source applies only to PDF.js code on the page. It does not permit `eval`. |
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, xterm in the Terminal feature, the Vite dev server, and plugins (CSV Viewer, PDF Viewer). | | `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, xterm in the Terminal feature, the Vite dev server, and plugins (CSV Viewer). |
| `img-src` | `'self' data: blob: https: http:` | `data:`: workspace images, browser frames, tab and site icons, and icons in CSS. `blob:`: background images. `https:` and `http:`: remote images in Markdown previews. | | `img-src` | `'self' data: blob: https: http:` | `data:`: workspace images, browser frames, tab and site icons, and icons in CSS. `blob:`: background images. `https:` and `http:`: remote images in Markdown previews. |
| `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: fonts that the PDF Viewer embeds. | | `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: PDF.js can load the embedded fonts of a PDF from data addresses. |
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the blur worker of the Background feature reads its image from a Blob URL. | | `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the blur worker of the Background feature reads its image from a Blob URL. |
| `worker-src` | `'self' blob:` | `'self'`: workers that the app serves. `blob:`: the PDF Viewer worker and the blur worker of the Background feature. | | `worker-src` | `'self' blob:` | `'self'`: workers that the app serves, such as the PDF.js worker of each PDF tab. `blob:`: the blur worker of the Background feature. |
| `object-src` | `'none'` | RuneStone uses no plugins of the web view. | | `object-src` | `'none'` | RuneStone uses no plugins of the web view. |
| `base-uri` | `'self'` | | | `base-uri` | `'self'` | |
| `form-action` | `'none'` | No form sends data to an address. | | `form-action` | `'none'` | No form sends data to an address. |
+3 -3
View File
@@ -2,9 +2,9 @@
[RuneStone](../README.md) · [User guide](user-guide.md) [RuneStone](../README.md) · [User guide](user-guide.md)
This guide explains how to install, enable, update, and remove optional plugins such as Project Management, PDF Viewer, and CSV Viewer. This guide explains how to install, enable, update, and remove optional plugins such as Project Management and CSV Viewer.
Manage all plugins in **Settings → Plug-ins**. The built-in browser, table formulas, Git, Background, and Terminal are part of RuneStone and are not plugins. To turn Git, Background, or Terminal off, see [Turn features on or off](user-guide.md#turn-features-on-or-off). Manage all plugins in **Settings → Plug-ins**. The built-in browser, table formulas, Git, Background, Terminal, and PDF Viewer are part of RuneStone and are not plugins. To turn Git, Background, Terminal, or PDF Viewer off, see [Turn features on or off](user-guide.md#turn-features-on-or-off).
Plugins run with the full access of RuneStone, including your files. There is no permission sandbox, and the author field does not prove who published the plugin. Enable only code that you trust. Plugins run with the full access of RuneStone, including your files. There is no permission sandbox, and the author field does not prove who published the plugin. Enable only code that you trust.
@@ -77,7 +77,6 @@ RuneStone uses the token for this request only and does not save it.
| --- | --- | | --- | --- |
| Project Management | [Project Management guide](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/project-management.md) | | Project Management | [Project Management guide](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/project-management.md) |
| Local Autocomplete | [Local Autocomplete trial guide](https://git.knottywyvern.com/kwyvern/RuneStone_LocalModel/src/branch/main/docs/trial-guide.md) | | Local Autocomplete | [Local Autocomplete trial guide](https://git.knottywyvern.com/kwyvern/RuneStone_LocalModel/src/branch/main/docs/trial-guide.md) |
| PDF Viewer | [PDF Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_PDFViewer/src/branch/master/README.md) |
| CSV Viewer | [CSV Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer/src/branch/main/README.md) | | CSV Viewer | [CSV Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer/src/branch/main/README.md) |
## Plugin help ## Plugin help
@@ -95,6 +94,7 @@ RuneStone uses the token for this request only and does not save it.
| An old Git plugin shows in the list | Uninstall it. RuneStone includes Git, and the first start after the update kept the plugin state. See [Turn features on or off](user-guide.md#turn-features-on-or-off). | | An old Git plugin shows in the list | Uninstall it. RuneStone includes Git, and the first start after the update kept the plugin state. See [Turn features on or off](user-guide.md#turn-features-on-or-off). |
| An old Background Slideshow plugin shows in the list | Uninstall it. RuneStone includes Background, and the first start after the update took the folder and the settings of the plugin. See [Show a background](guides/themes.md#show-a-background). | | An old Background Slideshow plugin shows in the list | Uninstall it. RuneStone includes Background, and the first start after the update took the folder and the settings of the plugin. See [Show a background](guides/themes.md#show-a-background). |
| An old Terminal plugin shows in the list | RuneStone includes Terminal. The plugin stays inactive and shows **Included with RuneStone**. Uninstall it. The first start after the update kept the plugin state and its terminal settings. See the [Terminal guide](guides/terminal.md). | | An old Terminal plugin shows in the list | RuneStone includes Terminal. The plugin stays inactive and shows **Included with RuneStone**. Uninstall it. The first start after the update kept the plugin state and its terminal settings. See the [Terminal guide](guides/terminal.md). |
| An old PDF Viewer plugin shows in the list | RuneStone includes PDF Viewer. The plugin stays inactive and shows **Included with RuneStone**. Uninstall it. The first start after the update kept the plugin state. See [Read PDF files](user-guide.md#read-pdf-files). |
| An old Table Formulas plugin shows in the list | Uninstall it. RuneStone does not run it. Your formulas stay in your files. See [Calculate with table formulas](guides/document-tools.md#calculate-with-table-formulas). | | An old Table Formulas plugin shows in the list | Uninstall it. RuneStone does not run it. Your formulas stay in your files. See [Calculate with table formulas](guides/document-tools.md#calculate-with-table-formulas). |
To see the installed files of a plugin, choose **Show files** beside it. **Open plugins folder** opens the folder for all plugins. To see the installed files of a plugin, choose **Show files** beside it. **Open plugins folder** opens the folder for all plugins.
+26 -5
View File
@@ -10,6 +10,7 @@ This guide explains how to work with files, documents, tabs, settings, and the b
| Create, find, or organize files | [Create and find files](#create-and-find-files) | | Create, find, or organize files | [Create and find files](#create-and-find-files) |
| Write, read, or follow a link | [Edit documents](#edit-documents) | | Write, read, or follow a link | [Edit documents](#edit-documents) |
| Work with images, diagrams, or tables | [Images, diagrams, and tables](guides/document-tools.md) | | Work with images, diagrams, or tables | [Images, diagrams, and tables](guides/document-tools.md) |
| Read a PDF file | [Read PDF files](#read-pdf-files) |
| Start a note from a template | [Use note templates](#use-note-templates) | | Start a note from a template | [Use note templates](#use-note-templates) |
| Arrange tabs and windows | [Manage tabs](#manage-tabs) | | Arrange tabs and windows | [Manage tabs](#manage-tabs) |
| Save, or recover from a changed file | [Save your work](#save-your-work) and [Resolve file conflicts](#resolve-file-conflicts) | | Save, or recover from a changed file | [Save your work](#save-your-work) and [Resolve file conflicts](#resolve-file-conflicts) |
@@ -128,6 +129,26 @@ In Write, these shortcuts format the selected text:
The menu also has link, search, extraction, and clipboard actions. RuneStone has no formatting toolbar. The menu also has link, search, extraction, and clipboard actions. RuneStone has no formatting toolbar.
Right-click a misspelled word to see spelling suggestions from the operating system. Right-click a misspelled word to see spelling suggestions from the operating system.
## Read PDF files
Select a PDF file in the file tree. It opens in its own tab. The file tree marks PDF files with a document icon.
| Action | How |
| --- | --- |
| Change the page | Select **Previous page** or **Next page**. Or type a number in the page field and press Enter. With the page area focused, press Page Up or Page Down. |
| Zoom | Select **Zoom in** or **Zoom out**, from 25% to 400%. **Fit width** fits the page to the tab again. |
| Rotate | Select **Rotate clockwise**. Each click turns the page by 90 degrees. |
| Copy text | Select text on the page with the pointer, then press Ctrl+C. |
| Show changes from another program | Select **Reload PDF**. The tab stays on the same page. |
| Open a protected PDF | Type the password, then select **Unlock**. RuneStone does not save the password. |
- A PDF file must be in the workspace and at most 64 MiB.
- The tab shows one page at a time. It does not edit PDF files, fill forms, open links, run scripts in a PDF, or print.
- Scanned pages show as images, so you cannot select their text.
- If a PDF does not open, the tab shows the error. Select **Reload PDF**, or try another copy of the file.
PDF Viewer is a built-in feature. To turn it off, see [Turn features on or off](#turn-features-on-or-off).
## Use note templates ## Use note templates
A template is a Markdown file in the workspace folder `.runestone/templates/`. A template is a Markdown file in the workspace folder `.runestone/templates/`.
@@ -158,7 +179,7 @@ RuneStone moves the current text of the tab, also unsaved text. It closes the so
If the move fails, the source tab stays open. If the move fails, the source tab stays open.
When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab. When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab.
This includes plugin tabs that show a file, such as a PDF. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening. This includes PDF tabs and plugin tabs that show a file. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening.
## Save your work ## Save your work
@@ -200,22 +221,22 @@ Settings apply at once to all workspaces on this computer and update all open wi
| --- | --- | | --- | --- |
| General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save | | General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save |
| Appearance | Color theme, transparency, background (a folder slideshow or one image), and custom themes. See [Appearance and custom themes](guides/themes.md). | | Appearance | Color theme, transparency, background (a folder slideshow or one image), and custom themes. See [Appearance and custom themes](guides/themes.md). |
| Features | Turn Git, Background, and Terminal on or off. See [Turn features on or off](#turn-features-on-or-off). | | Features | Turn Git, Background, Terminal, and PDF Viewer on or off. See [Turn features on or off](#turn-features-on-or-off). |
| Plug-ins | Install, enable, update, and remove plugins. See [Install and manage plugins](plugins.md). | | Plug-ins | Install, enable, update, and remove plugins. See [Install and manage plugins](plugins.md). |
| Browser | Homepage, search engine, profiles, ad blocking, and web data | | Browser | Homepage, search engine, profiles, ad blocking, and web data |
| Terminal | Default profile, font size, scrollback lines, and cursor blink. The page shows only while Terminal is on. See [Change the terminal settings](guides/terminal.md#change-the-terminal-settings). | | Terminal | Default profile, font size, scrollback lines, and cursor blink. The page shows only while Terminal is on. See [Change the terminal settings](guides/terminal.md#change-the-terminal-settings). |
### Turn features on or off ### Turn features on or off
Git, Background, and Terminal are built-in features with an off switch. Open **Settings → Features** and use the switch beside the feature. Git, Background, Terminal, and PDF Viewer are built-in features with an off switch. Open **Settings → Features** and use the switch beside the feature.
- A feature that is on uses no extra memory until you first use it, for example when you open Source control or the terminal panel. Background loads at the start only when you selected a folder or an image. - A feature that is on uses no extra memory until you first use it, for example when you open Source control, the terminal panel, or a PDF file. Background loads at the start only when you selected a folder or an image.
- A feature that is off does not load. Its buttons, commands, and tabs do not show. - A feature that is off does not load. Its buttons, commands, and tabs do not show.
- Terminal off ends the terminal sessions of every window. When a window runs a shell, RuneStone asks first. - Terminal off ends the terminal sessions of every window. When a window runs a shell, RuneStone asks first.
- A change applies at once in all windows. The code that a window loaded stays in memory until you restart RuneStone. - A change applies at once in all windows. The code that a window loaded stays in memory until you restart RuneStone.
After an update, Git takes the state of its old plugin package: on when the package was enabled, off when it was disabled. Without an old package, Git starts on. After an update, Git takes the state of its old plugin package: on when the package was enabled, off when it was disabled. Without an old package, Git starts on.
Terminal does the same with the old Terminal plugin, and it copies the terminal settings of that plugin. Terminal does the same with the old Terminal plugin, and it copies the terminal settings of that plugin. PDF Viewer does the same with the old PDF Viewer plugin.
Background starts on for every user. It takes the folder, the timing, and the targets of the Background Slideshow plugin when that plugin was on. Otherwise it shows your old background image, if you had one. See [Show a background](guides/themes.md#show-a-background). Background starts on for every user. It takes the folder, the timing, and the targets of the Background Slideshow plugin when that plugin was on. Otherwise it shows your old background image, if you had one. See [Show a background](guides/themes.md#show-a-background).
Settings → Plug-ins shows an old package as **Included with RuneStone**. You can uninstall it. Settings → Plug-ins shows an old package as **Included with RuneStone**. You can uninstall it.
+2 -1
View File
@@ -57,7 +57,8 @@
"@xterm/addon-fit": "0.11.0", "@xterm/addon-fit": "0.11.0",
"@xterm/xterm": "6.0.0", "@xterm/xterm": "6.0.0",
"markdown-it": "^15.0.2", "markdown-it": "^15.0.2",
"mermaid": "^12.0.0" "mermaid": "^12.0.0",
"pdfjs-dist": "6.4.299"
}, },
"devDependencies": { "devDependencies": {
"@sveltejs/adapter-static": "^3.0.10", "@sveltejs/adapter-static": "^3.0.10",
+134
View File
@@ -101,6 +101,9 @@ importers:
mermaid: mermaid:
specifier: ^12.0.0 specifier: ^12.0.0
version: 12.0.0 version: 12.0.0
pdfjs-dist:
specifier: 6.4.299
version: 6.4.299
devDependencies: devDependencies:
'@sveltejs/adapter-static': '@sveltejs/adapter-static':
specifier: ^3.0.10 specifier: ^3.0.10
@@ -278,6 +281,81 @@ packages:
resolution: {integrity: sha512-K8BeapFUfrfxbRAUQAG5oBOCwo1+bNWzaVnPxTCutkfrTBn6T/j91FIhqxWJ32SUeQ9T3iy1zcmPZ5ROZEvDrg==} resolution: {integrity: sha512-K8BeapFUfrfxbRAUQAG5oBOCwo1+bNWzaVnPxTCutkfrTBn6T/j91FIhqxWJ32SUeQ9T3iy1zcmPZ5ROZEvDrg==}
engines: {node: '>=22.12.0'} engines: {node: '>=22.12.0'}
'@napi-rs/[email protected]':
resolution: {integrity: sha512-trn7AaDzQ+yeeA0ezhkC7cB1ZDPtp4UYk0EvB5F8qtYL9jEVWtVrU30WOpI52DszoTxaTsCgf5PP4ZVaOlOIHQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [android]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-6Y2djEetL8copxfNK6hg7oig/xqTwOchv19hBOm+zBNdKc/02Z3kjZN5wrLzv/l5O04/bAQS6I/AlQpwBlXgPg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-OZoPwwu4TMMg8GTCFBrg8UFExwQTU/55i3uTC/izDat6PHE+ro9dimyQoOboFf91+NY7Pnn70ScR8f8I8+eZXw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-dZSYaKROuswU2eUWG5aBKndNVe68elo1YX93xtRax7q658tj8rYE+HwduovWJgs6qwv1r1/CLR60nDeBbyjvyg==}
engines: {node: '>= 10'}
cpu: [arm]
os: [linux]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-W6FzYE8ADHI93In1vi80KBL6btDtAMuj50Ch5ptkWS8xuntyzbR4h5JDUmXoakxZn2yMInksudTEqVSWoFqFGg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-+6fQ+rR49hkAa4voh2stLIwQ+4t+gmoseM8Bc53/DlMXb73IKymDPWK9A/NtWeqTW4ijWppYuyuxS2hPI8tzNA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-17XEMO3t9RW/TtHtSFf2AkaSWuCWdzbPeidz7zrOFawHxoLSJCnpTI1hN5aUvrZNnkNNmt/vZVJCh0ryUaik3A==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-lc48IwknVHBsNzXn9Xs5OkUsRX38Ml3Z1aOybQ51mMEzZckm8+4A0qROlyYHEoBPzr1kL3IU8ZUAqDb7wtdX8w==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-bGY1r26S2bs8UNFJcPWcCSNdCFbKep5PATsvtgtC9A5u6SRgr2/jJE/RlhHL5m9ZpixNDhVkLY/5h16Kx5V9YA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-2vRPBZoaIvJrUkDhZTE2Hn0YrnpJRCWVM3EJACoBKjuWI6WgPxGtUoRMsxRviCsyks8bKTSFdyw14CellnG2qA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-DUlW3lZPz63kYsf8mxgyyZuevhlH0T3/BGP9l+NazhB0F1+gL6D4hqZdnhZpw24DlWmTpATDcyYSZlJOi+DdfQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-b87ugZpQ5ViwqVBkjervxpwa0GmJPsKHLBNoZN6GpjWeHzTbDUGryriq+2DYW2XbB+xCqSIINQysC0/I87nPbw==}
engines: {node: '>= 10'}
'@oxc-project/[email protected]': '@oxc-project/[email protected]':
resolution: {integrity: sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==} resolution: {integrity: sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==}
@@ -1195,6 +1273,10 @@ packages:
[email protected]: [email protected]:
resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==} resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==}
[email protected]:
resolution: {integrity: sha512-AVl138zALtfaAPvADulE0PZThbYzCBS79nL4pOSL/6Sm/4AH5A21BD9VHt97OlCuzJuCpmeZtAtkinisF4Vb1g==}
engines: {node: '>=22.13.0 || >=24'}
[email protected]: [email protected]:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -1673,6 +1755,54 @@ snapshots:
dependencies: dependencies:
'@chevrotain/types': 11.1.2 '@chevrotain/types': 11.1.2
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optionalDependencies:
'@napi-rs/canvas-android-arm64': 1.0.13
'@napi-rs/canvas-darwin-arm64': 1.0.13
'@napi-rs/canvas-darwin-x64': 1.0.13
'@napi-rs/canvas-linux-arm-gnueabihf': 1.0.13
'@napi-rs/canvas-linux-arm64-gnu': 1.0.13
'@napi-rs/canvas-linux-arm64-musl': 1.0.13
'@napi-rs/canvas-linux-riscv64-gnu': 1.0.13
'@napi-rs/canvas-linux-x64-gnu': 1.0.13
'@napi-rs/canvas-linux-x64-musl': 1.0.13
'@napi-rs/canvas-win32-arm64-msvc': 1.0.13
'@napi-rs/canvas-win32-x64-msvc': 1.0.13
optional: true
'@oxc-project/[email protected]': {} '@oxc-project/[email protected]': {}
'@polka/[email protected]': {} '@polka/[email protected]': {}
@@ -2519,6 +2649,10 @@ snapshots:
[email protected]: {} [email protected]: {}
[email protected]:
optionalDependencies:
'@napi-rs/canvas': 1.0.13
[email protected]: {} [email protected]: {}
[email protected]: {} [email protected]: {}
+1 -1
View File
@@ -12,7 +12,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
/** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */ /** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */
export const FEATURE_FOLDERS = ["git", "background", "terminal"]; export const FEATURE_FOLDERS = ["git", "background", "terminal", "pdf"];
/** Libraries that only features need. */ /** Libraries that only features need. */
export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"]; export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"];
+5
View File
@@ -57,6 +57,11 @@ export const TABLE = {
pdf: { pdf: {
plugin: { id: "runestone.pdf-viewer", repo: "runestone-pdf-viewer", tag: "v0.0.5", zip: `${PLUGIN_RELEASES}/RuneStone_PDF_Viewer/releases/runestone.pdf-viewer-0.0.5.zip` }, plugin: { id: "runestone.pdf-viewer", repo: "runestone-pdf-viewer", tag: "v0.0.5", zip: `${PLUGIN_RELEASES}/RuneStone_PDF_Viewer/releases/runestone.pdf-viewer-0.0.5.zip` },
nativeKey: "pdf", nativeKey: "pdf",
/**
* Both modes use the same names. Native: the tree row opens a PDF tab, and the first tab loads the PDF Viewer feature
* and PDF.js (src/lib/features/pdf/), so the action includes that load. Each page canvas is an image named "PDF page N",
* and the page field is a spin button named "Page number". Enter in the field goes to the page.
*/
row: '[data-tree-rel="sample.pdf"]', row: '[data-tree-rel="sample.pdf"]',
firstPage: "PDF page 1", firstPage: "PDF page 1",
pageInput: "Page number", pageInput: "Page number",
+1 -1
View File
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
const root = fileURLToPath(new URL('../', import.meta.url)); const root = fileURLToPath(new URL('../', import.meta.url));
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..'); const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..');
export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_PDF_Viewer', 'RuneStone_CSV_Viewer']; export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_CSV_Viewer'];
const patterns = { const patterns = {
action: /\b(?:showActionMenu|actionMenu)\s*\(/g, action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
svelteMenu: /<ContextMenu\b/g, svelteMenu: /<ContextMenu\b/g,
+3 -2
View File
@@ -8,7 +8,7 @@ use crate::error::{Error, Result};
use crate::plugins::{legacy_packages, LegacyPackage}; use crate::plugins::{legacy_packages, LegacyPackage};
/// The packages that native features replace. A request for another ID fails. /// The packages that native features replace. A request for another ID fails.
pub const LEGACY_PACKAGES: [&str; 3] = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal"]; pub const LEGACY_PACKAGES: [&str; 4] = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer"];
fn check(ids: &[String]) -> Result<()> { fn check(ids: &[String]) -> Result<()> {
if ids.len() > LEGACY_PACKAGES.len() { if ids.len() > LEGACY_PACKAGES.len() {
@@ -35,12 +35,13 @@ mod tests {
assert!(check(&["runestone.git".into()]).is_ok()); assert!(check(&["runestone.git".into()]).is_ok());
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into()]).is_ok()); assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into()]).is_ok());
assert!(check(&["runestone.terminal".into()]).is_ok()); assert!(check(&["runestone.terminal".into()]).is_ok());
assert!(check(&["runestone.pdf-viewer".into()]).is_ok());
assert!(check(&LEGACY_PACKAGES.map(String::from)).is_ok()); assert!(check(&LEGACY_PACKAGES.map(String::from)).is_ok());
assert!(check(&[]).is_ok()); assert!(check(&[]).is_ok());
for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] { for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] {
assert!(check(&[id.into()]).is_err(), "{id}"); assert!(check(&[id.into()]).is_err(), "{id}");
} }
let too_many = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.git"].map(String::from); let too_many = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.git"].map(String::from);
assert!(too_many.len() > LEGACY_PACKAGES.len()); assert!(too_many.len() > LEGACY_PACKAGES.len());
assert!(check(&too_many).is_err()); assert!(check(&too_many).is_err());
} }
+38 -3
View File
@@ -1,10 +1,11 @@
// The native features of RuneStone. Each feature has an off switch in Settings → Features. // The native features of RuneStone. Each feature has an off switch in Settings → Features.
// This file is in the main bundle, so it holds only small static data: names, views, and commands. // This file is in the main bundle, so it holds only small static data: names, views, commands, and document types.
// The code of a feature loads with a dynamic import at first need (see `loader.ts`), and never while its switch is off. // The code of a feature loads with a dynamic import at first need (see `loader.ts`), and never while its switch is off.
import { message, tr } from "../i18n/index.ts"; import { message, tr } from "../i18n/index.ts";
import type { PluginCommand, PluginView } from "../plugins/sdk.ts"; import type { PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
import { identifyPdf } from "./pdfDocument.ts";
export type FeatureId = "git" | "background" | "terminal"; export type FeatureId = "git" | "background" | "terminal" | "pdf";
/** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */ /** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */
export interface FeatureViewInfo { export interface FeatureViewInfo {
@@ -26,6 +27,23 @@ export interface FeatureCommandInfo {
view?: string; view?: string;
} }
/**
* A document type of a feature. The file tree marks the files of the type, and a click opens them in a tab,
* without the feature code. The first tab of the type loads the feature and calls `FeatureInstance.mountDocument`.
*/
export interface FeatureDocumentInfo {
id: string;
/** Returns the title in the current language. The file tree shows it as the tooltip of the file icon. */
title: () => string;
icon: NonNullable<PluginDocumentType["icon"]>;
/** Lowercase file extensions without the dot. */
extensions: readonly string[];
/** "binary" when `identify` needs no file contents. */
content: "text" | "binary";
/** The document ID of a file, or null when the file is not of this type. */
identify(path: string, source: string): { id: string } | null;
}
export interface FeatureEntry { export interface FeatureEntry {
id: FeatureId; id: FeatureId;
/** The ID of the old plugin package. Saved tabs and tab transfers keep it as the owner ID. */ /** The ID of the old plugin package. Saved tabs and tab transfers keep it as the owner ID. */
@@ -41,6 +59,7 @@ export interface FeatureEntry {
followsPackage: boolean; followsPackage: boolean;
views: readonly FeatureViewInfo[]; views: readonly FeatureViewInfo[];
commands: readonly FeatureCommandInfo[]; commands: readonly FeatureCommandInfo[];
documentTypes: readonly FeatureDocumentInfo[];
} }
export const FEATURES: readonly FeatureEntry[] = [ export const FEATURES: readonly FeatureEntry[] = [
@@ -55,6 +74,7 @@ export const FEATURES: readonly FeatureEntry[] = [
{ id: "graph", title: () => tr("Git graph"), placement: "editor", icon: "git" }, { id: "graph", title: () => tr("Git graph"), placement: "editor", icon: "git" },
], ],
commands: [{ id: "graph", title: () => tr("Show Git graph"), icon: "git", view: "graph" }], commands: [{ id: "graph", title: () => tr("Show Git graph"), icon: "git", view: "graph" }],
documentTypes: [],
}, },
{ {
// Background replaces the Background Slideshow plugin and the background image of Appearance. Its settings are in // Background replaces the Background Slideshow plugin and the background image of Appearance. Its settings are in
@@ -68,6 +88,7 @@ export const FEATURES: readonly FeatureEntry[] = [
{ id: "next", title: () => tr("Next background image"), icon: "image" }, { id: "next", title: () => tr("Next background image"), icon: "image" },
{ id: "pause", title: () => tr("Pause background"), icon: "pause" }, { id: "pause", title: () => tr("Pause background"), icon: "pause" },
], ],
documentTypes: [],
}, },
{ {
// Terminal replaces the Terminal plugin. Its panel is not a view: the workbench and the terminal window show it // Terminal replaces the Terminal plugin. Its panel is not a view: the workbench and the terminal window show it
@@ -78,6 +99,20 @@ export const FEATURES: readonly FeatureEntry[] = [
defaultOn: true, followsPackage: true, defaultOn: true, followsPackage: true,
views: [], views: [],
commands: [], commands: [],
documentTypes: [],
},
{
// PDF Viewer replaces the PDF Viewer plugin. It has no view: its document type opens each PDF file in its own tab.
// The file tree marks PDF files without the module. The first PDF tab loads the module and PDF.js.
id: "pdf", owner: "runestone.pdf-viewer", name: message("PDF Viewer"),
description: message("Read PDF files of the workspace in tabs, with page controls, zoom, rotation, and text selection."),
keywords: "pdf document viewer page zoom rotate password pdf.js",
defaultOn: true, followsPackage: true,
views: [],
commands: [],
documentTypes: [
{ id: "pdf", title: () => tr("PDF document"), icon: "file", extensions: ["pdf"], content: "binary", identify: identifyPdf },
],
}, },
]; ];
+1
View File
@@ -8,6 +8,7 @@ const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
git: () => import("./git/index.ts"), git: () => import("./git/index.ts"),
background: () => import("./background/index.ts"), background: () => import("./background/index.ts"),
terminal: () => import("./terminal/index.ts"), terminal: () => import("./terminal/index.ts"),
pdf: () => import("./pdf/index.ts"),
}; };
const modules = new Map<FeatureId, Promise<FeatureModule>>(); const modules = new Map<FeatureId, Promise<FeatureModule>>();
+239
View File
@@ -0,0 +1,239 @@
<script lang="ts">
// One PDF tab: the toolbar, the status line, the password form, and one page with its text layer.
// The document and its worker live as long as the tab. `close` releases both.
import { onMount } from "svelte";
import { message, t } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte";
import type { PluginDocumentContext } from "$lib/plugins/sdk";
import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine";
import { MAX_ZOOM, MIN_ZOOM, RESIZE_SETTLE_MS, ZOOM_STEP, nextRotation, outputScale, pageNumber, zoomLevel } from "./model";
let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props();
type Status = { key: string; values?: Record<string, string | number>; alert?: boolean };
let page = $state(1);
let count = $state(0);
let zoom = $state(1);
let rotation = $state(0);
let fit = $state(true);
let status = $state<Status>({ key: message("Loading PDF…") });
let asking = $state<"needed" | "incorrect" | null>(null);
let reloading = $state(false);
let failed = $state(false);
let scroller: HTMLDivElement;
let sheet: HTMLDivElement;
let pageInput: HTMLInputElement;
let passwordInput: HTMLInputElement | undefined = $state();
let disposed = false;
let pdf: PDFDocumentProxy | undefined;
let opened: OpenPdf | undefined;
let answer: ((password: string) => void) | undefined;
let render: RenderTask | undefined;
let text: TextLayer | undefined;
let revision = 0;
let queue: Promise<void> = Promise.resolve();
let loading: Promise<void> = Promise.resolve();
let closing: Promise<void> | undefined;
const ready = $derived(count > 0);
function fail(reason: unknown) {
if (disposed) return;
failed = true;
status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true };
}
/** Draw the current page again. A newer request cancels the older one. */
function schedule() {
const request = ++revision;
render?.cancel(); text?.cancel();
if (pdf && !disposed) status = { key: message("Loading page {page}…"), values: { page } };
queue = queue.then(async () => {
if (disposed || request !== revision || !pdf || scroller.clientWidth === 0) return;
const pdfPage = await pdf.getPage(page);
if (disposed || request !== revision) return;
const angle = (pdfPage.rotate + rotation) % 360;
if (fit) zoom = zoomLevel((scroller.clientWidth - 32) / pdfPage.getViewport({ scale: 1, rotation: angle }).width);
const viewport = pdfPage.getViewport({ scale: zoom, rotation: angle });
const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio);
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.floor(viewport.width * scale));
canvas.height = Math.max(1, Math.floor(viewport.height * scale));
canvas.style.width = `${viewport.width}px`;
canvas.style.height = `${viewport.height}px`;
canvas.setAttribute("role", "img");
// The measurement tool and the smoke tests find the page by this English name. Keep "PDF page N".
canvas.setAttribute("aria-label", $t("PDF page {page}", { page }));
const layer = document.createElement("div");
layer.className = "textLayer";
sheet.style.width = `${viewport.width}px`;
sheet.style.height = `${viewport.height}px`;
sheet.style.setProperty("--total-scale-factor", String(zoom));
sheet.replaceChildren(canvas, layer);
render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] });
await render.promise;
if (disposed || request !== revision) return;
text = new TextLayer({ textContentSource: pdfPage.streamTextContent(), container: layer, viewport });
await text.render();
if (disposed || request !== revision) return;
status = { key: message("Page {page} of {count}"), values: { page, count } };
pdfPage.cleanup();
}).catch(reason => { if (!disposed && request === revision) fail(reason); });
}
function go(value: number) {
if (!pdf) return;
page = pageNumber(value, pdf.numPages);
pageInput.value = String(page);
scroller.scrollTop = 0;
schedule();
}
function setZoom(value: number) { fit = false; zoom = zoomLevel(value); schedule(); }
async function load() {
failed = false;
status = { key: message("Loading PDF…") };
const bytes = await readBytes(file.path);
if (disposed) return;
opened = openPdf(bytes, (reason, next) => {
if (disposed) return;
answer = next;
asking = reason;
status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") };
queueMicrotask(() => passwordInput?.focus());
});
pdf = await opened.promise;
if (disposed) return;
page = pageNumber(page, pdf.numPages);
count = pdf.numPages;
schedule();
}
async function release() {
revision++;
render?.cancel(); text?.cancel();
await queue;
const current = opened;
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0;
sheet?.replaceChildren();
await current?.close();
}
async function reload() {
if (reloading || disposed) return;
reloading = true;
try {
await loading;
await release();
if (!disposed) await (loading = load());
} catch (reason) { fail(reason); }
finally { reloading = false; }
}
function unlock(event: SubmitEvent) {
event.preventDefault();
if (!passwordInput || !answer) return;
const value = passwordInput.value;
passwordInput.value = "";
asking = null;
status = { key: message("Loading PDF…") };
const next = answer;
answer = undefined;
next(value);
}
function pageKey(event: KeyboardEvent) {
if (event.ctrlKey || event.metaKey || event.altKey || !ready) return;
if (event.key === "PageDown" || event.key === "PageUp") {
event.preventDefault();
go(page + (event.key === "PageDown" ? 1 : -1));
}
}
/** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */
export function close(): Promise<void> {
if (closing) return closing;
disposed = true;
closing = release().then(() => loading).catch(() => {});
return closing;
}
onMount(() => {
loading = load().catch(fail);
// A fit-width page follows the width of the tab. The first size draws at once. Later sizes wait until the size settles.
let width = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const observer = new ResizeObserver(() => {
const next = scroller.clientWidth;
if (next === 0 || next === width) return;
const first = width === 0;
width = next;
clearTimeout(timer);
if (!fit) return;
if (first) schedule();
else timer = setTimeout(schedule, RESIZE_SETTLE_MS);
});
observer.observe(scroller);
return () => { observer.disconnect(); clearTimeout(timer); void close(); };
});
</script>
<section class="pdf-viewer" aria-label={$t("PDF Viewer")}>
<div class="toolbar" role="group" aria-label={$t("PDF controls")}>
<IconButton icon="up" label={$t("Previous page")} disabled={!ready || page <= 1} onclick={() => go(page - 1)} />
<input bind:this={pageInput} class="page" type="number" min="1" max={Math.max(count, 1)} value={page} disabled={!ready}
aria-label={$t("Page number")} onchange={event => { if (Number(event.currentTarget.value) !== page) go(Number(event.currentTarget.value)); }}
onkeydown={event => { if (event.key === "Enter") go(Number(event.currentTarget.value)); }} />
<span class="count">/ {ready ? count : "—"}</span>
<IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} />
<span class="separator" aria-hidden="true"></span>
<IconButton icon="zoom-out" label={$t("Zoom out")} disabled={!ready || zoom <= MIN_ZOOM} onclick={() => setZoom(zoom / ZOOM_STEP)} />
<span class="zoom">{ready ? `${Math.round(zoom * 100)}%` : "—"}</span>
<IconButton icon="zoom-in" label={$t("Zoom in")} disabled={!ready || zoom >= MAX_ZOOM} onclick={() => setZoom(zoom * ZOOM_STEP)} />
<IconButton icon="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; schedule(); }} />
<IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); schedule(); }} />
<IconButton icon="refresh" label={$t("Reload PDF")} disabled={reloading || (!ready && !failed)} onclick={() => void reload()} />
</div>
<p class="status" class:alert={status.alert} role={status.alert ? "alert" : "status"} aria-live={status.alert ? "assertive" : "polite"}>{$t(status.key, status.values)}</p>
{#if asking}
<form class="password" onsubmit={unlock}>
<label>{$t("PDF password")} <input bind:this={passwordInput} type="password" autocomplete="off" /></label>
<button class="text-button" type="submit">{$t("Unlock")}</button>
</form>
{/if}
<!-- The page area takes focus for Page Up and Page Down. -->
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
<div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF page. Use Page Up and Page Down to change pages.")} onkeydown={pageKey}>
<div bind:this={sheet} class="sheet"></div>
</div>
</section>
<style>
.pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; }
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 8px; border-bottom: 1px solid var(--rs-border); }
.page { box-sizing: border-box; width: 64px; height: 28px; margin-left: 4px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: right; }
.page:disabled { color: var(--rs-text-dim); }
.count { margin: 0 4px; color: var(--rs-text-dim); white-space: nowrap; }
.separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); }
.zoom { min-width: 44px; color: var(--rs-text-dim); text-align: center; white-space: nowrap; }
.status { margin: 0; padding: 4px 12px; font-size: 12px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
.status.alert { color: var(--rs-error); }
.password { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; }
.password input { box-sizing: border-box; height: 28px; margin-left: 4px; padding: 2px 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
.text-button:hover { background: var(--rs-bg-active); }
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; }
.scroll:focus-visible { outline-offset: -2px; }
/* A PDF page is paper: white in both themes. */
.sheet { position: relative; margin: 0 auto; background: white; box-shadow: 0 2px 10px #0003; }
.sheet :global(canvas) { display: block; }
/* The text layer geometry follows the viewer styles of PDF.js 6 (Apache-2.0). See THIRD_PARTY_NOTICES.md. */
.sheet :global(.textLayer) { position: absolute; inset: 0; overflow: clip; text-align: initial; line-height: 1; letter-spacing: normal; word-spacing: normal; text-size-adjust: none; forced-color-adjust: none; transform-origin: 0 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)); }
.sheet :global(.textLayer :is(span, br)) { position: absolute; color: transparent; white-space: pre; cursor: text; transform-origin: 0 0; user-select: text; }
.sheet :global(.textLayer > :not(.markedContent)), .sheet :global(.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)); }
.sheet :global(.markedContent) { display: contents; }
.sheet :global(.textLayer ::selection) { background: color-mix(in srgb, var(--rs-selection) 65%, transparent); color: transparent; }
</style>
+69
View File
@@ -0,0 +1,69 @@
/// <reference types="vite/client" />
// PDF.js for the PDF Viewer feature. The worker, the character maps, the standard fonts, and the WebAssembly image
// decoders come from the app (`'self'`) as Vite assets, so a PDF never causes a network request.
// Each open document has its own worker. `close` stops it.
// The reference to the Vite types serves the unit test type check, which reaches this file through `loader.ts`.
import { getDocument, PDFWorker, PasswordResponses, type PDFDocumentLoadingTask, type PDFDocumentProxy } from "pdfjs-dist/build/pdf.min.mjs";
import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";
export { TextLayer, type PDFDocumentProxy, type RenderTask } from "pdfjs-dist/build/pdf.min.mjs";
// `build.assetsInlineLimit` in vite.config.js keeps these files out of the code, so each one is a file of the app.
// The JPEG 2000 and JBIG2 decoders are the only WebAssembly files that PDF.js asks for with `useWorkerFetch: false`.
// The viewer runs no PDF scripts (quickjs) and uses no ICC color profiles (qcms), as the PDF Viewer plugin did.
const assets = import.meta.glob<string>([
"/node_modules/pdfjs-dist/cmaps/*.bcmap",
"/node_modules/pdfjs-dist/standard_fonts/*.{pfb,ttf}",
"/node_modules/pdfjs-dist/wasm/{jbig2,openjpeg}.wasm",
], { query: "?url", import: "default", eager: true });
const folders: Record<string, string> = { cMapUrl: "cmaps", standardFontDataUrl: "standard_fonts", wasmUrl: "wasm" };
/** The app URL of a PDF.js data file, or undefined for an unknown kind or file. */
export function assetUrl(kind: string, filename: string): string | undefined {
const folder = folders[kind];
if (!folder || !/^[\w.-]+$/.test(filename)) return undefined;
return assets[`/node_modules/pdfjs-dist/${folder}/${filename}`];
}
/** PDF.js asks the window for its data files (`useWorkerFetch: false`). This class reads them from the app. */
class AppBinaryDataFactory {
async fetch({ kind, filename }: { kind: string; filename: string }): Promise<Uint8Array> {
const url = assetUrl(kind, filename);
if (!url) throw new Error(`PDF.js has no data file ${filename}.`);
const response = await fetch(url);
if (!response.ok) throw new Error(`PDF.js could not read ${filename}: ${response.status}.`);
return new Uint8Array(await response.arrayBuffer());
}
}
export interface OpenPdf {
/** Resolves with the document after the password, if the file needs one. */
promise: Promise<PDFDocumentProxy>;
/** Stop the load or release the document, and stop the worker. Later calls return the same promise. */
close(): Promise<void>;
}
/**
* Open the bytes of a PDF in a new worker. PDF.js calls `onPassword` for a protected file, with "incorrect" after a
* wrong password. The viewer calls `answer` with the next password.
*/
export function openPdf(data: Uint8Array, onPassword: (reason: "needed" | "incorrect", answer: (password: string) => void) => void): OpenPdf {
const port = new Worker(workerUrl, { type: "module", name: "PDF.js" });
const worker = PDFWorker.create({ port });
const task: PDFDocumentLoadingTask = getDocument({
data, worker, useWorkerFetch: false, BinaryDataFactory: AppBinaryDataFactory,
useSystemFonts: false, isImageDecoderSupported: false, enableXfa: false,
});
task.onPassword = (answer: (password: string) => void, reason: number) => {
onPassword(reason === PasswordResponses.INCORRECT_PASSWORD ? "incorrect" : "needed", answer);
};
let closing: Promise<void> | undefined;
return {
promise: task.promise,
close: () => closing ??= (async () => {
try { await task.destroy(); }
finally { worker.destroy(); port.terminate(); }
})(),
};
}
+32
View File
@@ -0,0 +1,32 @@
// The PDF Viewer feature. `loader.ts` imports this module when the first PDF tab opens. The file tree marks PDF files
// before that, through the document type of the catalog (`../pdfDocument.ts`).
// Each tab reads its file with `workspace_read_bytes` (64 MiB at most) and has its own PDF.js worker.
import { flushSync, mount, unmount } from "svelte";
import { tr } from "../../i18n/index.ts";
import { workspaceReadBytes } from "../../workspace/api.ts";
import type { FeatureContext, FeatureInstance } from "../types.ts";
import PdfViewer from "./PdfViewer.svelte";
export function start(_context: FeatureContext): FeatureInstance {
const tabs = new Set<() => Promise<void>>();
let stopped = false;
return {
mount() { throw new Error(tr("This view is unavailable.")); },
mountDocument(type, element, file) {
if (type !== "pdf") throw new Error(tr("This view is unavailable."));
if (stopped) throw new Error(tr("This feature is off."));
const viewer = mount(PdfViewer, { target: element, props: { file, readBytes: workspaceReadBytes } });
flushSync();
let closing: Promise<void> | undefined;
// Release the document and stop its worker first. Then remove the component.
const dispose = () => closing ??= viewer.close().then(() => unmount(viewer)).finally(() => { tabs.delete(dispose); });
tabs.add(dispose);
return dispose;
},
/** The host closes the PDF tabs first. Close what is left, so no worker stays. */
async dispose() {
stopped = true;
await Promise.allSettled([...tabs].map(dispose => dispose()));
},
};
}
+31
View File
@@ -0,0 +1,31 @@
// The limits of the PDF Viewer: page numbers, zoom, and the size of the page canvas.
export const MIN_ZOOM = 0.25;
export const MAX_ZOOM = 4;
/** Each zoom step multiplies or divides the zoom by this factor. */
export const ZOOM_STEP = 1.25;
/** A redraw after a resize waits until the size did not change for this time. */
export const RESIZE_SETTLE_MS = 150;
/** A whole page number from 1 to `count`. A value that is not a number gives page 1. */
export function pageNumber(value: number, count: number): number {
return Math.max(1, Math.min(count, Number.isFinite(value) ? Math.trunc(value) : 1));
}
/** A zoom factor from 0.25 to 4. A value that is not a finite number gives 1. */
export function zoomLevel(value: number): number {
return Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, Number.isFinite(value) ? value : 1));
}
/** The next clockwise rotation in degrees: 0, 90, 180, or 270. */
export function nextRotation(rotation: number): number {
return (rotation + 90) % 360;
}
/**
* The pixel scale of the page canvas. It follows the device pixel ratio up to 2, and keeps each side at most
* 8192 pixels and the area at most 16 million pixels, so a large page does not use too much memory.
*/
export function outputScale(width: number, height: number, deviceScale: number): number {
return Math.min(deviceScale || 1, 2, 8192 / width, 8192 / height, Math.sqrt(16_000_000 / (width * height)));
}
+4
View File
@@ -0,0 +1,4 @@
// The minified build of PDF.js has the same exports as the package entry.
declare module "pdfjs-dist/build/pdf.min.mjs" {
export * from "pdfjs-dist";
}
+7
View File
@@ -0,0 +1,7 @@
// The document identification of the PDF Viewer feature. It is in the main bundle, because the file tree marks
// PDF files before the feature module loads. The document ID is the workspace path, so two files never share a tab.
/** The document ID of a PDF file: its path with forward slashes. Any letter case of the extension matches. */
export function identifyPdf(path: string): { id: string } | null {
return /\.pdf$/i.test(path) ? { id: path.replaceAll("\\", "/") } : null;
}
+20 -6
View File
@@ -1,9 +1,9 @@
// A feature in the workbench of one window. Its views and commands come from the static catalog, so the // A feature in the workbench of one window. Its views, commands, and document types come from the static catalog, so the
// navigation buttons and the command palette show them without the feature code. The first mount, // navigation buttons, the command palette, and the file tree show them without the feature code. The first mount,
// restore, or action command loads the feature module and starts one instance for this window. // restore, or action command loads the feature module and starts one instance for this window.
// A launch rule (`launch.ts`) can also start the instance at once. // A launch rule (`launch.ts`) can also start the instance at once.
import { tr } from "../i18n/index.ts"; import { tr } from "../i18n/index.ts";
import type { Dispose, PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts"; import type { Dispose, PluginCommand, PluginDocumentContext, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
import type { FeatureEntry } from "./catalog.ts"; import type { FeatureEntry } from "./catalog.ts";
import { loadFeature } from "./loader.ts"; import { loadFeature } from "./loader.ts";
import type { FeatureContext, FeatureInstance, FeatureModule } from "./types.ts"; import type { FeatureContext, FeatureInstance, FeatureModule } from "./types.ts";
@@ -32,6 +32,13 @@ export class FeatureSession {
restoreTabState: async state => { await (await this.running()).restoreTabState?.(info.id, state); }, restoreTabState: async state => { await (await this.running()).restoreTabState?.(info.id, state); },
}); });
} }
for (const info of entry.documentTypes) {
this.documentTypes.set(info.id, {
id: info.id, get title() { return info.title(); }, icon: info.icon, extensions: [...info.extensions], content: info.content,
identify: (path, source) => info.identify(path, source),
mount: (element, document) => this.mountDocument(info.id, element, document),
});
}
for (const info of entry.commands) { for (const info of entry.commands) {
const view = info.view; const view = info.view;
this.commands.set(info.id, { id: info.id, get title() { return info.title(); }, icon: info.icon, this.commands.set(info.id, { id: info.id, get title() { return info.title(); }, icon: info.icon,
@@ -53,10 +60,17 @@ export class FeatureSession {
return (await this.running()).mount(id, element); return (await this.running()).mount(id, element);
} }
async mount(id: string, element: HTMLElement): Promise<Dispose> { private async mountDocument(type: string, element: HTMLElement, document: PluginDocumentContext): Promise<Dispose> {
const view = this.views.get(id); const instance = await this.running();
if (!instance.mountDocument) throw new Error(tr("This view is unavailable."));
return instance.mountDocument(type, element, document);
}
/** Mount a view, or with `document`, a document of the document type `id`. */
async mount(id: string, element: HTMLElement, document?: PluginDocumentContext): Promise<Dispose> {
const view = document ? this.documentTypes.get(id) : this.views.get(id);
if (!view) throw new Error(tr("This view is unavailable.")); if (!view) throw new Error(tr("This view is unavailable."));
const dispose = await view.mount(element); const dispose = document ? await (view as PluginDocumentType).mount(element, document) : await (view as PluginView).mount(element, { surface: "view" });
return async () => { return async () => {
if (typeof dispose === "function") await dispose(); if (typeof dispose === "function") await dispose();
element.replaceChildren(); element.replaceChildren();
+6 -1
View File
@@ -1,4 +1,4 @@
import type { Dispose } from "../plugins/sdk.ts"; import type { Dispose, PluginDocumentContext } from "../plugins/sdk.ts";
/** The host services that a running feature gets. A feature also uses other host modules directly. */ /** The host services that a running feature gets. A feature also uses other host modules directly. */
export interface FeatureContext { export interface FeatureContext {
@@ -13,6 +13,11 @@ export interface FeatureContext {
/** One running copy of a feature in one window. */ /** One running copy of a feature in one window. */
export interface FeatureInstance { export interface FeatureInstance {
mount(view: string, element: HTMLElement): Dispose | Promise<Dispose>; mount(view: string, element: HTMLElement): Dispose | Promise<Dispose>;
/**
* Show a document of a catalog document type in `element`. `document.path` follows a rename of the file.
* The returned function removes the document and stops its work, for example a worker.
*/
mountDocument?(type: string, element: HTMLElement, document: PluginDocumentContext): Dispose | Promise<Dispose>;
/** Run a command of the catalog that has no view. */ /** Run a command of the catalog that has no view. */
run?(command: string): void | Promise<void>; run?(command: string): void | Promise<void>;
/** The state of a tab for a transfer to another window. */ /** The state of a tab for a transfer to another window. */
+21
View File
@@ -3658,6 +3658,27 @@ export const messageRows: [string, string, string, string][] = [
["Use PowerShell for a path with quotes, % or !.", "Utilisez PowerShell pour un chemin contenant des guillemets, % ou !.", "引用符、%、! を含むパスには PowerShell を使用してください。", "对于包含引号、% 或 ! 的路径,请使用 PowerShell。"], ["Use PowerShell for a path with quotes, % or !.", "Utilisez PowerShell pour un chemin contenant des guillemets, % ou !.", "引用符、%、! を含むパスには PowerShell を使用してください。", "对于包含引号、% 或 ! 的路径,请使用 PowerShell。"],
["{title}: choices", "{title} : choix", "{title}: 選択肢", "{title}:选项"], ["{title}: choices", "{title} : choix", "{title}: 選択肢", "{title}:选项"],
["{up} {down} select · {enter} choose · {escape} close", "{up} {down} sélectionner · {enter} choisir · {escape} fermer", "{up} {down} 選択 · {enter} 決定 · {escape} 閉じる", "{up} {down} 选择 · {enter} 确定 · {escape} 关闭"], ["{up} {down} select · {enter} choose · {escape} close", "{up} {down} sélectionner · {enter} choisir · {escape} fermer", "{up} {down} 選択 · {enter} 決定 · {escape} 閉じる", "{up} {down} 选择 · {enter} 确定 · {escape} 关闭"],
// The PDF Viewer feature (src/lib/features/pdf/).
["PDF Viewer", "Lecteur PDF", "PDF ビューアー", "PDF 查看器"],
["Read PDF files of the workspace in tabs, with page controls, zoom, rotation, and text selection.", "Lisez les fichiers PDF de l’espace de travail dans des onglets, avec les commandes de page, le zoom, la rotation et la sélection de texte.", "ワークスペースの PDF ファイルをタブで読みます。ページ操作、ズーム、回転、テキスト選択を使えます。", "在标签页中阅读工作区的 PDF 文件,支持页面控制、缩放、旋转和文本选择。"],
["PDF document", "Document PDF", "PDF ドキュメント", "PDF 文档"],
["PDF controls", "Commandes PDF", "PDF の操作", "PDF 控件"],
["Previous page", "Page précédente", "前のページ", "上一页"],
["Next page", "Page suivante", "次のページ", "下一页"],
["Page number", "Numéro de page", "ページ番号", "页码"],
["Fit width", "Ajuster à la largeur", "幅に合わせる", "适应宽度"],
["Rotate clockwise", "Faire pivoter dans le sens horaire", "時計回りに回転", "顺时针旋转"],
["Reload PDF", "Recharger le PDF", "PDF を再読み込み", "重新加载 PDF"],
["Loading PDF…", "Chargement du PDF…", "PDF を読み込み中…", "正在加载 PDF…"],
["Loading page {page}…", "Chargement de la page {page}…", "{page} ページを読み込み中…", "正在加载第 {page} 页…"],
["Page {page} of {count}", "Page {page} sur {count}", "{page} / {count} ページ", "第 {page} 页,共 {count} 页"],
["PDF page {page}", "Page PDF {page}", "PDF の {page} ページ", "PDF 第 {page} 页"],
["PDF page. Use Page Up and Page Down to change pages.", "Page PDF. Utilisez Page préc. et Page suiv. pour changer de page.", "PDF のページ。Page Up と Page Down でページを切り替えます。", "PDF 页面。使用 Page Up 和 Page Down 翻页。"],
["PDF password", "Mot de passe du PDF", "PDF のパスワード", "PDF 密码"],
["Unlock", "Déverrouiller", "ロック解除", "解锁"],
["This PDF needs a password.", "Ce PDF nécessite un mot de passe.", "この PDF にはパスワードが必要です。", "此 PDF 需要密码。"],
["Incorrect password. Try again.", "Mot de passe incorrect. Réessayez.", "パスワードが正しくありません。もう一度入力してください。", "密码不正确。请重试。"],
["Cannot display this PDF. {reason}", "Impossible d’afficher ce PDF. {reason}", "この PDF を表示できません。{reason}", "无法显示此 PDF。{reason}"],
// The native features without the desktop host. // The native features without the desktop host.
["This feature needs the desktop app.", "Cette fonctionnalité nécessite l’application de bureau.", "この機能にはデスクトップアプリが必要です。", "此功能需要桌面应用。"], ["This feature needs the desktop app.", "Cette fonctionnalité nécessite l’application de bureau.", "この機能にはデスクトップアプリが必要です。", "此功能需要桌面应用。"],
]; ];
+5 -1
View File
@@ -26,7 +26,7 @@
<circle cx="12" cy="12" r="9" /><path d="M9.5 9a2.5 2.5 0 1 1 4 2c-1 .6-1.5 1-1.5 3M12 17h.01" /> <circle cx="12" cy="12" r="9" /><path d="M9.5 9a2.5 2.5 0 1 1 4 2c-1 .6-1.5 1-1.5 3M12 17h.01" />
{:else if icon === "puzzle"} {:else if icon === "puzzle"}
<path d="M9 3H4v6a3 3 0 1 1 0 6v5h6a3 3 0 1 1 6 0h4v-6a3 3 0 1 0 0-6V3h-5a3 3 0 1 1-6 0Z" /> <path d="M9 3H4v6a3 3 0 1 1 0 6v5h6a3 3 0 1 1 6 0h4v-6a3 3 0 1 0 0-6V3h-5a3 3 0 1 1-6 0Z" />
{:else if icon === "up" || icon === "down" || icon === "kanban" || icon === "link"} {:else if icon === "up" || icon === "down" || icon === "kanban" || icon === "link" || icon === "zoom-in" || icon === "zoom-out"}
{@html actionIcons[icon]} {@html actionIcons[icon]}
{:else if icon === "more"} {:else if icon === "more"}
<circle cx="5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="19" cy="12" r="1" /> <circle cx="5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="19" cy="12" r="1" />
@@ -150,6 +150,10 @@
<path d="M5 12h14" /> <path d="M5 12h14" />
{:else if icon === "toggle"} {:else if icon === "toggle"}
<rect x="3" y="7" width="18" height="10" rx="5" /><circle cx="16" cy="12" r="2.5" /> <rect x="3" y="7" width="18" height="10" rx="5" /><circle cx="16" cy="12" r="2.5" />
{:else if icon === "fit-width"}
<path d="M3 4v16M21 4v16M7 12h10M10 9l-3 3 3 3M14 9l3 3-3 3" />
{:else if icon === "rotate"}
<path d="M20 7v5h-5" /><path d="M20 12a8 8 0 1 0-2 6" />
{/if} {/if}
</svg> </svg>
<style> <style>
+5 -1
View File
@@ -57,7 +57,11 @@
| "download" | "download"
| "upload" | "upload"
| "minus" | "minus"
| "toggle"; | "toggle"
| "zoom-in"
| "zoom-out"
| "fit-width"
| "rotate";
type Props = { type Props = {
icon: IconName; icon: IconName;
+53
View File
@@ -0,0 +1,53 @@
// The PDF fixtures of the PDF Viewer smoke test. They come from the PDF Viewer plugin (tests/fixture.mjs and tests/fixtures/password.pdf).
// `samplePdf` makes two pages with text, a filled rectangle, and a shading. `passwordPdf` is a protected copy: its password is "reader".
/** Two US Letter pages with selectable text. The second page has a shading with a PostScript function. */
export function samplePdf() {
const objects = [
'<< /Type /Catalog /Pages 2 0 R >>',
'<< /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >>',
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> /Contents 4 0 R >>',
stream('q 0.15 0.35 0.7 rg 40 620 532 110 re f Q\nBT /F1 24 Tf 50 760 Td (RuneStone PDF test) Tj 0 -180 Td (Page one text selection) Tj ET'),
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> /Shading << /Sh1 8 0 R >> >> /Contents 6 0 R >>',
stream('BT /F1 24 Tf 50 700 Td (Second PDF page) Tj ET\nq 50 100 512 200 re W n /Sh1 sh Q'),
'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',
// A PostScript (type 4) function. PDF.js compiles it to WebAssembly, so the CSP test covers 'wasm-unsafe-eval'.
'<< /ShadingType 2 /ColorSpace /DeviceRGB /Coords [50 0 562 0] /Function 9 0 R /Extend [true true] >>',
stream('{dup dup 0.5 mul exch 1 exch sub}', '/FunctionType 4 /Domain [0 1] /Range [0 1 0 1 0 1] '),
];
let source = '%PDF-1.7\n%\xff\xfe\xfd\xfc\n';
const offsets = [0];
for (const [index, object] of objects.entries()) {
offsets.push(Buffer.byteLength(source, 'latin1'));
source += `${index + 1} 0 obj\n${object}\nendobj\n`;
}
const xref = Buffer.byteLength(source, 'latin1');
source += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
for (const offset of offsets.slice(1)) source += `${String(offset).padStart(10, '0')} 00000 n \n`;
source += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
return Buffer.from(source, 'latin1');
}
function stream(value, entries = '') { return `<< ${entries}/Length ${Buffer.byteLength(value)} >>\nstream\n${value}\nendstream`; }
/** A PDF that needs the password "reader". It is in Base64, so Git keeps its bytes. */
export function passwordPdf() {
return Buffer.from([
"JVBERi0xLjMKJeLjz9MKMSAwIG9iago8PAovVHlwZSAvQ2F0YWxvZwovUGFnZXMgMiAwIFIKPj4KZW5kb2JqCjIgMCBvYmoKPDwK",
"L1R5cGUgL1BhZ2VzCi9LaWRzIFsgMyAwIFIgNiAwIFIgXQovQ291bnQgMgo+PgplbmRvYmoKMyAwIG9iago8PAovVHlwZSAvUGFn",
"ZQovUGFyZW50IDIgMCBSCi9NZWRpYUJveCBbIDAgMCA2MTIgNzkyIF0KL1Jlc291cmNlcyA8PAovRm9udCA8PAovRjEgNCAwIFIK",
"Pj4KPj4KL0NvbnRlbnRzIDUgMCBSCj4+CmVuZG9iago0IDAgb2JqCjw8Ci9UeXBlIC9Gb250Ci9TdWJ0eXBlIC9UeXBlMQovQmFz",
"ZUZvbnQgL0hlbHZldGljYQo+PgplbmRvYmoKNSAwIG9iago8PAovTGVuZ3RoIDEyOQo+PgpzdHJlYW0KiVMq6xPVisMuZWp1BS9z",
"5/joxhOdf21xdCOrAUByO06B9ClJy0wK7H+l7flob+B4XwQ+KKd3qeABIfk8uLLWUfiax7FVaNp2eGUjy0N/ewS98OF0jZT+LA8R",
"0N0M4BiPmJfxIn77QBqq4SYw+MDG4ojtscK+qps1QL9MJXOnpwSBCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iago8PAovVHlwZSAv",
"UGFnZQovUGFyZW50IDIgMCBSCi9NZWRpYUJveCBbIDAgMCA2MTIgNzkyIF0KL1Jlc291cmNlcyA8PAovRm9udCA8PAovRjEgNCAw",
"IFIKPj4KPj4KL0NvbnRlbnRzIDcgMCBSCj4+CmVuZG9iago3IDAgb2JqCjw8Ci9MZW5ndGggNDYKPj4Kc3RyZWFtCiy55bSCEhQT",
"SUrkrVamBjYoo/MXPkuAMQr0FdQ5M5petMLGUzj2N+Fjt41Hj3gKZW5kc3RyZWFtCmVuZG9iago4IDAgb2JqCjw8Ci9WIDIKL1Ig",
"MwovTGVuZ3RoIDEyOAovUCA0Mjk0OTY3MjkyCi9GaWx0ZXIgL1N0YW5kYXJkCi9PIDxkOTJmZjZmZjA5YTk0ZDZjZGEwMjQzNTUw",
"YmIzZDlmMmJhYTA1NjM3NmQ4MmFkZTdhZTU3NGY2MTIyZWQyOTZmPgovVSA8YTAwYzdlNDVmMGY1MTgyOTIyOGE3ZjU2NGYxMGM1",
"MjAyOGJmNGU1ZTRlNzU4YTQxNjQwMDRlNTZmZmZhMDEwOD4KPj4KZW5kb2JqCnhyZWYKMCA5CjAwMDAwMDAwMDAgNjU1MzUgZiAK",
"MDAwMDAwMDAxNSAwMDAwMCBuIAowMDAwMDAwMDY0IDAwMDAwIG4gCjAwMDAwMDAxMjkgMDAwMDAgbiAKMDAwMDAwMDI1NyAwMDAw",
"MCBuIAowMDAwMDAwMzI3IDAwMDAwIG4gCjAwMDAwMDA1MDcgMDAwMDAgbiAKMDAwMDAwMDYzNSAwMDAwMCBuIAowMDAwMDAwNzMx",
"IDAwMDAwIG4gCnRyYWlsZXIKPDwKL1NpemUgOQovUm9vdCAxIDAgUgovSUQgWyA8NjI2NjY1NjIzNzY0MzUzOTM2Mzk2MjYxMzQ2",
"NTMyNjYzNDMyMzQzMjMyMzI2NjMyNjEzOTY0MzkzMjM3NjI2ND4gPDYyNjY2NTYyMzc2NDM1MzkzNjM5NjI2MTM0NjUzMjY2MzQz",
"MjM0MzIzMjMyNjYzMjYxMzk2NDM5MzIzNzYyNjQ+IF0KL0VuY3J5cHQgOCAwIFIKPj4Kc3RhcnR4cmVmCjk0NgolJUVPRgo=",
].join(""), "base64");
}
+229
View File
@@ -0,0 +1,229 @@
// The native PDF Viewer: the file tree marks PDF files without the module, the first PDF tab loads it, and each tab
// renders a page with selectable text, page controls, zoom, rotation, Page Up and Page Down, and Reload.
// It also checks two tabs, one worker for each open tab, a protected PDF, a damaged file, Off and On, no network request,
// no text read of a PDF, the owner ID of a tab transfer, a saved tab after a reload, both themes, and a narrow toolbar.
// It replaces tests/browser.mjs of the PDF Viewer plugin.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { passwordPdf, samplePdf } from "../../fixtures/pdf/fixtures.mjs";
await runSmoke("features/pdf", async ({ page }) => {
const output = await outputDir("features/pdf");
const origin = new URL(smokeUrl).origin;
const requests = [];
page.on("request", request => {
const url = request.url();
if (!url.startsWith(origin) && !/^(blob|data):/.test(url)) requests.push(url);
});
// Count the PDF.js workers that run (src/lib/features/pdf/engine.ts names them).
await page.addInitScript(() => {
const workers = new Set();
const NativeWorker = window.Worker;
window.Worker = class extends NativeWorker {
constructor(url, options) { super(url, options); if (options?.name === "PDF.js") workers.add(this); }
terminate() { workers.delete(this); super.terminate(); }
};
window.__PDF_WORKERS__ = workers;
});
await mockTauri(page, {
state: { sample: [...samplePdf()], password: [...passwordPdf()] },
commands: test => ({
...test.workspace({ root: "C:\\pdf-feature", files: { "Sample.pdf": "", "Other.PDF": "", "Broken.pdf": "", "Protected.pdf": "", "Slow.pdf": "", "note.md": "# Note\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
"plugin:window|destroy": () => null,
workspace_read_bytes: async ({ rel }) => {
if (rel === "Slow.pdf") await new Promise(resolve => setTimeout(resolve, 400));
const bytes = rel === "Broken.pdf" ? [1, 2, 3] : rel === "Protected.pdf" ? test.state.password : test.state.sample;
return new Uint8Array(bytes).buffer;
},
}),
});
// `window.requestClose()` sends the native close request, so the workbench saves its document tabs (tabs/lifecycle does the same).
await page.addInitScript(() => {
const internals = window.__TAURI_INTERNALS__;
const { transformCallback, invoke } = internals;
const callbacks = new Map(), handlers = [];
internals.transformCallback = (callback, once) => { const id = transformCallback(callback, once); callbacks.set(id, callback); return id; };
internals.invoke = (command, args = {}) => {
if (command === "plugin:event|listen" && args.event === "tauri://close-requested") handlers.push(args.handler);
return invoke(command, args);
};
window.requestClose = async () => {
for (const id of handlers) await callbacks.get(id)?.({ event: "tauri://close-requested", id, payload: null });
};
});
await page.goto(smokeUrl);
const row = name => page.locator(`[data-tree-rel="${name}"]`);
await row("Sample.pdf").waitFor();
await row("Sample.pdf").locator(".document-icon").waitFor();
assert.equal(await row("Other.PDF").locator(".document-icon").count(), 1, "Any letter case of the extension is a PDF");
assert.equal(await row("note.md").locator(".document-icon").count(), 0);
const loaded = () => page.evaluate(() => performance.getEntriesByType("resource").some(entry => {
const { pathname } = new URL(entry.name);
return pathname === "/src/lib/features/pdf/index.ts" || pathname.includes("pdfjs-dist");
}));
assert.equal(await loaded(), false, "The file tree marks PDF files without the module or PDF.js");
const workers = () => page.evaluate(() => window.__PDF_WORKERS__.size);
const active = page.locator(".plugin-editor-pane:visible");
const status = active.locator(".pdf-viewer .status");
const rendered = text => status.filter({ hasText: new RegExp(`^${text}$`) }).waitFor();
const button = name => active.getByRole("button", { name, exact: true });
const tab = name => page.getByRole("tab", { name, exact: true });
await row("Sample.pdf").click();
await rendered("Page 1 of 2");
assert.equal(await loaded(), true, "The first PDF tab loads the module");
await active.getByRole("img", { name: "PDF page 1", exact: true }).waitFor();
assert.match(await active.locator(".textLayer").innerText(), /Page one text selection/);
assert.ok(await active.locator("canvas").evaluate(canvas => {
const data = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data;
let colored = 0;
for (let index = 0; index < data.length; index += 4) if (data[index] < 200 && data[index + 2] > 100) colored++;
return colored > 1000;
}), "The page shows its blue rectangle");
assert.equal(await active.getByRole("spinbutton", { name: "Page number", exact: true }).inputValue(), "1");
assert.equal(await button("Fit width").getAttribute("aria-pressed"), "true");
assert.equal(await button("Previous page").isDisabled(), true);
assert.equal(await workers(), 1);
// Both themes. The page stays white paper.
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
await page.waitForTimeout(100);
await page.screenshot({ path: path.join(output, `viewer-${theme}.png`) });
}
// The tooltip of an icon button shows on keyboard focus.
await button("Rotate clockwise").focus();
await page.getByRole("tooltip", { name: "Rotate clockwise" }).waitFor();
await active.locator(".toolbar").screenshot({ path: path.join(output, "toolbar-focus.png") });
// A narrow window: the toolbar wraps and keeps every control inside the pane.
await page.setViewportSize({ width: 900, height: 720 });
await rendered("Page 1 of 2");
const toolbar = active.locator(".toolbar");
assert.equal(await toolbar.evaluate(node => node.scrollWidth > node.clientWidth), false, "No horizontal scroll in the toolbar");
const box = await toolbar.boundingBox();
for (const control of await toolbar.locator("button, input").all()) {
const item = await control.boundingBox();
assert.ok(item.x >= box.x - 1 && item.x + item.width <= box.x + box.width + 1, "Each control stays inside the toolbar");
}
await page.screenshot({ path: path.join(output, "viewer-900.png") });
await page.setViewportSize({ width: 1440, height: 1000 });
// Pages, zoom, rotation, and the keyboard.
await button("Next page").click();
await rendered("Page 2 of 2");
await active.getByRole("img", { name: "PDF page 2", exact: true }).waitFor();
assert.equal(await button("Next page").isDisabled(), true);
const zoomText = () => active.locator(".zoom").innerText();
const before = await zoomText();
await button("Zoom in").click();
await rendered("Page 2 of 2");
assert.notEqual(await zoomText(), before);
assert.equal(await button("Fit width").getAttribute("aria-pressed"), "false");
await button("Rotate clockwise").click();
await rendered("Page 2 of 2");
assert.ok(await active.locator("canvas").evaluate(canvas => canvas.width > canvas.height), "A rotated page is wider than high");
await active.locator(".scroll").focus();
await page.keyboard.press("PageUp");
await rendered("Page 1 of 2");
await page.keyboard.press("PageDown");
await rendered("Page 2 of 2");
const input = active.getByRole("spinbutton", { name: "Page number", exact: true });
await input.fill("1");
await input.press("Enter");
await rendered("Page 1 of 2");
await input.fill("99");
await input.press("Enter");
await rendered("Page 2 of 2");
assert.equal(await input.inputValue(), "2", "A page number above the count goes to the last page");
// A second tab, one tab for each file, and one worker for each open tab.
await row("Other.PDF").click();
await rendered("Page 1 of 2");
assert.equal(await workers(), 2);
await row("Other.PDF").click();
assert.equal(await tab("Other").count(), 1, "A second open selects the same tab");
await page.getByRole("button", { name: "Close Other", exact: true }).click();
await tab("Other").waitFor({ state: "detached" });
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1);
// A tab that closes before its file arrives starts no worker.
await row("Slow.pdf").click();
await tab("Slow").waitFor();
await page.getByRole("button", { name: "Close Slow", exact: true }).click();
await page.waitForTimeout(600);
assert.equal(await workers(), 1);
// A protected PDF.
await row("Protected.pdf").click();
const password = active.getByLabel("PDF password");
await password.waitFor();
await status.filter({ hasText: "This PDF needs a password." }).waitFor();
assert.equal(await password.evaluate(node => node === document.activeElement), true, "The password field takes focus");
await password.fill("incorrect");
await active.getByRole("button", { name: "Unlock", exact: true }).click();
await status.filter({ hasText: "Incorrect password. Try again." }).waitFor();
await page.screenshot({ path: path.join(output, "password.png") });
await password.fill("reader");
await password.press("Enter");
await rendered("Page 1 of 2");
await page.getByRole("button", { name: "Close Protected", exact: true }).click();
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1);
// A tab that closes while it asks for the password stops its worker.
await row("Protected.pdf").click();
await active.getByLabel("PDF password").waitFor();
await page.getByRole("button", { name: "Close Protected", exact: true }).click();
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1);
// Reload keeps the page and replaces the worker.
await tab("Sample").click();
await rendered("Page 2 of 2");
await button("Reload PDF").click();
await rendered("Page 2 of 2");
assert.equal(await workers(), 1);
// A damaged file shows an error, and Reload stays available.
await row("Broken.pdf").click();
await active.getByRole("alert").filter({ hasText: "Cannot display this PDF." }).waitFor();
assert.equal(await button("Reload PDF").isDisabled(), false);
assert.equal(await button("Next page").isDisabled(), true);
await page.screenshot({ path: path.join(output, "damaged.png") });
// Off closes the PDF tabs, stops every worker, and removes the marks. On opens PDF files again.
const switches = await page.evaluate(() => window.__TEST__.settings("features"));
await page.evaluate(value => window.__TEST__.writeSettings("features", value), { ...switches, pdf: false });
await active.locator(".pdf-viewer").waitFor({ state: "detached" });
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 0);
assert.equal(await page.locator(".pdf-viewer").count(), 0);
assert.equal(await tab("Sample").count(), 0);
await row("Sample.pdf").locator(".document-icon").waitFor({ state: "detached" });
await page.evaluate(value => window.__TEST__.writeSettings("features", value), { ...switches, pdf: true });
await row("Sample.pdf").locator(".document-icon").waitFor();
await row("Sample.pdf").click();
await rendered("Page 1 of 2");
assert.equal(await workers(), 1);
const textReads = await page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_read" && /\.pdf$/i.test(call.args.rel)));
assert.deepEqual(textReads, [], "A PDF is never read as text");
// A tab transfer names the old package and the document type. A reload reopens the saved PDF tab from its path.
const transfer = await page.evaluate(async () => {
const external = await import("/src/lib/plugins/external.ts");
let editors = [];
external.pluginEditors.subscribe(value => { editors = value; })();
const { owner, id, document } = external.pluginTabState(editors.find(view => view.document));
return { owner, id, document };
});
assert.deepEqual(transfer, { owner: "runestone.pdf-viewer", id: "pdf", document: { id: "Sample.pdf", path: "Sample.pdf" } });
await page.evaluate(() => window.requestClose());
await page.reload();
await rendered("Page 1 of 2");
assert.equal(await tab("Sample").count(), 1);
assert.deepEqual(requests, [], "No network request leaves the app");
console.log("PASS: PDF Viewer loads at first need, renders text and pages, zooms, rotates, reloads, unlocks, reports a damaged file, keeps one worker per tab, restores its tab, and Off removes it");
}, { timeout: 60000, viewport: { width: 1440, height: 1000 } });
+2 -2
View File
@@ -20,7 +20,7 @@ await runSmoke("features/settings", async ({ browser }) => {
const sourceControl = main.locator(".header-left").getByRole("button", { name: "Source control", exact: true }); const sourceControl = main.locator(".header-left").getByRole("button", { name: "Source control", exact: true });
await sourceControl.waitFor(); await sourceControl.waitFor();
// Without an old package, the migration stores the default of each feature. // Without an old package, the migration stores the default of each feature.
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true, terminal: true }); assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true, terminal: true, pdf: true });
const settings = await openPage(context, { timeout: 10000 }); const settings = await openPage(context, { timeout: 10000 });
await settings.goto(`${smokeUrl}/?settingsWindow=true`); await settings.goto(`${smokeUrl}/?settingsWindow=true`);
@@ -33,7 +33,7 @@ await runSmoke("features/settings", async ({ browser }) => {
await git.click(); await git.click();
await sourceControl.waitFor({ state: "detached" }); await sourceControl.waitFor({ state: "detached" });
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true, terminal: true }); assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true, terminal: true, pdf: true });
assert.equal(await settings.getByRole("status").innerText(), "Changes saved."); assert.equal(await settings.getByRole("status").innerText(), "Changes saved.");
await git.focus(); await git.focus();
await settings.keyboard.press("Space"); await settings.keyboard.press("Space");
+9 -9
View File
@@ -33,9 +33,9 @@ test("switches keep known booleans only, and missing keys take the default", ()
assert.deepEqual(storedSwitches({ git: false, terminal: "no", csv: true, other: "yes" }), { git: false }); assert.deepEqual(storedSwitches({ git: false, terminal: "no", csv: true, other: "yes" }), { git: false });
assert.deepEqual(storedSwitches(null), {}); assert.deepEqual(storedSwitches(null), {});
assert.deepEqual(storedSwitches(["git"]), {}); assert.deepEqual(storedSwitches(["git"]), {});
assert.deepEqual(switchesFrom(undefined), { git: true, background: true, terminal: true }); assert.deepEqual(switchesFrom(undefined), { git: true, background: true, terminal: true, pdf: true });
assert.deepEqual(switchesFrom({ git: false, background: false, terminal: false }), { git: false, background: false, terminal: false }); assert.deepEqual(switchesFrom({ git: false, background: false, terminal: false, pdf: false }), { git: false, background: false, terminal: false, pdf: false });
assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true, terminal: true }); assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true, terminal: true, pdf: true });
}); });
test("an installed package gives its state, and without a package the default applies", () => { test("an installed package gives its state, and without a package the default applies", () => {
@@ -71,10 +71,10 @@ test("the migration asks only for features without a switch, and keeps other key
write: async (value: unknown) => { writes.push(value); }, write: async (value: unknown) => { writes.push(value); },
legacy: async (ids: string[]) => { asked.push(ids); return packages; }, legacy: async (ids: string[]) => { asked.push(ids); return packages; },
}); });
assert.deepEqual(await migrateFeatures(host({ future: 1, background: false, terminal: true }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground(), presentTerminal()), ["git"]); assert.deepEqual(await migrateFeatures(host({ future: 1, background: false, terminal: true, pdf: true }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground(), presentTerminal()), ["git"]);
assert.deepEqual(asked, [["runestone.git"]]); assert.deepEqual(asked, [["runestone.git"]]);
assert.deepEqual(writes, [{ future: 1, background: false, terminal: true, git: false }]); assert.deepEqual(writes, [{ future: 1, background: false, terminal: true, pdf: true, git: false }]);
assert.deepEqual(await migrateFeatures(host({ git: true, background: true, terminal: true }, []), presentBackground(), presentTerminal()), []); assert.deepEqual(await migrateFeatures(host({ git: true, background: true, terminal: true, pdf: true }, []), presentBackground(), presentTerminal()), []);
assert.equal(asked.length, 1, "A stored switch needs no package read."); assert.equal(asked.length, 1, "A stored switch needs no package read.");
assert.equal(writes.length, 1); assert.equal(writes.length, 1);
}); });
@@ -84,7 +84,7 @@ test("a missing background section asks for the slideshow package and makes the
const switches: unknown[] = []; const switches: unknown[] = [];
const sections: BackgroundSettings[] = []; const sections: BackgroundSettings[] = [];
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { sections.push(value); } }; const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { sections.push(value); } };
const host = { read: () => ({ git: true, background: false, terminal: true }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } }; const host = { read: () => ({ git: true, background: false, terminal: true, pdf: true }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } };
assert.deepEqual(await migrateFeatures(host, background, presentTerminal()), []); assert.deepEqual(await migrateFeatures(host, background, presentTerminal()), []);
assert.deepEqual(asked, [["runestone.bg-slideshow"]]); assert.deepEqual(asked, [["runestone.bg-slideshow"]]);
assert.deepEqual(switches, [], "Stored switches stay."); assert.deepEqual(switches, [], "Stored switches stay.");
@@ -93,8 +93,8 @@ test("a missing background section asks for the slideshow package and makes the
// Both migrations together ask once for both packages. // Both migrations together ask once for both packages.
asked.length = 0; asked.length = 0;
await migrateFeatures({ ...host, read: () => undefined }, background, presentTerminal()); await migrateFeatures({ ...host, read: () => undefined }, background, presentTerminal());
assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow", "runestone.terminal"]]); assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer"]]);
assert.deepEqual(switches, [{ git: true, background: true, terminal: true }]); assert.deepEqual(switches, [{ git: true, background: true, terminal: true, pdf: true }]);
}); });
test("a failed package read writes nothing, so the next start tries again", async () => { test("a failed package read writes nothing, so the next start tries again", async () => {
+104
View File
@@ -0,0 +1,104 @@
// The PDF Viewer feature: the page and zoom limits, the document identification of the catalog, and the document
// mount of a feature session. The model tests come from the PDF Viewer plugin (tests/model.test.ts).
import { test } from "node:test";
import assert from "node:assert/strict";
import { featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
import { identifyPdf } from "../../../src/lib/features/pdfDocument.ts";
import { nextRotation, outputScale, pageNumber, zoomLevel } from "../../../src/lib/features/pdf/model.ts";
import { FeatureSession } from "../../../src/lib/features/session.ts";
import type { FeatureContext, FeatureInstance } from "../../../src/lib/features/types.ts";
import type { PluginDocumentContext } from "../../../src/lib/plugins/sdk.ts";
test("PDF identification handles uppercase extensions and distinct paths", () => {
assert.deepEqual(identifyPdf("notes\\Report.PDF"), { id: "notes/Report.PDF" });
assert.notDeepEqual(identifyPdf("a/report.pdf"), identifyPdf("b/report.pdf"));
for (const path of ["report.pdf.md", "pdf", "report.png"]) assert.equal(identifyPdf(path), null);
});
test("page and zoom inputs stay within supported bounds", () => {
assert.equal(pageNumber(NaN, 20), 1);
assert.equal(pageNumber(-3, 20), 1);
assert.equal(pageNumber(99, 20), 20);
assert.equal(pageNumber(2.8, 20), 2);
assert.equal(zoomLevel(Infinity), 1);
assert.equal(zoomLevel(0), .25);
assert.equal(zoomLevel(10), 4);
assert.deepEqual([0, 90, 180, 270].map(nextRotation), [90, 180, 270, 0]);
});
test("large PDF pages respect canvas dimension and memory limits", () => {
for (const [width, height] of [[612, 792], [20000, 500], [20000, 20000]]) {
const scale = outputScale(width, height, 3);
assert.ok(width * scale <= 8192);
assert.ok(height * scale <= 8192);
assert.ok(width * height * scale * scale <= 16_000_001);
}
});
test("the catalog gives PDF Viewer the old package ID and one binary document type", () => {
const pdf = featureEntry("pdf");
assert.equal(pdf.owner, "runestone.pdf-viewer");
assert.equal(featureOfOwner("runestone.pdf-viewer")?.id, "pdf");
assert.equal(pdf.defaultOn, true);
assert.equal(pdf.followsPackage, true);
assert.deepEqual(pdf.views, []);
assert.deepEqual(pdf.commands, []);
assert.deepEqual(pdf.documentTypes.map(type => [type.id, type.icon, type.content, [...type.extensions], type.title()]), [["pdf", "file", "binary", ["pdf"], "PDF document"]]);
assert.deepEqual(featureEntry("git").documentTypes, []);
});
function fakeContext(): FeatureContext {
return { openView: () => {}, openFile: async () => {}, onWorkspaceChange: () => () => {} };
}
test("a feature session identifies PDF files without loading the feature", () => {
let loads = 0;
const session = new FeatureSession(featureEntry("pdf"), fakeContext(), async () => { loads++; throw new Error("not loaded"); });
const type = session.documentTypes.get("pdf");
assert.ok(type);
assert.equal(type.title, "PDF document");
assert.equal(type.content, "binary");
assert.deepEqual(type.extensions, ["pdf"]);
assert.deepEqual(type.identify("docs/Guide.PDF", ""), { id: "docs/Guide.PDF" });
assert.equal(type.identify("docs/guide.md", ""), null);
assert.equal(loads, 0, "Identification does not load the feature.");
assert.equal(session.started, false);
});
test("the first document mount starts one instance, each tab gets the document, and stop disposes it", async () => {
const events: string[] = [];
let starts = 0;
const instance: FeatureInstance = {
mount: () => { throw new Error("no views"); },
mountDocument: (type, element, document) => {
events.push(`mount ${type} ${document.path}`);
element.textContent = document.id;
return () => { events.push(`unmount ${document.path}`); };
},
dispose: () => { events.push("dispose"); },
};
const session = new FeatureSession(featureEntry("pdf"), fakeContext(), async () => ({ start: () => { starts++; return instance; } }));
const element = () => ({ textContent: "", replaceChildren(this: { textContent: string }) { this.textContent = ""; } }) as unknown as HTMLElement;
const first = element(), second = element();
const a: PluginDocumentContext = { id: "a.pdf", path: "a.pdf" };
const b: PluginDocumentContext = { id: "b/B.PDF", path: "b/B.PDF" };
const closeA = await session.mount("pdf", first, a);
const closeB = await session.mount("pdf", second, b);
assert.equal(starts, 1, "Two tabs share one instance.");
assert.equal(first.textContent, "a.pdf");
await closeA();
assert.equal(first.textContent, "", "The host empties the element after the dispose.");
await assert.rejects(session.mount("missing", element(), a), /This view is unavailable/);
await assert.rejects(session.mount("pdf", element()), /This view is unavailable/, "Without a document, the ID names a view.");
await closeB();
await session.stop();
assert.deepEqual(events, ["mount pdf a.pdf", "mount pdf b/B.PDF", "unmount a.pdf", "unmount b/B.PDF", "dispose"]);
await assert.rejects(session.mount("pdf", element(), a), /This feature is off/);
});
test("a feature without a document mount refuses a document", async () => {
const instance: FeatureInstance = { mount: () => () => {}, dispose() {} };
const session = new FeatureSession(featureEntry("pdf"), fakeContext(), async () => ({ start: () => instance }));
await assert.rejects(session.mount("pdf", { replaceChildren() {} } as unknown as HTMLElement, { id: "a.pdf", path: "a.pdf" }), /This view is unavailable/);
await session.stop();
});
+2 -2
View File
@@ -261,9 +261,9 @@ test("the feature migration copies the terminal settings also when the package r
test("the terminal switch follows the enabled state of an installed Terminal plugin", async () => { test("the terminal switch follows the enabled state of an installed Terminal plugin", async () => {
const writes: unknown[] = []; const writes: unknown[] = [];
const host = { read: () => ({ git: true, background: true }), write: async (value: unknown) => { writes.push(value); }, const host = { read: () => ({ git: true, background: true, pdf: true }), write: async (value: unknown) => { writes.push(value); },
legacy: async (ids: string[]) => ids.map(id => ({ id, installed: true, enabled: false, settings: null })) }; legacy: async (ids: string[]) => ids.map(id => ({ id, installed: true, enabled: false, settings: null })) };
const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} }; const background = { missing: () => false, hasImage: () => false, migrateFolder: async () => false, write: async () => {} };
assert.deepEqual(await migrateFeatures(host, background, terminalHost(false, null)), ["terminal"]); assert.deepEqual(await migrateFeatures(host, background, terminalHost(false, null)), ["terminal"]);
assert.deepEqual(writes, [{ git: true, background: true, terminal: false }]); assert.deepEqual(writes, [{ git: true, background: true, pdf: true, terminal: false }]);
}); });
+11
View File
@@ -105,6 +105,17 @@ export default defineConfig(() => ({
worker: { worker: {
format: /** @type {"es"} */ ("es"), format: /** @type {"es"} */ ("es"),
}, },
optimizeDeps: {
// The minified PDF.js build is one ES module without imports. The dev server serves it as it is. Without this, the
// first PDF tab finds a new dependency and the dev server reloads the page.
exclude: ["pdfjs-dist"],
},
build: {
// The PDF Viewer reads the data files of PDF.js with fetch (src/lib/features/pdf/engine.ts). Keep them as files of
// the app, because the content security policy permits no data: address for fetch.
/** @param {string} file */
assetsInlineLimit: file => file.replaceAll("\\", "/").includes("/pdfjs-dist/") ? false : undefined,
},
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build` // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
// //