Make Background a native feature

- Background replaces the Background Slideshow plugin and the background image of Appearance. It shows a folder as a slideshow, or one image.
- It is on by default. Its module loads at launch only when a folder or an image is chosen.
- Rust keeps the one folder in background-folder.json. The interface never sends a path. Eight background_* commands replace the six deprecated backgrounds_* commands.
- The first start moves the slideshow folder and settings, and keeps the saved image as the image source.
- One blur worker with a cache, fewer folder reads, and a decode before each fade. The hub writes only the changed properties.
- Remove the deprecated folder methods of api.backgrounds. set, get, and subscribe stay for the Project Management plugin.
- Show the view buttons in the workbench test without text, after UI-056.
- Update the tests, the measurement tool, the docs, and UI-057.
This commit is contained in:
Knotty Wyvern
2026-10-29 17:25:17 -07:00
parent 115c32fa92
commit ab868bbe8e
81 changed files with 3179 additions and 812 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.
A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface (`src/`).
Git is a native feature with an off switch in Settings → Features (`src/lib/features/`). It does not use the plugin API.
Git and Background 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_Terminal`.
The [development guide](docs/development.md#architecture) maps the source folders.
+17
View File
@@ -352,6 +352,7 @@ Keyboard focus now scrolls only the menu panel. It cannot dismiss a menu by scro
- Evidence: All 11 slideshow unit tests, TypeScript checks, and the settings browser check pass.
- Limits: Native desktop appearance requires user review.
- Replaces: The 800-millisecond fade rule in the interface guide.
- Update 2026-10-29: The rule stays. The native Background feature implements it ([UI-057](#ui-057--background-replaces-background-image-and-background-slideshow)).
### UI-016 — Translucent code blocks
@@ -442,6 +443,7 @@ Evidence: RuneStone_Git/.audit/git-tooltip-evidence.json and git-tooltip-*.png.
- Shared implementation: The image sidecar API, optional blurredUrl frames, and separate foreground and cover layers.
- Evidence: Host frame and sidecar checks cover layout, cleanup, size limits, and external changes. Plugin checks accompany the card review.
- Limits: Native desktop appearance requires user review.
- Update 2026-10-29: The rule stays. The native Background feature implements it ([UI-057](#ui-057--background-replaces-background-image-and-background-slideshow)).
### UI-021 — Workspace links in document panes
@@ -1042,3 +1044,18 @@ Native shell, background image, and desktop acceptance remain open.
- Evidence: `tests/smoke/layout/viewModes.smoke.mjs`.
- Replaces / replaced by: The names of UI-049.
- Limits: None.
### UI-057 — Background replaces Background image and Background Slideshow
- Type: Rule change
- Date: 2026-10-29
- Status: Implemented for user review
- Decision source: The owner decisions of Phase 7, stage 7-2 (2026-10-29): Background is on for every user, also after an update, and decisions 4A, 5C, 6A, and 11A.
- Previous rule: Appearance → **Background image** kept one image for new tabs, and `appearance.ts` drew it. The Background Slideshow plugin (`runestone.bg-slideshow` 0.0.11) showed a folder through `api.backgrounds` and its deprecated folder methods, with its settings in its own settings view.
- New rule: Background is a native feature with a switch in Settings → Features. Appearance → **Background** has **Background source** (Folder, Image, or None), the folder and its timing and order, the one image, the layout, the per-image editor, and the targets. With Background off, the section shows one line that names Settings → Features, no image shows, and menus are opaque. With no folder and no image, the feature does not load. **Next background image** and **Pause background** are in the command palette. A blank browser tab, also in a browser window, shows the background.
- Reason: The owner chose response time and memory over the plugin API. One section replaces two places for the same background.
- Scope: Appearance → Background, the workarea background, browser windows, Project Management board frames, and the command palette.
- Shared implementation: `src/lib/features/background/`, `src/lib/features/backgroundSettings.ts`, `src/lib/features/launch.ts`, `src/lib/plugins/backgrounds.ts`, `src/lib/theme/background.css`, and `src-tauri/src/backgrounds.rs`.
- Evidence: `tests/smoke/features/background.smoke.mjs` and the updated `tests/smoke/appearance/background*.smoke.mjs`, with screenshots in both themes and at 360 pixels in `output/smoke/features/background/`.
- Replaces / replaced by: The Background image section of Appearance and the Background Slideshow plugin. The rules of [UI-015](#ui-015--slower-slideshow-fades) and [UI-020](#ui-020--per-image-slideshow-layout) stay.
- Limits: Each window has its own timer, so windows can show different images. The settings window runs no slideshow. The old package stays installed until the user removes it.
+15 -9
View File
@@ -63,10 +63,10 @@ Windows is the primary platform. macOS and Linux builds are experimental.
| `plugins.rs` | Plugin package review, installation, enable state, removal, and recovery |
| `plugin_sources.rs` | Plugin downloads from Gitea releases |
| `git.rs` | The Git service of the Git feature. It runs the `git` program. |
| `features.rs` | Reads the old plugin packages of the native features one time, for the switch migration. It changes no plugin file. |
| `features.rs` | Reads the old plugin packages of the native features one time, for the first-start migration. It changes no plugin file. |
| `pty.rs`, `terminal_platform.rs` | Pseudo-terminals for the Terminal plugin |
| `browser.rs` | The process of the built-in browser engine |
| `backgrounds.rs` | Background image folders for themes and plugins |
| `backgrounds.rs` | The image folder of the Background feature: the folder dialog, the kept folder (`background-folder.json` in the app data folder), the image list and reads, the sidecar file, and the folder migration from the Background Slideshow plugin |
| `spelling.rs` | Spelling suggestions from the operating system (Windows) |
| `settings.rs`, `theme.rs` | The Settings window and theme export |
| `preferences.rs` | The settings file of the user. It reads, writes, and migrates the file, and replaces a damaged file. |
@@ -88,7 +88,7 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command
| `settings/` | The settings store (`store.ts`), and the code that moves the old browser values to the settings file (`migration.ts`) |
| `plugins/` | The plugin runtime, the host types (`sdk.ts`, which also exports the SDK types), and Settings → Plug-ins |
| `browser/` | The interface of the built-in browser |
| `features/` | The native features with an off switch: the catalog (`catalog.ts`), the switches (`state.ts`), the first-start migration, the loader, and one folder for each feature (`git/`). See [Native features](#native-features). |
| `features/` | The native features with an off switch: the catalog (`catalog.ts`), the switches (`state.ts`), the first-start migration, the loader, the launch rules, the Background settings (`backgroundSettings.ts`), and one folder for each feature (`git/`, `background/`). See [Native features](#native-features). |
| `completion/` | Contracts and services that plugins use |
| `git/` | The Git service and its types, for the Git feature and the line history in the status bar |
| `theme/` | Appearance settings, palettes, and the theme tokens (`tokens.css`) |
@@ -116,7 +116,8 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command
| Documents | Ordinary files in the workspace folder |
| Workspace state: tab order, pins, bookmarks, templates, Project Management boards | `.runestone/` in the workspace |
| Installed plugins and their settings | The app data folder. See [plugin storage](plugin-host.md#storage-and-recovery). |
| Preferences: general settings, appearance, custom themes, display language | `settings.json` in the app config folder |
| Preferences: general settings, appearance, custom themes, display language, feature switches, Background | `settings.json` in the app config folder |
| The image folder of Background | `background-folder.json` in the app data folder. The image of the image source stays in the WebView storage (IndexedDB). |
| Browser profiles, bookmarks, history, browser settings, and Chromium caches | `browser/` in the local app data folder. On Windows, this is `%LOCALAPPDATA%\com.runestone.app\browser\`. See [Built-in browser runtime](#built-in-browser-runtime). |
| Window layout and the open tabs of each workspace | The WebView storage (`localStorage`) of the app. RuneStone can lose these values without harm. |
@@ -135,13 +136,14 @@ On macOS, it is `~/Library/Application Support/<identifier>/`. On Linux, it is `
"customThemes": [],
"customThemesLegacy": [],
"language": "en",
"features": { "git": true }
"features": { "git": true, "background": true },
"background": { "source": "folder", "seconds": 60, "order": "name", "paused": false, "targets": ["app"], "overlay": 0, "position": "center", "size": "cover" }
}
```
| Rule | Detail |
| --- | --- |
| Sections | `general`, `appearance`, `customThemes`, `customThemesLegacy` (the original version 1 themes), `language`, and `features` (the switches of the native features). The host does not interpret their values. The frontend normalizes each section. |
| Sections | `general`, `appearance`, `customThemes`, `customThemesLegacy` (the original version 1 themes), `language`, `features` (the switches of the native features), and `background` (the source, the timing, the targets, and the folder layout of Background). The host does not interpret their values. The frontend normalizes each section. |
| Size | At most 8 MiB in total. The appearance can hold an image data URL of up to 3,000,000 characters. |
| Writes | `settings_write` replaces one section. The host writes a complete temporary file and renames it. Then it sends `settings-changed` to all windows with the section, the revision, and the value. |
| Damaged file | The host moves the file to `settings.corrupt-<seconds>.json` and writes a new file with the defaults. The first window that reads the settings shows a message one time. |
@@ -206,22 +208,26 @@ Errors of the plugin API stay in English, because they are for plugin developers
## Native features
Git is a native feature: host code with an off switch in **Settings → Features**. It does not use the plugin API.
Git and Background are native features: host code with an off switch in **Settings → Features**. They do not use the plugin API.
| Part | File |
| --- | --- |
| The catalog: ID, old plugin ID, name, views, and commands | `src/lib/features/catalog.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 | `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` |
| 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` |
| 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.
- A command without a view loads the feature and calls `FeatureInstance.run`. A launch rule starts the instance at once when it wants it, and again after each change of its settings.
- Background has a launch rule: it loads when the `background` section selects a folder, or an image that exists. Its settings section and its "has a source" test are in `src/lib/features/backgroundSettings.ts`, in the main bundle. It also runs in browser windows. In the settings window, only its settings component loads (`mountSettings`).
- 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.
- 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.
- Saved tabs and tab transfers keep the ID of the old plugin package as the owner ID, for example `runestone.git`. `builtInPackages` in `external.ts` lists the old package, so it never loads.
- Off stops the feature at once in each window and closes its views. The loaded module stays in memory until the window reloads.
- To add a feature, add its entry to `catalog.ts`, its import to `loader.ts`, its folder to `FEATURE_FOLDERS` in `scripts/featureChunks.mjs`, and its old plugin ID to `LEGACY_PACKAGES` in `src-tauri/src/features.rs`.
- To add a feature, add its entry to `catalog.ts`, its import to `loader.ts`, its folder to `FEATURE_FOLDERS` in `scripts/featureChunks.mjs`, and its old plugin ID to `LEGACY_PACKAGES` in `src-tauri/src/features.rs`. Add a launch rule only when the feature must run without a view.
## Plugin SDK
+61 -9
View File
@@ -2,7 +2,7 @@
[RuneStone](../../README.md) · [User guide](../user-guide.md)
This guide explains how to choose colors, set a background image, and edit, create, or share a custom theme.
This guide explains how to choose colors, show a background, and edit, create, or share a custom theme.
Open **Settings → Appearance**. Appearance settings apply to all workspaces on this computer and to all open windows.
@@ -21,20 +21,72 @@ Each named theme has its own fonts and syntax colors. Fonts come from your compu
## Adjust transparency
**Transparent surfaces** tints work areas with a background image and compatible plugin surfaces.
**Transparent surfaces** tints work areas with a [background](#show-a-background) and compatible plugin surfaces.
Menus stay opaque. With a background image, menus are at least 92% opaque and blur the image.
Set **Transparency amount** from 0% to 100%. The default is 18%.
Turn off **Transparent surfaces** for opaque surfaces. Text and icons stay opaque in both cases.
## Set a background image
## Show a background
1. Choose **Choose image…** and select a PNG, JPEG, WebP, or GIF file up to 50 MiB.
2. Set **Image size** to **Fill**, **Fit**, or **Actual size**.
3. Set **Image position**.
4. Set **Image overlay** from -100% to 100%. Negative values lighten the image, and positive values darken it.
The **Background** section shows a folder of images as a slideshow, or one image, behind the workspace.
Set **Background source** to **Folder**, **Image**, or **None**.
The image shows in new tabs. RuneStone keeps it on this computer.
The Project Management plugin can keep a separate image for a board. The Background Slideshow plugin can replace the image for a time.
### Show a folder as a slideshow
1. Set **Background source** to **Folder**, or choose **Choose folder…**.
2. Select a folder with PNG, JPEG, GIF, or WebP images. Each image can be up to 64 MiB.
3. Set **Seconds per image** from 1 to 86,400.
4. Set **Image order** to **File name** or **Random**.
**File name** uses natural order, so `2.png` comes before `10.png`. **Random** does not repeat the current image when the folder has other images.
Images fade over two seconds. When your system reduces motion, the images change without a fade.
RuneStone reads the folder again when a window gets the focus, after a settings change, and after every 10 images.
Subfolders, links, and unreadable files do not show. When no image loads, the background goes away, and RuneStone tries again after the image time, at least 5 seconds.
**Remove folder** forgets the folder. It changes no file.
### Show one image
1. Set **Background source** to **Image**, or choose **Choose image…**.
2. Select a PNG, JPEG, WebP, or GIF file up to 50 MiB.
RuneStone keeps the image on this computer. **Remove image** deletes the saved copy. It does not change your file.
### Set the layout
- **Image size**: **Fill**, **Fit**, or **Actual size**.
- **Image position**: one of nine positions.
- **Image overlay**: from -100% to 100%. Negative values lighten the image, and positive values darken it.
The folder and the image keep separate layouts.
### Change one image of the folder
Portrait images show in full over a blurred fill by default. To change one image:
1. Open **Per-image appearance**.
2. Choose the image in **Image**. Type part of its name to find it.
3. Set **Fit**, **Position**, and **Overlay**. The preview shows the result.
4. Choose **Save image appearance**.
**Reset image appearance** returns the image to the folder layout.
RuneStone keeps these settings in `.runestone-backgrounds.json` in the image folder. When another program changed the file, choose **Reload image settings** and make the change again.
### Choose where the background shows
Under **Show the background in**, select **The workspace and new tabs**, **All Project Management boards**, or one board.
The board list comes from the Project Management plugin of the current workspace. A saved board that is not available shows as **Unavailable board**, so that you can clear it.
A blank tab of a browser window also shows the background.
### Next and Pause
- **Next background image** in the command palette (Ctrl+Shift+P) or **Next image** in the settings shows the next image in every window.
- **Pause background** in the command palette or **Pause slideshow** in the settings keeps the current image. Use the same command to resume.
### Turn Background off
Background is on by default. To turn it off, open **Settings → Features** and clear **Background**.
Off removes the background at once in all windows, and menus become opaque again. Your folder, image, and settings stay.
With **None** or without a folder or an image, Background does not load.
## Edit a theme
+17 -8
View File
@@ -159,14 +159,6 @@
"design": "API type declaration, no renderer",
"check": "pnpm check"
},
"RuneStone/src/lib/theme/AppearanceSettings.svelte": {
"counts": {
"action": 1,
"localPopup": 2
},
"design": "Shared action menu for image position and size. Theme choice uses preview cards (UI-047).",
"check": "tests/smoke/appearance/backgroundImages.smoke.mjs"
},
"RuneStone/src/lib/ui/actionMenu.ts": {
"counts": {
"action": 1,
@@ -327,6 +319,23 @@
},
"design": "Uses the host menu. Keeps a native selector for older hosts.",
"check": "RuneStone_Project_Management/tests/october-cards.spec.ts with PM_HOST_URL; both themes, narrow layout, keyboard focus"
},
"RuneStone/src/lib/features/background/BackgroundSettings.svelte": {
"counts": {
"action": 1,
"localPopup": 4
},
"design": "Shared action menu for the source, the order, the image position, and the image size. Theme choice stays on preview cards (UI-047).",
"check": "tests/smoke/features/background.smoke.mjs"
},
"RuneStone/src/lib/features/background/ImageEditor.svelte": {
"counts": {
"action": 1,
"picker": 2,
"localPopup": 2
},
"design": "Shared action menu for the fit and the position of one image. The image list is the shared searchable picker (rs-picker).",
"check": "tests/smoke/features/background.smoke.mjs"
}
}
}
+13 -27
View File
@@ -436,9 +436,6 @@ The host still accepts the native calls of released plugins. A later host can re
| Terminal | `invoke("pty_new_window")` | Open a terminal window | `api.pty.openWindow()` |
| Terminal | `invoke("pty_dictation")` | Start Windows voice typing | `api.pty.dictation()` |
| Terminal | `invoke("workspace_read", { rel: ".runestone/tasks.json" })` | Read the task list of the workspace | `api.workspace.read(path)` |
| Background Slideshow | `api.backgrounds.chooseFolder`, `list`, `read`, `defaultFolder`, `readImageSettings`, `writeImageSettings` | Read images and per-image settings from a folder outside the workspace | `api.files` with a folder grant |
| Background Slideshow | `api.workspace.readOptional(".runestone/pm/workspace.json")` | Read the board names of Project Management | A service of Project Management through `api.services` |
The Project Management, Local Autocomplete, PDF Viewer, 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.
@@ -508,27 +505,17 @@ Make the data of a service a documented contract of the provider. Give its name,
## Background API
`api.backgrounds` (`version: 1`) lets a plugin show image frames behind the RuneStone interface.
`api.backgrounds` (`version: 1`) lets a plugin show image frames behind the RuneStone interface, and read the frames of other owners.
Frames stay in the current window and do not change the saved appearance settings.
To read images from a folder outside the workspace, use [folder grants](#folder-grants).
The folder methods are deprecated. They accept a folder path from the plugin. Use [folder grants](#folder-grants) in new code.
The host keeps them for released versions of Background Slideshow.
| Method | Contract |
| --- | --- |
| `set(target, frame)` | Show a frame for a target. `null` removes the frame of this plugin. |
| `get(target)` | Return the active frame for a target, or `null`. |
| `subscribe(listener)` | Receive the target name when a frame changes. Returns a cleanup function. |
| Method | Optional | Contract |
| --- | --- | --- |
| `chooseFolder()` | | Deprecated. Use `files.chooseFolder()`. Open the folder picker. Returns an absolute path, or `null` on cancel. |
| `defaultFolder()` | yes | Deprecated. Use `files.pictureFolder("Backgrounds")`. Create `RuneStone Backgrounds` in the Pictures folder of the user and return its path. |
| `list(folder)` | | Deprecated. Use `files.list(grant)`. Return `{ name }` for PNG, JPEG, GIF, and WebP files directly in the folder. |
| `read(folder, name)` | | Deprecated. Use `files.readBytes(grant, name)`. Read one image as bytes, at most 50 MiB. |
| `readImageSettings(folder)` | yes | Deprecated. Use `files.readSidecar(grant, ".runestone-backgrounds.json")`. Read the per-image settings file text, or `null`. |
| `writeImageSettings(folder, contents, expected)` | yes | Deprecated. Use `files.writeSidecar`. Save the per-image settings file. See [Per-image settings](#per-image-settings). |
| `set(target, frame)` | | Show a frame for a target. `null` removes the frame of this plugin. |
| `get(target)` | | Return the active frame for a target, or `null`. |
| `subscribe(listener)` | | Receive the target name when a frame changes. Returns a cleanup function. |
Folders must be absolute paths without `..` segments.
The host rejects links, files with other extensions, files that are not raster images, and files over the size limit.
File access needs an enabled plugin in the current window. Pending reads fail after the plugin stops.
The folder methods of earlier hosts (`chooseFolder`, `defaultFolder`, `list`, `read`, `readImageSettings`, and `writeImageSettings`) are gone. The native Background feature replaced the Background Slideshow plugin that used them.
### Targets and frames
@@ -554,13 +541,12 @@ When more than one plugin sets a frame for a target, the most recent frame is sh
Disable removes the frames and subscriptions of the plugin before cleanup.
To share saved configuration across windows, use the plugin settings API.
Example: [Background Slideshow](https://git.knottywyvern.com/kwyvern/RuneStone_BG_Slideshow/src/branch/main/docs/development.md#integration) sets frames from local image folders.
Example: the native Background feature (`src/lib/features/background/index.ts`) sets frames from a local image folder through the host frames.
Example: [Project Management](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/development.md#pm-0229-slideshow-backgrounds) reads frames for board backgrounds.
### Per-image settings
The per-image settings file is `.runestone-backgrounds.json` in the image folder.
It must be JSON with `"schema": 1` and an `images` object, at most 1 MiB.
`writeImageSettings` compares the current file to `expected` (`null` when the file does not exist). It fails when the file changed, so external edits are not lost.
`files.writeSidecar` does the same comparison on the same file, but the host checks only that the text is JSON. The plugin checks the schema.
Example: the [Background Slideshow image settings](https://git.knottywyvern.com/kwyvern/RuneStone_BG_Slideshow/src/branch/main/docs/development.md#per-image-settings) give the storage format and the rendering behavior.
The per-image settings file of the Background feature is `.runestone-backgrounds.json` in the image folder.
It is JSON with `"schema": 1` and an `images` object, at most 1 MiB. Each key is a file name. Each value can have `fit` (`cover`, `contain`, `auto`, or `blurred`), `position`, and `overlay`.
A plugin with a folder grant can read and write the same file with `files.readSidecar` and `files.writeSidecar`. `writeSidecar` compares the current file to `expected` (`null` when the file does not exist). It fails when the file changed, so external edits are not lost. The host checks only that the text is JSON. The plugin checks the schema.
Example: `src/lib/features/background/imageSettings.ts` reads the file and applies it.
+10 -10
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.
`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, 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. Browser windows start no native feature. See [Native features](development.md#native-features).
Native features, such as Git and Background, 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).
`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
@@ -108,7 +108,7 @@ The uninstall dialog puts focus on **Cancel**. Escape cancels.
`plugins_load` returns the entry module and records a lease for the window. `plugins_release` ends the lease and records any cleanup error.
Updates and removals wait for all leases to end. A recorded cleanup error blocks enable, update, and removal until RuneStone restarts.
Native services for plugins, such as the background file commands, need a lease for the calling window.
Native services for plugins, such as the folder grant commands (`folders_*`), need a lease for the calling window.
## Gitea downloads
@@ -160,11 +160,11 @@ The policy stops a script that comes in through rendered content, for example a
| --- | --- | --- |
| `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`. |
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, the Vite dev server, and plugins (Terminal, CSV Viewer, PDF Viewer, Background Slideshow). |
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, the Vite dev server, and plugins (Terminal, CSV Viewer, PDF 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. |
| `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: fonts that the PDF Viewer embeds. |
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the Background Slideshow worker reads its image from a Blob URL. |
| `worker-src` | `'self' blob:` | `'self'`: workers that the app serves. The app starts no worker now. `blob:`: the PDF Viewer and Background Slideshow workers. |
| `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. |
| `object-src` | `'none'` | RuneStone uses no plugins of the web view. |
| `base-uri` | `'self'` | |
| `form-action` | `'none'` | No form sends data to an address. |
@@ -186,10 +186,10 @@ Workers that the app loads from its own files get no policy. Workers from Blob U
| Capability | Windows | Plugins | Commands |
| --- | --- | --- | --- |
| `default.json` | `main`, `workspace-*`, `terminal-*` | All enabled plugins | All app commands |
| `settings.json` | `settings-main`, `settings-workspace-*` | All enabled plugins | Settings, plugins, backgrounds, completion, browser |
| `browser.json` | `browser-*` | Only the built-in browser (`builtInModules` in `src/lib/plugins/external.ts`) | Browser, `plugins_snapshot`, settings, spelling, and window controls |
| `settings.json` | `settings-main`, `settings-workspace-*` | All enabled plugins | Settings, plugins, the Background folder, folder grants, completion, browser |
| `browser.json` | `browser-*` | Only the built-in browser (`builtInModules` in `src/lib/plugins/external.ts`) | Browser, `plugins_snapshot`, settings, spelling, window controls, and the read commands of the Background folder (`background_folder`, `background_list`, `background_read`, `background_read_sidecar`) |
A browser window loads no installed plugin, so its capability has no workspace, file, Git, terminal, or plugin package commands. `tests/unit/plugins/windowCapabilities.spec.ts` and `tests/smoke/browser/window.smoke.mjs` check this.
A browser window loads no installed plugin, so its capability has no workspace, file, Git, terminal, or plugin package commands. The Background feature runs there to show the background behind a blank tab, so the window can read the Background folder. `tests/unit/plugins/windowCapabilities.spec.ts` and `tests/smoke/browser/window.smoke.mjs` check this.
The other windows load every enabled plugin. A smaller command set for them would limit only the app code, not the plugins. That split belongs to the plugin isolation work. Findings for that work:
@@ -197,7 +197,7 @@ The other windows load every enabled plugin. A smaller command set for them woul
- Settings windows use no `workspace_*`, `git_*`, or `pty_*` commands, but plugin settings views run there.
- Commands that need a workspace (`workspace_*`, `git_*`, `pty_open`, `pty_new_window`) fail in a window without a bound workspace.
- `pty_write`, `pty_resize`, and `pty_close` do not check the window that opened the terminal.
- `backgrounds_*` need a plugin lease of the calling window.
- `folders_*` need a plugin lease of the calling window. The `background_*` commands of the Background feature need no lease. They take no path: the host keeps the folder that the folder dialog gave.
- `browser_request` needs the session token that `browser_connect` gives the window. A plugin lease does not replace it.
- A new command for plugins goes in `default.json` and, if settings views need it, in `settings.json`. Add it to `browser.json` only when the built-in browser needs it.
@@ -207,7 +207,7 @@ The other windows load every enabled plugin. A smaller command set for them woul
| --- | --- |
| `src-tauri/src/plugins.rs` | Package checks, discovery, installation, updates, persistence, removal, leases, settings, and assets |
| `src-tauri/src/plugin_sources.rs` | Gitea link parsing and release downloads |
| `src-tauri/src/backgrounds.rs` | Background folder and image commands. Deprecated for plugins: use folder grants |
| `src-tauri/src/backgrounds.rs` | The image folder of the native Background feature. Plugins use folder grants |
| `src-tauri/src/folders.rs` | Folder grants for `api.files`: the picker, stored grants, listing, reads, and settings files beside the images |
| `src-tauri/src/pty.rs` | Terminal sessions for `api.pty`. A session with an IPC channel gets raw output bytes; a session without one gets the older window events |
| `src/lib/plugins/sdk.ts` | The public package API types |
+1 -1
View File
@@ -77,7 +77,6 @@ RuneStone uses the token for this request only and does not save it.
| --- | --- |
| Terminal | [Terminal guide](guides/terminal.md) |
| Project Management | [Project Management guide](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/project-management.md) |
| Background Slideshow | [Background Slideshow usage](https://git.knottywyvern.com/kwyvern/RuneStone_BG_Slideshow/src/branch/main/docs/usage.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) |
@@ -95,6 +94,7 @@ RuneStone uses the token for this request only and does not save it.
| A Gitea release has no usable package | Check the release tag. Ask the publisher for a release with one attached plugin ZIP. |
| An old Browser plugin shows in the list | Uninstall it. The built-in browser keeps your profiles and bookmarks. |
| 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 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.
+13 -8
View File
@@ -173,13 +173,13 @@ Decisions: [UI-004](design-decisions.md#ui-004--detached-tab-work-area), [UI-039
- Controls wrap at narrow widths, and the content area scrolls. Long navigation must leave room for the selected page.
- General offers the interface language through the shared action menu.
- **Features** lists each native feature in one card: its name, one line of description, and a switch. The page sits between Appearance and Plug-ins, and the `toggle` icon marks it. A failed load shows its cause under the switch in the error color.
- A feature that is off shows no controls: no navigation button, ribbon button, command, or tab.
- A feature that is off shows no controls: no navigation button, ribbon button, command, or tab. A settings section of an off feature shows one line that names Settings → Features.
- The transparency slider covers 0% to 100% and uses the accent and surface tokens of the current theme.
- Appearance shows a preview card for each theme. The arrow keys move between the cards and select a theme. The current card has the selection outline and a check mark.
- **Edit theme** opens the theme editor as a workbench tab in the window that opened Settings. The editor shows every color role in groups, with a swatch, a hex field, the lowest contrast result, and a reset button. Each change shows at once in that window. Save writes a short schema 3 theme with a base.
- Custom theme files use schema 3: one `mode`, an optional built-in `base` theme, the `colors` that differ from the base, and `fonts` stacks for interface, prose, headings, and code. The export writes every color and font. Schema 1 and 2 imports convert to schema 3. A schema 1 import selects the palette of the current appearance.
Decisions: [UI-028](design-decisions.md#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes), [UI-042](design-decisions.md#ui-042--theme-file-format-3-and-terminal-colors), [UI-047](design-decisions.md#ui-047--theme-editor-tab-and-theme-cards), [UI-055](design-decisions.md#ui-055--settings--features-and-native-git).
Decisions: [UI-028](design-decisions.md#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes), [UI-042](design-decisions.md#ui-042--theme-file-format-3-and-terminal-colors), [UI-047](design-decisions.md#ui-047--theme-editor-tab-and-theme-cards), [UI-055](design-decisions.md#ui-055--settings--features-and-native-git), [UI-057](design-decisions.md#ui-057--background-replaces-background-image-and-background-slideshow).
## Typography and tables
@@ -194,6 +194,8 @@ Decisions: [UI-005](design-decisions.md#ui-005--heading-spacing).
## Themes and background images
Background images come from the native Background feature (`src/lib/features/background/`). Appearance → Background holds its settings: the source (a folder, one image, or none), the layout, the per-image editor, and the targets.
### Palettes
- Color choices obey [Functional color](ui-color.md).
@@ -221,8 +223,9 @@ Decisions: [UI-009](design-decisions.md#ui-009--character-theme-appearances), [U
- Code blocks in Write and Read use `--rs-code-block-bg`.
- New-tab buttons use `--rs-image-control-bg` and `--rs-image-control-hover-bg`. Their tint keeps labels readable while the image stays visible. The new-tab screen shows only its action buttons, with icons, labels, and shortcuts.
- Headers and dialogs keep their own surfaces.
- The app work area and Project Management keep separate images and settings in every theme. An image can be up to 50 MiB. Image bytes stay in IndexedDB, and settings keep a small reference.
- Each image has a size, nine alignment positions, and an overlay from -100% (darker) to 100% (lighter), set with a slider or a typed value.
- The app work area and Project Management keep separate images and settings in every theme. The one image of Background can be up to 50 MiB. Its bytes stay in IndexedDB, and the appearance settings keep a small reference.
- The folder and the one image each have a size, nine alignment positions, and an overlay from -100% (lighter) to 100% (darker), set with a slider or a typed value.
- Without a background frame, every surface and menu is opaque. With Background off, no image shows.
Decisions: [UI-010](design-decisions.md#ui-010--background-surface-visibility), [UI-011](design-decisions.md#ui-011--backgrounds-across-the-work-area), [UI-016](design-decisions.md#ui-016--translucent-code-blocks).
@@ -238,13 +241,15 @@ Decisions: [UI-014](design-decisions.md#ui-014--readable-project-management-surf
### Slideshow
- A slideshow frame overrides the saved board image while it is active. A temporary board frame comes before the all-board frame. Removal restores the saved image.
- A folder of the Background feature is a slideshow. Its frame overrides the saved board image while it is active. A temporary board frame comes before the all-board frame. Removal restores the saved image.
- When the app and Project Management show the same frame, the host draws it once across both sidebars and the board. Distinct board frames keep their own area.
- Images fade over two seconds. Reduced motion removes the fade. Short intervals and manual Next can interrupt it.
- Portrait images show in full over a blurred cover layer by default. The image editor previews a per-image fit, position, and overlay, and saves or resets the override. Global settings apply to other images. The [plugin API](plugin-development.md#plugin-api) defines the storage.
- A new browser tab on `about:blank` shows the host background. A loaded page keeps its own rendering, even when it is empty.
- The next image loads and decodes before its fade starts. A new frame changes only the custom properties with a new value.
- Portrait images show in full over a blurred cover layer by default. The image editor previews a per-image fit, position, and overlay, and saves or resets the override. The folder layout applies to other images. The sidecar file `.runestone-backgrounds.json` in the folder keeps the overrides.
- **Next background image** and **Pause background** are in the command palette. Next reaches every window. Pause keeps the current image and stops the timer.
- A new browser tab on `about:blank` shows the host background, also in a browser window. A loaded page keeps its own rendering, even when it is empty.
Decisions: [UI-015](design-decisions.md#ui-015--slower-slideshow-fades), [UI-020](design-decisions.md#ui-020--per-image-slideshow-layout).
Decisions: [UI-015](design-decisions.md#ui-015--slower-slideshow-fades), [UI-020](design-decisions.md#ui-020--per-image-slideshow-layout), [UI-057](design-decisions.md#ui-057--background-replaces-background-image-and-background-slideshow).
## Tooltips and text selection
+7 -6
View File
@@ -199,21 +199,22 @@ Settings apply at once to all workspaces on this computer and update all open wi
| Category | Settings |
| --- | --- |
| General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save |
| Appearance | Color theme, transparency, background image, and custom themes. See [Appearance and custom themes](guides/themes.md). |
| Features | Turn Git on or off. See [Turn features on or off](#turn-features-on-or-off). |
| 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 and Background 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). |
| Browser | Homepage, search engine, profiles, ad blocking, and web data |
### Turn features on or off
Git is a built-in feature with an off switch. Open **Settings → Features** and use the switch beside the feature.
Git and Background 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.
- A feature that is on uses no extra memory until you first use it, for example when you open Source control. 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 change applies at once in all windows. The code that a window loaded stays in memory until you restart RuneStone.
After an update, each new built-in feature takes the state of its old plugin package: on when the package was enabled, off when it was disabled.
Without an old package, the feature starts on. Settings → Plug-ins shows an old package as **Included with RuneStone**. You can uninstall it.
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.
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.
### Display language
+4 -7
View File
@@ -9,15 +9,12 @@ export interface BackgroundFrame {
transitionMs?: number;
}
/** The folder methods are deprecated. Use `FilesApi` folder grants in new code. */
/**
* The background frames of each target in one window. A plugin can show a frame and read the current frame.
* Use the `FilesApi` folder grants to read image files.
*/
export interface BackgroundApi {
readonly version: 1;
chooseFolder(): Promise<string | null>;
defaultFolder?(): Promise<string>;
list(folder: string): Promise<{ name: string }[]>;
read(folder: string, name: string): Promise<Uint8Array>;
readImageSettings?(folder: string): Promise<string | null>;
writeImageSettings?(folder: string, contents: string, expected: string | null): Promise<void>;
set(target: string, frame: BackgroundFrame | null): void;
get(target: string): BackgroundFrame | null;
subscribe(listener: (target: string) => void): () => void;
+1 -1
View File
@@ -12,7 +12,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
/** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */
export const FEATURE_FOLDERS = ["git"];
export const FEATURE_FOLDERS = ["git", "background"];
/** Libraries that only features need. */
export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"];
+4 -1
View File
@@ -31,7 +31,10 @@ export const TABLE = {
background: {
plugin: { id: "runestone.bg-slideshow", repo: "runestone-bg-slideshow", tag: "v0.0.11", zip: `${PLUGIN_RELEASES}/RuneStone_Background_Slideshow/releases/runestone.bg-slideshow-0.0.11.zip` },
nativeKey: "background",
/** The style property of the body that holds the current background image. The action counts its changes. */
/**
* The style property of the body that holds the current background image. The action counts its changes.
* Native: `backgroundHub.applyApp` (src/lib/plugins/backgrounds.ts) sets it for each new image of Background.
*/
imageProperty: { plugin: "--rs-background-image", native: "--rs-background-image" },
changes: 3,
seconds: 10,
+15 -1
View File
@@ -3,7 +3,7 @@
// The tool starts a test build with an isolated identifier, drives it through CDP, and stops only the process tree that it started.
// Run `node scripts/measureFeatures.mjs --help` for the arguments. The results go to output/phase-7/<stage>/.
import { existsSync } from "node:fs";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
@@ -47,6 +47,19 @@ async function seedBackgroundPlugin(folders, backgrounds) {
await writeFile(path.join(folder, "settings.json"), JSON.stringify({ grant, folder: backgrounds, seconds: TABLE.features.background.seconds, order: "name", enabled: true, targets: ["app"], overlay: 0, position: "center", size: "cover" }));
}
/**
* Write the `background` settings and the host folder file of the native Background before the first start
* (src/lib/features/backgroundSettings.ts and src-tauri/src/backgrounds.rs). The settings file has no other section,
* so the first start keeps it and migrates only the feature switches.
*/
async function seedBackgroundNative(folders, backgrounds) {
await mkdir(folders.roaming, { recursive: true });
const background = { source: "folder", seconds: TABLE.features.background.seconds, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover" };
await writeFile(path.join(folders.roaming, "settings.json"), JSON.stringify({ schema: 1, revision: 1, background }, null, 2) + "\n");
// The host accepts the folder only at its resolved path.
await writeFile(path.join(folders.roaming, "background-folder.json"), JSON.stringify({ schema: 1, path: await realpath.native(backgrounds) }, null, 2));
}
/** The features that are on in the running app. */
async function readState(app, mode, invoke) {
if (mode === "plugin") {
@@ -142,6 +155,7 @@ export async function main(argv = process.argv.slice(2)) {
log(`Resetting ${folders.roaming} and ${folders.local}.`);
await resetData(folders, options.identifier);
if (options.mode === "plugin" && options.features.includes("background")) await seedBackgroundPlugin(folders, fixture.backgrounds);
if (options.mode === "native" && options.features.includes("background")) await seedBackgroundNative(folders, fixture.backgrounds);
// The setup start opens the workspace. It also proves the test identity.
let session = await app.launch({ exe, port: options.port });
+8 -6
View File
@@ -3,12 +3,14 @@ fn main() {
tauri_build::Attributes::new().app_manifest(
tauri_build::AppManifest::new().commands(&[
"theme_export",
"backgrounds_choose_folder",
"backgrounds_default_folder",
"backgrounds_list",
"backgrounds_read",
"backgrounds_read_image_settings",
"backgrounds_write_image_settings",
"background_choose_folder",
"background_folder",
"background_clear_folder",
"background_list",
"background_read",
"background_read_sidecar",
"background_write_sidecar",
"background_migrate",
"folders_choose",
"folders_picture",
"folders_grants",
+4
View File
@@ -13,6 +13,10 @@
"allow-browser-engine-install",
"allow-browser-engine-cancel",
"allow-plugins-snapshot",
"allow-background-folder",
"allow-background-list",
"allow-background-read",
"allow-background-read-sidecar",
"allow-settings-read",
"allow-window-snap-layouts",
"allow-settings-write",
+8 -6
View File
@@ -97,12 +97,14 @@
"allow-pty-new-window",
"allow-pty-dictation",
"opener:allow-reveal-item-in-dir",
"allow-backgrounds-choose-folder",
"allow-backgrounds-default-folder",
"allow-backgrounds-list",
"allow-backgrounds-read",
"allow-backgrounds-read-image-settings",
"allow-backgrounds-write-image-settings",
"allow-background-choose-folder",
"allow-background-folder",
"allow-background-clear-folder",
"allow-background-list",
"allow-background-read",
"allow-background-read-sidecar",
"allow-background-write-sidecar",
"allow-background-migrate",
"allow-folders-choose",
"allow-folders-picture",
"allow-folders-grants",
+8 -6
View File
@@ -43,12 +43,14 @@
"allow-browser-engine-remove",
"allow-completion-request",
"allow-completion-cancel",
"allow-backgrounds-choose-folder",
"allow-backgrounds-default-folder",
"allow-backgrounds-list",
"allow-backgrounds-read",
"allow-backgrounds-read-image-settings",
"allow-backgrounds-write-image-settings",
"allow-background-choose-folder",
"allow-background-folder",
"allow-background-clear-folder",
"allow-background-list",
"allow-background-read",
"allow-background-read-sidecar",
"allow-background-write-sidecar",
"allow-background-migrate",
"allow-folders-choose",
"allow-folders-picture",
"allow-folders-grants",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-choose-folder"
description = "Enables the background_choose_folder command without any pre-configured scope."
commands.allow = ["background_choose_folder"]
[[permission]]
identifier = "deny-background-choose-folder"
description = "Denies the background_choose_folder command without any pre-configured scope."
commands.deny = ["background_choose_folder"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-clear-folder"
description = "Enables the background_clear_folder command without any pre-configured scope."
commands.allow = ["background_clear_folder"]
[[permission]]
identifier = "deny-background-clear-folder"
description = "Denies the background_clear_folder command without any pre-configured scope."
commands.deny = ["background_clear_folder"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-folder"
description = "Enables the background_folder command without any pre-configured scope."
commands.allow = ["background_folder"]
[[permission]]
identifier = "deny-background-folder"
description = "Denies the background_folder command without any pre-configured scope."
commands.deny = ["background_folder"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-list"
description = "Enables the background_list command without any pre-configured scope."
commands.allow = ["background_list"]
[[permission]]
identifier = "deny-background-list"
description = "Denies the background_list command without any pre-configured scope."
commands.deny = ["background_list"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-migrate"
description = "Enables the background_migrate command without any pre-configured scope."
commands.allow = ["background_migrate"]
[[permission]]
identifier = "deny-background-migrate"
description = "Denies the background_migrate command without any pre-configured scope."
commands.deny = ["background_migrate"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-read"
description = "Enables the background_read command without any pre-configured scope."
commands.allow = ["background_read"]
[[permission]]
identifier = "deny-background-read"
description = "Denies the background_read command without any pre-configured scope."
commands.deny = ["background_read"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-read-sidecar"
description = "Enables the background_read_sidecar command without any pre-configured scope."
commands.allow = ["background_read_sidecar"]
[[permission]]
identifier = "deny-background-read-sidecar"
description = "Denies the background_read_sidecar command without any pre-configured scope."
commands.deny = ["background_read_sidecar"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-write-sidecar"
description = "Enables the background_write_sidecar command without any pre-configured scope."
commands.allow = ["background_write_sidecar"]
[[permission]]
identifier = "deny-background-write-sidecar"
description = "Denies the background_write_sidecar command without any pre-configured scope."
commands.deny = ["background_write_sidecar"]
@@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-choose-folder"
description = "Enables the backgrounds_choose_folder command without any pre-configured scope."
commands.allow = ["backgrounds_choose_folder"]
[[permission]]
identifier = "deny-backgrounds-choose-folder"
description = "Denies the backgrounds_choose_folder command without any pre-configured scope."
commands.deny = ["backgrounds_choose_folder"]
@@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-default-folder"
description = "Enables the backgrounds_default_folder command without any pre-configured scope."
commands.allow = ["backgrounds_default_folder"]
[[permission]]
identifier = "deny-backgrounds-default-folder"
description = "Denies the backgrounds_default_folder command without any pre-configured scope."
commands.deny = ["backgrounds_default_folder"]
@@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-list"
description = "Enables the backgrounds_list command without any pre-configured scope."
commands.allow = ["backgrounds_list"]
[[permission]]
identifier = "deny-backgrounds-list"
description = "Denies the backgrounds_list command without any pre-configured scope."
commands.deny = ["backgrounds_list"]
@@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-read"
description = "Enables the backgrounds_read command without any pre-configured scope."
commands.allow = ["backgrounds_read"]
[[permission]]
identifier = "deny-backgrounds-read"
description = "Denies the backgrounds_read command without any pre-configured scope."
commands.deny = ["backgrounds_read"]
@@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-read-image-settings"
description = "Enables the backgrounds_read_image_settings command without any pre-configured scope."
commands.allow = ["backgrounds_read_image_settings"]
[[permission]]
identifier = "deny-backgrounds-read-image-settings"
description = "Denies the backgrounds_read_image_settings command without any pre-configured scope."
commands.deny = ["backgrounds_read_image_settings"]
@@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-write-image-settings"
description = "Enables the backgrounds_write_image_settings command without any pre-configured scope."
commands.allow = ["backgrounds_write_image_settings"]
[[permission]]
identifier = "deny-backgrounds-write-image-settings"
description = "Denies the backgrounds_write_image_settings command without any pre-configured scope."
commands.deny = ["backgrounds_write_image_settings"]
+391 -301
View File
@@ -1,99 +1,46 @@
//! The image folder of the Background feature (`src/lib/features/background/`).
//!
//! The host keeps one folder in `background-folder.json` in the app data folder. Only the folder dialog
//! sets it, so the interface never sends a folder path. The commands read the image files directly in
//! that folder and the sidecar file `.runestone-backgrounds.json` with the per-image settings.
//! They use the rules of the plugin folder grants (`folders.rs`): plain file names only, no links,
//! raster images up to 64 MiB, a sidecar up to 1 MiB, and at most 10,000 files in the folder.
use crate::error::{Error, Result};
use crate::folders;
use crate::fsutil::{self, is_link};
use crate::plugins::PluginState;
use base64::Engine;
use serde::Serialize;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use tauri::{AppHandle, Manager, Window};
use tauri_plugin_dialog::DialogExt;
const IMAGE_LIMIT: u64 = 50 * 1024 * 1024;
const SETTINGS_LIMIT: u64 = 1024 * 1024;
const SETTINGS_FILE: &str = ".runestone-backgrounds.json";
const FOLDER_FILE: &str = "background-folder.json";
const SIDECAR: &str = ".runestone-backgrounds.json";
/// The old plugin whose folder grant the migration takes.
const LEGACY_PLUGIN: &str = "runestone.bg-slideshow";
const FOLDER_FILE_LIMIT: u64 = 64 * 1024;
#[derive(Debug, Serialize)]
pub struct BackgroundFile {
name: String,
/// Serializes changes to the folder file.
static LOCK: Mutex<()> = Mutex::new(());
#[derive(Debug, Serialize, Deserialize)]
struct FolderFile {
schema: u32,
path: PathBuf,
}
fn require_plugin(app: &AppHandle, label: &str, id: &str) -> Result<()> {
app.state::<PluginState>().require_lease(app, label, id)
/// The folder file and the plugin data of one app data folder.
struct Host {
data: PathBuf,
}
/// Check the lease on a blocking worker, because the plugin lock can wait for package work.
async fn check_plugin(app: &AppHandle, window: &Window, id: &str) -> Result<()> {
let (app, label, id) = (app.clone(), window.label().to_owned(), id.to_owned());
tauri::async_runtime::spawn_blocking(move || require_plugin(&app, &label, &id)).await?
}
fn folder_root(folder: &Path) -> Result<PathBuf> {
if !folder.is_absolute()
|| folder
.components()
.any(|part| matches!(part, Component::ParentDir))
{
return Err("Supply an absolute background folder path without parent segments.".into());
}
let root = dunce::canonicalize(folder)?;
if !root.is_dir() {
return Err("The background folder does not exist.".into());
}
Ok(root)
}
fn supported(name: &str) -> bool {
fn raster(name: &str) -> bool {
Path::new(name)
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
matches!(
extension.to_ascii_lowercase().as_str(),
"png" | "jpg" | "jpeg" | "gif" | "webp"
)
})
}
fn image_path(root: &Path, name: &str) -> Result<PathBuf> {
if name.is_empty()
|| name.contains(['/', '\\', ':'])
|| name.ends_with(['.', ' '])
|| !supported(name)
|| Path::new(name).components().count() != 1
|| !matches!(
Path::new(name).components().next(),
Some(Component::Normal(_))
)
{
return Err("Supply one PNG, JPEG, GIF, or WebP filename.".into());
}
let path = root.join(name);
let metadata = fs::symlink_metadata(&path)?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Background images must be ordinary files, not links.".into());
}
let resolved = dunce::canonicalize(&path)?;
if resolved.parent() != Some(root) {
return Err("The background image is outside its folder.".into());
}
Ok(path)
}
fn list_images(folder: &Path) -> Result<Vec<BackgroundFile>> {
let root = folder_root(folder)?;
let mut images = Vec::new();
for entry in fs::read_dir(&root)? {
let entry = entry?;
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
if supported(&name) && image_path(&root, &name).is_ok() {
images.push(BackgroundFile { name });
}
}
images.sort_by(|a, b| a.name.cmp(&b.name));
Ok(images)
.is_some_and(|extension| matches!(extension.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "gif" | "webp"))
}
fn raster_signature(bytes: &[u8]) -> bool {
@@ -104,176 +51,205 @@ fn raster_signature(bytes: &[u8]) -> bool {
|| (bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP")
}
fn read_image(folder: &Path, name: &str) -> Result<Vec<u8>> {
let root = folder_root(folder)?;
let path = image_path(&root, name)?;
// Open the entry itself so a replaced link cannot redirect the read.
let file = fsutil::open_entry(&path)?;
let metadata = file.metadata()?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Background images must be ordinary files, not links.".into());
}
if metadata.len() > IMAGE_LIMIT {
return Err("The background image exceeds 50 MiB.".into());
}
image_path(&root, name)?;
let Some(bytes) = fsutil::read_to_limit(file, IMAGE_LIMIT)? else {
return Err("The background image exceeds 50 MiB.".into());
/// Read a small JSON file. A missing file gives `None`. A link or a folder is an error.
fn read_json<T: for<'de> Deserialize<'de>>(path: &Path, limit: u64) -> Result<Option<T>> {
let metadata = match fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error.into()),
};
if !metadata.is_file() || is_link(&metadata) {
return Err(Error::new(format!("{} must be an ordinary file.", path.display())));
}
let Some(bytes) = fsutil::read_to_limit(fsutil::open_entry(path)?, limit)? else {
return Err(Error::new(format!("{} is too large.", path.display())));
};
Ok(Some(serde_json::from_slice(&bytes)?))
}
impl Host {
fn file(&self) -> PathBuf {
self.data.join(FOLDER_FILE)
}
fn stored(&self) -> Result<Option<PathBuf>> {
let Some(file) = read_json::<FolderFile>(&self.file(), FOLDER_FILE_LIMIT)? else { return Ok(None) };
if file.schema != 1 {
return Err("Unknown background folder file schema.".into());
}
Ok(Some(file.path))
}
fn save(&self, path: &Path) -> Result<()> {
fs::create_dir_all(&self.data)?;
let bytes = serde_json::to_vec_pretty(&FolderFile { schema: 1, path: path.to_path_buf() })?;
let temp = self.data.join(format!("{FOLDER_FILE}.{}.tmp", uuid::Uuid::new_v4()));
Ok(fsutil::replace_file(&self.file(), &temp, &bytes)?)
}
/// Keep `folder` as the background folder. It must be an existing folder, not a whole drive.
fn choose(&self, folder: &Path) -> Result<String> {
let root = folders::granted_root(folder)?;
let _lock = LOCK.lock()?;
self.save(&root)?;
Ok(root.to_string_lossy().into_owned())
}
/// The kept folder for display, or `None`.
fn folder(&self) -> Result<Option<String>> {
Ok(self.stored()?.map(|path| path.to_string_lossy().into_owned()))
}
fn clear(&self) -> Result<()> {
let _lock = LOCK.lock()?;
match fs::remove_file(self.file()) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()),
_ => Ok(()),
}
}
/// The kept folder, still an ordinary folder at the same resolved path.
/// A folder that became a link or a file does not redirect the access.
fn root(&self) -> Result<PathBuf> {
let path = self.stored()?.ok_or_else(|| Error::new("Choose a background folder first."))?;
let metadata = fs::symlink_metadata(&path).map_err(|_| Error::new("The background folder is missing. Choose the folder again."))?;
if !metadata.is_dir() || is_link(&metadata) || dunce::canonicalize(&path)? != path {
return Err("The background folder changed into a link or a file. Choose the folder again.".into());
}
Ok(path)
}
/// The names of the raster images directly in the folder.
fn list(&self) -> Result<Vec<String>> {
Ok(folders::list_files(&self.root()?)?
.into_iter()
.map(|entry| entry.name)
.filter(|name| raster(name))
.collect())
}
fn read(&self, name: &str) -> Result<Vec<u8>> {
if !raster(name) {
return Err("Supply one PNG, JPEG, GIF, or WebP file name.".into());
}
let bytes = folders::read_file(&self.root()?, name)?;
if !raster_signature(&bytes) {
return Err("The file is not a supported raster image.".into());
}
Ok(bytes)
}
#[tauri::command]
pub async fn backgrounds_default_folder(
app: AppHandle,
window: Window,
id: String,
) -> Result<String> {
check_plugin(&app, &window, &id).await?;
let pictures = app.path().picture_dir()?;
let folder = pictures.join("RuneStone Backgrounds");
let created = folder.clone();
tauri::async_runtime::spawn_blocking(move || fs::create_dir_all(created)).await??;
check_plugin(&app, &window, &id).await?;
folder_root(&folder).map(|root| root.to_string_lossy().into_owned())
fn read_sidecar(&self) -> Result<Option<String>> {
folders::read_sidecar(&self.root()?, SIDECAR)
}
#[tauri::command]
pub async fn backgrounds_choose_folder(
app: AppHandle,
window: Window,
id: String,
) -> Result<Option<String>> {
check_plugin(&app, &window, &id).await?;
let picker_app = app.clone();
let picker_window = window.clone();
let selected = tauri::async_runtime::spawn_blocking(move || {
picker_app
.dialog()
.file()
.set_parent(&picker_window)
.set_title("Choose background image folder")
.blocking_pick_folder()
})
.await?;
check_plugin(&app, &window, &id).await?;
selected
.map(|source| {
let path = source.into_path().map_err(Error::from_display)?;
folder_root(&path).map(|root| root.to_string_lossy().into_owned())
})
.transpose()
}
#[tauri::command]
pub async fn backgrounds_list(
app: AppHandle,
window: Window,
id: String,
folder: String,
) -> Result<Vec<BackgroundFile>> {
check_plugin(&app, &window, &id).await?;
let result = tauri::async_runtime::spawn_blocking(move || list_images(Path::new(&folder)))
.await??;
check_plugin(&app, &window, &id).await?;
Ok(result)
}
#[tauri::command]
pub async fn backgrounds_read(
app: AppHandle,
window: Window,
id: String,
folder: String,
name: String,
) -> Result<String> {
check_plugin(&app, &window, &id).await?;
let result =
tauri::async_runtime::spawn_blocking(move || read_image(Path::new(&folder), &name))
.await??;
check_plugin(&app, &window, &id).await?;
Ok(base64::engine::general_purpose::STANDARD.encode(result))
}
fn read_image_settings(folder: &Path) -> Result<Option<String>> {
let root = folder_root(folder)?;
let path = root.join(SETTINGS_FILE);
let metadata = match fs::symlink_metadata(&path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(Error::from(error)),
};
if !metadata.is_file() || is_link(&metadata) || metadata.len() > SETTINGS_LIMIT {
return Err("Image settings must be an ordinary file within 1 MiB.".into());
}
let file = fsutil::open_entry(&path)?;
let metadata = file.metadata()?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Image settings must be an ordinary file, not a link.".into());
}
let Some(bytes) = fsutil::read_to_limit(file, SETTINGS_LIMIT)? else {
return Err("Image settings exceed 1 MiB.".into());
};
String::from_utf8(bytes).map(Some).map_err(Error::from)
}
fn write_image_settings(folder: &Path, contents: &str, expected: Option<&str>) -> Result<()> {
static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _lock = WRITE_LOCK.lock()?;
if contents.len() as u64 > SETTINGS_LIMIT {
return Err("Image settings exceed 1 MiB.".into());
}
/// Save the per-image settings only if the file still holds `expected` (`None` when it does not exist).
fn write_sidecar(&self, contents: &str, expected: Option<&str>) -> Result<()> {
let value: serde_json::Value = serde_json::from_str(contents)?;
if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1)
|| !value.get("images").is_some_and(serde_json::Value::is_object)
{
if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1) || !value.get("images").is_some_and(serde_json::Value::is_object) {
return Err("Use image settings with schema 1 and an images object.".into());
}
let root = folder_root(folder)?;
if read_image_settings(&root)?.as_deref() != expected {
return Err("Image settings changed. Reload them before saving.".into());
folders::write_sidecar(&self.root()?, SIDECAR, contents, expected)
}
let path = root.join(SETTINGS_FILE);
if expected.is_some() {
fsutil::write_text(&path, contents, expected)
} else {
// Publish a complete new file without replacing a file created by another process.
let temp = root.join(format!(".runestone-backgrounds-{}.tmp", uuid::Uuid::new_v4()));
Ok(fsutil::create_file(&path, &temp, contents.as_bytes())?)
/// Take the folder of the old Background Slideshow grant when the host has no folder yet.
/// Returns the folder after the migration, or `None`. It changes no plugin file.
fn migrate(&self) -> Result<Option<String>> {
let _lock = LOCK.lock()?;
if let Some(path) = self.stored()? {
return Ok(Some(path.to_string_lossy().into_owned()));
}
let plugin_data = self.data.join("plugin-data");
let settings = plugin_data.join(LEGACY_PLUGIN).join("settings.json");
let Some(value) = read_json::<serde_json::Value>(&settings, 1024 * 1024).ok().flatten() else { return Ok(None) };
let Some(grant) = value.get("grant").and_then(serde_json::Value::as_str).filter(|grant| !grant.is_empty()) else { return Ok(None) };
let Ok(path) = folders::plugin_grant(&plugin_data, LEGACY_PLUGIN, grant) else { return Ok(None) };
self.save(&path)?;
Ok(Some(path.to_string_lossy().into_owned()))
}
}
fn host(app: &AppHandle) -> Result<Host> {
Ok(Host { data: app.path().app_data_dir()? })
}
/// Run `work` on a blocking worker, because the file system calls can wait.
async fn run<T: Send + 'static>(app: &AppHandle, work: impl FnOnce(Host) -> Result<T> + Send + 'static) -> Result<T> {
let host = host(app)?;
tauri::async_runtime::spawn_blocking(move || work(host)).await?
}
/// Show the folder dialog and keep the chosen folder. Returns the folder for display, or `None` after Cancel.
#[tauri::command]
pub async fn backgrounds_read_image_settings(app: AppHandle, window: Window, id: String, folder: String) -> Result<Option<String>> {
check_plugin(&app, &window, &id).await?;
let result = tauri::async_runtime::spawn_blocking(move || read_image_settings(Path::new(&folder))).await??;
check_plugin(&app, &window, &id).await?;
Ok(result)
pub async fn background_choose_folder(app: AppHandle, window: Window, title: Option<String>) -> Result<Option<String>> {
let (picker_app, picker_window) = (app.clone(), window.clone());
let title = title.filter(|title| !title.trim().is_empty() && title.len() <= 200).unwrap_or_else(|| "Choose the background folder".into());
let selected = tauri::async_runtime::spawn_blocking(move || {
picker_app.dialog().file().set_parent(&picker_window).set_title(title).blocking_pick_folder()
})
.await?;
let Some(selected) = selected else { return Ok(None) };
let folder = selected.into_path().map_err(Error::from_display)?;
run(&app, move |host| host.choose(&folder)).await.map(Some)
}
#[tauri::command]
pub async fn backgrounds_write_image_settings(app: AppHandle, window: Window, id: String, folder: String, contents: String, expected: Option<String>) -> Result<()> {
check_plugin(&app, &window, &id).await?;
// Check the lease again immediately before the write on the blocking worker.
tauri::async_runtime::spawn_blocking(move || {
require_plugin(&app, window.label(), &id)?;
write_image_settings(Path::new(&folder), &contents, expected.as_deref())
}).await?
pub async fn background_folder(app: AppHandle) -> Result<Option<String>> {
run(&app, |host| host.folder()).await
}
#[tauri::command]
pub async fn background_clear_folder(app: AppHandle) -> Result<()> {
run(&app, |host| host.clear()).await
}
#[tauri::command]
pub async fn background_list(app: AppHandle) -> Result<Vec<String>> {
run(&app, |host| host.list()).await
}
/// Return the bytes as an `ArrayBuffer`, not as JSON or base64 text.
#[tauri::command]
pub async fn background_read(app: AppHandle, name: String) -> Result<tauri::ipc::Response> {
Ok(tauri::ipc::Response::new(run(&app, move |host| host.read(&name)).await?))
}
#[tauri::command]
pub async fn background_read_sidecar(app: AppHandle) -> Result<Option<String>> {
run(&app, |host| host.read_sidecar()).await
}
#[tauri::command]
pub async fn background_write_sidecar(app: AppHandle, contents: String, expected: Option<String>) -> Result<()> {
run(&app, move |host| host.write_sidecar(&contents, expected.as_deref())).await
}
#[tauri::command]
pub async fn background_migrate(app: AppHandle) -> Result<Option<String>> {
run(&app, |host| host.migrate()).await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::folders::LIST_LIMIT;
const PNG: &[u8] = b"\x89PNG\r\n\x1a\n";
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let root = std::env::temp_dir()
.join(format!("runestone-backgrounds-{}", uuid::Uuid::new_v4()));
let root = std::env::temp_dir().join(format!("runestone-background-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
Self(root)
Self(dunce::canonicalize(root).unwrap())
}
fn folder(&self, name: &str) -> PathBuf {
let path = self.0.join(name);
fs::create_dir_all(&path).unwrap();
path
}
fn host(&self) -> Host {
Host { data: self.folder("app") }
}
}
impl Drop for Fixture {
@@ -282,103 +258,217 @@ mod tests {
}
}
#[test]
fn image_settings_preserve_external_changes_and_validate_file_limits() {
let fixture = Fixture::new();
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
let next = r#"{"schema":1,"images":{}}"#;
assert_eq!(read_image_settings(&fixture.0).unwrap(), None);
write_image_settings(&fixture.0, first, None).unwrap();
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
assert!(write_image_settings(&fixture.0, next, None).is_err());
assert!(write_image_settings(&fixture.0, next, Some("stale")).is_err());
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
write_image_settings(&fixture.0, next, Some(first)).unwrap();
assert!(write_image_settings(&fixture.0, r#"{"schema":2,"images":{}}"#, Some(next)).is_err());
assert!(write_image_settings(&fixture.0, &"x".repeat(SETTINGS_LIMIT as usize + 1), Some(next)).is_err());
fs::File::create(fixture.0.join(SETTINGS_FILE)).unwrap().set_len(SETTINGS_LIMIT + 1).unwrap();
assert!(read_image_settings(&fixture.0).is_err());
/// Make a link, or return `false` when Windows does not allow links for this user.
fn link(original: &Path, link: &Path, folder: bool) -> bool {
#[cfg(unix)]
{
let _ = folder;
std::os::unix::fs::symlink(original, link).unwrap();
true
}
#[cfg(windows)]
{
let result = if folder { std::os::windows::fs::symlink_dir(original, link) } else { std::os::windows::fs::symlink_file(original, link) };
match result {
Ok(()) => true,
Err(error) if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => {
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
false
}
Err(error) => panic!("{error}"),
}
}
}
#[test]
fn listing_is_nonrecursive_and_filters_extensions() {
fn the_host_keeps_one_folder_until_it_is_cleared() {
let fixture = Fixture::new();
fs::write(fixture.0.join("a.PNG"), b"\x89PNG\r\n\x1a\n").unwrap();
fs::write(fixture.0.join("b.jpg"), b"\xff\xd8\xff").unwrap();
fs::write(fixture.0.join("text.svg"), b"<svg />").unwrap();
fs::create_dir(fixture.0.join("nested.gif")).unwrap();
fs::write(fixture.0.join("nested.gif/hidden.png"), b"png").unwrap();
let names: Vec<_> = list_images(&fixture.0)
.unwrap()
.into_iter()
.map(|image| image.name)
.collect();
assert_eq!(names, vec!["a.PNG", "b.jpg"]);
assert_eq!(
read_image(&fixture.0, "a.PNG").unwrap(),
b"\x89PNG\r\n\x1a\n"
);
let images = fixture.folder("images");
let other = fixture.folder("other");
let host = fixture.host();
assert_eq!(host.folder().unwrap(), None);
assert!(host.list().unwrap_err().to_string().contains("Choose a background folder"));
assert_eq!(host.choose(&images).unwrap(), images.to_string_lossy());
// A new host reads the kept folder, as after a restart.
assert_eq!(fixture.host().folder().unwrap(), Some(images.to_string_lossy().into_owned()));
host.choose(&other).unwrap();
assert_eq!(host.folder().unwrap(), Some(other.to_string_lossy().into_owned()));
host.clear().unwrap();
host.clear().unwrap();
assert_eq!(host.folder().unwrap(), None);
}
#[test]
fn reads_reject_traversal_invalid_images_and_oversized_files() {
fn the_chosen_folder_must_be_an_existing_folder() {
let fixture = Fixture::new();
for name in [
"../escape.png",
"nested/image.png",
"nested\\image.png",
"C:\\image.png",
"image.png:stream",
"image.svg",
] {
assert!(read_image(&fixture.0, name).is_err(), "{name}");
}
assert!(list_images(Path::new("relative")).is_err());
fs::write(fixture.0.join("invalid.png"), b"<svg />").unwrap();
assert!(read_image(&fixture.0, "invalid.png")
.unwrap_err()
.to_string()
.contains("raster"));
let file = fs::File::create(fixture.0.join("large.png")).unwrap();
file.set_len(IMAGE_LIMIT + 1).unwrap();
assert!(read_image(&fixture.0, "large.png")
.unwrap_err()
.to_string()
.contains("50 MiB"));
let host = fixture.host();
let images = fixture.folder("images");
assert!(host.choose(Path::new("relative")).is_err());
assert!(host.choose(&images.join("..").join("images")).is_err());
assert!(host.choose(&fixture.0.join("missing")).is_err());
fs::write(fixture.0.join("file.txt"), "x").unwrap();
assert!(host.choose(&fixture.0.join("file.txt")).is_err());
let drive = images.ancestors().last().unwrap().to_path_buf();
assert!(host.choose(&drive).is_err());
assert_eq!(host.folder().unwrap(), None);
// A damaged folder file is an error, not a silent reset.
fs::write(host.file(), "{damaged").unwrap();
assert!(host.folder().is_err());
fs::write(host.file(), r#"{"schema":2,"path":"C:\\"}"#).unwrap();
assert!(host.folder().is_err());
}
#[test]
fn raster_types_are_recognized() {
for bytes in [
b"\x89PNG\r\n\x1a\n".as_slice(),
b"\xff\xd8\xff",
b"GIF87a",
b"GIF89a",
b"RIFF0000WEBP",
] {
assert!(raster_signature(bytes));
fn the_listing_has_only_the_raster_files_directly_in_the_folder() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let host = fixture.host();
host.choose(&images).unwrap();
fs::write(images.join("b.PNG"), PNG).unwrap();
fs::write(images.join("a.jpg"), b"\xff\xd8\xff").unwrap();
fs::write(images.join("c.webp"), b"RIFF0000WEBP").unwrap();
fs::write(images.join("text.svg"), b"<svg />").unwrap();
fs::write(images.join("notes.md"), b"# notes").unwrap();
fs::write(images.join(SIDECAR), b"{}").unwrap();
fixture.folder("images/nested.gif");
fs::write(images.join("nested.gif/hidden.png"), PNG).unwrap();
assert_eq!(host.list().unwrap(), vec!["a.jpg", "b.PNG", "c.webp"]);
assert_eq!(host.read("b.PNG").unwrap(), PNG);
}
assert!(!raster_signature(b"RIFF0000WAVE"));
#[test]
fn reads_reject_other_names_other_types_and_large_files() {
let fixture = Fixture::new();
let images = fixture.folder("images");
fs::write(fixture.0.join("outside.png"), PNG).unwrap();
let host = fixture.host();
host.choose(&images).unwrap();
for name in ["../outside.png", "nested/image.png", "nested\\image.png", "C:\\image.png", "image.png:stream", "image.svg", "notes.md", "", "nul.png"] {
assert!(host.read(name).is_err(), "{name}");
}
fs::write(images.join("fake.png"), b"<svg />").unwrap();
assert!(host.read("fake.png").unwrap_err().to_string().contains("raster"));
fs::File::create(images.join("large.png")).unwrap().set_len(folders::READ_LIMIT + 1).unwrap();
assert!(host.read("large.png").unwrap_err().to_string().contains("64 MiB"));
}
#[test]
fn the_listing_has_a_size_limit() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let host = fixture.host();
host.choose(&images).unwrap();
for index in 0..=LIST_LIMIT {
fs::write(images.join(format!("{index}.png")), b"").unwrap();
}
assert!(host.list().unwrap_err().to_string().contains("10000"));
}
#[test]
fn links_cannot_escape_the_folder() {
let fixture = Fixture::new();
let outside = Fixture::new();
let original = outside.0.join("outside.png");
fs::write(&original, b"\x89PNG\r\n\x1a\n").unwrap();
let link = fixture.0.join("link.png");
#[cfg(unix)]
std::os::unix::fs::symlink(&original, &link).unwrap();
#[cfg(windows)]
if let Err(error) = std::os::windows::fs::symlink_file(&original, &link) {
if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) {
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
let images = fixture.folder("images");
let outside = fixture.folder("outside");
fs::write(outside.join("secret.png"), PNG).unwrap();
let host = fixture.host();
host.choose(&images).unwrap();
if !link(&outside.join("secret.png"), &images.join("link.png"), false) {
return;
}
panic!("{error}");
assert!(host.list().unwrap().is_empty());
assert!(host.read("link.png").is_err());
// A kept folder that is replaced by a link loses its access.
let moved = fixture.folder("moved");
host.choose(&moved).unwrap();
fs::remove_dir(&moved).unwrap();
assert!(link(&outside, &moved, true));
assert!(host.list().unwrap_err().to_string().contains("Choose the folder again"));
}
assert!(list_images(&fixture.0).unwrap().is_empty());
assert!(read_image(&fixture.0, "link.png").is_err());
#[test]
fn the_sidecar_keeps_external_changes_and_needs_schema_one() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let host = fixture.host();
host.choose(&images).unwrap();
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
let next = r#"{"schema":1,"images":{}}"#;
assert_eq!(host.read_sidecar().unwrap(), None);
host.write_sidecar(first, None).unwrap();
assert_eq!(host.read_sidecar().unwrap().as_deref(), Some(first));
assert!(host.write_sidecar(next, None).is_err());
assert!(host.write_sidecar(next, Some("stale")).is_err());
host.write_sidecar(next, Some(first)).unwrap();
assert_eq!(fs::read_to_string(images.join(SIDECAR)).unwrap(), next);
for bad in [r#"{"schema":2,"images":{}}"#, r#"{"schema":1,"images":[]}"#, "not json"] {
assert!(host.write_sidecar(bad, Some(next)).is_err(), "{bad}");
}
assert!(host.write_sidecar(&format!(r#"{{"schema":1,"images":{{}},"x":"{}"}}"#, "x".repeat(folders::SIDECAR_LIMIT as usize)), Some(next)).is_err());
fs::File::create(images.join(SIDECAR)).unwrap().set_len(folders::SIDECAR_LIMIT + 1).unwrap();
assert!(host.read_sidecar().is_err());
}
fn seed_plugin(fixture: &Fixture, folder: &Path, settings: &str) -> String {
let grant = uuid::Uuid::new_v4().to_string();
let data = fixture.folder(&format!("app/plugin-data/{LEGACY_PLUGIN}"));
fs::write(data.join("folder-grants.json"), serde_json::to_vec(&serde_json::json!({ "schema": 1, "grants": [{ "id": grant, "path": folder }] })).unwrap()).unwrap();
fs::write(data.join("settings.json"), settings.replace("GRANT", &grant)).unwrap();
grant
}
#[test]
fn the_migration_takes_the_folder_of_the_old_grant() {
let fixture = Fixture::new();
let images = fixture.folder("images");
seed_plugin(&fixture, &images, r#"{"grant":"GRANT","enabled":true}"#);
let data = fixture.0.join("app/plugin-data").join(LEGACY_PLUGIN);
let before = (fs::read(data.join("folder-grants.json")).unwrap(), fs::read(data.join("settings.json")).unwrap());
let host = fixture.host();
assert_eq!(host.migrate().unwrap(), Some(images.to_string_lossy().into_owned()));
assert_eq!(host.folder().unwrap(), Some(images.to_string_lossy().into_owned()));
assert_eq!((fs::read(data.join("folder-grants.json")).unwrap(), fs::read(data.join("settings.json")).unwrap()), before, "The migration changes no plugin file.");
}
#[test]
fn the_migration_keeps_an_existing_host_folder() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let chosen = fixture.folder("chosen");
seed_plugin(&fixture, &images, r#"{"grant":"GRANT"}"#);
let host = fixture.host();
host.choose(&chosen).unwrap();
assert_eq!(host.migrate().unwrap(), Some(chosen.to_string_lossy().into_owned()));
assert_eq!(host.folder().unwrap(), Some(chosen.to_string_lossy().into_owned()));
}
#[test]
fn the_migration_without_a_usable_grant_keeps_no_folder() {
// No plugin data.
let fixture = Fixture::new();
assert_eq!(fixture.host().migrate().unwrap(), None);
// Settings without a grant, with an unknown grant, and with damaged JSON.
for settings in [r#"{"folder":"D:\\Pictures"}"#, r#"{"grant":"6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90"}"#, r#"{"grant":"not-a-uuid"}"#, "{damaged"] {
let fixture = Fixture::new();
let images = fixture.folder("images");
seed_plugin(&fixture, &images, settings);
let host = fixture.host();
assert_eq!(host.migrate().unwrap(), None, "{settings}");
assert_eq!(host.folder().unwrap(), None);
}
// A granted folder that no longer exists.
let fixture = Fixture::new();
let images = fixture.folder("images");
seed_plugin(&fixture, &images, r#"{"grant":"GRANT"}"#);
fs::remove_dir(&images).unwrap();
assert_eq!(fixture.host().migrate().unwrap(), None);
}
#[test]
fn raster_types_are_recognized() {
for bytes in [PNG, b"\xff\xd8\xff", b"GIF87a", b"GIF89a", b"RIFF0000WEBP"] {
assert!(raster_signature(bytes));
}
assert!(!raster_signature(b"RIFF0000WAVE"));
assert!(raster("A.JPEG") && raster("b.gif") && !raster("c.svg") && !raster("png"));
}
}
+3 -2
View File
@@ -8,7 +8,7 @@ use crate::error::{Error, Result};
use crate::plugins::{legacy_packages, LegacyPackage};
/// The packages that native features replace. A request for another ID fails.
pub const LEGACY_PACKAGES: [&str; 1] = ["runestone.git"];
pub const LEGACY_PACKAGES: [&str; 2] = ["runestone.git", "runestone.bg-slideshow"];
fn check(ids: &[String]) -> Result<()> {
if ids.len() > LEGACY_PACKAGES.len() {
@@ -33,10 +33,11 @@ mod tests {
#[test]
fn only_the_packages_of_native_features_are_read() {
assert!(check(&["runestone.git".into()]).is_ok());
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into()]).is_ok());
assert!(check(&[]).is_ok());
for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] {
assert!(check(&[id.into()]).is_err(), "{id}");
}
assert!(check(&["runestone.git".into(), "runestone.git".into()]).is_err());
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into(), "runestone.git".into()]).is_err());
}
}
+16 -10
View File
@@ -18,9 +18,9 @@ use tauri_plugin_dialog::DialogExt;
const GRANTS_FILE: &str = "folder-grants.json";
const GRANT_LIMIT: usize = 64;
const READ_LIMIT: u64 = 64 * 1024 * 1024;
const SIDECAR_LIMIT: u64 = 1024 * 1024;
const LIST_LIMIT: usize = 10_000;
pub(crate) const READ_LIMIT: u64 = 64 * 1024 * 1024;
pub(crate) const SIDECAR_LIMIT: u64 = 1024 * 1024;
pub(crate) const LIST_LIMIT: usize = 10_000;
/// Serializes changes to grant files and sidecar files.
static LOCK: Mutex<()> = Mutex::new(());
@@ -47,7 +47,7 @@ pub struct FolderGrant {
#[derive(Debug, Serialize, PartialEq)]
pub struct FolderEntry {
name: String,
pub(crate) name: String,
size: u64,
}
@@ -172,7 +172,7 @@ impl Grants {
}
/// Resolve a chosen folder. Reject relative paths, parent segments, files, and whole drives.
fn granted_root(folder: &Path) -> Result<PathBuf> {
pub(crate) fn granted_root(folder: &Path) -> Result<PathBuf> {
if !folder.is_absolute() || folder.components().any(|part| matches!(part, Component::ParentDir)) {
return Err("Supply an absolute folder path without parent segments.".into());
}
@@ -200,7 +200,7 @@ fn file_path(root: &Path, name: &str) -> Result<PathBuf> {
}
/// Open one ordinary file. Reject links, also a link that replaces the file after the check.
fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
pub(crate) fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Granted folder access is limited to ordinary files, not links or folders.".into());
@@ -213,7 +213,7 @@ fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
Ok((file, opened.len()))
}
fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
pub(crate) fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
let mut entries = Vec::new();
for entry in fs::read_dir(root)? {
let entry = entry?;
@@ -232,7 +232,7 @@ fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
Ok(entries)
}
fn read_file(root: &Path, name: &str) -> Result<Vec<u8>> {
pub(crate) fn read_file(root: &Path, name: &str) -> Result<Vec<u8>> {
let path = file_path(root, name)?;
let (file, size) = open_plain(root, &path)?;
if size > READ_LIMIT {
@@ -251,7 +251,7 @@ fn sidecar_path(root: &Path, name: &str) -> Result<PathBuf> {
file_path(root, name)
}
fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
pub(crate) fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
let path = sidecar_path(root, name)?;
match fs::symlink_metadata(&path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
@@ -267,7 +267,7 @@ fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
}
/// Save a sidecar only if it still holds `expected` (`None` when the file does not exist).
fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>) -> Result<()> {
pub(crate) fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>) -> Result<()> {
let path = sidecar_path(root, name)?;
if contents.len() as u64 > SIDECAR_LIMIT {
return Err("The sidecar file exceeds 1 MiB.".into());
@@ -285,6 +285,12 @@ fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>
}
}
/// The folder of one grant of `plugin` in the plugin data folder `data`, with the checks of a normal access.
/// The Background feature uses it to take the folder of the old Background Slideshow plugin. It changes no file.
pub(crate) fn plugin_grant(data: &Path, plugin: &str, id: &str) -> Result<PathBuf> {
Grants { data: data.to_path_buf() }.resolve(plugin, id)
}
fn grants(app: &AppHandle) -> Result<Grants> {
Ok(Grants { data: app.path().app_data_dir()?.join("plugin-data") })
}
+8 -6
View File
@@ -38,12 +38,14 @@ pub fn run() {
.manage(preferences::PreferencesState::default())
.manage(tab_transfer::TabTransferState::default())
.invoke_handler(tauri::generate_handler![
backgrounds::backgrounds_choose_folder,
backgrounds::backgrounds_default_folder,
backgrounds::backgrounds_list,
backgrounds::backgrounds_read,
backgrounds::backgrounds_read_image_settings,
backgrounds::backgrounds_write_image_settings,
backgrounds::background_choose_folder,
backgrounds::background_folder,
backgrounds::background_clear_folder,
backgrounds::background_list,
backgrounds::background_read,
backgrounds::background_read_sidecar,
backgrounds::background_write_sidecar,
backgrounds::background_migrate,
folders::folders_choose,
folders::folders_picture,
folders::folders_grants,
+2 -2
View File
@@ -20,8 +20,8 @@ use crate::fsutil;
pub const FILE_NAME: &str = "settings.json";
pub const SCHEMA: u64 = 1;
/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion.
/// `features` holds the switches of the native features.
pub const SECTIONS: [&str; 6] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features"];
/// `features` holds the switches of the native features. `background` holds the settings of the Background feature.
pub const SECTIONS: [&str; 7] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background"];
/// The appearance section can hold an image data URL of up to 3,000,000 characters.
pub const MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
pub const CHANGED_EVENT: &str = "settings-changed";
+1
View File
@@ -3,6 +3,7 @@
@import "./lib/ui/menu.css";
@import "./lib/ui/switch.css";
@import "./lib/theme/base.css";
@import "./lib/theme/background.css";
@import "./lib/ui/tooltip.css";
@import "./lib/layout/reading.css";
@import "./lib/editor/noteTitle.css";
@@ -0,0 +1,299 @@
<!--
Appearance → Background. The source is a folder (a slideshow), one image, or none. The folder layout and the order
are in the `background` settings section. The image and its layout stay in `appearance.newTabBackground`.
This component also works in the settings window, where the slideshow does not run. It sends Next to every window.
-->
<script lang="ts">
import { onDestroy, onMount } from "svelte";
import { t, tr } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte";
import { showActionMenu } from "$lib/ui/managedActionMenu";
import { onSettingsChange } from "$lib/settings/store";
import { serviceHub } from "$lib/plugins/services";
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, saveAppearance, type Appearance } from "$lib/theme/appearance";
import { removeBackgroundImage, saveBackgroundImage } from "$lib/theme/backgroundImages";
import { hasImage, normalizeLayout, readBackground, writeBackground, type BackgroundLayout, type BackgroundSettings, type BackgroundSource } from "../backgroundSettings";
import { folderHost, readSavedImage, sendBackgroundCommand } from "./sources";
import { imageNames } from "./imageSettings";
import ImageEditor from "./ImageEditor.svelte";
/** The Project Management service that lists the boards of the workspace as `{ id, name }[]`. Stage 7-5 makes it native. */
const BOARD_SERVICE = ["runestone.pm", "boards"] as const;
const boardId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
let settings = $state<BackgroundSettings>(readBackground());
let appearance = $state<Appearance>(readAppearance());
let folder = $state<string | null>(null);
let folderNote = $state("");
let boards = $state<{ id: string; name: string }[]>([]);
let boardsNote = $state("");
let previewUrl = $state("");
let error = $state("");
let imageInput: HTMLInputElement;
let imageRevision = 0;
let boardRevision = 0;
let previewKey = "";
let closeMenu = () => {};
let disposed = false;
const image = $derived(appearance.newTabBackground);
const layout = $derived<BackgroundLayout | null>(settings.source === "folder" ? normalizeLayout(settings) : settings.source === "image" && hasImage(appearance) ? normalizeLayout(image) : null);
const sourceLabels = $derived<Record<BackgroundSource, string>>({ folder: $t("Folder"), image: $t("Image"), none: $t("None") });
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
const sizeLabels = $derived([$t("Fill"), $t("Fit"), $t("Actual size")]);
const orderLabels = $derived({ name: $t("File name"), random: $t("Random") });
const targets = $derived([
{ id: "app", name: $t("The workspace and new tabs") },
{ id: "pm-all", name: $t("All Project Management boards") },
...boards.map(board => ({ id: `pm-board:${board.id}`, name: $t("Board: {name}", { name: board.name }) })),
// Keep saved targets without a current board, so that the user can remove them.
...settings.targets.filter(id => id.startsWith("pm-board:") && !boards.some(board => `pm-board:${board.id}` === id))
.map(id => ({ id, name: $t("Unavailable board: {id}", { id: id.slice(9) }) })),
]);
const report = (reason: unknown) => { if (!disposed) error = reason instanceof Error ? reason.message : String(reason); };
function save(next: BackgroundSettings) {
settings = next; error = "";
writeBackground(next).catch(() => report(tr("Could not save the background settings.")));
}
function saveImageAppearance(next: Appearance) {
try {
saveAppearance(next).catch(() => report(tr("Could not save appearance settings.")));
appearance = readAppearance(); error = ""; return true;
} catch { report(tr("Could not save appearance settings.")); return false; }
}
function changeLayout(patch: Partial<BackgroundLayout>) {
if (settings.source === "folder") save({ ...settings, ...patch });
else if (image) saveImageAppearance({ ...appearance, newTabBackground: { ...image, ...patch } });
}
function changeOverlay(input: HTMLInputElement) {
const percent = input.valueAsNumber;
if (!Number.isFinite(percent)) return;
changeLayout({ overlay: Math.round(Math.max(-100, Math.min(100, percent))) / 100 });
}
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
closeMenu();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
}
async function chooseSource(source: BackgroundSource) {
error = "";
if (source === "folder" && !folder) { await chooseFolder(); return; }
if (source === "image" && !hasImage(appearance)) { imageInput.click(); return; }
save({ ...settings, source });
}
async function chooseFolder() {
try {
const chosen = await folderHost.choose(tr("Choose the background folder"));
if (!chosen || disposed) return;
folder = chosen;
save({ ...settings, source: "folder" });
await sendBackgroundCommand("reload");
void inspectFolder();
} catch (reason) { report(reason); }
}
async function removeFolder() {
try {
await folderHost.clear();
folder = null; folderNote = "";
if (settings.source === "folder") save({ ...settings, source: "none" });
await sendBackgroundCommand("reload");
} catch (reason) { report(reason); }
}
/** Count the images of the folder, so that the user sees a problem at once. */
async function inspectFolder() {
if (!folder) { folderNote = ""; return; }
try {
const count = imageNames(await folderHost.list()).length;
if (!disposed) folderNote = count ? tr(count === 1 ? "{count} image." : "{count} images.", { count }) : tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files.");
} catch (reason) { if (!disposed) folderNote = reason instanceof Error ? reason.message : String(reason); }
}
async function importImage(file?: File) {
if (!file) return;
const revision = ++imageRevision;
try {
if (!["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)) throw new Error(tr("Choose a PNG, JPEG, WebP, or GIF image."));
const imageId = await saveBackgroundImage(file);
if (revision !== imageRevision) { await removeBackgroundImage(imageId); return; }
const old = appearance.newTabBackground?.imageId;
if (saveImageAppearance({ ...appearance, newTabBackground: { ...appearance.newTabBackground, image: undefined, imageId, overlay: appearance.newTabBackground?.overlay ?? 0 } })) {
if (settings.source !== "image") save({ ...settings, source: "image" });
if (old) await removeBackgroundImage(old);
} else await removeBackgroundImage(imageId);
} catch (reason) { if (revision === imageRevision) report(reason); }
finally { if (revision === imageRevision) imageInput.value = ""; }
}
async function removeImage() {
imageRevision++;
const old = appearance.newTabBackground?.imageId;
if (saveImageAppearance({ ...appearance, newTabBackground: undefined }) && old) {
try { await removeBackgroundImage(old); } catch { report(tr("Could not remove the saved image from storage.")); }
}
}
function toggleTarget(id: string, on: boolean) {
save({ ...settings, targets: on ? [...new Set([...settings.targets, id])] : settings.targets.filter(target => target !== id) });
}
async function discoverBoards() {
const revision = ++boardRevision;
const service = serviceHub.get(...BOARD_SERVICE, () => !disposed);
if (!service || typeof service.list !== "function") {
boards = []; boardsNote = tr("Turn on Project Management to show the background on one board.");
return;
}
try {
const rows = await service.list();
if (disposed || revision !== boardRevision) return;
boards = (Array.isArray(rows) ? rows : []).flatMap((row: unknown) => {
if (!row || typeof row !== "object" || !("id" in row) || typeof row.id !== "string" || !boardId.test(row.id)) return [];
return [{ id: row.id, name: "name" in row && typeof row.name === "string" && row.name ? row.name : row.id }];
}).filter((board, index, rows) => rows.findIndex(other => other.id === board.id) === index);
boardsNote = boards.length ? "" : tr("The workspace has no boards.");
} catch (reason) {
if (!disposed && revision === boardRevision) boardsNote = tr("Could not read the workspace boards: {error}", { error: reason instanceof Error ? reason.message : String(reason) });
}
}
/** The preview of the saved image. It uses its own blob URL, so it works in every window. */
async function updatePreview() {
const saved = settings.source === "image" ? appearance.newTabBackground : undefined;
const key = saved && hasImage(appearance) ? saved.imageId ?? `${saved.image?.length}:${saved.image?.slice(-48)}` : "";
if (key === previewKey) return;
previewKey = key;
if (previewUrl) URL.revokeObjectURL(previewUrl);
previewUrl = "";
if (!key || !saved) return;
try {
const url = URL.createObjectURL(await readSavedImage(saved));
if (disposed || previewKey !== key) { URL.revokeObjectURL(url); return; }
previewUrl = url;
} catch (reason) { report(reason); }
}
const overlayShade = $derived(layout ? `linear-gradient(rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}),rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}))` : "none");
$effect(() => { void settings.source; void appearance.newTabBackground; void updatePreview(); });
onMount(() => {
const read = () => { settings = readBackground(); appearance = readAppearance(); };
const stops = [onSettingsChange("background", read), onSettingsChange("appearance", read), serviceHub.subscribe((plugin, name) => { if (plugin === BOARD_SERVICE[0] && name === BOARD_SERVICE[1]) void discoverBoards(); })];
void folderHost.current().then(value => { if (!disposed) { folder = value; void inspectFolder(); } }, () => { folder = null; });
void discoverBoards();
return () => stops.forEach(stop => stop());
});
onDestroy(() => { disposed = true; closeMenu(); if (previewUrl) URL.revokeObjectURL(previewUrl); });
</script>
<div class="background-settings">
<div class="card">
<div class="setting-row"><span>{$t("Background source")}</span><button class="picker" aria-label={$t("Background source")} aria-haspopup="menu"
onclick={event => picker(event, $t("Background source"), (["folder", "image", "none"] as const).map(source => ({ label: sourceLabels[source], checked: settings.source === source, run: () => void chooseSource(source) })))}>{sourceLabels[settings.source]}<Icon icon="chevron-down" /></button></div>
{#if settings.source === "folder"}
<div class="setting-row folder-row"><label for="background-folder">{$t("Image folder")}</label><div class="controls folder-controls">
<input id="background-folder" readonly value={folder ?? ""} title={folder ?? ""} placeholder={$t("No folder selected")} />
<button onclick={() => void chooseFolder()}><Icon icon="folder-open" />{$t("Choose folder…")}</button>
{#if folder}<button onclick={() => void removeFolder()}>{$t("Remove folder")}</button>{/if}
</div></div>
<div class="setting-row"><label for="background-seconds">{$t("Seconds per image")}</label><input id="background-seconds" type="number" min="1" max="86400" step="1" value={settings.seconds}
onchange={event => { if (event.currentTarget.reportValidity()) save({ ...settings, seconds: event.currentTarget.valueAsNumber }); }} /></div>
<div class="setting-row"><span>{$t("Image order")}</span><button class="picker" aria-label={$t("Image order")} aria-haspopup="menu"
onclick={event => picker(event, $t("Image order"), (["name", "random"] as const).map(order => ({ label: orderLabels[order], checked: settings.order === order, run: () => save({ ...settings, order }) })))}>{orderLabels[settings.order]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Slideshow")}</span><div class="controls">
<button onclick={() => void sendBackgroundCommand("next").catch(report)}><Icon icon="arrow-right" />{$t("Next image")}</button>
<button aria-pressed={settings.paused} onclick={() => save({ ...settings, paused: !settings.paused })}>{settings.paused ? $t("Resume slideshow") : $t("Pause slideshow")}</button>
</div></div>
{:else if settings.source === "image"}
<div class="background-preview" role="img" aria-label={$t("Background image preview")}
style:background-image={previewUrl ? `${overlayShade}, url("${previewUrl}")` : "none"}
style:background-size={layout ? `100% 100%, ${layout.size}` : undefined}
style:background-position={layout ? `center, ${layout.position}` : undefined}><span>{$t("Background")}</span></div>
<div class="actions">
<button onclick={() => imageInput.click()}>{$t("Choose image…")}</button>
{#if image}<button onclick={() => void removeImage()}>{$t("Remove image")}</button>{/if}
</div>
{/if}
{#if layout}
<div class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("Image position")} aria-haspopup="menu"
onclick={event => picker(event, $t("Image position"), BACKGROUND_POSITIONS.map((value, index) => ({ label: positionLabels[index], checked: layout?.position === value, run: () => changeLayout({ position: value }) })))}>{positionLabels[BACKGROUND_POSITIONS.indexOf(layout.position)]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Image size")}</span><button class="picker" aria-label={$t("Image size")} aria-haspopup="menu"
onclick={event => picker(event, $t("Image size"), BACKGROUND_SIZES.map((value, index) => ({ label: sizeLabels[index], checked: layout?.size === value, run: () => changeLayout({ size: value }) })))}>{sizeLabels[BACKGROUND_SIZES.indexOf(layout.size)]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Image overlay")}</span><div class="controls overlay-controls">
<input type="range" aria-label={$t("Image overlay")} min="-100" max="100" value={Math.round(layout.overlay * 100)} oninput={event => changeOverlay(event.currentTarget)} />
<label class="overlay-value"><input type="number" aria-label={$t("Image overlay percentage")} min="-100" max="100" step="1" value={Math.round(layout.overlay * 100)}
oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((layout?.overlay ?? 0) * 100)); }} /><span>%</span></label>
</div></div>
{/if}
</div>
<input bind:this={imageInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importImage(event.currentTarget.files?.[0])} />
{#if settings.source === "folder"}
<p>{$t("Add PNG, JPEG, GIF, or WebP images to the folder. Portrait images show in full over a blurred fill.")}</p>
{#if folderNote}<p role="status">{folderNote}</p>{/if}
{:else if settings.source === "image"}
<p>{$t("PNG, JPEG, WebP, or GIF, up to 50 MiB. The image stays on this device.")}</p>
{:else}
<p>{$t("Choose a folder for a slideshow, or one image.")}</p>
{/if}
{#if layout}<p>{$t("Move the overlay left to lighten the image or right to darken it.")}</p>{/if}
{#if settings.source === "folder" && folder}
<ImageEditor {settings} />
{/if}
{#if settings.source !== "none"}
<fieldset class="targets">
<legend>{$t("Show the background in")}</legend>
{#each targets as target (target.id)}
<label class="check"><input type="checkbox" checked={settings.targets.includes(target.id)} onchange={event => toggleTarget(target.id, event.currentTarget.checked)} /><span>{target.name}</span></label>
{/each}
{#if boardsNote}<p>{boardsNote}</p>{/if}
</fieldset>
{/if}
{#if error}<p role="alert">{error}</p>{/if}
</div>
<style>
.background-settings { display: grid; gap: var(--rs-settings-gap); min-width: 0; }
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
.card { padding: 0 var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); min-width: 0; }
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; min-width: 0; }
.card > * + * { border-top: 1px solid var(--rs-border); }
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; max-width: 100%; }
.folder-controls { flex: 1 1 320px; justify-content: flex-end; }
.folder-controls input { flex: 1 1 160px; min-width: 120px; width: 0; }
input:not([type=checkbox]):not([type=range]), button { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
button { display: inline-flex; align-items: center; gap: 6px; background: var(--rs-bg-elevated); cursor: pointer; }
button:hover { background: var(--rs-bg-active); }
button[aria-pressed="true"] { border-color: var(--rs-accent); }
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
.picker { max-width: 100%; background: var(--rs-bg); }
input[type=number] { width: 88px; }
:is(button, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
.actions { display: flex; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; }
.background-preview { height: 120px; margin-top: var(--rs-settings-row-padding); background-color: var(--rs-bg); background-repeat: no-repeat; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); display: grid; place-items: center; }
.background-preview span { padding: 8px 14px; background: var(--rs-bg-elevated); border-radius: var(--rs-control-radius); }
.overlay-controls input[type=range] { width: 160px; max-width: 100%; min-width: 0; appearance: none; background: transparent; height: var(--rs-settings-control-height); margin: 0; cursor: pointer; }
.overlay-controls input[type=range]::-webkit-slider-runnable-track { height: 6px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
.overlay-controls input[type=range]::-webkit-slider-thumb { appearance: none; width: 18px; height: 18px; margin-top: -7px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
.overlay-controls input[type=range]::-moz-range-track { height: 4px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
.overlay-controls input[type=range]::-moz-range-thumb { width: 14px; height: 14px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
.overlay-controls input[type=range]:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; border-radius: var(--rs-control-radius); }
.overlay-value { display: flex; align-items: center; gap: 4px; }
.overlay-value input { width: 64px; }
.targets { display: grid; gap: 2px; min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
.targets legend { padding: 0 4px; color: var(--rs-text); }
.check { display: flex; align-items: center; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); overflow-wrap: anywhere; }
.check input { flex-shrink: 0; accent-color: var(--rs-accent); }
[role=alert] { color: var(--rs-error); }
</style>
@@ -0,0 +1,227 @@
<!--
The appearance of one image of the folder: fit, position, and overlay. It saves the sidecar file of the folder
(`.runestone-backgrounds.json`) only when the file did not change since the read. Then every window reads it again.
-->
<script lang="ts">
import { onDestroy, untrack } from "svelte";
import { t, tr } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte";
import { showActionMenu } from "$lib/ui/managedActionMenu";
import { BACKGROUND_POSITIONS } from "$lib/theme/appearance";
import { normalizeLayout, type BackgroundSettings } from "../backgroundSettings";
import { folderHost, sendBackgroundCommand } from "./sources";
import { imageAppearance, imageFits, imageNames, parseImageSettings, sidecarName, type ImageAppearance, type ImageSettings } from "./imageSettings";
let { settings }: { settings: BackgroundSettings } = $props();
let names = $state<string[]>([]);
let selected = $state("");
let query = $state("");
let pickerOpen = $state(false);
let draft = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
let baseline = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
let saved = $state<ImageSettings>({ schema: 1, images: {} });
let source: string | null = null;
let url = $state("");
let portrait = false;
let loaded = $state(false);
let busy = $state(false);
let status = $state({ text: "", error: false });
let generation = 0;
let closed = false;
let closeMenu = () => {};
let trigger: HTMLButtonElement | undefined = $state();
let search: HTMLInputElement | undefined = $state();
const pickerId = $props.id();
const filtered = $derived(names.filter(name => name.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())));
const fitLabels = $derived<Record<string, string>>({ cover: $t("Fill"), contain: $t("Fit"), auto: $t("Actual size"), blurred: $t("Full image with blurred fill") });
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
const changed = $derived(draft.fit !== baseline.fit || draft.position !== baseline.position || draft.overlay !== baseline.overlay);
const report = (reason: unknown) => { if (!closed) status = { text: reason instanceof Error ? reason.message : String(reason), error: true }; };
/** The values that differ from the inherited appearance. Only these go to the file. */
function changes(): Partial<ImageAppearance> {
return {
...(draft.fit !== baseline.fit ? { fit: draft.fit } : {}),
...(draft.position !== baseline.position ? { position: draft.position } : {}),
...(draft.overlay !== baseline.overlay ? { overlay: draft.overlay } : {}),
};
}
async function load() {
const revision = ++generation;
loaded = false; pickerOpen = false; names = [];
if (url) URL.revokeObjectURL(url);
url = "";
try {
const [text, list] = await Promise.all([folderHost.readSidecar(), folderHost.list()]);
if (closed || revision !== generation) return;
saved = parseImageSettings(text); source = text;
names = imageNames(list);
if (!names.includes(selected)) selected = names[0] ?? "";
if (selected) await choose(selected);
else status = { text: tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."), error: false };
} catch (reason) { report(reason); }
}
async function choose(name: string) {
const revision = ++generation;
selected = name; loaded = false;
if (url) URL.revokeObjectURL(url);
url = "";
try {
const next = URL.createObjectURL(await folderHost.read(name));
try {
const image = new Image(); image.src = next; await image.decode();
if (closed || revision !== generation) { URL.revokeObjectURL(next); return; }
portrait = image.naturalHeight > image.naturalWidth;
} catch (error) { URL.revokeObjectURL(next); throw error; }
url = next;
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
baseline = { ...draft };
loaded = true;
status = { text: saved.images[name] ? tr("Saved appearance.") : tr("Default appearance."), error: false };
} catch (reason) { report(reason); }
}
/** A change of the folder layout changes the inherited values. Keep the edits of the user. */
function inherit() {
if (!loaded) return;
const next = imageAppearance(normalizeLayout(settings), saved.images[selected], portrait);
if (next.fit === baseline.fit && next.position === baseline.position && next.overlay === baseline.overlay) return;
const edited = changes();
baseline = next;
draft = { ...next, ...edited };
}
async function write(reset: boolean) {
if (!loaded || busy) return;
const edited = changes();
if (!reset && !Object.keys(edited).length) return;
busy = true;
const revision = generation, name = selected;
try {
const next = structuredClone($state.snapshot(saved)) as ImageSettings;
if (reset) delete next.images[name]; else next.images[name] = { ...next.images[name], ...edited };
const contents = JSON.stringify(next, null, 2) + "\n";
await folderHost.writeSidecar(contents, source);
if (closed || revision !== generation) return;
source = contents; saved = next;
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
baseline = { ...draft };
status = { text: reset ? tr("Default appearance restored.") : tr("Image appearance saved."), error: false };
await sendBackgroundCommand("reload");
} catch (reason) { report(reason); }
finally { busy = false; }
}
function menu(event: MouseEvent, field: "fit" | "position") {
closeMenu();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
const values: readonly string[] = field === "fit" ? imageFits : BACKGROUND_POSITIONS;
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === "fit" ? $t("Image fit") : $t("Position of this image"), parent: anchor.closest("dialog") ?? undefined,
items: values.map((value, index) => ({ label: field === "fit" ? fitLabels[value] : positionLabels[index], radio: true, checked: draft[field] === value,
run: () => { draft = { ...draft, [field]: value }; } })) }).close;
}
function overlay(input: HTMLInputElement) {
if (input.validity.valid && Number.isFinite(input.valueAsNumber)) draft = { ...draft, overlay: Math.round(Math.max(-100, Math.min(100, input.valueAsNumber))) / 100 };
}
function openPicker() {
if (pickerOpen) { pickerOpen = false; return; }
query = ""; pickerOpen = true;
queueMicrotask(() => search?.focus());
}
function pick(name: string) {
pickerOpen = false;
void choose(name).then(() => trigger?.focus());
}
function moveFocus(event: KeyboardEvent, list: HTMLElement) {
const rows = [...list.querySelectorAll<HTMLButtonElement>("button")];
if (!rows.length) return;
const index = rows.indexOf(document.activeElement as HTMLButtonElement);
const next = event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : index < 0 ? (event.key === "ArrowDown" ? 0 : rows.length - 1) : Math.max(0, Math.min(rows.length - 1, index + (event.key === "ArrowDown" ? 1 : -1)));
event.preventDefault();
rows[next].focus();
}
$effect(() => { void settings.size; void settings.position; void settings.overlay; untrack(inherit); });
void load();
onDestroy(() => { closed = true; generation++; closeMenu(); if (url) URL.revokeObjectURL(url); });
</script>
<details class="image-editor">
<summary>{$t("Per-image appearance")}</summary>
<p>{$t("Choose an image to change its fit, position, and overlay. Portrait images show in full over a blurred fill by default.")}</p>
<fieldset disabled={busy}>
<div class="row"><span>{$t("Image")}</span>
<button bind:this={trigger} class="choice" aria-label={$t("Image to change")} aria-expanded={pickerOpen} aria-controls={pickerId} disabled={!names.length} onclick={openPicker}>
<span class="name">{selected || $t("Choose an image")}</span><Icon icon="chevron-down" /></button></div>
{#if pickerOpen}
<!-- svelte-ignore a11y_no_static_element_interactions (Escape closes the picker.) -->
<div id={pickerId} class="rs-picker image-picker" onkeydown={event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); pickerOpen = false; trigger?.focus(); } }}>
<input bind:this={search} type="search" aria-label={$t("Find an image")} placeholder={$t("Find an image")} bind:value={query}
onkeydown={event => { if (event.key === "ArrowDown" || event.key === "ArrowUp") moveFocus(event, event.currentTarget.nextElementSibling as HTMLElement); else if (event.key === "Enter" && filtered[0]) { event.preventDefault(); pick(filtered[0]); } }} />
<div class="options" role="listbox" aria-label={$t("Image files")} tabindex="-1"
onkeydown={event => { if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) moveFocus(event, event.currentTarget); }}>
{#each filtered.slice(0, 100) as name (name)}
<button class="rs-picker-row" role="option" tabindex="-1" aria-selected={name === selected} onclick={() => pick(name)}>{name}</button>
{/each}
</div>
<p role="status">{!filtered.length ? $t("No matching images.") : filtered.length > 100 ? $t("{count} matches. Type more of the name to see other images.", { count: filtered.length }) : $t(filtered.length === 1 ? "{count} image." : "{count} images.", { count: filtered.length })}</p>
</div>
{/if}
<div class="preview" role="img" aria-label={selected ? $t("Selected image preview: {name}", { name: selected }) : $t("Selected image preview")}>
{#if url}
{#if draft.fit === "blurred"}<span class="fill" style:background-image={`url("${url}")`}></span>{/if}
<span class="foreground" style:background-image={`url("${url}")`} style:background-size={draft.fit === "blurred" ? "contain" : draft.fit} style:background-position={draft.position}></span>
{/if}
<span class="shade" style:background={draft.overlay < 0 ? "white" : "black"} style:opacity={String(Math.abs(draft.overlay))}></span>
</div>
<div class="row"><span>{$t("Fit")}</span><button class="choice" aria-label={$t("Image fit")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "fit")}>{fitLabels[draft.fit]}<Icon icon="chevron-down" /></button></div>
<div class="row"><span>{$t("Position")}</span><button class="choice" aria-label={$t("Position of this image")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "position")}>{positionLabels[BACKGROUND_POSITIONS.indexOf(draft.position)]}<Icon icon="chevron-down" /></button></div>
<div class="row"><span>{$t("Overlay")}</span><div class="controls">
<input type="range" min="-100" max="100" aria-label={$t("Overlay of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} />
<input type="number" min="-100" max="100" step="1" required aria-label={$t("Overlay percentage of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} /><span>%</span>
</div></div>
<div class="controls">
<button disabled={!loaded || !changed} onclick={() => void write(false)}><Icon icon="save" />{$t("Save image appearance")}</button>
<button disabled={!loaded || !saved.images[selected]} onclick={() => void write(true)}><Icon icon="undo" />{$t("Reset image appearance")}</button>
<button onclick={() => void load()}><Icon icon="refresh" />{$t("Reload image settings")}</button>
</div>
</fieldset>
{#if status.text}<p role={status.error ? "alert" : "status"} class:error={status.error}>{status.text}</p>{/if}
</details>
<style>
.image-editor { display: grid; gap: var(--rs-settings-gap); min-width: 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
summary { cursor: pointer; min-height: var(--rs-settings-control-height); line-height: var(--rs-settings-control-height); border-radius: var(--rs-control-radius); }
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
.error { color: var(--rs-error); }
fieldset { display: grid; gap: var(--rs-settings-gap); min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: 0; border: 0; }
.row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
button:not(.rs-picker-row), input:not([type=range]) { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
button:not(.rs-picker-row) { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
button:not(.rs-picker-row):hover:not(:disabled) { background: var(--rs-bg-active); }
button:disabled, input:disabled { opacity: .55; cursor: default; }
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
:is(button, input, summary):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
.choice { max-width: 100%; min-width: 0; }
.choice .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
input[type=number] { width: 72px; }
input[type=range] { width: 160px; max-width: 100%; accent-color: var(--rs-accent); }
.image-picker { display: grid; gap: var(--rs-settings-gap); width: 100%; min-width: 0; position: static; }
.image-picker input { width: 100%; min-width: 0; }
.options { display: grid; gap: 2px; max-height: 220px; overflow: auto; min-width: 0; }
.options button { justify-content: flex-start; text-align: left; overflow-wrap: anywhere; }
.preview { position: relative; width: 100%; height: 170px; overflow: hidden; border-radius: var(--rs-control-radius); background-color: var(--rs-bg-active); }
.fill, .foreground, .shade { position: absolute; inset: 0; background-repeat: no-repeat; pointer-events: none; }
.fill { inset: -24px; filter: blur(18px); background-size: cover; background-position: center; }
</style>
+83
View File
@@ -0,0 +1,83 @@
// The blurred fill of a portrait image. One worker does the decode, the resize, and the filter away from the
// input and paint work of the window. It lives as long as the Background instance.
import { tr } from "../../i18n/index.ts";
const workerSource = `
self.onmessage = async ({ data: { id, url, width, height } }) => {
let image;
try {
const source = await (await fetch(url)).blob();
image = await createImageBitmap(source, { resizeWidth: width, resizeHeight: height, resizeQuality: 'high' });
const canvas = new OffscreenCanvas(width, height);
const context = canvas.getContext('2d');
context.filter = 'blur(24px)';
context.drawImage(image, -48, -48, width + 96, height + 96);
self.postMessage({ id, blob: await canvas.convertToBlob({ type: 'image/png' }) });
} catch (error) {
self.postMessage({ id, error: error instanceof Error ? error.message : String(error) });
} finally { image?.close(); }
};`;
/** The size of the blurred copy. Its long side is at most 1024 pixels. */
export function blurSize(width: number, height: number): { width: number; height: number } {
const scale = Math.min(1, 1024 / Math.max(width, height, 1));
return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
}
export class BlurWorker {
private worker?: Worker;
private workerUrl?: string;
private serial = 0;
private pending = new Map<number, { resolve: (blob: Blob) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>();
/** A blob URL of the blurred copy of the image at `url`. The caller releases it. */
async blur(url: string, width: number, height: number): Promise<string> {
const size = blurSize(width, height);
if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined") return URL.createObjectURL(await this.inWindow(url, size));
const worker = this.start();
const id = ++this.serial;
const blob = await new Promise<Blob>((resolve, reject) => {
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(tr("The blurred image took too long to load."))); }, 10000);
this.pending.set(id, { resolve, reject, timer });
worker.postMessage({ id, url, ...size });
});
return URL.createObjectURL(blob);
}
private start(): Worker {
if (this.worker) return this.worker;
this.workerUrl = URL.createObjectURL(new Blob([workerSource], { type: "text/javascript" }));
const worker = this.worker = new Worker(this.workerUrl);
worker.onmessage = ({ data }) => {
const request = this.pending.get(data?.id);
if (!request) return;
this.pending.delete(data.id); clearTimeout(request.timer);
if (data.blob instanceof Blob) request.resolve(data.blob);
else request.reject(new Error(data.error || tr("Cannot create the blurred image.")));
};
worker.onerror = () => this.fail(new Error(tr("Cannot create the blurred image.")));
return worker;
}
/** A fallback for a window without OffscreenCanvas. */
private async inWindow(url: string, size: { width: number; height: number }): Promise<Blob> {
const image = new Image(); image.src = url; await image.decode();
const canvas = document.createElement("canvas");
canvas.width = size.width; canvas.height = size.height;
const context = canvas.getContext("2d")!;
context.filter = "blur(24px)";
context.drawImage(image, -48, -48, size.width + 96, size.height + 96);
return new Promise<Blob>((resolve, reject) => canvas.toBlob(value => value ? resolve(value) : reject(new Error(tr("Cannot create the blurred image."))), "image/png"));
}
private fail(error: Error) {
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
this.pending.clear();
// A failed worker starts again at the next request.
this.worker?.terminate(); this.worker = undefined;
if (this.workerUrl) URL.revokeObjectURL(this.workerUrl);
this.workerUrl = undefined;
}
dispose() { this.fail(new Error(tr("This feature is off."))); }
}
+337
View File
@@ -0,0 +1,337 @@
// The Background engine: it shows the images of a source as background frames, one after the other.
// It comes from the engine of the Background Slideshow plugin, with these changes for the open card
// "Lag before image transition": the next image loads and decodes before its fade, the blurred fills of the
// last images stay in a cache, and the folder list and the sidecar are read again only after a settings change,
// on window focus, or after every 10 images.
import { tr } from "../../i18n/index.ts";
import type { BackgroundFrame } from "../../plugins/backgroundContracts.ts";
import type { BackgroundLayout } from "../backgroundSettings.ts";
import { imageAppearance, imageNames, parseImageSettings, sequence, type ImageAppearance, type ImageSettings } from "./imageSettings.ts";
/** The time of the fade from one image to the next. */
export const transitionMs = 2000;
/** The folder list and the sidecar are read again after this number of images. */
export const RESCAN_SLIDES = 10;
/** The number of blurred fills that stay in the cache. */
export const BLUR_CACHE = 3;
/** The shortest wait before a new try after an error. */
export const RETRY_MS = 5000;
/** Where the images come from: the image folder of the host, or the one saved image. */
export interface ImageSource {
/** A different key means a different folder or image. The engine then starts again. */
readonly key: string;
/** True for a folder: the images change on a timer, and the sidecar and the portrait default apply. */
readonly timed: boolean;
/** The image names. */
list(): Promise<string[]>;
read(name: string): Promise<Blob>;
/** The text of the sidecar file, or null. */
sidecar(): Promise<string | null>;
}
export interface LoadedImage { url: string; width: number; height: number }
/** The browser services of the engine. Tests replace them. */
export interface Runtime {
/** Make a blob URL and decode the image before it shows. */
load(blob: Blob): Promise<LoadedImage>;
/** Make the blurred fill of a loaded image. The engine releases the URL. */
blur(image: LoadedImage): Promise<string>;
release(url: string): void;
later(callback: () => void, milliseconds: number): unknown;
cancel(timer: unknown): void;
random(): number;
now(): number;
}
export interface Frames { set(target: string, frame: BackgroundFrame | null): void }
export interface EngineSettings extends BackgroundLayout {
seconds: number;
order: "name" | "random";
paused: boolean;
targets: string[];
}
export interface Status { message: string; image: string | null; count: number; error: boolean }
interface Shown { name: string; key: string; image: LoadedImage; appearance: ImageAppearance; blurred?: string }
interface Prepared { name: string; key: string; image: LoadedImage }
function toFrame(shown: Shown): BackgroundFrame {
const frame: BackgroundFrame = { url: shown.image.url, overlay: shown.appearance.overlay, position: shown.appearance.position,
size: shown.appearance.fit === "blurred" ? "contain" : shown.appearance.fit };
if (shown.blurred) frame.blurredUrl = shown.blurred;
return frame;
}
const sameAppearance = (a: ImageAppearance, b: ImageAppearance) => a.fit === b.fit && a.position === b.position && a.overlay === b.overlay;
export class Slideshow {
status: Status = { message: "", image: null, count: 0, error: false };
private source: ImageSource | null = null;
private settings: EngineSettings | null = null;
private revision = 0;
private stopped = false;
private timer: unknown;
/** When the current timer fires, or null without a timer. */
private due: number | null = null;
private names: string[] | null = null;
private imageSettings: ImageSettings = { schema: 1, images: {} };
private sidecarError = "";
private stale = true;
private slides = 0;
private shown: Shown | null = null;
/** The image that the current frame fades from. */
private previous: Shown | null = null;
private targets = new Set<string>();
/** The blurred fills, oldest first. */
private blurs = new Map<string, string>();
private prepared: { name: string; work: Promise<Prepared | null>; discarded: boolean } | null = null;
/** Changes at each `clear`, so that a late blurred fill of an old image does not enter the cache. */
private epoch = 0;
private listeners = new Set<() => void>();
private frames: Frames;
private runtime: Runtime;
constructor(frames: Frames, runtime: Runtime) { this.frames = frames; this.runtime = runtime; }
subscribe(listener: () => void) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
private notify() { for (const listener of [...this.listeners]) listener(); }
/** Use a new source or new settings. The current image stays when the source is the same and still has it. */
configure(source: ImageSource | null, settings: EngineSettings): Promise<void> {
if (this.stopped) return Promise.resolve();
if (source?.key !== this.source?.key) {
this.clear();
this.names = null;
}
this.source = source;
this.settings = { ...settings, targets: [...settings.targets] };
this.stale = true;
return this.update(false);
}
/** Read the list and the sidecar again before the next image, for example after a window focus. */
invalidate() { this.stale = true; }
/** Read the list and the sidecar again now, and apply them to the current image. */
reload = () => { this.stale = true; return this.update(false); };
/** Show the next image now. */
next = () => this.update(true);
dispose() {
if (this.stopped) return;
this.stopped = true; this.revision++;
this.runtime.cancel(this.timer); this.timer = undefined;
this.clear(); this.listeners.clear();
}
private async update(advance: boolean): Promise<void> {
if (this.stopped) return;
const revision = ++this.revision;
const remaining = this.due === null ? null : Math.max(0, this.due - this.runtime.now());
this.runtime.cancel(this.timer); this.timer = undefined; this.due = null;
const valid = () => !this.stopped && revision === this.revision;
const source = this.source, settings = this.settings;
try {
if (!source || !settings) { this.clear(); this.setStatus(tr("Choose a folder or an image to show a background.")); return; }
if (!settings.targets.length) { this.clear(); this.setStatus(tr("Select where to show the background.")); return; }
if (this.stale || !this.names) {
const [list, sidecar] = await Promise.all([source.list(), source.timed ? source.sidecar() : Promise.resolve(null)]);
if (!valid()) return;
this.names = source.timed ? imageNames(list) : [...list];
try { this.imageSettings = parseImageSettings(sidecar); this.sidecarError = ""; }
catch (reason) { this.imageSettings = { schema: 1, images: {} }; this.sidecarError = reason instanceof Error ? reason.message : String(reason); }
this.stale = false; this.slides = 0;
if (this.prepared && !this.names.includes(this.prepared.name)) this.discardPrepared();
}
const names = this.names;
this.status.count = names.length;
if (!names.length) throw new Error(tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."));
const shown = this.shown;
if (shown && names.includes(shown.name) && (!advance || names.length === 1)) {
await this.reapply(shown, settings, valid);
if (!valid()) return;
this.schedule(remaining ?? settings.seconds * 1000, revision);
this.prepare();
return;
}
let failures = 0;
const order = sequence(names, shown?.name ?? null, settings.order, this.runtime.random);
const candidates = this.prepared && order.includes(this.prepared.name) ? [this.prepared.name, ...order.filter(name => name !== this.prepared!.name)] : order;
for (const name of candidates) {
let loaded: Prepared | null = null;
let next: Shown;
try {
loaded = await this.load(name);
if (!valid()) { if (loaded) this.runtime.release(loaded.image.url); return; }
if (!loaded) throw new Error(tr("The image cannot be displayed."));
next = { ...loaded, appearance: this.appearanceOf(name, loaded.image, settings) };
if (next.appearance.fit === "blurred") {
next.blurred = await this.blurOf(loaded);
if (!valid()) { this.runtime.release(loaded.image.url); return; }
}
} catch {
if (loaded) this.runtime.release(loaded.image.url);
if (!valid()) return;
failures++; continue;
}
this.publish(next, settings, true);
const message = failures ? tr("{name}: skipped {count} unreadable images.", { name, count: failures }) : name;
this.status = { image: name, count: names.length, error: !!this.sidecarError, message: this.sidecarError ? `${message} ${this.sidecarError}` : message };
this.notify();
if (++this.slides >= RESCAN_SLIDES) this.stale = true;
this.schedule(settings.seconds * 1000, revision);
this.prepare();
return;
}
throw new Error(tr("No readable images in this folder. Check the image files."));
} catch (error) {
if (!valid()) return;
this.clear();
this.status = { ...this.status, image: null, error: true, message: error instanceof Error ? error.message : String(error) };
this.notify();
if (source?.timed && settings) this.schedule(Math.max(RETRY_MS, settings.seconds * 1000), revision, true);
}
}
private setStatus(message: string) {
this.status = { message, image: null, count: 0, error: false };
this.notify();
}
private appearanceOf(name: string, image: LoadedImage, settings: EngineSettings): ImageAppearance {
if (!this.source?.timed) return { fit: settings.size, position: settings.position, overlay: settings.overlay };
return imageAppearance(settings, this.imageSettings.images[name], image.height > image.width);
}
/** The image of `name`: the prepared image when it matches, or a new read. */
private async load(name: string): Promise<Prepared | null> {
const prepared = this.prepared;
if (prepared?.name === name) {
this.prepared = null;
const result = await prepared.work.catch(() => null);
if (result) return result;
}
const source = this.source!;
const blob = await source.read(name);
const image = await this.runtime.load(blob);
return { name, key: `${source.key}\n${name}\n${blob.size}`, image };
}
/** Load and decode the next image of a timed source now, so that its fade starts on time. */
private prepare() {
const source = this.source, settings = this.settings, names = this.names, shown = this.shown;
if (!source?.timed || !settings || settings.paused || !names || names.length < 2 || !shown || this.prepared) return;
const name = sequence(names, shown.name, settings.order, this.runtime.random)[0];
const entry: { name: string; work: Promise<Prepared | null>; discarded: boolean } = { name, work: Promise.resolve(null), discarded: false };
entry.work = (async (): Promise<Prepared | null> => {
const blob = await source.read(name);
const image = await this.runtime.load(blob);
// A prepared image that nobody wants any more goes away at once.
if (this.stopped || entry.discarded) { this.runtime.release(image.url); return null; }
const result = { name, key: `${source.key}\n${name}\n${blob.size}`, image };
const appearance = imageAppearance(settings, this.imageSettings.images[name], image.height > image.width);
if (appearance.fit === "blurred") await this.blurOf(result).catch(() => undefined);
return result;
})();
entry.work.catch(() => undefined);
this.prepared = entry;
}
private discardPrepared() {
const prepared = this.prepared;
this.prepared = null;
if (!prepared) return;
prepared.discarded = true;
void prepared.work.then(result => { if (result) this.runtime.release(result.image.url); }, () => undefined);
}
/** The blurred fill of an image, from the cache when possible. */
private async blurOf(image: Prepared): Promise<string> {
const cached = this.blurs.get(image.key);
if (cached) { this.blurs.delete(image.key); this.blurs.set(image.key, cached); return cached; }
const epoch = this.epoch;
const url = await this.runtime.blur(image.image);
if (this.stopped || epoch !== this.epoch) { this.runtime.release(url); throw new Error(tr("The background changed.")); }
const again = this.blurs.get(image.key);
if (again) { this.runtime.release(url); return again; }
this.blurs.set(image.key, url);
this.trimBlurs(url);
return url;
}
/** Release the oldest blurred fills beyond the cache size. Fills that a frame shows stay. */
private trimBlurs(keep?: string) {
const used = new Set([this.shown?.blurred, this.previous?.blurred, keep]);
for (const [key, url] of this.blurs) {
if (this.blurs.size <= BLUR_CACHE) break;
if (used.has(url)) continue;
this.blurs.delete(key); this.runtime.release(url);
}
}
/** Apply new settings or new image settings to the image that shows, without a fade. */
private async reapply(shown: Shown, settings: EngineSettings, valid: () => boolean) {
const appearance = this.appearanceOf(shown.name, shown.image, settings);
const sameTargets = settings.targets.length === this.targets.size && settings.targets.every(target => this.targets.has(target));
const needsBlur = appearance.fit === "blurred" && !shown.blurred;
if (sameTargets && sameAppearance(appearance, shown.appearance) && !needsBlur) return;
const next: Shown = { ...shown, appearance, blurred: undefined };
if (appearance.fit === "blurred") {
next.blurred = await this.blurOf(shown);
if (!valid()) return;
}
this.publish(next, settings, false);
this.notify();
}
/** Show `next` on every target. With `fade`, the frame fades from the image that showed before. */
private publish(next: Shown, settings: EngineSettings, fade: boolean) {
const old = this.shown;
const frame = toFrame(next);
if (fade && old) { frame.previous = toFrame(old); frame.transitionMs = transitionMs; }
try {
for (const target of this.targets) if (!settings.targets.includes(target)) this.frames.set(target, null);
// Track the new targets before the frames go out, so that a cleanup also clears a partial publish.
for (const target of settings.targets) this.targets.add(target);
for (const target of settings.targets) this.frames.set(target, frame);
} catch (error) {
if (next.image !== old?.image) this.runtime.release(next.image.url);
throw error;
}
this.targets = new Set(settings.targets);
// Keep the image of the fade until the next frame replaces it.
const release = this.previous;
if (release && release.image !== next.image && release.image !== old?.image) this.runtime.release(release.image.url);
this.previous = fade && old && old.image !== next.image ? old : null;
if (!fade && old && old.image !== next.image) this.runtime.release(old.image.url);
this.shown = next;
this.trimBlurs();
}
/** Remove the frames of every target and release every image. */
private clear() {
for (const target of this.targets) { try { this.frames.set(target, null); } catch { /* The window can close before the cleanup. */ } }
this.targets.clear();
const images = new Set([this.shown?.image.url, this.previous?.image.url]);
for (const url of images) if (url) this.runtime.release(url);
for (const url of this.blurs.values()) this.runtime.release(url);
this.blurs.clear();
this.epoch++;
this.discardPrepared();
this.shown = null; this.previous = null;
this.status = { ...this.status, image: null };
}
private schedule(milliseconds: number, revision: number, retry = false) {
const settings = this.settings;
if (this.stopped || this.revision !== revision || !this.source?.timed || !settings) return;
if (settings.paused && !retry) return;
this.due = this.runtime.now() + milliseconds;
this.timer = this.runtime.later(() => { this.timer = undefined; this.due = null; void this.update(true); }, milliseconds);
}
}
@@ -0,0 +1,57 @@
// The per-image settings: the sidecar file `.runestone-backgrounds.json` in the image folder.
// The Background Slideshow plugin used the same file, so the settings of each image stay.
import { BACKGROUND_POSITIONS } from "../../theme/appearance.ts";
import { tr } from "../../i18n/index.ts";
import type { BackgroundLayout, BackgroundPosition } from "../backgroundSettings.ts";
export const sidecarName = ".runestone-backgrounds.json";
/** `blurred` shows the full image over a blurred copy that fills the view. Portrait images use it by default. */
export const imageFits = ["cover", "contain", "auto", "blurred"] as const;
export type ImageFit = typeof imageFits[number];
export interface ImageAppearance { fit: ImageFit; position: BackgroundPosition; overlay: number }
/** Unknown keys of the file and of each image stay when RuneStone saves the file. */
export interface ImageSettings { schema: 1; images: Record<string, Partial<ImageAppearance>>; [key: string]: unknown }
/** Read the sidecar text. `null` (no file) gives empty settings. Invalid settings throw an error. */
export function parseImageSettings(source: string | null): ImageSettings {
if (source === null) return { schema: 1, images: {} };
const value = JSON.parse(source);
if (!value || value.schema !== 1 || !value.images || typeof value.images !== "object" || Array.isArray(value.images)) {
throw new Error(tr("The image settings file must use schema 1 and an images object."));
}
for (const [name, raw] of Object.entries(value.images)) {
const appearance = raw as Partial<ImageAppearance>;
if (!name || /[\\/]/.test(name) || !appearance || typeof appearance !== "object" || Array.isArray(appearance)
|| ("fit" in appearance && !imageFits.includes(appearance.fit!))
|| ("position" in appearance && !BACKGROUND_POSITIONS.includes(appearance.position!))
|| ("overlay" in appearance && (typeof appearance.overlay !== "number" || !Number.isFinite(appearance.overlay) || Math.abs(appearance.overlay) > 1))) {
throw new Error(tr("Invalid image settings for {name}.", { name }));
}
}
return value;
}
/** The appearance of one image: the folder layout, the portrait default, then the saved values of the image. */
export function imageAppearance(layout: BackgroundLayout, override: Partial<ImageAppearance> | undefined, portrait: boolean): ImageAppearance {
return { fit: portrait ? "blurred" : layout.size, position: layout.position, overlay: layout.overlay, ...override };
}
/** The supported image names, without duplicates, in natural order. */
export function imageNames(names: readonly string[]): string[] {
return [...new Set(names.filter(name => !/[\\/]/.test(name) && /\.(png|jpe?g|gif|webp)$/i.test(name)))]
.sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }) || a.localeCompare(b, "en"));
}
/** The order of the next images after `current`. A random order puts the current image last. */
export function sequence(names: readonly string[], current: string | null, order: "name" | "random", random = Math.random): string[] {
if (order === "name") {
const index = current === null ? -1 : names.indexOf(current);
return [...names.slice(index + 1), ...names.slice(0, index + 1)];
}
const rest = names.filter(name => name !== current);
for (let i = rest.length - 1; i > 0; i--) {
const j = Math.min(i, Math.max(0, Math.floor(random() * (i + 1))));
[rest[i], rest[j]] = [rest[j], rest[i]];
}
return current && names.includes(current) ? [...rest, current] : rest;
}
+84
View File
@@ -0,0 +1,84 @@
// The Background feature. `loader.ts` imports this module when a folder or an image is selected (`launch.ts`),
// at a palette command, or when Appearance → Background shows its settings.
// It shows the images through `backgroundHub`, so the workarea, browser tabs, and Project Management boards get the frames.
import { mount, unmount } from "svelte";
import { tr } from "../../i18n/index.ts";
import { backgroundHub } from "../../plugins/backgrounds.ts";
import { readAppearance } from "../../theme/appearance.ts";
import { hasImage, normalizeLayout, onBackgroundChange, readBackground, writeBackground } from "../backgroundSettings.ts";
import type { FeatureContext, FeatureInstance } from "../types.ts";
import { BlurWorker } from "./blur.ts";
import { Slideshow, type ImageSource } from "./engine.ts";
import { browserRuntime, folderHost, folderSource, imageSource, onBackgroundCommand, sendBackgroundCommand } from "./sources.ts";
import BackgroundSettings from "./BackgroundSettings.svelte";
export function start(_context: FeatureContext): FeatureInstance {
const owner = Symbol("background");
const blur = new BlurWorker();
const engine = new Slideshow({ set: (target, frame) => backgroundHub.set(owner, target, frame) }, browserRuntime(blur));
/** The host folder for display. `undefined` until the first read. */
let folder: string | null | undefined;
let generation = 0;
let disposed = false;
/** The last source and settings. A change of another appearance setting, such as the theme, gives the same value. */
let applied = "";
/** Give the engine the current source and settings. `reread` asks the host for its folder again. */
async function apply(reread: boolean) {
const run = ++generation;
const settings = readBackground();
const appearance = readAppearance();
let source: ImageSource | null = null;
let layout = normalizeLayout(settings);
if (settings.source === "folder") {
if (reread || folder === undefined) {
try { folder = await folderHost.current(); } catch { folder = null; }
if (disposed || run !== generation) return;
}
source = folder ? folderSource(folder) : null;
} else if (settings.source === "image" && hasImage(appearance)) {
source = imageSource(appearance.newTabBackground!);
layout = normalizeLayout(appearance.newTabBackground);
}
const next = { ...settings, ...layout };
const signature = JSON.stringify([source?.key ?? null, next]);
if (!reread && signature === applied) return;
applied = signature;
await engine.configure(source, next);
}
const stopSettings = onBackgroundChange(() => { void apply(false); });
const stopCommands = onBackgroundCommand(command => {
if (command === "next") void engine.next();
else { engine.invalidate(); void apply(true); }
});
// Another window or program can change the folder. A focus reads the folder, the list, and the sidecar again.
const focus = () => { engine.invalidate(); void apply(true); };
window.addEventListener("focus", focus);
void apply(true);
return {
mount() { throw new Error(tr("This view is unavailable.")); },
async run(command) {
if (command === "next") await sendBackgroundCommand("next");
else if (command === "pause") {
const settings = readBackground();
await writeBackground({ ...settings, paused: !settings.paused });
} else throw new Error(tr("This command is unavailable."));
},
dispose() {
disposed = true; generation++;
stopSettings(); stopCommands();
window.removeEventListener("focus", focus);
engine.dispose();
blur.dispose();
backgroundHub.removeOwner(owner);
},
};
}
/** The settings of Appearance → Background. They work also in a window where Background does not run. */
export function mountSettings(element: HTMLElement) {
const component = mount(BackgroundSettings, { target: element });
return () => { void unmount(component); };
}
+108
View File
@@ -0,0 +1,108 @@
// The image sources of Background, the host folder commands (`src-tauri/src/backgrounds.rs`), the browser runtime of the
// engine, and the commands that reach the Background instance of every window.
import { invoke, isTauri } from "@tauri-apps/api/core";
import { emit, listen } from "@tauri-apps/api/event";
import { tr } from "../../i18n/index.ts";
import { readBackgroundImage } from "../../theme/backgroundImages.ts";
import type { Appearance } from "../../theme/appearance.ts";
import type { BlurWorker } from "./blur.ts";
import type { ImageSource, LoadedImage, Runtime } from "./engine.ts";
const types: Record<string, string> = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
const typeOf = (name: string) => types[name.split(".").pop()!.toLowerCase()] ?? "application/octet-stream";
/** The host commands of the image folder. The host keeps the folder, so no command takes a path. */
export const folderHost = {
/** Show the folder dialog. Returns the chosen folder for display, or null after Cancel. */
choose: (title: string) => invoke<string | null>("background_choose_folder", { title }),
/** The current folder for display, or null. */
current: () => invoke<string | null>("background_folder"),
clear: () => invoke<void>("background_clear_folder"),
list: () => invoke<string[]>("background_list"),
read: async (name: string): Promise<Blob> => {
const bytes = await invoke<ArrayBuffer | Uint8Array | number[]>("background_read", { name });
return new Blob([bytes instanceof ArrayBuffer ? bytes : Uint8Array.from(bytes)], { type: typeOf(name) });
},
readSidecar: () => invoke<string | null>("background_read_sidecar"),
writeSidecar: (contents: string, expected: string | null) => invoke<void>("background_write_sidecar", { contents, expected }),
};
/** The images of the host folder. `folder` is the path for display. It makes the key, so another folder starts again. */
export function folderSource(folder: string): ImageSource {
return { key: `folder:${folder}`, timed: true, list: folderHost.list, read: folderHost.read, sidecar: folderHost.readSidecar };
}
/** The saved image of Appearance, from IndexedDB or from an old data URL. */
export async function readSavedImage(background: NonNullable<Appearance["newTabBackground"]>): Promise<Blob> {
if (background.imageId) {
const blob = await readBackgroundImage(background.imageId);
if (!blob) throw new Error(tr("The saved background image is missing. Choose the image again."));
return blob;
}
const image = background.image ?? "";
const [header, data] = image.split(",");
const bytes = Uint8Array.from(atob(data ?? ""), character => character.charCodeAt(0));
return new Blob([bytes], { type: header.slice(5, header.indexOf(";")) });
}
/** A short hash of a data URL, so that another old image gets another key. */
function hash(text: string): string {
let value = 0x811c9dc5;
for (let index = 0; index < text.length; index++) value = Math.imul(value ^ text.charCodeAt(index), 0x01000193);
return (value >>> 0).toString(16);
}
/** The one saved image. It has no timer. */
export function imageSource(background: NonNullable<Appearance["newTabBackground"]>): ImageSource {
const id = background.imageId ?? `data:${background.image?.length ?? 0}:${hash(background.image ?? "")}`;
return { key: `image:${id}`, timed: false, list: async () => ["image"], read: () => readSavedImage(background), sidecar: async () => null };
}
/** Make a blob URL and decode the image before it shows, so the fade does not wait for the decode. */
export async function loadImage(blob: Blob): Promise<LoadedImage> {
const url = URL.createObjectURL(blob);
try {
const image = new Image();
let timer: ReturnType<typeof setTimeout> | undefined;
image.src = url;
await Promise.race([image.decode(), new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(tr("The image took too long to load."))), 10000); })])
.finally(() => clearTimeout(timer));
return { url, width: image.naturalWidth, height: image.naturalHeight };
} catch (error) { URL.revokeObjectURL(url); throw error; }
}
export function browserRuntime(blur: BlurWorker): Runtime {
return {
load: loadImage,
blur: image => blur.blur(image.url, image.width, image.height),
release: url => URL.revokeObjectURL(url),
later: (callback, milliseconds) => setTimeout(callback, milliseconds),
cancel: timer => clearTimeout(timer as ReturnType<typeof setTimeout>),
random: Math.random,
now: () => Date.now(),
};
}
/** `next` shows the next image. `reload` reads the folder, the list, and the sidecar again. */
export type BackgroundCommand = "next" | "reload";
const EVENT = "background-command";
/** Send a command to the Background instance of every window, this window too. */
export async function sendBackgroundCommand(command: BackgroundCommand): Promise<void> {
if (isTauri()) await emit(EVENT, command);
else window.dispatchEvent(new CustomEvent(EVENT, { detail: command }));
}
/** Receive the commands of every window. Returns the function that stops it. */
export function onBackgroundCommand(listener: (command: BackgroundCommand) => void): () => void {
const accept = (value: unknown) => { if (value === "next" || value === "reload") listener(value); };
if (!isTauri()) {
const handle = (event: Event) => accept((event as CustomEvent).detail);
window.addEventListener(EVENT, handle);
return () => window.removeEventListener(EVENT, handle);
}
let stopped = false;
let off: (() => void) | undefined;
void listen<unknown>(EVENT, event => accept(event.payload)).then(unlisten => { if (stopped) unlisten(); else off = unlisten; }, () => undefined);
return () => { stopped = true; off?.(); };
}
+119
View File
@@ -0,0 +1,119 @@
// The settings of the Background feature: the `background` section of the settings file.
// This file is in the main bundle, because the launch rule and the first-start migration need it without the feature code.
// The image source keeps its image and its layout in `appearance.newTabBackground`, so an older version still shows it.
// The host keeps the image folder itself (`src-tauri/src/backgrounds.rs`). The interface never sends a folder path.
import { onSettingsChange, readSection, writeSection } from "../settings/store.ts";
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, type Appearance } from "../theme/appearance.ts";
import type { LegacyPlugin } from "./migration.ts";
export const BACKGROUND_SOURCES = ["folder", "image", "none"] as const;
export type BackgroundSource = typeof BACKGROUND_SOURCES[number];
export type BackgroundPosition = typeof BACKGROUND_POSITIONS[number];
export type BackgroundSize = typeof BACKGROUND_SIZES[number];
/** The views that show the background: the workspace, all Project Management boards, or one board. */
export const BACKGROUND_TARGET = /^(?:app|pm-all|pm-board:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
export interface BackgroundLayout {
/** From -1 (white) to 1 (black). */
overlay: number;
position: BackgroundPosition;
size: BackgroundSize;
}
export interface BackgroundSettings extends BackgroundLayout {
source: BackgroundSource;
/** The time of each image of a folder, from 1 to 86,400 seconds. */
seconds: number;
order: "name" | "random";
/** A paused folder keeps its current image. */
paused: boolean;
targets: string[];
}
export const DEFAULT_BACKGROUND: Readonly<BackgroundSettings> = Object.freeze({
source: "none", seconds: 60, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover",
});
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
}
/** The folder layout fields from any value. Invalid fields take the defaults. */
export function normalizeLayout(value: unknown): BackgroundLayout {
const raw = record(value);
return {
overlay: typeof raw.overlay === "number" && Number.isFinite(raw.overlay) ? Math.max(-1, Math.min(1, raw.overlay)) : 0,
position: BACKGROUND_POSITIONS.includes(raw.position as BackgroundPosition) ? raw.position as BackgroundPosition : "center",
size: BACKGROUND_SIZES.includes(raw.size as BackgroundSize) ? raw.size as BackgroundSize : "cover",
};
}
/** Valid settings from any value. Invalid fields take the defaults. */
export function normalizeBackground(value: unknown): BackgroundSettings {
const raw = record(value);
return {
source: BACKGROUND_SOURCES.includes(raw.source as BackgroundSource) ? raw.source as BackgroundSource : "none",
seconds: typeof raw.seconds === "number" && Number.isFinite(raw.seconds) ? Math.max(1, Math.min(86400, Math.round(raw.seconds))) : 60,
order: raw.order === "random" ? "random" : "name",
paused: raw.paused === true,
targets: Array.isArray(raw.targets)
? [...new Set(raw.targets.filter((target): target is string => typeof target === "string" && BACKGROUND_TARGET.test(target)))]
: ["app"],
...normalizeLayout(raw),
};
}
export function readBackground(): BackgroundSettings {
return normalizeBackground(readSection("background"));
}
/** Save the settings. Keys of a newer version stay. */
export function writeBackground(next: BackgroundSettings): Promise<void> {
return writeSection("background", { ...record(readSection("background")), ...normalizeBackground(next) });
}
/** True when the appearance has a saved background image. */
export function hasImage(appearance: Appearance = readAppearance()): boolean {
return !!(appearance.newTabBackground?.image || appearance.newTabBackground?.imageId);
}
/** True when Background has something to show: a folder, or an image that exists. */
export function hasBackgroundSource(settings: BackgroundSettings = readBackground(), appearance: Appearance = readAppearance()): boolean {
return settings.source === "folder" || (settings.source === "image" && hasImage(appearance));
}
/** Run `listener` after each change of the background or appearance settings. Returns the function that stops it. */
export function onBackgroundChange(listener: () => void): () => void {
const stops = [onSettingsChange("background", listener), onSettingsChange("appearance", listener)];
return () => stops.forEach(stop => stop());
}
/** The host side of the first-start migration of the `background` section. */
export interface BackgroundMigrationHost {
/** True when the settings file has no `background` section. */
missing(): boolean;
/** True when the appearance has a saved background image. */
hasImage(): boolean;
/** Copy the folder of the old plugin grant to the host. True when the host has a folder after the call. */
migrateFolder(): Promise<boolean>;
write(value: BackgroundSettings): Promise<void>;
}
/**
* Make the `background` section from the old Background Slideshow plugin and the old background image.
* The source is the folder when the plugin was installed, enabled, and on, and its folder migrated.
* Otherwise it is the image when one exists. The kept plugin settings give the sequence, the targets, and the layout.
*/
export async function migrateBackground(legacy: LegacyPlugin | undefined, host: BackgroundMigrationHost): Promise<BackgroundSettings> {
const kept = record(legacy?.settings);
// Migrate the folder whenever a grant exists, so that a later choice of Folder brings it back.
let folder = false;
if (typeof kept.grant === "string" && kept.grant) {
try { folder = await host.migrateFolder(); } catch (reason) { console.error("RuneStone could not take the old background folder.", reason); }
}
const slideshow = !!legacy?.installed && legacy.enabled && kept.enabled === true && folder;
const copied = Object.fromEntries(["seconds", "order", "targets", "overlay", "position", "size"].filter(key => key in kept).map(key => [key, kept[key]]));
const value = normalizeBackground({ ...copied, source: slideshow ? "folder" : host.hasImage() ? "image" : "none", paused: false });
await host.write(value);
return value;
}
+21 -6
View File
@@ -2,9 +2,9 @@
// This file is in the main bundle, so it holds only small static data: names, views, and commands.
// 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 type { PluginView } from "../plugins/sdk.ts";
import type { PluginCommand, PluginView } from "../plugins/sdk.ts";
export type FeatureId = "git";
export type FeatureId = "git" | "background";
/** 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 {
@@ -21,9 +21,9 @@ export interface FeatureViewInfo {
export interface FeatureCommandInfo {
id: string;
title: () => string;
icon?: PluginView["icon"];
/** The view that the command opens. */
view: string;
icon?: PluginCommand["icon"];
/** The view that the command opens. Without a view, the command loads the feature and calls `FeatureInstance.run`. */
view?: string;
}
export interface FeatureEntry {
@@ -37,6 +37,8 @@ export interface FeatureEntry {
keywords: string;
/** The switch for a user who never installed the old package. */
defaultOn: boolean;
/** True when the first start gives the switch the state of the old package. False when every user gets `defaultOn`. */
followsPackage: boolean;
views: readonly FeatureViewInfo[];
commands: readonly FeatureCommandInfo[];
}
@@ -46,7 +48,7 @@ export const FEATURES: readonly FeatureEntry[] = [
id: "git", owner: "runestone.git", name: message("Git"),
description: message("Review changes, stage files, commit, and see the commit graph of the workspace repository."),
keywords: "git source control commit stage diff graph branch push pull blame",
defaultOn: true,
defaultOn: true, followsPackage: true,
views: [
{ id: "source-control", title: () => tr("Source control"), placement: "sidebar", icon: "git", navigation: true },
{ id: "diff", title: () => tr("Git diff"), placement: "editor", icon: "git" },
@@ -54,6 +56,19 @@ export const FEATURES: readonly FeatureEntry[] = [
],
commands: [{ id: "graph", title: () => tr("Show Git graph"), icon: "git", view: "graph" }],
},
{
// Background replaces the Background Slideshow plugin and the background image of Appearance. Its settings are in
// Appearance → Background. It loads at the start only when a folder or an image is selected (see `launch.ts`).
id: "background", owner: "runestone.bg-slideshow", name: message("Background"),
description: message("Show a folder of images as a slideshow, or one image, behind the workspace and the boards."),
keywords: "background image wallpaper slideshow folder picture photo overlay blur",
defaultOn: true, followsPackage: false,
views: [],
commands: [
{ id: "next", title: () => tr("Next background image"), icon: "image" },
{ id: "pause", title: () => tr("Pause background"), icon: "pause" },
],
},
];
export function featureEntry(id: FeatureId): FeatureEntry {
+32
View File
@@ -0,0 +1,32 @@
// Launch rules: a feature with a rule starts its instance as soon as the rule wants it, without a view or a command.
// A feature without a rule loads at first need. `syncFeatures` in `src/lib/plugins/external.ts` applies the rules.
import type { FeatureId } from "./catalog.ts";
import { hasBackgroundSource, onBackgroundChange } from "./backgroundSettings.ts";
export interface LaunchRule {
/** True when the feature also runs in browser windows. Other features stay out of them. */
browserWindow: boolean;
/** True when the rule also starts the feature in the settings window. */
settingsWindow: boolean;
/** True when the instance must run now. */
wanted(): boolean;
/** Run `listener` after each change that can change `wanted`. Returns the function that stops it. */
subscribe(listener: () => void): () => void;
}
export const LAUNCH_RULES: Partial<Record<FeatureId, LaunchRule>> = {
// Background starts at the start of a window when a folder or an image is selected, and at once when the user selects one.
// The settings window shows the settings only, so the slideshow does not run there.
background: { browserWindow: true, settingsWindow: false, wanted: () => hasBackgroundSource(), subscribe: onBackgroundChange },
};
/** True when a feature runs in a window of this kind. */
export function runsInWindow(id: FeatureId, window: { browserWindow: boolean }): boolean {
return !window.browserWindow || !!LAUNCH_RULES[id]?.browserWindow;
}
/** True when the launch rule of a feature wants its instance now in a window of this kind. */
export function launchWanted(id: FeatureId, window: { settingsWindow: boolean }): boolean {
const rule = LAUNCH_RULES[id];
return !!rule && (!window.settingsWindow || rule.settingsWindow) && rule.wanted();
}
+1
View File
@@ -6,6 +6,7 @@ import type { FeatureModule } from "./types.ts";
const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
git: () => import("./git/index.ts"),
background: () => import("./background/index.ts"),
};
const modules = new Map<FeatureId, Promise<FeatureModule>>();
+26 -9
View File
@@ -1,9 +1,13 @@
// The first start of a version with a new native feature. The switch takes the state of the old plugin package.
// The first start of a version with a new native feature. The switch takes the state of the old plugin package,
// or the default of the feature when the feature does not follow its package (`followsPackage`).
// `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing.
// The first start also makes the `background` section from the old Background Slideshow settings (`backgroundSettings.ts`).
import { invoke, isTauri } from "@tauri-apps/api/core";
import { readSection, writeSection } from "../settings/store.ts";
import { FEATURES, type FeatureEntry, type FeatureId } from "./catalog.ts";
import { readAppearance } from "../theme/appearance.ts";
import { FEATURES, featureEntry, type FeatureEntry, type FeatureId } from "./catalog.ts";
import { storedSwitches } from "./state.ts";
import { hasImage, migrateBackground, writeBackground, type BackgroundMigrationHost } from "./backgroundSettings.ts";
/** What the host reports about one old plugin package. */
export interface LegacyPlugin {
@@ -14,9 +18,9 @@ export interface LegacyPlugin {
settings: unknown;
}
/** An installed package gives its enabled state. Without a package, the default of the feature applies. */
/** An installed package gives its enabled state. Without a package, or for a feature that does not follow its package, the default applies. */
export function legacySwitch(entry: FeatureEntry, legacy: LegacyPlugin | undefined): boolean {
return legacy?.installed ? legacy.enabled : entry.defaultOn;
return entry.followsPackage && legacy?.installed ? legacy.enabled : entry.defaultOn;
}
export interface MigrationHost {
@@ -31,24 +35,37 @@ const desktopHost: MigrationHost = {
legacy: ids => invoke<LegacyPlugin[]>("features_legacy", { ids }),
};
const desktopBackground: BackgroundMigrationHost = {
missing: () => readSection("background") === undefined,
hasImage: () => hasImage(readAppearance()),
migrateFolder: async () => !!await invoke<string | null>("background_migrate"),
write: writeBackground,
};
/**
* Give each feature without a stored switch the state of its old package. It runs before the first render.
* When the host cannot report the packages, nothing is written, so the next start tries again.
* Give each feature without a stored switch the state of its old package, and make a missing `background` section.
* It runs before the first render. When the host cannot report the packages, nothing is written, so the next start tries again.
*/
export async function migrateFeatures(host: MigrationHost = desktopHost): Promise<FeatureId[]> {
export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground): Promise<FeatureId[]> {
const current = host.read();
const stored = storedSwitches(current);
const missing = FEATURES.filter(entry => stored[entry.id] === undefined);
if (!missing.length) return [];
const backgroundOwner = featureEntry("background").owner;
const backgroundMissing = background.missing();
const owners = [...new Set([...missing.map(entry => entry.owner), ...backgroundMissing ? [backgroundOwner] : []])];
if (!owners.length) return [];
let legacy: LegacyPlugin[];
try { legacy = await host.legacy(missing.map(entry => entry.owner)); }
try { legacy = await host.legacy(owners); }
catch (reason) {
console.error("RuneStone could not read the old plugin packages. The feature defaults apply.", reason);
return [];
}
if (missing.length) {
const next: Record<string, unknown> = current && typeof current === "object" && !Array.isArray(current) ? { ...current as Record<string, unknown> } : {};
for (const entry of missing) next[entry.id] = legacySwitch(entry, legacy.find(item => item.id === entry.owner));
await host.write(next);
}
if (backgroundMissing) await migrateBackground(legacy.find(item => item.id === backgroundOwner), background);
return missing.map(entry => entry.id);
}
+11 -2
View File
@@ -1,6 +1,7 @@
// A feature in the workbench of one window. Its views and commands come from the static catalog, so the
// navigation buttons and the command palette show them without the feature code. The first mount,
// restore, or 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.
import { tr } from "../i18n/index.ts";
import type { Dispose, PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
import type { FeatureEntry } from "./catalog.ts";
@@ -32,7 +33,9 @@ export class FeatureSession {
});
}
for (const info of entry.commands) {
this.commands.set(info.id, { id: info.id, get title() { return info.title(); }, icon: info.icon, run: () => context.openView(info.view) });
const view = info.view;
this.commands.set(info.id, { id: info.id, get title() { return info.title(); }, icon: info.icon,
run: view ? () => context.openView(view) : async () => { await (await this.running()).run?.(info.id); } });
}
}
@@ -62,6 +65,12 @@ export class FeatureSession {
async launch(id: string) { this.context.openView(id); }
/** Load the module and start the instance now, without a view. Later calls use the same instance. */
async start(): Promise<void> { await this.running(); }
/** True after the instance started. */
get started(): boolean { return this.instance !== undefined; }
async run(id: string) {
const command = this.commands.get(id);
if (!command) throw new Error(tr("This command is unavailable."));
+4
View File
@@ -13,6 +13,8 @@ export interface FeatureContext {
/** One running copy of a feature in one window. */
export interface FeatureInstance {
mount(view: string, element: HTMLElement): Dispose | Promise<Dispose>;
/** Run a command of the catalog that has no view. */
run?(command: string): void | Promise<void>;
/** The state of a tab for a transfer to another window. */
saveTabState?(view: string): unknown;
restoreTabState?(view: string, state: unknown): void | Promise<void>;
@@ -23,4 +25,6 @@ export interface FeatureInstance {
/** The module that `loader.ts` imports at first need. */
export interface FeatureModule {
start(context: FeatureContext): FeatureInstance;
/** Show the settings of the feature in `element`, also in a window where the feature does not run. */
mountSettings?(element: HTMLElement): Dispose;
}
+72 -24
View File
@@ -347,12 +347,6 @@ export const messageRows: [string, string, string, string][] = [
"透過をオフにすると背景が不透明になり、合成処理を減らせます。文字とアイコンは常に不透明です。",
"关闭透明效果可使界面不透明并减少合成工作量。文本和图标始终保持不透明。"
],
[
"Background image",
"Image de fond",
"背景画像",
"背景图片"
],
[
"Background image preview",
"Aperçu de l’image de fond",
@@ -461,12 +455,6 @@ export const messageRows: [string, string, string, string][] = [
"実際のサイズ",
"实际大小"
],
[
"Move left to lighten the image or right to darken it.",
"Déplacez vers la gauche pour éclaircir, ou vers la droite pour assombrir.",
"左に動かすと明るく、右に動かすと暗くなります。",
"向左移动可提亮图片,向右移动可调暗。"
],
[
"Background image file",
"Fichier de l’image de fond",
@@ -485,18 +473,6 @@ export const messageRows: [string, string, string, string][] = [
"画像を削除",
"删除图片"
],
[
"Reset background",
"Réinitialiser le fond",
"背景をリセット",
"重置背景"
],
[
"PNG, JPEG, WebP, or GIF, up to 50 MiB. The image applies to new tabs on this device.",
"PNG, JPEG, WebP ou GIF, jusqu’à 50 Mio. L’image s’applique aux nouveaux onglets de cet appareil.",
"PNG、JPEG、WebP、GIF(最大50 MiB)。この端末の新しいタブに適用します。",
"支持 PNG、JPEG、WebP 或 GIF,最大 50 MiB。此图片用于此设备上的新标签页。"
],
[
"Could not read appearance settings.",
"Impossible de lire les paramètres d’apparence.",
@@ -3515,6 +3491,78 @@ export const messageRows: [string, string, string, string][] = [
["No commits yet. Create a commit to start the graph.", "Aucun commit pour l’instant. Créez un commit pour commencer le graphe.", "まだコミットがありません。コミットを作成するとグラフが始まります。", "还没有提交。创建一个提交以开始图表。"],
["Parents: {parents}", "Parents : {parents}", "親: {parents}", "父提交:{parents}"],
["Root commit", "Commit racine", "ルートコミット", "根提交"],
["Add PNG, JPEG, GIF, or WebP images to the folder. Portrait images show in full over a blurred fill.", "Ajoutez des images PNG, JPEG, GIF ou WebP au dossier. Les images en portrait s’affichent en entier sur un fond flou.", "フォルダーに PNG、JPEG、GIF、WebP の画像を追加してください。縦長の画像は、ぼかした背景の上に全体が表示されます。", "将 PNG、JPEG、GIF 或 WebP 图像添加到该文件夹。纵向图像会完整显示在模糊的填充背景上。"],
["All Project Management boards", "Tous les tableaux de Project Management", "Project Management のすべてのボード", "所有 Project Management 看板"],
["Background is off. Turn it on in Settings → Features.", "L’arrière-plan est désactivé. Activez-le dans Paramètres → Fonctionnalités.", "背景はオフです。[設定]→[機能]でオンにしてください。", "背景已关闭。请在“设置”→“功能”中将其打开。"],
["Background source", "Source de l’arrière-plan", "背景のソース", "背景来源"],
["Board: {name}", "Tableau : {name}", "ボード: {name}", "看板:{name}"],
["Cannot create the blurred image.", "Impossible de créer l’image floue.", "ぼかした画像を作成できません。", "无法创建模糊图像。"],
["Choose a folder for a slideshow, or one image.", "Choisissez un dossier pour un diaporama, ou une seule image.", "スライドショーのフォルダー、または 1 枚の画像を選択してください。", "选择一个文件夹作为幻灯片,或选择一张图像。"],
["Choose a folder or an image to show a background.", "Choisissez un dossier ou une image pour afficher un arrière-plan.", "背景を表示するには、フォルダーまたは画像を選択してください。", "选择一个文件夹或一张图像以显示背景。"],
["Choose an image", "Choisir une image", "画像を選択", "选择图像"],
["Choose an image to change its fit, position, and overlay. Portrait images show in full over a blurred fill by default.", "Choisissez une image pour modifier son ajustement, sa position et son voile. Par défaut, les images en portrait s’affichent en entier sur un fond flou.", "画像を選択すると、サイズ調整、位置、オーバーレイを変更できます。縦長の画像は、既定でぼかした背景の上に全体が表示されます。", "选择一张图像以更改其适应方式、位置和叠加层。默认情况下,纵向图像会完整显示在模糊的填充背景上。"],
["Choose folder…", "Choisir un dossier…", "フォルダーを選択…", "选择文件夹…"],
["Choose the background folder", "Choisir le dossier de l’arrière-plan", "背景のフォルダーを選択", "选择背景文件夹"],
["Could not read the workspace boards: {error}", "Impossible de lire les tableaux de l’espace de travail : {error}", "ワークスペースのボードを読み込めませんでした: {error}", "无法读取工作区看板:{error}"],
["Could not save the background settings.", "Impossible d’enregistrer les paramètres de l’arrière-plan.", "背景の設定を保存できませんでした。", "无法保存背景设置。"],
["Default appearance restored.", "Apparence par défaut rétablie.", "既定の外観に戻しました。", "已恢复默认外观。"],
["Default appearance.", "Apparence par défaut.", "既定の外観です。", "默认外观。"],
["File name", "Nom de fichier", "ファイル名", "文件名"],
["Find an image", "Rechercher une image", "画像を検索", "查找图像"],
["Folder", "Dossier", "フォルダー", "文件夹"],
["Full image with blurred fill", "Image entière sur fond flou", "ぼかした背景の上に全体を表示", "完整图像加模糊填充"],
["Image appearance saved.", "Apparence de l’image enregistrée.", "画像の外観を保存しました。", "已保存图像外观。"],
["Image files", "Fichiers image", "画像ファイル", "图像文件"],
["Image fit", "Ajustement de l’image", "画像のサイズ調整", "图像适应方式"],
["Image folder", "Dossier d’images", "画像フォルダー", "图像文件夹"],
["Image order", "Ordre des images", "画像の順序", "图像顺序"],
["Image to change", "Image à modifier", "変更する画像", "要更改的图像"],
["Invalid image settings for {name}.", "Paramètres d’image non valides pour {name}.", "{name} の画像設定が無効です。", "{name} 的图像设置无效。"],
["Move the overlay left to lighten the image or right to darken it.", "Déplacez le voile vers la gauche pour éclaircir l’image ou vers la droite pour l’assombrir.", "オーバーレイを左に動かすと画像が明るくなり、右に動かすと暗くなります。", "向左移动叠加层可使图像变亮,向右移动可使其变暗。"],
["Next background image", "Image d’arrière-plan suivante", "次の背景画像", "下一张背景图像"],
["Next image", "Image suivante", "次の画像", "下一张图像"],
["No folder selected", "Aucun dossier sélectionné", "フォルダーが選択されていません", "未选择文件夹"],
["No matching images.", "Aucune image correspondante.", "一致する画像はありません。", "没有匹配的图像。"],
["No readable images in this folder. Check the image files.", "Aucune image lisible dans ce dossier. Vérifiez les fichiers image.", "このフォルダーに読み込める画像がありません。画像ファイルを確認してください。", "此文件夹中没有可读取的图像。请检查图像文件。"],
["No supported images in this folder. Add PNG, JPEG, GIF, or WebP files.", "Aucune image prise en charge dans ce dossier. Ajoutez des fichiers PNG, JPEG, GIF ou WebP.", "このフォルダーに対応する画像がありません。PNG、JPEG、GIF、WebP のファイルを追加してください。", "此文件夹中没有受支持的图像。请添加 PNG、JPEG、GIF 或 WebP 文件。"],
["None", "Aucune", "なし", "无"],
["Overlay", "Voile", "オーバーレイ", "叠加层"],
["Overlay of this image", "Voile de cette image", "この画像のオーバーレイ", "此图像的叠加层"],
["Overlay percentage of this image", "Pourcentage du voile de cette image", "この画像のオーバーレイの割合", "此图像的叠加层百分比"],
["PNG, JPEG, WebP, or GIF, up to 50 MiB. The image stays on this device.", "PNG, JPEG, WebP ou GIF, jusqu’à 50 Mio. L’image reste sur cet appareil.", "PNG、JPEG、WebP、GIF、最大 50 MiB。画像はこのデバイスに保存されます。", "PNG、JPEG、WebP 或 GIF,最大 50 MiB。图像保存在此设备上。"],
["Pause background", "Mettre l’arrière-plan en pause", "背景を一時停止", "暂停背景"],
["Pause slideshow", "Mettre le diaporama en pause", "スライドショーを一時停止", "暂停幻灯片"],
["Per-image appearance", "Apparence par image", "画像ごとの外観", "每张图像的外观"],
["Position", "Position", "位置", "位置"],
["Position of this image", "Position de cette image", "この画像の位置", "此图像的位置"],
["Random", "Aléatoire", "ランダム", "随机"],
["Reload image settings", "Recharger les paramètres d’image", "画像の設定を再読み込み", "重新加载图像设置"],
["Remove folder", "Retirer le dossier", "フォルダーを解除", "移除文件夹"],
["Reset image appearance", "Réinitialiser l’apparence de l’image", "画像の外観をリセット", "重置图像外观"],
["Resume slideshow", "Reprendre le diaporama", "スライドショーを再開", "继续幻灯片"],
["Save image appearance", "Enregistrer l’apparence de l’image", "画像の外観を保存", "保存图像外观"],
["Saved appearance.", "Apparence enregistrée.", "保存された外観です。", "已保存的外观。"],
["Seconds per image", "Secondes par image", "画像ごとの秒数", "每张图像的秒数"],
["Select where to show the background.", "Sélectionnez où afficher l’arrière-plan.", "背景を表示する場所を選択してください。", "请选择显示背景的位置。"],
["Selected image preview", "Aperçu de l’image sélectionnée", "選択した画像のプレビュー", "所选图像的预览"],
["Selected image preview: {name}", "Aperçu de l’image sélectionnée : {name}", "選択した画像のプレビュー: {name}", "所选图像的预览:{name}"],
["Show a folder of images as a slideshow, or one image, behind the workspace and the boards.", "Affichez un dossier d’images en diaporama, ou une seule image, derrière l’espace de travail et les tableaux.", "ワークスペースとボードの背後に、画像フォルダーをスライドショーとして、または 1 枚の画像を表示します。", "在工作区和看板后方以幻灯片形式显示图像文件夹,或显示一张图像。"],
["Show the background in", "Afficher l’arrière-plan dans", "背景を表示する場所", "在以下位置显示背景"],
["Slideshow", "Diaporama", "スライドショー", "幻灯片"],
["The background changed.", "L’arrière-plan a changé.", "背景が変更されました。", "背景已更改。"],
["The blurred image took too long to load.", "Le chargement de l’image floue a pris trop de temps.", "ぼかした画像の読み込みに時間がかかりすぎました。", "模糊图像加载时间过长。"],
["The image cannot be displayed.", "Impossible d’afficher l’image.", "画像を表示できません。", "无法显示该图像。"],
["The image settings file must use schema 1 and an images object.", "Le fichier des paramètres d’image doit utiliser le schéma 1 et un objet images.", "画像の設定ファイルは、スキーマ 1 と images オブジェクトを使用する必要があります。", "图像设置文件必须使用架构 1 和 images 对象。"],
["The image took too long to load.", "Le chargement de l’image a pris trop de temps.", "画像の読み込みに時間がかかりすぎました。", "图像加载时间过长。"],
["The saved background image is missing. Choose the image again.", "L’image d’arrière-plan enregistrée est introuvable. Choisissez de nouveau l’image.", "保存された背景画像が見つかりません。画像をもう一度選択してください。", "找不到已保存的背景图像。请重新选择图像。"],
["The workspace and new tabs", "L’espace de travail et les nouveaux onglets", "ワークスペースと新しいタブ", "工作区和新标签页"],
["The workspace has no boards.", "L’espace de travail ne contient aucun tableau.", "ワークスペースにボードがありません。", "工作区中没有看板。"],
["Turn on Project Management to show the background on one board.", "Activez Project Management pour afficher l’arrière-plan sur un tableau.", "1 つのボードに背景を表示するには、Project Management をオンにしてください。", "打开 Project Management 才能在某个看板上显示背景。"],
["Unavailable board: {id}", "Tableau indisponible : {id}", "利用できないボード: {id}", "不可用的看板:{id}"],
["{count} image.", "{count} image.", "{count} 枚の画像。", "{count} 张图像。"],
["{count} images.", "{count} images.", "{count} 枚の画像。", "{count} 张图像。"],
["{count} matches. Type more of the name to see other images.", "{count} résultats. Saisissez une plus grande partie du nom pour voir d’autres images.", "{count} 件一致しました。ほかの画像を表示するには、名前をさらに入力してください。", "{count} 个匹配项。请输入更多名称以查看其他图像。"],
["{name}: skipped {count} unreadable images.", "{name} : {count} images illisibles ignorées.", "{name}: 読み込めない {count} 枚の画像をスキップしました。", "{name}:已跳过 {count} 张无法读取的图像。"],
];
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
+3
View File
@@ -88,6 +88,8 @@
</header>
{#if message}<p class="error" role="alert">{message}</p>{/if}
<main class="pages">
<!-- A blank browser tab shows the background of the Background feature (src/lib/theme/background.css). -->
<div class="workarea-background" aria-hidden="true"></div>
{#each $pluginEditors as view (view.key)}
{@const position = bounds[view.key]}
<!-- svelte-ignore a11y_no_static_element_interactions (Input selects its browser pane.) -->
@@ -114,6 +116,7 @@
.header :global(.tabs) { flex: 0 1 auto; min-width: 80px; height: 100%; border-bottom: 0; }
.window-drag-space { flex: 1; min-width: 120px; align-self: stretch; }
.pages { position: relative; flex: 1; min-height: 0; overflow: hidden; }
.workarea-background { position: absolute; inset: 0; }
.pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow: hidden; }
.pane.inactive { display: none; }
.pane.split { border: 1px solid var(--rs-border); }
+1 -27
View File
@@ -1469,37 +1469,11 @@
background: var(--rs-bg);
}
/* The layer styles are in src/lib/theme/background.css. */
.workarea-background {
position: absolute;
inset: var(--rs-titlebar-height) 0 22px;
z-index: -1;
pointer-events: none;
background-color: var(--rs-new-tab-bg, var(--rs-bg));
background-image: var(--rs-background-image, var(--rs-new-tab-image, none));
background-size: var(--rs-background-layer-sizes, 100% 100%, var(--rs-background-size, cover));
background-position: var(--rs-background-layer-positions, center, var(--rs-background-position, center));
background-repeat: no-repeat;
}
.workarea-background::before,
.workarea-background::after {
content: '';
position: absolute;
inset: 0;
pointer-events: none;
background-repeat: no-repeat;
}
.workarea-background::before {
background-image: var(--rs-background-previous-image, none);
background-size: var(--rs-background-previous-layer-sizes, 100% 100%, var(--rs-background-previous-size, cover));
background-position: var(--rs-background-previous-layer-positions, center, var(--rs-background-previous-position, center));
}
.workarea-background::after {
background-image: var(--rs-background-transition-image, none);
background-size: var(--rs-background-layer-sizes, 100% 100%, var(--rs-background-size, cover));
background-position: var(--rs-background-layer-positions, center, var(--rs-background-position, center));
}
.shell.left-open {
-3
View File
@@ -1,5 +1,2 @@
// The public background types are in the plugin SDK (packages/plugin-sdk/src/backgrounds.ts).
import type { BackgroundApi } from "./sdk.ts";
export type { BackgroundApi, BackgroundFrame } from "./sdk.ts";
export type BackgroundFiles = Pick<BackgroundApi, 'chooseFolder' | 'defaultFolder' | 'list' | 'read' | 'readImageSettings' | 'writeImageSettings'>;
+34 -22
View File
@@ -28,11 +28,16 @@ function checkTarget(target: string) {
}
}
/** Each window retains temporary frames without changing saved appearance settings. */
/**
* The background frames of one window, for each target. The Background feature (`src/lib/features/background/`) and
* plugins set them. The `app` frame sets the custom properties of the body that the workarea background reads.
*/
export class BackgroundHub {
private frames = new Map<string, Map<symbol, BackgroundFrame>>();
private listeners = new Set<(target: string) => void>();
private restore?: () => void;
/** The values that `applyApp` set last. A new frame changes only the properties with a new value. */
private applied = new Map<string, string>();
private body: () => HTMLElement | undefined;
constructor(body: () => HTMLElement | undefined = () => typeof document === 'undefined' ? undefined : document.body) {
@@ -82,9 +87,14 @@ export class BackgroundHub {
private applyApp() {
const frame = this.get('app');
if (!frame) { this.restore?.(); this.restore = undefined; return; }
if (!frame) { this.restore?.(); this.restore = undefined; this.applied.clear(); return; }
const body = this.body();
if (!body) return;
const put = (key: typeof properties[number], value: string) => {
if (this.applied.get(key) === value) return;
this.applied.set(key, value);
body.style.setProperty(key, value);
};
if (!this.restore) {
const previous = properties.map(key => [key, body.style.getPropertyValue(key), body.style.getPropertyPriority(key)]);
this.restore = () => {
@@ -95,28 +105,30 @@ export class BackgroundHub {
};
}
const { overlay, image: currentImage, sizes, positions: layerPositions } = image(frame);
body.style.setProperty('--rs-background-overlay', overlay);
body.style.setProperty('--rs-background-image', currentImage);
body.style.setProperty('--rs-background-position', frame.position);
body.style.setProperty('--rs-background-size', frame.size);
body.style.setProperty('--rs-background-layer-sizes', sizes);
body.style.setProperty('--rs-background-layer-positions', layerPositions);
body.style.setProperty('--rs-background-previous-layer-sizes', frame.previous ? image(frame.previous).sizes : sizes);
body.style.setProperty('--rs-background-previous-layer-positions', frame.previous ? image(frame.previous).positions : layerPositions);
body.style.setProperty('--rs-workarea-sidebar-bg', 'var(--rs-image-sidebar-bg)');
body.style.setProperty('--rs-workarea-editor-bg', 'var(--rs-image-editor-bg)');
body.style.setProperty('--rs-workarea-surface-opacity', 'var(--rs-surface-opacity, 82%)');
body.style.setProperty('--rs-workarea-plugin-bg', 'var(--rs-transparent-plugin-bg, transparent)');
body.style.setProperty('--rs-menu-bg', 'var(--rs-image-menu-bg)');
body.style.setProperty('--rs-menu-active-bg', 'var(--rs-image-menu-active-bg)');
body.style.setProperty('--rs-menu-backdrop', 'var(--rs-image-menu-backdrop)');
body.style.setProperty('--rs-background-transition-image', frame.previous ? currentImage : 'none');
body.style.setProperty('--rs-background-previous-image', frame.previous ? image(frame.previous).image : 'none');
body.style.setProperty('--rs-background-previous-position', frame.previous?.position ?? frame.position);
body.style.setProperty('--rs-background-previous-size', frame.previous?.size ?? frame.size);
const previous = frame.previous ? image(frame.previous) : undefined;
put('--rs-background-overlay', overlay);
put('--rs-background-image', currentImage);
put('--rs-background-position', frame.position);
put('--rs-background-size', frame.size);
put('--rs-background-layer-sizes', sizes);
put('--rs-background-layer-positions', layerPositions);
put('--rs-background-previous-layer-sizes', previous ? previous.sizes : sizes);
put('--rs-background-previous-layer-positions', previous ? previous.positions : layerPositions);
put('--rs-workarea-sidebar-bg', 'var(--rs-image-sidebar-bg)');
put('--rs-workarea-editor-bg', 'var(--rs-image-editor-bg)');
put('--rs-workarea-surface-opacity', 'var(--rs-surface-opacity, 82%)');
put('--rs-workarea-plugin-bg', 'var(--rs-transparent-plugin-bg, transparent)');
put('--rs-menu-bg', 'var(--rs-image-menu-bg)');
put('--rs-menu-active-bg', 'var(--rs-image-menu-active-bg)');
put('--rs-menu-backdrop', 'var(--rs-image-menu-backdrop)');
put('--rs-background-transition-image', previous ? currentImage : 'none');
put('--rs-background-previous-image', previous ? previous.image : 'none');
put('--rs-background-previous-position', frame.previous?.position ?? frame.position);
put('--rs-background-previous-size', frame.previous?.size ?? frame.size);
if (typeof document !== 'undefined') {
for (const element of body.querySelectorAll('.workarea-background')) {
for (const animation of element.getAnimations()) animation.cancel();
// The fade runs on `::after`. Only `subtree` returns the animations of pseudo-elements.
for (const animation of element.getAnimations({ subtree: true })) animation.cancel();
if (frame.previous && frame.transitionMs && !window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
element.animate([{ opacity: 0 }, { opacity: 1 }], { duration: frame.transitionMs, easing: 'ease-in-out', pseudoElement: '::after' });
}
+23 -12
View File
@@ -13,6 +13,7 @@ import { locale } from "../i18n";
import { FEATURES, type FeatureEntry } from "../features/catalog";
import { FeatureSession } from "../features/session";
import { featureSwitches, type FeatureSwitches } from "../features/state";
import { LAUNCH_RULES, launchWanted, runsInWindow } from "../features/launch";
import type { FeatureContext } from "../features/types";
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
@@ -104,6 +105,7 @@ let queue: Promise<void> = Promise.resolve();
export function waitForPluginStartup() { return queue; }
let started = false;
let browserWindow = false;
let settingsWindow = false;
let generation = 0;
let documentOpenVersion = 0;
export function cancelPluginDocumentOpen() { documentOpenVersion++; }
@@ -272,14 +274,7 @@ async function activate(row: InstalledPlugin, builtin?: PluginModule) {
completionTransport,
pty: ptyTransport,
files: filesTransport(id),
backgrounds: {
chooseFolder: () => invoke<string | null>('backgrounds_choose_folder', { id }),
defaultFolder: () => invoke<string>('backgrounds_default_folder', { id }),
list: folder => invoke<{ name: string }[]>('backgrounds_list', { id, folder }),
read: async (folder, name) => Uint8Array.from(atob(await invoke<string>('backgrounds_read', { id, folder, name })), character => character.charCodeAt(0)),
readImageSettings: folder => invoke<string | null>('backgrounds_read_image_settings', { id, folder }),
writeImageSettings: (folder, contents, expected) => invoke<void>('backgrounds_write_image_settings', { id, folder, contents, expected }),
},
backgrounds: true,
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
workspace: {
list: path => workspaceList(path ?? ""), read: workspaceRead,
@@ -387,23 +382,38 @@ function featureContext(entry: FeatureEntry): FeatureContext {
onWorkspaceChange: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
};
}
/** Start each native feature that is on, and stop each one that is off. The feature code loads later, at first need. */
/**
* Start each native feature that is on, and stop each one that is off. The feature code loads later, at first need,
* or at once when the launch rule of the feature wants it (`src/lib/features/launch.ts`).
*/
function syncFeatures(switches: FeatureSwitches) {
queue = queue.then(async () => {
for (const entry of FEATURES) {
if (!runsInWindow(entry.id, { browserWindow })) continue;
const loaded = sessions.get(entry.owner);
if (switches[entry.id] && !loaded) {
sessions.set(entry.owner, { hash: "feature", session: new FeatureSession(entry, featureContext(entry)) });
publish();
} else if (!switches[entry.id] && loaded?.hash === "feature") await stop(entry.owner);
}
launchFeatures();
}).catch(reason => pluginServiceError.set(String(reason)));
}
/** A browser window starts only the built-in modules for browser windows, no native feature, and no installed plugin. */
/** Start the instance of each running feature whose launch rule wants it now. */
function launchFeatures() {
for (const entry of FEATURES) {
const loaded = sessions.get(entry.owner);
if (loaded?.hash !== "feature" || !launchWanted(entry.id, { settingsWindow })) continue;
const session = loaded.session as FeatureSession;
if (!session.started) void session.start().catch(reason => report(entry.owner, reason));
}
}
/** A browser window starts the built-in modules for browser windows and the features with a browser window rule. It loads no installed plugin. */
export function startExternalPlugins(options: { browserWindow?: boolean } = {}): () => void {
if (!isTauri() || started) return () => {};
started = true;
browserWindow = options.browserWindow === true;
settingsWindow = new URLSearchParams(location.search).get("settingsWindow") === "true";
let disposed = false;
let off: (() => void) | undefined;
void listen("plugins-changed", () => { void refreshPlugins(); }).then(unlisten => { if (disposed) unlisten(); else off = unlisten; }).catch(reason => pluginServiceError.set(String(reason)));
@@ -415,7 +425,8 @@ export function startExternalPlugins(options: { browserWindow?: boolean } = {}):
await activate({ manifest: { schemaVersion: 1, id: builtIn.id, name: builtIn.name, author: "RuneStone", description: `Built-in ${builtIn.name.toLowerCase()}`, version: "0.0.0", apiVersion: 1, entry: "builtin", access: "full-app" }, hash: "builtin", enabled: true, installedAt: null, path: "", error: null, removal: false }, module);
}).catch(reason => report(builtIn.id, reason));
}
const offFeatures = browserWindow ? undefined : featureSwitches.subscribe(syncFeatures);
const offFeatures = featureSwitches.subscribe(syncFeatures);
const offLaunch = Object.values(LAUNCH_RULES).map(rule => rule.subscribe(launchFeatures));
// Feature titles follow the interface language.
const offLocale = locale.subscribe(() => publish());
void refreshPlugins();
@@ -423,7 +434,7 @@ export function startExternalPlugins(options: { browserWindow?: boolean } = {}):
const focus = () => { void refreshPlugins(); };
window.addEventListener("focus", focus);
return () => {
disposed = true; started = false; generation++; off?.(); offFeatures?.(); offLocale(); window.removeEventListener("focus", focus);
disposed = true; started = false; generation++; off?.(); offFeatures(); offLaunch.forEach(stop => stop()); offLocale(); window.removeEventListener("focus", focus);
for (const id of [...sessions.keys()]) void stop(id).catch(reason => report(id, reason));
};
}
+2 -8
View File
@@ -4,12 +4,12 @@ import { registerCompletionInput } from "../completion/input.ts";
import { showActionMenu } from "../ui/managedActionMenu.ts";
import { backgroundHub } from "./backgrounds.ts";
import { serviceHub as defaultServiceHub, type ServiceHub } from "./services.ts";
import type { BackgroundFiles } from "./backgroundContracts.ts";
import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext, PtyApi, PtyOpenOptions, PtySession, PtyTransport } from "./sdk.ts";
/** The host services that a session gives to its plugin. The host binds them to the plugin ID. */
export type SessionServices = Pick<PluginApi, "workspace" | "settings" | "assets"> & {
openFile?: PluginApi["openFile"]; backgrounds?: BackgroundFiles;
/** True gives the plugin `api.backgrounds`: the background frames of each target. */
openFile?: PluginApi["openFile"]; backgrounds?: boolean;
completionTransport?: NonNullable<PluginApi["completion"]>["transport"];
pty?: PtyTransport; files?: FilesTransport; serviceHub?: ServiceHub;
};
@@ -70,12 +70,6 @@ export class ExternalSession {
services: this.servicesApi(this.services.serviceHub ?? defaultServiceHub),
...(this.services.backgrounds ? { backgrounds: {
version: 1 as const,
chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()),
...(this.services.backgrounds.defaultFolder ? { defaultFolder: () => this.backgroundRequest(() => this.services.backgrounds!.defaultFolder!()) } : {}),
list: (folder: string) => this.backgroundRequest(() => this.services.backgrounds!.list(folder)),
read: (folder: string, name: string) => this.backgroundRequest(() => this.services.backgrounds!.read(folder, name)),
...(this.services.backgrounds.readImageSettings ? { readImageSettings: (folder: string) => this.backgroundRequest(() => this.services.backgrounds!.readImageSettings!(folder)) } : {}),
...(this.services.backgrounds.writeImageSettings ? { writeImageSettings: (folder: string, contents: string, expected: string | null) => this.backgroundRequest(() => this.services.backgrounds!.writeImageSettings!(folder, contents, expected)) } : {}),
set: (target: string, frame: import('./backgroundContracts.ts').BackgroundFrame | null) => { this.check(); backgroundHub.set(this.backgroundOwner, target, frame); },
get: (target: string) => { this.check(); return backgroundHub.get(target); },
subscribe: (listener: (target: string) => void) => {
+2 -1
View File
@@ -10,7 +10,7 @@
import { invoke, isTauri } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language', 'features'] as const;
export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language', 'features', 'background'] as const;
export type SettingsSection = typeof SETTINGS_SECTIONS[number];
export type SettingsSections = Partial<Record<SettingsSection, unknown>>;
@@ -22,6 +22,7 @@ export const LEGACY_KEYS: Readonly<Record<SettingsSection, string>> = {
customThemesLegacy: 'runestone.custom-themes.legacy',
language: 'runestone.language',
features: 'runestone.features',
background: 'runestone.background',
};
/** Make the first settings file from the old localStorage values. `read` returns the value of a key, or null. */
+27 -70
View File
@@ -1,43 +1,42 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onMount, onDestroy } from 'svelte';
import { onMount } from 'svelte';
import { invoke, isTauri } from '@tauri-apps/api/core';
import { customThemes, installTheme, parseCustomTheme, removeTheme, type CustomTheme } from './customThemes';
import IconButton from '$lib/ui/IconButton.svelte';
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { saveBackgroundImage, removeBackgroundImage } from './backgroundImages';
import { onSettingsChange } from '$lib/settings/store';
import { featureSwitches } from '$lib/features/state';
import { loadFeature } from '$lib/features/loader';
import ThemePicker from './ThemePicker.svelte';
import { requestThemeEditor } from './themeEditorRequest';
import { DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, themeNotice, BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
import { DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, themeNotice, readAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
let appearance = $state<Appearance>({ ...DEFAULT_APPEARANCE });
let error = $state('');
let status = $state('');
let exporting = $state(false);
let backgroundInput: HTMLInputElement;
let backgroundRevision = 0;
let backgroundHost = $state<HTMLElement>();
let backgroundError = $state('');
let installed = $state<CustomTheme[]>([]);
let themeInput: HTMLInputElement;
let closePicker = () => {};
const themes = $derived([...BUILTIN_THEMES, ...installed.map(theme => ({ id: `custom:${theme.id}` as ThemeName, name: theme.name }))].flatMap(theme =>
themeModes(theme.id).map(mode => ({
theme: theme.id, mode, name: themeModes(theme.id).length === 1 ? theme.name : `${theme.name} ${mode === 'light' ? $t('Light') : $t('Dark')}`,
}))));
const notice = $derived(themeNotice(appearance.theme));
onDestroy(() => closePicker());
const positionLabels = $derived([$t('Center'), $t('Top left'), $t('Top center'), $t('Top right'), $t('Center left'), $t('Center right'), $t('Bottom left'), $t('Bottom center'), $t('Bottom right')]);
const sizeLabels = $derived([$t('Fill'), $t('Fit'), $t('Actual size')]);
function backgroundPicker(event: MouseEvent, field: 'position' | 'size') {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
const values = field === 'position' ? BACKGROUND_POSITIONS : BACKGROUND_SIZES;
const labels = field === 'position' ? positionLabels : sizeLabels;
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === 'position' ? $t('Image position') : $t('Image size'), parent: anchor.closest('dialog') ?? undefined,
items: values.map((value, index) => ({ label: labels[index], radio: true, checked: value === appearance.newTabBackground?.[field],
run: () => change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, [field]: value } }) })) }).close;
}
// The settings of Background come from the feature module. The module loads only while Background is on.
$effect(() => {
const host = backgroundHost;
if (!host || !$featureSwitches.background) return;
let dispose: (() => void) | undefined;
let stopped = false;
backgroundError = '';
loadFeature('background').then(module => {
if (stopped || !module.mountSettings) return;
dispose = module.mountSettings(host);
}, reason => { if (!stopped) backgroundError = $t('{name} could not load: {error}', { name: $t('Background'), error: String(reason) }); });
return () => { stopped = true; dispose?.(); };
});
onMount(() => {
const read = () => { try { installed = customThemes(); appearance = readAppearance(); } catch { error = $t('Could not read appearance settings.'); } };
read();
@@ -51,18 +50,6 @@
}
catch { error = $t('Could not save appearance settings.'); return false; }
}
function changeOverlay(input: HTMLInputElement) {
const percent = input.valueAsNumber;
if (!Number.isFinite(percent)) return;
change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, overlay: Math.round(Math.max(-100, Math.min(100, percent))) / 100 } });
}
async function removeBackground() {
backgroundRevision++;
const old = appearance.newTabBackground?.imageId;
if (change({ ...appearance, newTabBackground: undefined }) && old) {
try { await removeBackgroundImage(old); } catch { error = $t('Could not remove the saved image from storage.'); }
}
}
async function importTheme(file?: File) {
if (!file) return;
try {
@@ -73,20 +60,6 @@
} catch (reason) { error = String(reason); }
finally { themeInput.value = ''; }
}
async function importBackground(file?: File) {
if (!file) return;
const revision = ++backgroundRevision;
try {
if (!['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(file.type)) throw new Error($t('Choose a PNG, JPEG, WebP, or GIF image.'));
const imageId = await saveBackgroundImage(file);
if (revision !== backgroundRevision) { await removeBackgroundImage(imageId); return; }
const old = appearance.newTabBackground?.imageId;
if (change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, image: undefined, imageId, overlay: appearance.newTabBackground?.overlay ?? 0 } })) {
if (old) await removeBackgroundImage(old);
} else await removeBackgroundImage(imageId);
} catch (reason) { if (revision === backgroundRevision) error = String(reason); }
finally { if (revision === backgroundRevision) backgroundInput.value = ''; }
}
async function exportTemplate() {
if (exporting) return;
exporting = true; error = ''; status = '';
@@ -132,23 +105,13 @@
<div class="setting-row"><label for="surface-transparency">{$t("Transparency amount")}</label><div class="overlay-controls"><input id="surface-transparency" type="range" min="0" max="100" step="1" disabled={appearance.transparency?.enabled === false} value={appearance.transparency?.amount ?? 18} oninput={event => change({ ...appearance, transparency: { enabled: true, amount: event.currentTarget.valueAsNumber } })} /><output for="surface-transparency">{appearance.transparency?.amount ?? 18}%</output></div></div>
</div>
<p>{$t("Turn off transparency to use opaque surfaces and reduce compositing work. Text and icons remain opaque.")}</p>
<h3>{$t("Background image")}</h3>
<div class="background-preview" aria-label={$t("Background image preview")}><span>{$t("Background")}</span></div>
{#if appearance.newTabBackground}
<div class="card">
<div class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("Image position")} aria-haspopup="menu" onclick={event => backgroundPicker(event, 'position')}>{positionLabels[BACKGROUND_POSITIONS.indexOf(appearance.newTabBackground.position ?? 'center')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Image size")}</span><button class="picker" aria-label={$t("Image size")} aria-haspopup="menu" onclick={event => backgroundPicker(event, 'size')}>{sizeLabels[BACKGROUND_SIZES.indexOf(appearance.newTabBackground.size ?? 'cover')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Image overlay")}</span><div class="overlay-controls"><input type="range" aria-label={$t("Image overlay")} min="-100" max="100" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} /><label class="overlay-value"><input type="number" aria-label={$t("Image overlay percentage")} min="-100" max="100" step="1" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((appearance.newTabBackground?.overlay ?? 0) * 100)); }} /><span>%</span></label></div></div>
</div>
<p>{$t("Move left to lighten the image or right to darken it.")}</p>
<h3>{$t("Background")}</h3>
{#if $featureSwitches.background}
<div class="background-host" bind:this={backgroundHost}></div>
{#if backgroundError}<p role="alert">{backgroundError}</p>{/if}
{:else}
<p>{$t("Background is off. Turn it on in Settings → Features.")}</p>
{/if}
<div class="theme-actions">
<input bind:this={backgroundInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importBackground(event.currentTarget.files?.[0])} />
<button onclick={() => backgroundInput.click()}>{$t("Choose image…")}</button>
{#if appearance.newTabBackground}<button onclick={() => void removeBackground()}>{$t("Remove image")}</button>{/if}
<button disabled={!appearance.newTabBackground} onclick={() => void removeBackground()}>{$t("Reset background")}</button>
</div>
<p>{$t("PNG, JPEG, WebP, or GIF, up to 50 MiB. The image applies to new tabs on this device.")}</p>
{#if status}<p role="status">{status}</p>{/if}
{#if error}<p role="alert">{error}</p>{/if}
<style>
@@ -156,10 +119,6 @@
p{color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.5}
.card{padding:0 var(--rs-settings-row-padding);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated)}
label,.setting-row{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:var(--rs-settings-gap);padding:var(--rs-settings-row-padding) 0}
.setting-row+.setting-row{border-top:1px solid var(--rs-border)}
.picker{display:flex;align-items:center;gap:8px;min-height:var(--rs-settings-control-height);max-width:100%;padding:4px 8px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
.picker :global(svg){width:14px;height:14px;flex-shrink:0}
.picker:focus-visible{outline:2px solid var(--rs-focus);outline-offset:2px}
.theme-preview{display:flex;gap:var(--rs-settings-gap);margin-top:var(--rs-settings-gap);padding:var(--rs-settings-row-padding);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);min-height:100px}
.preview-sidebar{display:flex;flex-direction:column;gap:var(--rs-settings-gap);width:22%;padding:var(--rs-settings-row-padding);background:var(--rs-bg-elevated);border-radius:var(--rs-control-radius)}
.preview-sidebar span{height:6px;background:var(--rs-text-dim);opacity:.5;border-radius:var(--rs-control-radius)}
@@ -187,13 +146,11 @@
.overlay-controls input[type=range]:disabled{cursor:default}
.overlay-controls input[type=range]:disabled::-webkit-slider-thumb{background:var(--rs-text-dim)}
.overlay-controls input[type=range]:disabled::-moz-range-thumb{background:var(--rs-text-dim)}
.overlay-value{padding:0;gap:4px;flex-wrap:nowrap}
.overlay-value input{width:64px;min-height:var(--rs-settings-control-height);box-sizing:border-box;padding:4px 6px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);font:inherit}
.overlay-value input:focus-visible{outline:2px solid var(--rs-focus);outline-offset:2px}
[role=alert]{color:var(--rs-error)}
.theme-actions{display:flex;gap:var(--rs-settings-gap);flex-wrap:wrap;margin-top:var(--rs-settings-gap)}
.theme-actions button{display:inline-flex;align-items:center;gap:6px;min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);padding:4px 8px}
.theme-actions button :global(svg){width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:2}
h3{margin-top:var(--rs-settings-section-gap);font-size:14px}.background-preview{height:120px;background-color:var(--rs-bg);background-image:var(--rs-background-image,none);background-size:100% 100%,var(--rs-background-size,cover);background-position:center,var(--rs-background-position,center);background-repeat:no-repeat;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);display:grid;place-items:center;margin-bottom:var(--rs-settings-gap)}.background-preview span{padding:8px 14px;background:var(--rs-bg-elevated);border-radius:var(--rs-control-radius)}
h3{margin-top:var(--rs-settings-section-gap);font-size:14px}
.background-host{min-width:0}
</style>
+5 -61
View File
@@ -1,5 +1,4 @@
import { customThemes, FONT_ROLES, type ThemeFonts, type CustomTheme } from './customThemes.ts';
import { readBackgroundImage } from './backgroundImages.ts';
import { readSection, writeSection } from '../settings/store.ts';
import { BUILTIN_THEMES as THEME_DATA, DEFAULT_FONTS, DEFAULT_THEME, LEGACY_THEME_IDS, builtinTheme, type BuiltinThemeId } from './themes/index.ts';
import { ROLES, resolveColors, type Mode, type ResolvedColors } from './roles.ts';
@@ -90,70 +89,15 @@ export function applyTransparency(value: Appearance['transparency'], root: HTMLE
root.style.setProperty('--rs-hover-surface-opacity', `${100 - amount * 8 / 18}%`);
root.style.setProperty('--rs-transparent-plugin-bg', 'transparent');
}
const backgroundUrls = new WeakMap<HTMLElement, { image: string; url: string }>();
const backgroundRequests = new WeakMap<HTMLElement, string | undefined>();
function applyBackgroundSurfaces(root: HTMLElement, hasImage: boolean) {
root.style.setProperty('--rs-workarea-sidebar-bg', hasImage ? 'var(--rs-image-sidebar-bg)' : 'var(--rs-bg-elevated)');
root.style.setProperty('--rs-workarea-editor-bg', hasImage ? 'var(--rs-image-editor-bg)' : 'var(--rs-bg)');
root.style.setProperty('--rs-workarea-surface-opacity', hasImage ? 'var(--rs-surface-opacity)' : '100%');
root.style.setProperty('--rs-workarea-plugin-bg', hasImage ? 'var(--rs-transparent-plugin-bg)' : 'var(--rs-bg)');
root.style.setProperty('--rs-menu-bg', hasImage ? 'var(--rs-image-menu-bg)' : 'var(--rs-bg-elevated)');
root.style.setProperty('--rs-menu-active-bg', hasImage ? 'var(--rs-image-menu-active-bg)' : 'var(--rs-bg-active)');
root.style.setProperty('--rs-menu-backdrop', hasImage ? 'var(--rs-image-menu-backdrop)' : 'none');
}
async function applySavedBackground(root: HTMLElement, background?: Appearance['newTabBackground']) {
const id = background?.imageId;
backgroundRequests.set(root, id);
if (!id) { applyBackgroundImage(root, background?.image); return; }
const previous = backgroundUrls.get(root);
if (previous?.image === id) { root.style.setProperty('--rs-new-tab-image', `url("${previous.url}")`); applyBackgroundSurfaces(root, true); return; }
applyBackgroundImage(root);
try {
const file = await readBackgroundImage(id);
if (!file || backgroundRequests.get(root) !== id) return;
const url = URL.createObjectURL(file);
const old = backgroundUrls.get(root);
backgroundUrls.set(root, { image: id, url });
root.style.setProperty('--rs-new-tab-image', `url("${url}")`);
applyBackgroundSurfaces(root, true);
if (old) URL.revokeObjectURL(old.url);
} catch { /* Keep the theme usable if image storage is unavailable. */ }
}
function applyBackgroundImage(root: HTMLElement, image?: string) {
const previous = backgroundUrls.get(root);
if (image && previous?.image === image) {
root.style.setProperty('--rs-new-tab-image', `url("${previous.url}")`);
applyBackgroundSurfaces(root, true);
return;
}
let url: string | undefined;
if (image) {
try {
const [header, data] = image.split(',');
const bytes = Uint8Array.from(atob(data), character => character.charCodeAt(0));
url = URL.createObjectURL(new Blob([bytes], { type: header.slice(5, header.indexOf(';')) }));
} catch { /* Invalid saved image data must not stop the theme update. */ }
}
// Large data URLs exceed Chromium's CSS variable limit. Keep only a short blob URL in CSS.
root.style.setProperty('--rs-new-tab-image', url ? `url("${url}")` : 'none');
applyBackgroundSurfaces(root, !!url);
if (image && url) backgroundUrls.set(root, { image, url });
else backgroundUrls.delete(root);
if (previous) URL.revokeObjectURL(previous.url);
}
/**
* Apply the theme, the fonts, and the transparency. The Background feature (`src/lib/features/background/`) shows the
* saved image of `newTabBackground` through the background frames, so this function does not draw it.
*/
export function applyAppearance(value: Appearance, root = document.documentElement) {
const normalized = normalizeAppearance(value);
const { theme, newTabBackground } = normalized;
const { theme } = normalized;
const { mode, colors, fonts } = resolveTheme(theme, normalized.mode);
applyTransparency(normalized.transparency, root);
root.style.setProperty('--rs-new-tab-bg', 'var(--rs-bg)');
const overlay = newTabBackground?.overlay ?? 0;
const shade = overlay < 0 ? '255,255,255' : '0,0,0';
root.style.setProperty('--rs-background-overlay', `linear-gradient(rgba(${shade},${Math.abs(overlay)}),rgba(${shade},${Math.abs(overlay)}))`);
root.style.setProperty('--rs-background-image', newTabBackground ? 'var(--rs-background-overlay), var(--rs-new-tab-image, none)' : 'none');
root.style.setProperty('--rs-background-position', newTabBackground?.position ?? 'center');
root.style.setProperty('--rs-background-size', newTabBackground?.size ?? 'cover');
void applySavedBackground(root, newTabBackground);
root.dataset.theme = mode;
root.dataset.palette = theme;
root.style.colorScheme = mode;
+34
View File
@@ -0,0 +1,34 @@
/*
* The background layer behind the workarea of the workbench and behind a blank browser tab of a browser window.
* `backgroundHub.applyApp` (src/lib/plugins/backgrounds.ts) sets the custom properties on the body and fades `::after`.
* Each window places the layer with its own `position` and `inset`.
*/
.workarea-background {
pointer-events: none;
background-color: var(--rs-bg);
background-image: var(--rs-background-image, none);
background-size: var(--rs-background-layer-sizes, 100% 100%, var(--rs-background-size, cover));
background-position: var(--rs-background-layer-positions, center, var(--rs-background-position, center));
background-repeat: no-repeat;
}
.workarea-background::before,
.workarea-background::after {
content: '';
position: absolute;
inset: 0;
pointer-events: none;
background-repeat: no-repeat;
}
.workarea-background::before {
background-image: var(--rs-background-previous-image, none);
background-size: var(--rs-background-previous-layer-sizes, 100% 100%, var(--rs-background-previous-size, cover));
background-position: var(--rs-background-previous-layer-positions, center, var(--rs-background-previous-position, center));
}
.workarea-background::after {
background-image: var(--rs-background-transition-image, none);
background-size: var(--rs-background-layer-sizes, 100% 100%, var(--rs-background-size, cover));
background-position: var(--rs-background-layer-positions, center, var(--rs-background-position, center));
}
+16 -1
View File
@@ -88,6 +88,18 @@ export async function chooseView(scope, name) {
return scope.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name, exact: true }).click();
}
/**
* Select the image source of Background, so that the saved image of `appearance.newTabBackground` shows
* (src/lib/features/backgroundSettings.ts). Call it after the test saves an image. It waits until the frame is on the body.
*/
export async function showSavedImage(page) {
await page.evaluate(async () => {
const { readBackground, writeBackground } = await import("/src/lib/features/backgroundSettings.ts");
await writeBackground({ ...readBackground(), source: "image" });
});
await page.waitForFunction(() => document.body.style.getPropertyValue("--rs-background-image").includes("blob:"));
}
/**
* Mock the Tauri IPC layer before the app loads. The mock handles the event plugin.
*
@@ -195,7 +207,7 @@ function installMock(options, commands) {
if (target !== pageId) channel.postMessage({ event, payload, target });
};
const SETTINGS_FILE = "runestone.smoke.settings-file", TRANSFERS = "runestone.smoke.tab-transfers";
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features"];
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background"];
const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } };
const settingsFile = () => readJson(SETTINGS_FILE, null);
const snapshot = () => {
@@ -227,6 +239,9 @@ function installMock(options, commands) {
features_legacy: () => [],
// The editor asks for the Git line of the cursor while the Git feature is on. Tests of Git replace it.
git_blame: () => null,
// src-tauri/src/backgrounds.rs: the host has no background folder. Tests of the Background folder replace these.
background_folder: () => null,
background_migrate: () => null,
settings_migrate: ({ sections }) => {
if (!settingsFile()) localStorage.setItem(SETTINGS_FILE, JSON.stringify({ schema: 1, revision: 1, ...sections }));
return snapshot();
@@ -1,7 +1,8 @@
// Workarea backgrounds in both themes: splash, writer, reader, split, Source, narrow layouts, fades, reduced motion, and removal.
// The saved image shows through the Background feature (src/lib/features/background/). The test also sets its own frames.
import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
import { chooseView, mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
import { chooseView, mockTauri, openPage, outputDir, runSmoke, showSavedImage, smokeUrl } from '../_harness/index.mjs';
const viewport = { width: 1280, height: 820 };
@@ -43,6 +44,7 @@ await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
const urls = [make('#bd486c', '#438f67'), make('#286f9b', '#725ea2')].map(url => URL.createObjectURL(blob(url)));
window.backgroundTest = { hub: backgroundHub, owner: Symbol(), urls, saved, theme };
}, theme);
await showSavedImage(page);
const background = page.locator('.workarea-background');
const style = (locator, property, pseudo) => locator.evaluate((node, [property, pseudo]) => getComputedStyle(node, pseudo)[property], [property, pseudo]);
async function openWelcome() {
@@ -120,12 +122,14 @@ await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
await page.screenshot({ path: `${output}/${theme}-splash-narrow.png` });
await page.emulateMedia({ reducedMotion: 'reduce' });
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.set(owner, 'app', { url: urls[0], overlay: 0.2, position: 'center', size: 'cover', previous: { url: urls[1], overlay: 0.2, position: 'center', size: 'cover' }, transitionMs: 2000 }); });
assert.equal(await background.evaluate(node => node.getAnimations().length), 0);
assert.equal(await background.evaluate(node => node.getAnimations({ subtree: true }).length), 0);
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.removeOwner(owner); urls.forEach(URL.revokeObjectURL); });
assert.equal(await page.evaluate(() => document.body.style.getPropertyValue('--rs-background-previous-image')), '');
// The frame of Background (the saved image) shows again, without a fade.
assert.equal(await page.evaluate(() => document.body.style.getPropertyValue('--rs-background-previous-image')), 'none');
assert.match(await style(background, 'backgroundImage'), /blob:/);
await page.evaluate(async () => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode: window.backgroundTest.theme }); });
assert.equal(await style(background, 'backgroundImage'), 'none');
await page.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage === 'none');
assert.equal(await page.evaluate(() => document.body.style.getPropertyValue('--rs-background-image')), '', 'Without an image, the body has no background properties');
await openWelcome();
await page.locator('.editor > .body').waitFor();
assert.equal(await style(page.locator('.editor > .body'), 'backgroundColor'), await style(page.locator('.shell'), 'backgroundColor'));
@@ -4,7 +4,9 @@ import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
// The image is painted on .workarea-background, not on the empty tab (src/lib/layout/Workbench.svelte:1258, 1543).
// The image is painted on .workarea-background, not on the empty tab (src/lib/theme/background.css).
// Background (src/lib/features/background/) loads after the first render, so each check waits for the image.
const waitForImage = page => page.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
await runSmoke('appearance/backgroundImages', async ({ browser }) => {
const output = await outputDir('appearance/backgroundImages');
@@ -50,7 +52,7 @@ await runSmoke('appearance/backgroundImages', async ({ browser }) => {
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
let url = await background();
assert.equal(await decoded(main, url), 700, 'The actual new-tab image decodes');
await main.reload(); await main.locator('.empty').waitFor();
await main.reload(); await main.locator('.empty').waitFor(); await waitForImage(main);
url = await background(); assert.equal(await decoded(main, url), 700, 'The saved image survives reload');
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
@@ -60,8 +62,7 @@ await runSmoke('appearance/backgroundImages', async ({ browser }) => {
await main.waitForFunction(old => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(document.querySelector('.workarea-background')).backgroundImage)?.[1] !== old, url);
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image decodes');
assert.ok(await settings.evaluate(() => JSON.stringify(window.__TEST__.settings('appearance')).length < 500), 'Image bytes stay outside the settings file');
await main.reload(); await main.locator('.empty').waitFor();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
await main.reload(); await main.locator('.empty').waitFor(); await waitForImage(main);
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image survives reload');
const acceptedId = await savedImageId();
@@ -4,7 +4,8 @@ import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
// The image is painted on .workarea-background, not on the empty tab (src/lib/layout/Workbench.svelte:1258, 1543).
// The image is painted on .workarea-background, not on the empty tab (src/lib/theme/background.css).
// The controls are in Appearance → Background (src/lib/features/background/BackgroundSettings.svelte).
await runSmoke('appearance/backgroundLayout', async ({ browser }) => {
const output = await outputDir('appearance/backgroundLayout');
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
@@ -1,4 +1,4 @@
// The empty tab background image: set it in Settings, keep it after a reload, remove it, and leave Reset background disabled.
// The empty tab background image: set it in Settings, keep it after a reload, and remove it. The source stays Image.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
@@ -24,13 +24,14 @@ await runSmoke(name, async ({ browser }) => {
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=", "base64");
// The image now lives on the work area layer behind the empty tab (src/lib/layout/Workbench.svelte:1258, :1543-1549).
// The image lives on the work area layer behind the empty tab (src/lib/theme/background.css).
const layer = ".workarea-background";
await settings.getByLabel("Background image file", { exact: true }).setInputFiles({ name: "test.png", mimeType: "image/png", buffer: png });
await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage.includes("blob:"), layer);
assert.equal(await page.evaluate(() => window.__TEST__.settings("background").source), "image", "A chosen image selects the image source");
await page.reload();
await page.locator(".empty").waitFor();
assert.ok(await page.locator(layer).evaluate(node => getComputedStyle(node).backgroundImage.includes("blob:")), "Background survives restart");
await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage.includes("blob:"), layer);
await settings.getByRole("button", { name: "Remove image", exact: true }).click();
await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage === "none", layer);
for (const mode of ["light", "dark"]) {
@@ -42,8 +43,10 @@ await runSmoke(name, async ({ browser }) => {
await settings.setViewportSize({ width: 650, height: 760 });
await settings.screenshot({ path: path.join(output, `appearance-${mode}-narrow.png`) });
}
assert.equal(await settings.getByRole("button", { name: "Reset background", exact: true }).isDisabled(), true);
assert.equal(await settings.getByRole("button", { name: "Reset background", exact: true }).count(), 0);
assert.equal(await settings.getByRole("button", { name: "Background source", exact: true }).innerText(), "Image");
assert.equal(await settings.getByRole("button", { name: "Choose image…", exact: true }).count(), 1);
await page.waitForFunction(() => !window.__TEST__.settings("appearance").newTabBackground);
assert.deepEqual([...page.errors, ...settings.errors], []);
console.log("PASS: background image applies, survives a reload, and is removed; Reset background is disabled");
console.log("PASS: background image applies, survives a reload, and is removed; the image source stays selected");
});
+12 -3
View File
@@ -1,4 +1,5 @@
// Theme variants: transparency slider in eight variants, custom theme fonts, a single tooltip, and slideshow command icons.
// Theme variants: transparency slider in eight variants, custom theme fonts, a single tooltip, plugin command icons,
// and the native Background commands in the command palette.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
@@ -53,13 +54,21 @@ await runSmoke('appearance/themeVariants', async ({ browser }) => {
const main = await openPage(context); await main.goto(smokeUrl);
await main.bringToFront();
await main.getByRole('button', { name: 'Files', exact: true }).waitFor();
// The commands of the native Background feature (src/lib/features/catalog.ts) are in the command palette, without the feature code.
await main.keyboard.press('Control+Shift+P');
const palette = main.getByRole('dialog', { name: 'Commands', exact: true });
await palette.getByRole('textbox', { name: 'Find a command', exact: true }).fill('background');
for (const title of ['Next background image', 'Pause background']) await palette.getByRole('button').filter({ hasText: title }).first().waitFor();
assert.equal(await main.evaluate(async () => (await import('/src/lib/features/loader.ts')).featureRequested('background')), false, 'The palette lists the commands without the feature code');
await main.keyboard.press('Escape');
// A third-party plugin with command icons. The Commands menu lists plugin commands only (src/lib/plugins/PluginAccessMenu.svelte).
await main.evaluate(async () => {
const loaded = performance.getEntriesByType('resource').map(entry => entry.name).find(name => new URL(name).pathname === '/src/lib/plugins/external.ts');
const { pluginTools, refreshPlugins } = await import(loaded || '/src/lib/plugins/external.ts');
await refreshPlugins();
const invoke = window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke = (command, args) => command === 'plugins_snapshot' ? Promise.resolve(null) : invoke(command, args);
const commands = [{ owner: 'runestone.background-slideshow', id: 'next-image', title: 'Next background image', kind: 'command', surface: 'commands', icon: 'skip-forward' }, { owner: 'runestone.background-slideshow', id: 'pause-resume', title: 'Pause or resume background slideshow', kind: 'command', surface: 'commands', icon: 'pause' }];
const commands = [{ owner: 'org.test.slideshow', id: 'next-image', title: 'Next test image', kind: 'command', surface: 'commands', icon: 'skip-forward' }, { owner: 'org.test.slideshow', id: 'pause-resume', title: 'Pause or resume test slideshow', kind: 'command', surface: 'commands', icon: 'pause' }];
pluginTools.set(commands);
});
const visibleTooltips = () => main.locator('[role=tooltip]:visible').count();
@@ -77,7 +86,7 @@ await runSmoke('appearance/themeVariants', async ({ browser }) => {
await button.click(); await main.getByRole('menu').waitFor();
const paths = await main.locator('.rs-menu svg').evaluateAll(nodes => nodes.map(node => node.innerHTML));
assert(paths.some(path => path.includes('M7 4v16'))); assert(paths.some(path => path.includes('m4 4 12 8')));
await main.screenshot({ path: path.join(output, `${mode}-slideshow-command-icons.png`) }); await main.keyboard.press('Escape');
await main.screenshot({ path: path.join(output, `${mode}-plugin-command-icons.png`) }); await main.keyboard.press('Escape');
}
assert.deepEqual([...page.errors, ...main.errors], []);
console.log('PASS: eight theme variants, slider endpoints, persistence, disabled states, narrow layout, font import/export, single tooltip, and command icons.');
@@ -1,7 +1,7 @@
// Tab tooltips, translucent text selection, zero-transparency backgrounds, a stable transparency slider, and the themed install checkbox.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { mockTauri, outputDir, runSmoke, showSavedImage, smokeUrl } from "../_harness/index.mjs";
await runSmoke("appearance/tooltipsAndSelection", async ({ page }) => {
const output = await outputDir("appearance/tooltipsAndSelection");
@@ -35,6 +35,7 @@ await runSmoke("appearance/tooltipsAndSelection", async ({ page }) => {
const { saveAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ theme: "default", mode, transparency: { enabled: true, amount: 0 }, newTabBackground: { image: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=" } });
}, mode);
await showSavedImage(page);
const tab = page.getByRole("tab", { name: /welcome\.md/ });
assert.equal(await tab.getAttribute("title"), null);
await page.mouse.move(600, 600);
@@ -50,9 +51,10 @@ await runSmoke("appearance/tooltipsAndSelection", async ({ page }) => {
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.click(); await page.keyboard.press("Control+a");
const colors = await writer.evaluate(node => {
const root = getComputedStyle(document.documentElement);
const root = getComputedStyle(document.documentElement), body = getComputedStyle(document.body);
// Background sets the image and the surfaces on the body (src/lib/plugins/backgrounds.ts).
return { selection: root.getPropertyValue("--rs-selection"), bg: getComputedStyle(node, "::selection").backgroundColor,
text: getComputedStyle(node).color, image: root.getPropertyValue("--rs-new-tab-image"), pluginBg: root.getPropertyValue("--rs-workarea-plugin-bg") };
text: getComputedStyle(node).color, image: body.getPropertyValue("--rs-background-image"), pluginBg: body.getPropertyValue("--rs-workarea-plugin-bg") };
});
assert.match(colors.selection.trim(), /^#[0-9a-f]{6}a6$/i);
assert.match(colors.bg, /0\.65/);
+2 -1
View File
@@ -1,6 +1,6 @@
// Editor menu surfaces: Writer, spelling, Source, and code menus share the file menu styles; and the code tint match in both themes.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, showSavedImage, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/surfaces", async ({ page }) => {
await mockTauri(page, {
@@ -42,6 +42,7 @@ await runSmoke("editor/surfaces", async ({ page }) => {
c.fillStyle = g; c.fillRect(0, 0, 800, 600);
saveAppearance({ theme: 'default', mode, newTabBackground: { image: canvas.toDataURL(), overlay: .15, position: 'center', size: 'cover' } });
}, theme);
await showSavedImage(page);
await page.locator('[data-tree-rel="a.md"]').click({ button: 'right' });
const reference = await styles(menu('File actions'));
await dismiss();
+212
View File
@@ -0,0 +1,212 @@
// The native Background feature (src/lib/features/background/): a folder slideshow with mocked host commands, a fade,
// reduced motion, Next and Pause from the command palette, the targets, menus at 92% with an image and opaque with
// Background off, a browser window, the settings section in both themes and at 360 pixels, the image source,
// and the first-start migration from seeded plugin settings and from a seeded image.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
const SETTINGS_FILE = "runestone.smoke.settings-file";
const PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=";
/**
* The host commands of the image folder (src-tauri/src/backgrounds.rs). Each image is a PNG of one color.
* The mock runs this function in the page, so it uses only `test`. `test.state.legacy` is an old plugin package.
*/
function folderCommands(test) {
const snapshot = { profiles: [{ id: "user", name: "User" }], tabs: [], bookmarks: [], settings: { search: "duckduckgo", adblock: true, linkDestination: "internal", personalRules: "", homepage: "", filterLists: [] } };
return {
...test.workspace({ root: "C:\\background-feature", files: { "note.md": "# Note\n\nText." } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
"plugin:window|is_maximized": () => false,
spelling_menu_install: () => null,
spelling_menu_uninstall: () => null,
background_folder: () => test.state.folder,
background_choose_folder: () => test.state.folder,
background_clear_folder: () => { test.state.folder = null; return null; },
background_list: () => test.state.names,
background_read: async ({ name }) => {
const [width, height] = name.startsWith("portrait") ? [300, 600] : [640, 400];
const canvas = new OffscreenCanvas(width, height);
const context = canvas.getContext("2d");
context.fillStyle = test.state.colors[name] ?? "#808080"; context.fillRect(0, 0, width, height);
return (await canvas.convertToBlob({ type: "image/png" })).arrayBuffer();
},
background_read_sidecar: () => test.state.sidecar,
background_write_sidecar: ({ contents, expected }) => {
if (expected !== test.state.sidecar) throw "The sidecar file changed. Read it again before you save.";
test.state.sidecar = contents;
return null;
},
background_migrate: () => test.state.folder,
features_legacy: ({ ids }) => test.state.legacy ? ids.filter(id => id === test.state.legacy.id).map(() => test.state.legacy) : [],
browser_connect: () => "background-session",
browser_stop: () => null,
browser_request: () => structuredClone(snapshot),
};
}
const folderState = { folder: "D:\\Backgrounds", names: ["a.png", "b.png", "portrait.png"], colors: { "a.png": "#3a6ea5", "b.png": "#a5533a", "portrait.png": "#4f8a4b" }, sidecar: null };
const image = page => page.evaluate(() => document.body.style.getPropertyValue("--rs-background-image"));
const waitForChange = (page, old) => page.waitForFunction(old => { const value = document.body.style.getPropertyValue("--rs-background-image"); return value.includes("blob:") && value !== old; }, old, { timeout: 15000 });
async function command(page, title) {
await page.keyboard.press("Control+Shift+P");
const palette = page.getByRole("dialog", { name: "Commands", exact: true });
await palette.getByRole("textbox", { name: "Find a command", exact: true }).fill(title);
await palette.getByRole("button").filter({ hasText: title }).first().waitFor();
await page.keyboard.press("Enter");
}
async function menuBackground(page) {
await page.locator('[data-tree-rel="note.md"]').click({ button: "right" });
const menu = page.getByRole("menu", { name: "File actions", exact: true });
await menu.waitFor();
const color = await menu.evaluate(node => getComputedStyle(node).backgroundColor);
await page.keyboard.press("Escape");
return color;
}
await runSmoke("features/background", async ({ browser }) => {
const output = await outputDir("features/background");
// A folder slideshow of 2 seconds, from a settings file that exists before the start.
const context = await browser.newContext({ viewport: { width: 1200, height: 820 } });
await mockTauri(context, { state: folderState, commands: folderCommands });
await context.addInitScript(([key, file]) => { if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(file)); }, [SETTINGS_FILE, {
schema: 1, revision: 1, features: { git: true, background: true },
background: { source: "folder", seconds: 2, order: "name", paused: false, targets: ["app"], overlay: 0.1, position: "center", size: "cover" },
}]);
const main = await openPage(context);
await main.goto(smokeUrl);
await main.locator('[data-tree-rel="note.md"]').waitFor();
await waitForChange(main, "");
const first = await image(main);
assert.match(first, /rgba\(0,0,0,0\.1\)/, "The folder overlay applies");
// The timer shows the next image with a fade of 2 seconds.
await waitForChange(main, first);
assert.equal(await main.locator(".workarea-background").evaluate(node => node.getAnimations({ subtree: true }).length), 1, "The image fades in");
assert.notEqual(await main.evaluate(() => document.body.style.getPropertyValue("--rs-background-previous-image")), "none");
await main.screenshot({ path: path.join(output, "folder-fade.png") });
// Pause keeps the image. Next still works. The same command resumes.
await command(main, "Pause background");
await main.waitForFunction(() => window.__TEST__.settings("background").paused === true);
const paused = await image(main);
await main.waitForTimeout(3000);
assert.equal(await image(main), paused, "A paused slideshow keeps its image");
await command(main, "Next background image");
await waitForChange(main, paused);
// The folder has a portrait image after b.png. It shows in full over a blurred fill.
await main.waitForFunction(() => document.body.style.getPropertyValue("--rs-background-layer-sizes") === "100% 100%, contain, cover", null, { timeout: 15000 });
await main.screenshot({ path: path.join(output, "portrait.png") });
await command(main, "Pause background");
await main.waitForFunction(() => window.__TEST__.settings("background").paused === false);
// Reduced motion: the next image shows without a fade.
await main.emulateMedia({ reducedMotion: "reduce" });
const before = await image(main);
await command(main, "Next background image");
await waitForChange(main, before);
assert.equal(await main.locator(".workarea-background").evaluate(node => node.getAnimations({ subtree: true }).length), 0, "Reduced motion has no fade");
await main.emulateMedia({ reducedMotion: "no-preference" });
// With an image, menus are at least 92% opaque and blur it (UI-043).
assert.match(await menuBackground(main), /0\.92/);
// Targets: only the boards removes the workspace frame. The frame of all boards stays for Project Management.
await main.evaluate(() => window.__TEST__.writeSettings("background", { ...window.__TEST__.settings("background"), targets: ["pm-all"] }));
await main.waitForFunction(() => document.body.style.getPropertyValue("--rs-background-image") === "");
assert.equal(await main.evaluate(async () => !!(await import("/src/lib/plugins/backgrounds.ts")).backgroundHub.get("pm-all")), true);
assert.match(await menuBackground(main), /^rgb\(/, "Without a workspace image, menus are opaque");
await main.evaluate(() => window.__TEST__.writeSettings("background", { ...window.__TEST__.settings("background"), targets: ["app"] }));
await waitForChange(main, "");
// A browser window shows the background behind a blank tab, and calls only the commands that browser.json grants.
const browserPage = await openPage(context);
await mockTauri(browserPage, { label: "browser-background", state: folderState, commands: folderCommands });
await browserPage.goto(smokeUrl + "/?browserWindow=true");
await browserPage.getByRole("application", { name: "RuneStone browser" }).waitFor();
assert.equal(await browserPage.evaluate(() => window.__TEST__.label), "browser-background");
await browserPage.waitForFunction(() => getComputedStyle(document.querySelector(".workarea-background")).backgroundImage.includes("blob:"), null, { timeout: 15000 });
await browserPage.screenshot({ path: path.join(output, "browser-window.png") });
const granted = new Set(JSON.parse(await readFile(path.join(repoRoot, "src-tauri/capabilities/browser.json"), "utf8")).permissions);
const calls = await browserPage.evaluate(() => [...new Set(window.__TEST__.calls.map(call => call.command))]);
for (const call of calls.filter(name => name.startsWith("background_"))) assert(granted.has(`allow-${call.replaceAll("_", "-")}`), `browser.json grants ${call}`);
assert(calls.includes("background_read"), "The browser window reads the folder images");
await browserPage.close();
// The settings section in both themes and at 360 pixels.
const settings = await openPage(context);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
const section = settings.locator(".background-settings");
await section.waitFor();
assert.equal(await settings.getByRole("button", { name: "Background source", exact: true }).innerText(), "Folder");
assert.equal(await settings.getByRole("textbox", { name: "Image folder", exact: true }).inputValue(), "D:\\Backgrounds");
await settings.getByRole("status").filter({ hasText: "3 images." }).waitFor();
assert.equal(await settings.evaluate(async () => (await import("/src/lib/features/loader.ts")).featureRequested("background")), true, "The section loads the feature module");
assert.equal(await settings.evaluate(() => document.body.style.getPropertyValue("--rs-background-image")), "", "The slideshow does not run in the settings window");
await settings.locator("summary").filter({ hasText: "Per-image appearance" }).click();
await settings.getByRole("button", { name: "Image fit", exact: true }).waitFor();
await settings.waitForFunction(() => !document.querySelector('button[aria-label="Image fit"]').disabled);
for (const theme of ["dark", "light"]) {
await settings.evaluate(async mode => { const { saveAppearance, readAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ ...readAppearance(), theme: "default", mode }); }, theme);
for (const width of [1100, 360]) {
// A tall window shows the whole section, also the targets below the per-image editor.
await settings.setViewportSize({ width, height: 1800 });
await section.scrollIntoViewIfNeeded();
assert.equal(await settings.locator(".content").evaluate(node => node.scrollWidth <= node.clientWidth + 1), true, `No horizontal scroll at ${width} pixels`);
await section.screenshot({ path: path.join(output, `settings-${theme}-${width}.png`) });
}
}
await settings.setViewportSize({ width: 1100, height: 900 });
// The per-image editor saves only the changed values of the selected image.
await settings.getByRole("button", { name: "Image fit", exact: true }).click();
await settings.getByRole("menuitemradio", { name: "Fit", exact: true }).click();
await settings.getByRole("button", { name: "Save image appearance", exact: true }).click();
await settings.getByRole("status").filter({ hasText: "Image appearance saved." }).waitFor();
assert.deepEqual(JSON.parse(await settings.evaluate(() => window.__TEST__.state.sidecar)), { schema: 1, images: { "a.png": { fit: "contain" } } });
// Off applies at once in every window: the image goes away, and menus are opaque again.
await settings.getByRole("button", { name: "Features", exact: true }).click();
await settings.getByRole("switch", { name: "Background", exact: true }).click();
await main.waitForFunction(() => document.body.style.getPropertyValue("--rs-background-image") === "");
assert.match(await menuBackground(main), /^rgb\(/, "With Background off, menus are opaque");
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
await settings.getByText("Background is off. Turn it on in Settings → Features.", { exact: true }).waitFor();
await settings.screenshot({ path: path.join(output, "settings-off.png") });
await settings.getByRole("button", { name: "Features", exact: true }).click();
await settings.getByRole("switch", { name: "Background", exact: true }).click();
await waitForChange(main, "");
assert.deepEqual([...main.errors, ...settings.errors], []);
await context.close();
// The image source and the migration from a seeded image: the old image of Appearance shows without a timer.
const imageContext = await browser.newContext({ viewport: { width: 1000, height: 700 } });
await mockTauri(imageContext, { commands: test => ({ ...test.workspace({ root: "C:\\background-image", files: { "note.md": "# Note" } }), plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }) }) });
await imageContext.addInitScript(image => { if (!localStorage.getItem("runestone.smoke.settings-file")) localStorage.setItem("runestone.appearance", JSON.stringify({ theme: "default", mode: "dark", newTabBackground: { image, overlay: 0.2, position: "top", size: "contain" } })); }, `data:image/png;base64,${PNG}`);
const imagePage = await openPage(imageContext);
await imagePage.goto(smokeUrl);
await waitForChange(imagePage, "");
assert.deepEqual(await imagePage.evaluate(() => window.__TEST__.settings("background")), { source: "image", seconds: 60, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover" });
assert.equal(await imagePage.evaluate(() => document.body.style.getPropertyValue("--rs-background-position")), "top", "The image keeps its own layout");
assert.equal(await imagePage.evaluate(() => window.__TEST__.calls.some(call => call.command === "background_migrate")), false, "Without a plugin grant, no folder migrates");
assert.deepEqual(imagePage.errors, []);
await imageContext.close();
// The migration from the kept settings of an enabled Background Slideshow plugin.
const migrationContext = await browser.newContext({ viewport: { width: 1000, height: 700 } });
const legacy = { id: "runestone.bg-slideshow", installed: true, enabled: true,
settings: { grant: "6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90", folder: "D:\\Old", enabled: true, seconds: 7, order: "random", targets: ["app", "pm-all"], overlay: 0.3, position: "top", size: "contain" } };
await mockTauri(migrationContext, { state: { ...folderState, folder: "D:\\Old", legacy }, commands: folderCommands });
const migrated = await openPage(migrationContext);
await migrated.goto(smokeUrl);
await waitForChange(migrated, "");
assert.deepEqual(await migrated.evaluate(() => window.__TEST__.settings("background")), { source: "folder", seconds: 7, order: "random", paused: false, targets: ["app", "pm-all"], overlay: 0.3, position: "top", size: "contain" });
assert.deepEqual(await migrated.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true });
assert.equal(await migrated.evaluate(() => window.__TEST__.calls.filter(call => call.command === "background_migrate").length), 1);
assert.deepEqual(migrated.errors, []);
await migrationContext.close();
console.log("PASS: folder slideshow, fade, pause and next, portrait fill, reduced motion, menus, targets, browser window, settings section, off switch, image source, and migrations.");
});
+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 });
await sourceControl.waitFor();
// Without an old package, the migration stores the default of each feature.
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true });
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true });
const settings = await openPage(context, { timeout: 10000 });
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
@@ -33,7 +33,7 @@ await runSmoke("features/settings", async ({ browser }) => {
await git.click();
await sourceControl.waitFor({ state: "detached" });
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false });
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true });
assert.equal(await settings.getByRole("status").innerText(), "Changes saved.");
await git.focus();
await settings.keyboard.press("Space");
+2 -2
View File
@@ -137,10 +137,10 @@ await runSmoke("layout/workbench", async ({ page }) => {
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["reader-showcase.md"] });
}, showcase);
await quickOpen("reader-showcase.md");
// Each view choice shows an icon and its name. The tooltip adds the shortcut (src/lib/layout/ViewModes.svelte).
// Each view choice shows only an icon (UI-056). The accessible name and the tooltip give its name and shortcut (src/lib/layout/ViewModes.svelte).
const read = page.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name: "Read", exact: true });
const readTip = page.getByRole("tooltip").filter({ hasText: "Read (Ctrl+Shift+E)" });
assert.equal(await read.innerText(), "Read");
assert.equal(await read.innerText(), "");
assert.equal(await read.locator("svg").count(), 1);
await read.hover();
await readTip.waitFor({ state: "visible" });
+2 -1
View File
@@ -1,7 +1,7 @@
// Shared menu design: styles, themes, icons, disabled rows, focus return, submenus, spelling menus, scrolling, and viewport edges.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { mockTauri, outputDir, runSmoke, showSavedImage, smokeUrl } from "../_harness/index.mjs";
await runSmoke("menus/consistency", async ({ page }) => {
const output = await outputDir("menus/consistency");
@@ -69,6 +69,7 @@ await runSmoke("menus/consistency", async ({ page }) => {
context.fillStyle = gradient; context.fillRect(0, 0, 800, 600);
saveAppearance({ theme: 'default', mode, newTabBackground: { image: canvas.toDataURL(), overlay: 0.15, position: 'center', size: 'cover' } });
}, theme);
await showSavedImage(page);
await row.focus();
await row.click({ button: "right" });
const file = menu("File actions");
+456
View File
@@ -0,0 +1,456 @@
// The Background feature: the engine (ported from the Background Slideshow plugin), the per-image settings,
// the sources, the settings section, the launch rule, and the first-start migration.
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_BACKGROUND, hasBackgroundSource, migrateBackground, normalizeBackground, normalizeLayout, type BackgroundMigrationHost, type BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts";
import { LAUNCH_RULES, launchWanted, runsInWindow } from "../../../src/lib/features/launch.ts";
import { BLUR_CACHE, RESCAN_SLIDES, Slideshow, transitionMs, type EngineSettings, type ImageSource, type Runtime } from "../../../src/lib/features/background/engine.ts";
import { imageAppearance, imageNames, parseImageSettings, sequence } from "../../../src/lib/features/background/imageSettings.ts";
import { folderSource, imageSource, readSavedImage } from "../../../src/lib/features/background/sources.ts";
import type { LegacyPlugin } from "../../../src/lib/features/migration.ts";
import type { BackgroundFrame } from "../../../src/lib/plugins/backgroundContracts.ts";
const settle = () => new Promise(resolve => setImmediate(resolve));
const on: EngineSettings = { ...normalizeBackground({ source: "folder", seconds: 3, targets: ["app", "pm-all"] }) };
function fixture({ width = 200, height = 100 } = {}) {
const frames = new Map<string, BackgroundFrame>();
const released: string[] = [];
const reads: string[] = [];
const counts = { list: 0, sidecar: 0, blur: 0 };
let names = ["2.png", "1.png", "10.png"];
let sidecar: string | null = null;
let serial = 0;
let scheduled: { callback: () => void; delay: number } | undefined;
const source = (key = "folder:D:\\Pictures"): ImageSource => ({
key, timed: true,
list: async () => { counts.list++; return names; },
read: async name => { reads.push(name); return new Blob([name]); },
sidecar: async () => { counts.sidecar++; return sidecar; },
});
const runtime: Runtime = {
load: async blob => ({ url: `blob:${await blob.text()}-${serial++}`, width, height }),
blur: async image => { counts.blur++; return `${image.url}-blur`; },
release: url => { released.push(url); },
later: (callback, delay) => { scheduled = { callback, delay }; return scheduled; },
cancel: () => { scheduled = undefined; },
random: () => 0,
now: () => 0,
};
const engine = new Slideshow({ set: (target, frame) => { if (frame) frames.set(target, frame); else frames.delete(target); } }, runtime);
return {
engine, frames, released, reads, counts, runtime, source,
names: (value: string[]) => { names = value; },
sidecar: (value: string | null) => { sidecar = value; },
scheduled: () => scheduled,
/** Run the timer, then let the read of the next prepared image finish. */
tick: async () => { await scheduled!.callback(); await settle(); await settle(); },
};
}
test("settings and names normalize, and the order is natural", () => {
assert.equal(normalizeBackground({ seconds: NaN }).seconds, 60);
assert.equal(normalizeBackground({ seconds: -2 }).seconds, 1);
assert.equal(normalizeBackground({ seconds: 1e9 }).seconds, 86400);
assert.equal(normalizeBackground({ overlay: Infinity }).overlay, 0);
assert.equal(normalizeBackground({ overlay: -3 }).overlay, -1);
assert.deepEqual(normalizeBackground({ targets: ["app", "app", "bogus", "pm-board:../x", "pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1"] }).targets, ["app", "pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1"]);
assert.deepEqual(normalizeBackground(null), { ...DEFAULT_BACKGROUND, targets: ["app"] });
assert.deepEqual(normalizeBackground({ source: "web", order: "shuffle", paused: "yes", position: "middle", size: "100px" }), { ...DEFAULT_BACKGROUND, targets: ["app"] });
assert.deepEqual(normalizeLayout({ overlay: 0.5, position: "top left", size: "auto" }), { overlay: 0.5, position: "top left", size: "auto" });
assert.deepEqual(imageNames(["10.png", "2.png", "README.md", "../bad.png", "2.png", "a.JPEG"]), ["2.png", "10.png", "a.JPEG"]);
assert.deepEqual(sequence(["a", "b", "c"], "b", "name"), ["c", "a", "b"]);
assert.notEqual(sequence(["a", "b", "c"], "a", "random", () => 0)[0], "a");
assert.deepEqual(sequence(["a"], "a", "random"), ["a"]);
});
test("a folder rotates, shows one frame on every target, and a pause keeps the current image", async () => {
const f = fixture();
await f.engine.configure(f.source(), { ...on, overlay: -0.4, position: "top left", size: "contain" });
assert.equal(f.engine.status.image, "1.png");
assert.equal(f.scheduled()!.delay, 3000);
assert.equal(f.frames.get("app")!.overlay, -0.4);
assert.equal(f.frames.get("app")!.size, "contain");
assert.deepEqual(f.frames.get("app"), f.frames.get("pm-all"));
await f.tick();
assert.equal(f.engine.status.image, "2.png");
await f.engine.next();
assert.equal(f.engine.status.image, "10.png");
await f.engine.configure(f.source(), { ...on, paused: true });
assert.equal(f.engine.status.image, "10.png", "A pause keeps the image.");
assert.equal(f.scheduled(), undefined, "A pause has no timer.");
assert.equal(f.frames.size, 2);
await f.engine.next();
assert.equal(f.engine.status.image, "1.png", "Next works during a pause.");
assert.equal(f.scheduled(), undefined);
await f.engine.configure(null, on);
assert.equal(f.frames.size, 0, "Without a source, the frames go away.");
f.engine.dispose();
});
test("unreadable images are skipped, and an empty folder tries again", async () => {
const f = fixture();
const read = f.source();
const source: ImageSource = { ...read, read: async name => { if (name === "1.png") throw new Error("removed"); return read.read(name); } };
await f.engine.configure(source, on);
assert.equal(f.engine.status.image, "2.png");
assert.match(f.engine.status.message, /skipped 1/);
f.names([]);
f.engine.invalidate();
await f.engine.next();
assert.equal(f.frames.size, 0);
assert.equal(f.engine.status.error, true);
assert.equal(f.scheduled()!.delay, 5000);
f.names(["restored.png"]);
f.engine.invalidate();
await f.tick();
assert.equal(f.engine.status.image, "restored.png");
f.engine.dispose();
});
test("both images of a fade stay alive, and each image is released once", async () => {
const f = fixture();
await f.engine.configure(f.source(), on);
const first = f.frames.get("app")!;
assert.equal(first.previous, undefined);
await f.engine.next(); await settle();
const second = f.frames.get("app")!;
assert.deepEqual(second.previous, first);
assert.equal(second.transitionMs, transitionMs);
assert.equal(f.released.length, 0);
await f.engine.next(); await settle();
const third = f.frames.get("app")!;
assert.deepEqual(third.previous, { url: second.url, overlay: 0, position: "center", size: "cover" });
assert.deepEqual(f.released, [first.url]);
f.engine.dispose();
await settle();
assert.equal(new Set(f.released).size, f.released.length, "No URL is released twice.");
for (const url of [first.url, second.url, third.url]) assert.ok(f.released.includes(url), url);
});
test("a settings change keeps the current image and applies the new layout without a fade", async () => {
const f = fixture();
await f.engine.configure(f.source(), on);
const first = f.frames.get("app")!;
await f.engine.configure(f.source(), { ...on, overlay: 0.4, position: "bottom", targets: ["app"] });
const changed = f.frames.get("app")!;
assert.equal(changed.url, first.url);
assert.equal(changed.overlay, 0.4);
assert.equal(changed.position, "bottom");
assert.equal(changed.previous, undefined);
assert.equal(f.frames.has("pm-all"), false, "A removed target loses its frame.");
assert.equal(f.engine.status.image, "1.png");
assert.deepEqual(f.released, []);
f.engine.dispose();
});
test("the next image is read and decoded before its fade", async () => {
const f = fixture();
await f.engine.configure(f.source(), on);
await settle(); await settle();
assert.deepEqual(f.reads, ["1.png", "2.png"], "The next image loads after the current one shows.");
await f.tick();
assert.equal(f.engine.status.image, "2.png");
assert.deepEqual(f.reads, ["1.png", "2.png", "10.png"], "The timer used the prepared image without a new read.");
// A change of order drops the prepared image when the folder no longer has it.
f.names(["1.png", "2.png"]);
f.engine.invalidate();
await f.tick();
assert.equal(f.engine.status.image, "1.png");
assert.ok(f.released.some(url => url.startsWith("blob:10.png")), "The unused prepared image is released.");
f.engine.dispose();
});
test("a missing folder shows an error, and the folder recovers on the next try", async () => {
const f = fixture();
const missing: ImageSource = { ...f.source(), list: async () => { throw new Error("The background folder is missing. Choose the folder again."); } };
await f.engine.configure(missing, on);
assert.equal(f.engine.status.error, true);
assert.match(f.engine.status.message, /Choose the folder again/);
assert.equal(f.frames.size, 0);
await f.engine.configure(f.source("folder:D:\\Other"), on);
assert.equal(f.engine.status.error, false);
assert.equal(f.engine.status.image, "1.png");
f.engine.dispose();
});
test("a host failure clears the published targets and releases every image", async () => {
const f = fixture();
let fail = false;
const engine = new Slideshow({ set: (target, frame) => {
if (fail && target === "pm-all" && frame) throw new Error("Background access ended.");
if (frame) f.frames.set(target, frame); else f.frames.delete(target);
} }, f.runtime);
await engine.configure(f.source(), on);
await engine.next(); await settle();
fail = true;
await engine.next(); await settle();
assert.equal(engine.status.error, true);
assert.equal(f.frames.size, 0);
assert.equal(new Set(f.released).size, f.released.length, "No URL is released twice.");
assert.ok(f.released.length >= 3);
engine.dispose();
});
test("another source starts again, and a late read of the old source is ignored", async () => {
const f = fixture();
let resolve!: (value: string[]) => void;
const slow: ImageSource = { ...f.source("folder:D:\\Slow"), list: () => new Promise(done => { resolve = done; }) };
const pending = f.engine.configure(slow, on);
await settle();
await f.engine.configure(f.source("folder:D:\\Other"), on);
const current = f.frames.get("app")!.url;
resolve(["stale.png"]);
await pending;
assert.equal(f.frames.get("app")!.url, current);
assert.equal(f.engine.status.image, "1.png");
f.engine.dispose();
});
test("the list and the sidecar are read again only after a change, a focus, or every 10 images", async () => {
const f = fixture();
await f.engine.configure(f.source(), { ...on, seconds: 1 });
assert.deepEqual([f.counts.list, f.counts.sidecar], [1, 1]);
for (let index = 1; index < RESCAN_SLIDES; index++) await f.tick();
assert.deepEqual([f.counts.list, f.counts.sidecar], [1, 1], "Nine timer images read nothing again.");
await f.tick();
assert.deepEqual([f.counts.list, f.counts.sidecar], [2, 2], "The eleventh image reads the folder again.");
f.engine.invalidate();
await f.tick();
assert.deepEqual([f.counts.list, f.counts.sidecar], [3, 3], "A focus reads it again.");
await f.engine.configure(f.source(), { ...on, seconds: 2 });
assert.deepEqual([f.counts.list, f.counts.sidecar], [4, 4], "A settings change reads it again.");
f.engine.dispose();
});
test("a late image after disposal is released and never published", async () => {
const f = fixture();
let resolve!: (value: { url: string; width: number; height: number }) => void;
f.runtime.load = () => new Promise(done => { resolve = done; });
const pending = f.engine.configure(f.source(), on);
await settle(); await settle();
f.engine.dispose();
resolve({ url: "blob:late", width: 1, height: 1 });
await pending;
assert.deepEqual(f.released, ["blob:late"]);
assert.equal(f.frames.size, 0);
assert.equal(f.scheduled(), undefined);
});
test("disposal clears the targets and stops the timer", async () => {
const f = fixture();
await f.engine.configure(f.source(), on);
const timer = f.scheduled()!;
f.engine.dispose();
timer.callback();
await settle();
assert.equal(f.frames.size, 0);
assert.equal(f.scheduled(), undefined);
});
test("the image source shows one image without a timer and without the portrait default", async () => {
const f = fixture({ width: 100, height: 300 });
const image: ImageSource = { key: "image:abc", timed: false, list: async () => ["image"], read: async () => new Blob(["saved"]), sidecar: async () => { throw new Error("not asked"); } };
await f.engine.configure(image, { ...on, size: "cover" });
assert.equal(f.frames.get("app")!.size, "cover");
assert.equal(f.frames.get("app")!.blurredUrl, undefined);
assert.equal(f.scheduled(), undefined);
await f.engine.next();
assert.equal(f.frames.get("app")!.previous, undefined, "Next keeps the one image.");
assert.equal(f.counts.blur, 0);
f.engine.dispose();
});
test("the sidecar keeps file names and other data, and rejects invalid appearance", () => {
const value = { schema: 1, owner: "personal", images: { "Portrait.png": { fit: "blurred", position: "top", overlay: -0.25 } } };
assert.deepEqual(parseImageSettings(JSON.stringify(value)), value);
assert.deepEqual(parseImageSettings(null), { schema: 1, images: {} });
for (const source of ["{}", '{"schema":2,"images":{}}', '{"schema":1,"images":[]}', '{"schema":1,"images":{"../a.png":{"fit":"cover"}}}', '{"schema":1,"images":{"a.png":{"fit":"crop"}}}', '{"schema":1,"images":{"a.png":{"overlay":2}}}']) {
assert.throws(() => parseImageSettings(source), source);
}
const layout = { overlay: 0.3, position: "center" as const, size: "auto" as const };
assert.equal(imageAppearance(layout, undefined, true).fit, "blurred");
assert.equal(imageAppearance(layout, undefined, false).fit, "auto");
assert.equal(imageAppearance(layout, { fit: "cover", position: "bottom", overlay: -0.2 }, true).fit, "cover");
});
test("a partial image override inherits every other field", () => {
const source = { schema: 1, owner: "personal", images: { "Portrait.png": { position: "top", note: "keep" }, "Other.png": {} } };
assert.deepEqual(parseImageSettings(JSON.stringify(source)), source);
const layout = { overlay: 0.3, position: "center" as const, size: "auto" as const };
assert.deepEqual(imageAppearance(layout, { position: "top" }, false), { fit: "auto", position: "top", overlay: 0.3 });
assert.deepEqual(imageAppearance({ ...layout, size: "contain", overlay: -0.4 }, { position: "top" }, false), { fit: "contain", position: "top", overlay: -0.4 });
assert.deepEqual(imageAppearance(layout, { overlay: 0 }, true), { fit: "blurred", position: "center", overlay: 0 });
for (const value of [null, [], "cover", 1, { fit: null }, { position: "invalid" }, { overlay: "0" }, { overlay: null }]) {
assert.throws(() => parseImageSettings(JSON.stringify({ schema: 1, images: { "Image.png": value } })));
}
});
test("a partial override stays while the folder layout changes", async () => {
const f = fixture();
f.names(["A.png"]);
f.sidecar(JSON.stringify({ schema: 1, images: { "A.png": { position: "top" } } }));
await f.engine.configure(f.source(), on);
assert.equal(f.frames.get("app")!.size, "cover");
await f.engine.configure(f.source(), { ...on, size: "contain", overlay: -0.4, position: "bottom" });
assert.equal(f.frames.get("app")!.size, "contain");
assert.equal(f.frames.get("app")!.overlay, -0.4);
assert.equal(f.frames.get("app")!.position, "top");
f.engine.dispose();
});
test("a portrait image shows in full over a blurred fill that stays alive through the fade", async () => {
const f = fixture({ width: 100, height: 300 });
f.names(["A.png", "B.png"]);
await f.engine.configure(f.source(), on);
const first = f.frames.get("app")!;
assert.equal(first.size, "contain");
assert.equal(first.blurredUrl, `${first.url}-blur`);
f.sidecar(JSON.stringify({ schema: 1, images: { "B.png": { fit: "cover", position: "bottom", overlay: 0.4 } } }));
f.engine.invalidate();
await f.engine.next(); await settle();
const second = f.frames.get("app")!;
assert.equal(second.size, "cover"); assert.equal(second.position, "bottom"); assert.equal(second.overlay, 0.4);
assert.equal(second.blurredUrl, undefined);
assert.equal(second.previous!.blurredUrl, first.blurredUrl);
assert.equal(f.released.includes(first.blurredUrl!), false, "The fill of the fade stays.");
f.engine.dispose(); await settle();
for (const url of [first.url, first.blurredUrl!, second.url]) assert.ok(f.released.includes(url), url);
});
test("the blurred fills of the last three images stay in the cache", async () => {
const f = fixture({ width: 100, height: 300 });
f.names(["A.png", "B.png", "C.png", "D.png", "E.png"]);
await f.engine.configure(f.source(), { ...on, order: "name" });
for (let index = 0; index < 4; index++) { await f.engine.next(); await settle(); await settle(); }
const blurs = f.counts.blur;
const releasedBlurs = f.released.filter(url => url.endsWith("-blur")).length;
assert.ok(releasedBlurs >= 1, "Old fills beyond the cache are released.");
assert.ok(blurs - releasedBlurs <= BLUR_CACHE + 1, "At most the cache and the prepared fill stay.");
// The same image again uses the cached fill.
const repeat = fixture({ width: 100, height: 300 });
repeat.names(["A.png", "B.png"]);
await repeat.engine.configure(repeat.source(), on);
for (let index = 0; index < 4; index++) { await repeat.engine.next(); await settle(); await settle(); }
assert.equal(repeat.counts.blur, 2, "Two images that alternate use their cached fills.");
f.engine.dispose(); repeat.engine.dispose();
});
test("a late blurred fill is released when the source goes away", async () => {
let resolve!: (url: string) => void;
const f = fixture({ width: 100, height: 300 });
f.names(["A.png"]);
f.runtime.blur = () => new Promise(done => { resolve = done; });
const loading = f.engine.configure(f.source(), on);
await settle(); await settle();
await f.engine.configure(null, on);
resolve("blob:blur");
await loading;
assert.equal(f.frames.size, 0);
assert.ok(f.released.includes("blob:blur"));
assert.ok(f.released.some(url => url.startsWith("blob:A.png")));
f.engine.dispose();
});
test("the sources have stable keys, and the saved image of an old data URL decodes", async () => {
assert.equal(folderSource("D:\\Pictures").key, "folder:D:\\Pictures");
assert.equal(folderSource("D:\\Pictures").timed, true);
const id = "01234567-89ab-cdef-0123-456789abcdef";
assert.equal(imageSource({ imageId: id }).key, `image:${id}`);
assert.equal(imageSource({ imageId: id }).timed, false);
assert.deepEqual(await imageSource({ imageId: id }).list(), ["image"]);
const data = "data:image/png;base64,iVBORw0KGgo=";
const blob = await readSavedImage({ image: data });
assert.equal(blob.type, "image/png");
assert.deepEqual([...new Uint8Array(await blob.arrayBuffer())], [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
assert.notEqual(imageSource({ image: data }).key, imageSource({ image: data.replace("KGgo", "KGgp") }).key);
});
test("Background has a source only with a folder or an existing image", () => {
const appearance = { theme: "default" as const, mode: "dark" as const };
const withImage = { ...appearance, newTabBackground: { imageId: "01234567-89ab-cdef-0123-456789abcdef" } };
assert.equal(hasBackgroundSource(normalizeBackground({ source: "none" }), withImage), false);
assert.equal(hasBackgroundSource(normalizeBackground({ source: "folder" }), appearance), true);
assert.equal(hasBackgroundSource(normalizeBackground({ source: "image" }), appearance), false);
assert.equal(hasBackgroundSource(normalizeBackground({ source: "image" }), withImage), true);
});
test("the launch rule starts Background when it has a source, also in browser windows, but not in the settings window", () => {
const rule = LAUNCH_RULES.background!;
assert.equal(rule.browserWindow, true);
assert.equal(LAUNCH_RULES.git, undefined, "Git loads at first need.");
assert.equal(runsInWindow("background", { browserWindow: true }), true);
assert.equal(runsInWindow("git", { browserWindow: true }), false);
assert.equal(runsInWindow("git", { browserWindow: false }), true);
assert.equal(launchWanted("git", { settingsWindow: false }), false);
// In Node the settings are empty, so the source is "none".
assert.equal(rule.wanted(), false);
assert.equal(launchWanted("background", { settingsWindow: false }), false);
const wanted = rule.wanted;
rule.wanted = () => true;
try {
assert.equal(launchWanted("background", { settingsWindow: false }), true);
assert.equal(launchWanted("background", { settingsWindow: true }), false);
} finally { rule.wanted = wanted; }
});
function migrationHost({ image = false, folder = true, fails = false } = {}) {
const calls = { folder: 0 };
const written: BackgroundSettings[] = [];
const host: BackgroundMigrationHost = {
missing: () => true,
hasImage: () => image,
migrateFolder: async () => { calls.folder++; if (fails) throw new Error("no folder"); return folder; },
write: async value => { written.push(value); },
};
return { host, calls, written };
}
const plugin = (installed: boolean, enabled: boolean, settings: unknown): LegacyPlugin => ({ id: "runestone.bg-slideshow", installed, enabled, settings });
const grant = "6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90";
const kept = { grant, folder: "D:\\Pictures", seconds: 10, order: "random", enabled: true, targets: ["app", "pm-all"], overlay: 0.25, position: "top", size: "contain" };
test("the migration selects the folder of an installed, enabled, and running slideshow", async () => {
const { host, calls, written } = migrationHost({ image: true });
const value = await migrateBackground(plugin(true, true, kept), host);
assert.equal(calls.folder, 1);
assert.deepEqual(value, { source: "folder", seconds: 10, order: "random", paused: false, targets: ["app", "pm-all"], overlay: 0.25, position: "top", size: "contain" });
assert.deepEqual(written, [value]);
});
test("a disabled package, a stopped slideshow, or a lost folder gives the image or none, and the folder still migrates", async () => {
for (const [legacy, folder] of [[plugin(true, false, kept), true], [plugin(true, true, { ...kept, enabled: false }), true], [plugin(false, false, kept), true], [plugin(true, true, kept), false]] as const) {
const withImage = migrationHost({ image: true, folder });
assert.equal((await migrateBackground(legacy, withImage.host)).source, "image");
assert.equal(withImage.calls.folder, 1, "A kept grant always migrates its folder.");
const without = migrationHost({ folder });
const value = await migrateBackground(legacy, without.host);
assert.equal(value.source, "none");
assert.equal(value.seconds, 10, "The kept settings still give the sequence and the layout.");
}
});
test("a failed folder migration is not a failed start", async () => {
const errors = console.error;
console.error = () => {};
try {
const { host, written } = migrationHost({ image: true, fails: true });
assert.equal((await migrateBackground(plugin(true, true, kept), host)).source, "image");
assert.equal(written.length, 1);
} finally { console.error = errors; }
});
test("without the old plugin, an image gives the image source and nothing gives none", async () => {
const image = migrationHost({ image: true });
assert.deepEqual(await migrateBackground(undefined, image.host), { ...DEFAULT_BACKGROUND, targets: ["app"], source: "image" });
assert.equal(image.calls.folder, 0, "Without a grant, no folder migrates.");
const none = migrationHost();
assert.deepEqual(await migrateBackground(plugin(false, false, null), none.host), { ...DEFAULT_BACKGROUND, targets: ["app"] });
// Settings of version 0.0.10 and earlier have a path and no grant. Only a grant migrates.
const old = migrationHost();
assert.equal((await migrateBackground(plugin(true, true, { folder: "D:\\Pictures", enabled: true }), old.host)).source, "none");
assert.equal(old.calls.folder, 0);
// Invalid kept values take the defaults.
const invalid = migrationHost();
const value = await migrateBackground(plugin(true, true, { grant, enabled: true, seconds: "x", targets: ["bogus"], overlay: 9 }), invalid.host);
assert.deepEqual([value.source, value.seconds, value.targets, value.overlay], ["folder", 60, [], 1]);
});
+65 -7
View File
@@ -4,6 +4,7 @@ import assert from "node:assert/strict";
import { FEATURES, featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
import { storedSwitches, switchesFrom } from "../../../src/lib/features/state.ts";
import { legacySwitch, migrateFeatures, type LegacyPlugin } from "../../../src/lib/features/migration.ts";
import type { BackgroundMigrationHost, BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts";
import { featureErrors, featureRequested, loadFeature } from "../../../src/lib/features/loader.ts";
import { FeatureSession } from "../../../src/lib/features/session.ts";
import type { FeatureContext, FeatureInstance, FeatureModule } from "../../../src/lib/features/types.ts";
@@ -18,15 +19,22 @@ test("each feature keeps the ID of its old plugin package as its owner ID", () =
assert.deepEqual(git.views.map(view => [view.id, view.placement]), [["source-control", "sidebar"], ["diff", "editor"], ["graph", "editor"]]);
assert.equal(git.views[0].title(), "Source control");
assert.deepEqual(git.commands.map(command => [command.id, command.view]), [["graph", "graph"]]);
const background = featureEntry("background");
assert.equal(background.owner, "runestone.bg-slideshow");
assert.equal(featureOfOwner("runestone.bg-slideshow")?.id, "background");
assert.deepEqual(background.views, []);
assert.deepEqual(background.commands.map(command => [command.id, command.view, command.title()]), [["next", undefined, "Next background image"], ["pause", undefined, "Pause background"]]);
assert.equal(background.defaultOn, true);
assert.equal(background.followsPackage, false);
});
test("switches keep known booleans only, and missing keys take the default", () => {
assert.deepEqual(storedSwitches({ git: false, terminal: true, other: "yes" }), { git: false });
assert.deepEqual(storedSwitches(null), {});
assert.deepEqual(storedSwitches(["git"]), {});
assert.deepEqual(switchesFrom(undefined), { git: true });
assert.deepEqual(switchesFrom({ git: false }), { git: false });
assert.deepEqual(switchesFrom({ git: "false" }), { git: true });
assert.deepEqual(switchesFrom(undefined), { git: true, background: true });
assert.deepEqual(switchesFrom({ git: false, background: false }), { git: false, background: false });
assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true });
});
test("an installed package gives its state, and without a package the default applies", () => {
@@ -36,8 +44,19 @@ test("an installed package gives its state, and without a package the default ap
assert.equal(legacySwitch(git, legacy(false, false)), true);
assert.equal(legacySwitch(git, legacy(true, false)), false);
assert.equal(legacySwitch(git, legacy(true, true)), true);
// Background is on for every user, also after an update with a disabled Background Slideshow package.
const background = featureEntry("background");
for (const [installed, enabled] of [[false, false], [true, false], [true, true]]) {
assert.equal(legacySwitch(background, { id: "runestone.bg-slideshow", installed, enabled, settings: null }), true);
}
assert.equal(legacySwitch(background, undefined), true);
});
/** A background host with a section already present: the migration of the section does not run. */
function presentBackground(): BackgroundMigrationHost {
return { missing: () => false, hasImage: () => false, migrateFolder: async () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } };
}
test("the migration asks only for features without a switch, and keeps other keys", async () => {
const writes: unknown[] = [];
const asked: string[][] = [];
@@ -46,20 +65,39 @@ test("the migration asks only for features without a switch, and keeps other key
write: async (value: unknown) => { writes.push(value); },
legacy: async (ids: string[]) => { asked.push(ids); return packages; },
});
assert.deepEqual(await migrateFeatures(host({ future: 1 }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }])), ["git"]);
assert.deepEqual(await migrateFeatures(host({ future: 1, background: false }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground()), ["git"]);
assert.deepEqual(asked, [["runestone.git"]]);
assert.deepEqual(writes, [{ future: 1, git: false }]);
assert.deepEqual(await migrateFeatures(host({ git: true }, [])), []);
assert.deepEqual(writes, [{ future: 1, background: false, git: false }]);
assert.deepEqual(await migrateFeatures(host({ git: true, background: true }, []), presentBackground()), []);
assert.equal(asked.length, 1, "A stored switch needs no package read.");
assert.equal(writes.length, 1);
});
test("a missing background section asks for the slideshow package and makes the section", async () => {
const asked: string[][] = [];
const switches: unknown[] = [];
const sections: BackgroundSettings[] = [];
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { sections.push(value); } };
const host = { read: () => ({ git: true, background: false }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } };
assert.deepEqual(await migrateFeatures(host, background), []);
assert.deepEqual(asked, [["runestone.bg-slideshow"]]);
assert.deepEqual(switches, [], "Stored switches stay.");
assert.equal(sections.length, 1);
assert.equal(sections[0].source, "image");
// Both migrations together ask once for both packages.
asked.length = 0;
await migrateFeatures({ ...host, read: () => undefined }, background);
assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow"]]);
assert.deepEqual(switches, [{ git: true, background: true }]);
});
test("a failed package read writes nothing, so the next start tries again", async () => {
const writes: unknown[] = [];
const error = console.error;
console.error = () => {};
try {
const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } });
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { writes.push(value); } };
const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } }, background);
assert.deepEqual(result, []);
assert.deepEqual(writes, []);
} finally { console.error = error; }
@@ -97,9 +135,29 @@ test("a feature session shows its views and commands without loading the feature
await session.launch("source-control");
assert.deepEqual(opened, ["graph", "source-control"]);
assert.equal(loads, 0, "Commands and navigation do not load the feature.");
assert.equal(session.started, false);
await session.stop();
});
test("an action command loads the feature and runs it, and start loads it without a view", async () => {
const runs: string[] = [];
let starts = 0;
const instance: FeatureInstance = { mount: () => () => {}, run: command => { runs.push(command); }, dispose() { runs.push("dispose"); } };
const session = new FeatureSession(featureEntry("background"), fakeContext(), async () => ({ start: () => { starts++; return instance; } }));
assert.deepEqual([...session.commands.keys()], ["next", "pause"]);
assert.equal(session.commands.get("pause")?.title, "Pause background");
assert.equal(session.started, false);
await session.run("next");
assert.equal(session.started, true);
await session.start();
await session.run("pause");
assert.equal(starts, 1, "One instance runs the commands and the start.");
await session.stop();
assert.deepEqual(runs, ["next", "pause", "dispose"]);
await assert.rejects(session.run("missing"), /This command is unavailable/);
await assert.rejects(session.start(), /This feature is off/);
});
test("the first mount starts one instance, and stop disposes it", async () => {
const events: string[] = [];
let starts = 0;
+3 -3
View File
@@ -30,12 +30,12 @@ test("a feature module in a start chunk fails, and a separate dynamic chunk pass
chunk("app.js", { isEntry: true, moduleIds: [`${root}src/lib/features/catalog.ts`] }),
chunk("git.js", { isDynamicEntry: true, facadeModuleId: `${root}src/lib/features/git/index.ts`, moduleIds: [`${root}src/lib/features/git/index.ts`], size: 2048 }),
];
assert.deepEqual(checkChunks(good), { problems: [], sizes: { git: 2048 } });
assert.deepEqual(checkChunks(good, ["git"]), { problems: [], sizes: { git: 2048 } });
const bad = [
chunk("app.js", { isEntry: true, imports: ["shared.js"] }),
chunk("shared.js", { moduleIds: [`${root}src/lib/features/git/model.ts`] }),
chunk("git.js", { isDynamicEntry: true, facadeModuleId: `${root}src/lib/features/git/index.ts` }),
];
assert.deepEqual(checkChunks(bad).problems, ["shared.js loads at start and contains src/lib/features/git/model.ts"]);
assert.deepEqual(checkChunks([chunk("app.js", { isEntry: true })]).problems, ["No chunk starts at src/lib/features/git/index.ts."]);
assert.deepEqual(checkChunks(bad, ["git"]).problems, ["shared.js loads at start and contains src/lib/features/git/model.ts"]);
assert.deepEqual(checkChunks([chunk("app.js", { isEntry: true })], ["git"]).problems, ["No chunk starts at src/lib/features/git/index.ts."]);
});
+1 -2
View File
@@ -65,9 +65,8 @@ test("a required function stays bound to its parent object", async () => {
test("the current host gives every SDK feature when all services are present", async () => {
const pty = { open: async () => {}, write: async () => {}, resize: async () => {}, close: async () => {}, profiles: async () => [], openWindow: async () => {}, dictation: async () => {} };
const files = { chooseFolder: async () => null, pictureFolder: async () => ({ id: "g", path: "p", name: "n" }), grants: async () => [], revoke: async () => false, list: async () => [], readBytes: async () => new Uint8Array(), readSidecar: async () => null, writeSidecar: async () => {} };
const backgrounds = { chooseFolder: async () => null, list: async () => [], read: async () => new Uint8Array() };
const { api, session } = await hostApi({
pty, files, backgrounds, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {},
pty, files, backgrounds: true, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {},
workspace: { ...base.workspace, listMarkdown: async () => [], readMany: async () => [], readBytes: async () => new Uint8Array(), readOptional: async () => null, create: async () => {}, subscribe: () => () => {} },
settings: { ...base.settings, subscribe: () => () => {} },
}, true);
+2 -2
View File
@@ -65,6 +65,6 @@ test('Migration keeps renamed theme IDs and a background image data URL', () =>
});
test('Every section has one old key', () => {
// `runestone.features` came after the settings file. Only the browser preview uses it.
assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.features', 'runestone.language', 'runestone.settings']);
// `runestone.features` and `runestone.background` came after the settings file. Only the browser preview uses them.
assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.background', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.features', 'runestone.language', 'runestone.settings']);
});
+34 -18
View File
@@ -103,20 +103,13 @@ test('subscriber errors do not prevent frame cleanup or remaining notifications'
assert.equal(hub.get('pm-all'), null);
});
test('disable removes frames and subscriptions before cleanup and rejects pending file results', async () => {
test('disable removes frames and subscriptions before cleanup', async () => {
let api!: PluginApi;
let finishRead!: (value: Uint8Array) => void;
let finishList!: (value: { name: string }[]) => void;
let finishPicker!: (value: string | null) => void;
const session = new ExternalSession('org.test.backgrounds', {
workspace: { list: async () => [], read: async () => '', write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
backgrounds: {
chooseFolder: () => new Promise(resolve => { finishPicker = resolve; }),
list: () => new Promise(resolve => { finishList = resolve; }),
read: () => new Promise(resolve => { finishRead = resolve; }),
},
backgrounds: true,
}, () => {}, () => {});
let notifications = 0;
await session.start({ activate(value) {
@@ -130,26 +123,49 @@ test('disable removes frames and subscriptions before cleanup and rejects pendin
assert.throws(() => api.backgrounds!.get('app'), /disabled/);
});
} });
const pending = [api.backgrounds!.read('folder', 'file.png'), api.backgrounds!.list('folder'), api.backgrounds!.chooseFolder()];
const rejected = pending.map(request => assert.rejects(request, /disabled/));
// The deprecated folder methods are gone. Plugins use the folder grants of `api.files`.
for (const name of ['chooseFolder', 'defaultFolder', 'list', 'read', 'readImageSettings', 'writeImageSettings']) assert.equal(name in api.backgrounds!, false, name);
await session.stop();
finishRead(new Uint8Array([1])); finishList([{ name: 'file.png' }]); finishPicker('folder');
await Promise.all(rejected);
assert.equal(notifications, 2);
assert.throws(() => api.backgrounds!.set('app', frame), /disabled/);
assert.throws(() => api.backgrounds!.read('folder', 'file.png'), /disabled/);
assert.throws(() => api.backgrounds!.subscribe(() => {}), /disabled/);
assert.equal(backgroundHub.get('app'), null);
});
test('background commands are allowed in main and settings windows', () => {
test('the Background commands are allowed in the windows that use them, and the old plugin commands are gone', () => {
const build = readFileSync(new URL('../../../src-tauri/build.rs', import.meta.url), 'utf8');
for (const scope of ['default', 'settings']) {
const all = ['background_choose_folder', 'background_folder', 'background_clear_folder', 'background_list', 'background_read', 'background_read_sidecar', 'background_write_sidecar', 'background_migrate'];
const scopes: Record<string, string[]> = { default: all, settings: all, browser: ['background_folder', 'background_list', 'background_read', 'background_read_sidecar'] };
for (const [scope, commands] of Object.entries(scopes)) {
const capability = JSON.parse(readFileSync(new URL(`../../../src-tauri/capabilities/${scope}.json`, import.meta.url), 'utf8'));
for (const command of ['backgrounds_choose_folder', 'backgrounds_default_folder', 'backgrounds_list', 'backgrounds_read', 'backgrounds_read_image_settings', 'backgrounds_write_image_settings']) {
for (const command of all) {
assert(build.includes(`"${command}"`), `${command} needs a generated desktop permission`);
assert(capability.permissions.includes(`allow-${command.replaceAll('_', '-')}`), `${scope} must allow ${command}`);
assert.equal(capability.permissions.includes(`allow-${command.replaceAll('_', '-')}`), commands.includes(command), `${scope} and ${command}`);
}
assert.equal(capability.permissions.some((permission: string) => permission.startsWith('allow-backgrounds-')), false, `${scope} has no old plugin command`);
}
assert.equal(/"backgrounds_/.test(build), false);
});
test('a new app frame changes only the custom properties with a new value', () => {
const writes: string[] = [];
const properties = new Map<string, string>();
const style = { getPropertyValue: (key: string) => properties.get(key) ?? '', getPropertyPriority: () => '',
setProperty: (key: string, value: string) => { writes.push(key); properties.set(key, value); }, removeProperty: (key: string) => { properties.delete(key); } };
const hub = new BackgroundHub(() => ({ style }) as unknown as HTMLElement), owner = Symbol();
hub.set(owner, 'app', frame);
assert.equal(writes.length, 19);
writes.length = 0;
hub.set(owner, 'app', { ...frame, url: 'blob:http://localhost/second' });
assert.deepEqual(writes, ['--rs-background-image']);
writes.length = 0;
hub.set(owner, 'app', { ...frame, url: 'blob:http://localhost/second' });
assert.deepEqual(writes, [], 'The same frame writes nothing');
hub.removeOwner(owner);
assert.equal(properties.size, 0);
writes.length = 0;
hub.set(owner, 'app', frame);
assert.equal(writes.length, 19, 'After a removal, the next frame writes every property again');
hub.removeOwner(owner);
});