diff --git a/CLAUDE.md b/CLAUDE.md index 37c25a0..988fb27 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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. diff --git a/docs/design-decisions.md b/docs/design-decisions.md index 6daedc0..f74b8e4 100644 --- a/docs/design-decisions.md +++ b/docs/design-decisions.md @@ -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. diff --git a/docs/development.md b/docs/development.md index ee3c4e4..b0f950d 100644 --- a/docs/development.md +++ b/docs/development.md @@ -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//`. 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-.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//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 diff --git a/docs/guides/themes.md b/docs/guides/themes.md index e4de9f8..2e871e6 100644 --- a/docs/guides/themes.md +++ b/docs/guides/themes.md @@ -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 diff --git a/docs/menu-surfaces.json b/docs/menu-surfaces.json index 8d61bc3..20277aa 100644 --- a/docs/menu-surfaces.json +++ b/docs/menu-surfaces.json @@ -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" } } } diff --git a/docs/plugin-development.md b/docs/plugin-development.md index c3479e5..175c753 100644 --- a/docs/plugin-development.md +++ b/docs/plugin-development.md @@ -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. diff --git a/docs/plugin-host.md b/docs/plugin-host.md index be2b646..1da69e7 100644 --- a/docs/plugin-host.md +++ b/docs/plugin-host.md @@ -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//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 ` diff --git a/src/lib/features/background/ImageEditor.svelte b/src/lib/features/background/ImageEditor.svelte new file mode 100644 index 0000000..5479851 --- /dev/null +++ b/src/lib/features/background/ImageEditor.svelte @@ -0,0 +1,227 @@ + + + +
+ {$t("Per-image appearance")} +

{$t("Choose an image to change its fit, position, and overlay. Portrait images show in full over a blurred fill by default.")}

+
+
{$t("Image")} +
+ {#if pickerOpen} + +
{ if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); pickerOpen = false; trigger?.focus(); } }}> + { 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]); } }} /> +
{ if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) moveFocus(event, event.currentTarget); }}> + {#each filtered.slice(0, 100) as name (name)} + + {/each} +
+

{!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 })}

+
+ {/if} + +
{$t("Fit")}
+
{$t("Position")}
+
{$t("Overlay")}
+ overlay(event.currentTarget)} /> + overlay(event.currentTarget)} />% +
+
+ + + +
+
+ {#if status.text}

{status.text}

{/if} +
+ + diff --git a/src/lib/features/background/blur.ts b/src/lib/features/background/blur.ts new file mode 100644 index 0000000..a9ee618 --- /dev/null +++ b/src/lib/features/background/blur.ts @@ -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 void; reject: (error: Error) => void; timer: ReturnType }>(); + + /** 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 { + 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((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 { + 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((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."))); } +} diff --git a/src/lib/features/background/engine.ts b/src/lib/features/background/engine.ts new file mode 100644 index 0000000..f98bc94 --- /dev/null +++ b/src/lib/features/background/engine.ts @@ -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; + read(name: string): Promise; + /** The text of the sidecar file, or null. */ + sidecar(): Promise; +} + +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; + /** Make the blurred fill of a loaded image. The engine releases the URL. */ + blur(image: LoadedImage): Promise; + 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(); + /** The blurred fills, oldest first. */ + private blurs = new Map(); + private prepared: { name: string; work: Promise; 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 { + 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 { + 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 { + 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; discarded: boolean } = { name, work: Promise.resolve(null), discarded: false }; + entry.work = (async (): Promise => { + 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 { + 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); + } +} diff --git a/src/lib/features/background/imageSettings.ts b/src/lib/features/background/imageSettings.ts new file mode 100644 index 0000000..5b83c8f --- /dev/null +++ b/src/lib/features/background/imageSettings.ts @@ -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>; [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; + 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 | 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; +} diff --git a/src/lib/features/background/index.ts b/src/lib/features/background/index.ts new file mode 100644 index 0000000..9d1b157 --- /dev/null +++ b/src/lib/features/background/index.ts @@ -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); }; +} diff --git a/src/lib/features/background/sources.ts b/src/lib/features/background/sources.ts new file mode 100644 index 0000000..26cd10d --- /dev/null +++ b/src/lib/features/background/sources.ts @@ -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 = { 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("background_choose_folder", { title }), + /** The current folder for display, or null. */ + current: () => invoke("background_folder"), + clear: () => invoke("background_clear_folder"), + list: () => invoke("background_list"), + read: async (name: string): Promise => { + const bytes = await invoke("background_read", { name }); + return new Blob([bytes instanceof ArrayBuffer ? bytes : Uint8Array.from(bytes)], { type: typeOf(name) }); + }, + readSidecar: () => invoke("background_read_sidecar"), + writeSidecar: (contents: string, expected: string | null) => invoke("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): Promise { + 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): 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 { + const url = URL.createObjectURL(blob); + try { + const image = new Image(); + let timer: ReturnType | undefined; + image.src = url; + await Promise.race([image.decode(), new Promise((_, 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), + 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 { + 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(EVENT, event => accept(event.payload)).then(unlisten => { if (stopped) unlisten(); else off = unlisten; }, () => undefined); + return () => { stopped = true; off?.(); }; +} diff --git a/src/lib/features/backgroundSettings.ts b/src/lib/features/backgroundSettings.ts new file mode 100644 index 0000000..fe1376e --- /dev/null +++ b/src/lib/features/backgroundSettings.ts @@ -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 = Object.freeze({ + source: "none", seconds: 60, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover", +}); + +function record(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +} + +/** 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 { + 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; + write(value: BackgroundSettings): Promise; +} + +/** + * 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 { + 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; +} diff --git a/src/lib/features/catalog.ts b/src/lib/features/catalog.ts index 869a1c6..855c947 100644 --- a/src/lib/features/catalog.ts +++ b/src/lib/features/catalog.ts @@ -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 { diff --git a/src/lib/features/launch.ts b/src/lib/features/launch.ts new file mode 100644 index 0000000..6bf2c6e --- /dev/null +++ b/src/lib/features/launch.ts @@ -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> = { + // 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(); +} diff --git a/src/lib/features/loader.ts b/src/lib/features/loader.ts index 8627093..be5fd1c 100644 --- a/src/lib/features/loader.ts +++ b/src/lib/features/loader.ts @@ -6,6 +6,7 @@ import type { FeatureModule } from "./types.ts"; const imports: Record Promise> = { git: () => import("./git/index.ts"), + background: () => import("./background/index.ts"), }; const modules = new Map>(); diff --git a/src/lib/features/migration.ts b/src/lib/features/migration.ts index 0bc4fc9..47c3a4c 100644 --- a/src/lib/features/migration.ts +++ b/src/lib/features/migration.ts @@ -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("features_legacy", { ids }), }; +const desktopBackground: BackgroundMigrationHost = { + missing: () => readSection("background") === undefined, + hasImage: () => hasImage(readAppearance()), + migrateFolder: async () => !!await invoke("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 { +export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground): Promise { 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 []; } - const next: Record = current && typeof current === "object" && !Array.isArray(current) ? { ...current as Record } : {}; - for (const entry of missing) next[entry.id] = legacySwitch(entry, legacy.find(item => item.id === entry.owner)); - await host.write(next); + if (missing.length) { + const next: Record = current && typeof current === "object" && !Array.isArray(current) ? { ...current as Record } : {}; + 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); } diff --git a/src/lib/features/session.ts b/src/lib/features/session.ts index f28a29b..2b62ff3 100644 --- a/src/lib/features/session.ts +++ b/src/lib/features/session.ts @@ -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 { 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.")); diff --git a/src/lib/features/types.ts b/src/lib/features/types.ts index 42a3d8b..35b8845 100644 --- a/src/lib/features/types.ts +++ b/src/lib/features/types.ts @@ -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; + /** Run a command of the catalog that has no view. */ + run?(command: string): void | Promise; /** The state of a tab for a transfer to another window. */ saveTabState?(view: string): unknown; restoreTabState?(view: string, state: unknown): void | Promise; @@ -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; } diff --git a/src/lib/i18n/messages.ts b/src/lib/i18n/messages.ts index 2d9ab4d..d206299 100644 --- a/src/lib/i18n/messages.ts +++ b/src/lib/i18n/messages.ts @@ -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, Record> = { fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])), diff --git a/src/lib/layout/BrowserWindow.svelte b/src/lib/layout/BrowserWindow.svelte index 509d141..11399f9 100644 --- a/src/lib/layout/BrowserWindow.svelte +++ b/src/lib/layout/BrowserWindow.svelte @@ -88,6 +88,8 @@ {#if message}{/if}
+ + {#each $pluginEditors as view (view.key)} {@const position = bounds[view.key]} @@ -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); } diff --git a/src/lib/layout/Workbench.svelte b/src/lib/layout/Workbench.svelte index b254d1f..87b10e2 100644 --- a/src/lib/layout/Workbench.svelte +++ b/src/lib/layout/Workbench.svelte @@ -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 { diff --git a/src/lib/plugins/backgroundContracts.ts b/src/lib/plugins/backgroundContracts.ts index 3dc6dde..3d0f89d 100644 --- a/src/lib/plugins/backgroundContracts.ts +++ b/src/lib/plugins/backgroundContracts.ts @@ -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; diff --git a/src/lib/plugins/backgrounds.ts b/src/lib/plugins/backgrounds.ts index 04ad295..6aae7f0 100644 --- a/src/lib/plugins/backgrounds.ts +++ b/src/lib/plugins/backgrounds.ts @@ -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>(); 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(); 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' }); } diff --git a/src/lib/plugins/external.ts b/src/lib/plugins/external.ts index cd42e40..bce3f42 100644 --- a/src/lib/plugins/external.ts +++ b/src/lib/plugins/external.ts @@ -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({ root: "", plugins: [] }); @@ -104,6 +105,7 @@ let queue: Promise = 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('backgrounds_choose_folder', { id }), - defaultFolder: () => invoke('backgrounds_default_folder', { id }), - list: folder => invoke<{ name: string }[]>('backgrounds_list', { id, folder }), - read: async (folder, name) => Uint8Array.from(atob(await invoke('backgrounds_read', { id, folder, name })), character => character.charCodeAt(0)), - readImageSettings: folder => invoke('backgrounds_read_image_settings', { id, folder }), - writeImageSettings: (folder, contents, expected) => invoke('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)); }; } diff --git a/src/lib/plugins/externalSession.ts b/src/lib/plugins/externalSession.ts index 56bb14b..8e90da0 100644 --- a/src/lib/plugins/externalSession.ts +++ b/src/lib/plugins/externalSession.ts @@ -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 & { - openFile?: PluginApi["openFile"]; backgrounds?: BackgroundFiles; + /** True gives the plugin `api.backgrounds`: the background frames of each target. */ + openFile?: PluginApi["openFile"]; backgrounds?: boolean; completionTransport?: NonNullable["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) => { diff --git a/src/lib/settings/store.ts b/src/lib/settings/store.ts index ca73a40..ea7cb92 100644 --- a/src/lib/settings/store.ts +++ b/src/lib/settings/store.ts @@ -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>; @@ -22,6 +22,7 @@ export const LEGACY_KEYS: Readonly> = { 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. */ diff --git a/src/lib/theme/AppearanceSettings.svelte b/src/lib/theme/AppearanceSettings.svelte index c3dbcbf..59e95b4 100644 --- a/src/lib/theme/AppearanceSettings.svelte +++ b/src/lib/theme/AppearanceSettings.svelte @@ -1,43 +1,42 @@