Compare commits

..
14 Commits
Author SHA1 Message Date
Knotty Wyvern 7c2d526e13 Remove AGENTS.md and raise the lowest Opus subagent effort to high
AGENTS.md only pointed to CLAUDE.md. No tracked file outside docs/archive links to it.
2026-10-30 00:48:21 -07:00
Knotty Wyvern 424a817c90 Give the unstaged group of Source control its own title
The Changes section and its unstaged group both showed "Changes (2)".
The group title is now "Unstaged changes (2)". The section title keeps the total count.
2026-10-30 00:21:43 -07:00
Knotty Wyvern d849c3c1b5 Name a plugin that stays in two usage examples 2026-10-29 22:22:23 -07:00
Knotty Wyvern c68a1afb6d Set the version to 0.1.51 2026-10-29 22:22:01 -07:00
Knotty Wyvern 956ead818b Translate Project Management and add its tests and guide
- Every interface string of Project Management goes through the catalog: 539 new rows with fr, ja, and zh-CN.
- Storage and model messages use a local message() marker and stay free of host imports. The interface translates them.
- A board renders again when the language changes. Dates use the interface language.
- Fix: the ribbon button waits for the feature switches at startup, and the settings code loads no feature module.
- Add six smoke tests: board state, cards, menus, drag and drop, views, and language.
- Add docs/guides/project-management.md and UI-060. Update the user, plugin, SDK, host, development, and interface docs and CLAUDE.md.
- Name the fake board view of tree/renameUndo "Board fixture", because the native Project Management button is now in the ribbon.
2026-10-29 21:53:09 -07:00
Knotty Wyvern e66f089176 Make Project Management a native feature
- Move the storage and model of the plugin into src/lib/features/pm/ as pure TypeScript, so the skill can still bundle them.
- Move the DOM interface onto the host menus, the shared tooltip, and the host icons.
- A ribbon button opens Project Management. Board tabs keep the owner runestone.pm and the board-<hex> view IDs through view patterns.
- Read only .runestone/pm/. Offer the plugin migration, with backups, for legacy notes.
- A save, move, or delete reads only that card again. Watcher paths reach the feature.
- Add Settings → Project Management and the projectManagement section. View states move to localStorage.
- Background reads the boards from workspace.json. Remove api.backgrounds and the boards service.
- Add yaml 2.9.1. Use the host markdown-it.
- Move 18 plugin test files to tests/unit/features/pm/ and add native tests.
2026-10-29 20:54:29 -07:00
Knotty Wyvern e6deecc092 Make PDF Viewer a native feature
- Move the PDF Viewer plugin into src/lib/features/pdf/ with pdfjs-dist 6.4.299 (minified builds).
- A static pdf document type marks PDF files and opens them as tabs. The first PDF tab loads the module.
- The worker, the character maps, the fonts, and the decoders come from the app. One worker for each tab.
- The toolbar uses IconButton and the shared tooltip, with the new zoom-in, zoom-out, fit-width, and rotate icons.
- Add THIRD_PARTY_NOTICES.md for PDF.js and xterm.
- Update the tests, the menu inventory, the docs, and UI-059.
2026-10-29 19:41:17 -07:00
Knotty Wyvern 833f793244 Make Terminal a native feature
- Move the Terminal plugin into src/lib/features/terminal/ on the host Svelte runtime, with xterm 6.0.0 and addon-fit 0.11.0.
- Buttons, shortcuts, Help rows, and the close guard follow the Terminal switch. The first use loads the module.
- Add Settings → Terminal and the terminal settings section. The first start copies the old runestone.terminal key.
- The 16 ANSI colors come from the --rs-ansi-* tokens.
- Off asks first when a shell runs in any window (pty_running).
- Rust: no pty-data or pty-exit events, an owner check for write, resize, and close, output joined up to 64 KiB or 8 ms, and the sessions of a reloaded page close.
- Remove api.pty, the terminal contribution, TerminalSlot, and the plugin loader of the smoke harness.
- Check only the tested switches in the Background smoke test.
- Update the tests, the menu inventory, the docs, and UI-058.
2026-10-29 19:02:58 -07:00
Knotty Wyvern 53b9cea7f0 Fix the folder path of the Background measurement
realpath from node:fs/promises has no native form. Use realpathSync.native from node:fs.
2026-10-29 17:43:18 -07:00
Knotty Wyvern ab868bbe8e Make Background a native feature
- Background replaces the Background Slideshow plugin and the background image of Appearance. It shows a folder as a slideshow, or one image.
- It is on by default. Its module loads at launch only when a folder or an image is chosen.
- Rust keeps the one folder in background-folder.json. The interface never sends a path. Eight background_* commands replace the six deprecated backgrounds_* commands.
- The first start moves the slideshow folder and settings, and keeps the saved image as the image source.
- One blur worker with a cache, fewer folder reads, and a decode before each fade. The hub writes only the changed properties.
- Remove the deprecated folder methods of api.backgrounds. set, get, and subscribe stay for the Project Management plugin.
- Show the view buttons in the workbench test without text, after UI-056.
- Update the tests, the measurement tool, the docs, and UI-057.
2026-10-29 17:25:17 -07:00
Knotty Wyvern 115c32fa92 Show the view control with icons only
- Write, Source, Read, and Split show icons only, at every width.
- Each control keeps its accessible name and a tooltip with its shortcut.
- UI-056 records the rule. It replaces the names of UI-049.
2026-10-29 16:28:25 -07:00
Knotty Wyvern 8c43f598fb Set the version to 0.1.50 2026-10-29 16:20:11 -07:00
Knotty Wyvern 4e5c3cb165 Add the memory and response measurement of native features
- scripts/measureFeatures.mjs starts a test build with remote debugging, runs each scenario 3 times, and writes the medians to output/phase-7/<stage>/.
- It records the private bytes and the working set of the process tree, the JS heap, the start time, the first-need time, and long tasks.
- It refuses the installed RuneStone and its identifier, and it stops only the process tree that it started.
- Plugin mode installs the plugin ZIPs through a local Gitea-format server. Native mode uses the features settings section.
2026-10-29 15:52:19 -07:00
Knotty Wyvern d3218b2501 Make Git a native feature with an off switch
- Add the native feature runtime in src/lib/features/: the catalog, the switches, the first-start migration, the loader, and the feature sessions.
- Add Settings → Features and the features settings section.
- Add features_legacy. It reads the old plugin packages and changes nothing.
- Move Git from the plugin into src/lib/features/git/, on host internals.
- Remove api.git, the git contribution key, and the SDK Git types.
- Add pnpm check:features. It fails when a feature module loads at start.
- Update the tests, the menu inventory, the docs, and UI-055.
2026-10-29 15:51:21 -07:00
253 changed files with 27514 additions and 1966 deletions
-3
View File
@@ -1,3 +0,0 @@
# Agent instructions
The instructions for AI agents in this repository are in [CLAUDE.md](CLAUDE.md). Read and obey that file.
+4 -2
View File
@@ -2,7 +2,8 @@
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/`).
Optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_Terminal`.
Git, Background, Terminal, PDF Viewer, and Project Management are native features with an off switch in Settings → Features (`src/lib/features/`). They do not use the plugin API.
Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_CSV_Viewer`.
The [development guide](docs/development.md#architecture) maps the source folders.
## Skills
@@ -24,6 +25,7 @@ The [development guide](docs/development.md#architecture) maps the source folder
| `pnpm test` | Unit tests (`tests/unit/`) |
| `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust tests |
| `pnpm check:menus` | Menu surface inventory |
| `pnpm check:features` | Build check: no native feature module loads at start |
| `pnpm smoke [filter...]` | Browser smoke tests (`tests/smoke/`). See [Browser smoke tests](docs/development.md#browser-smoke-tests). |
| `pnpm build:installer --version <version>` | Windows installer. See [Builds](docs/builds.md). |
| `pnpm build:browser-engine --release-url <url> --version <version>` | Browser engine ZIP and its pin. See [Build the browser engine](docs/builds.md#build-the-browser-engine). |
@@ -117,5 +119,5 @@ Rules from the owner:
## Subagents
Use only Haiku 5.5 (`model: "haiku"`) or Opus 5.5 (`model: "opus"`, effort `medium` to `xhigh`). Never use Sonnet or Fable.
Use only Haiku 5.5 (`model: "haiku"`) or Opus 5.5 (`model: "opus"`, effort `high` to `xhigh`). Never use Sonnet or Fable.
The `runestone-project-management` skill maps task types to models and lists what each brief must contain.
File diff suppressed because it is too large Load Diff
+95 -1
View File
@@ -352,6 +352,7 @@ Keyboard focus now scrolls only the menu panel. It cannot dismiss a menu by scro
- Evidence: All 11 slideshow unit tests, TypeScript checks, and the settings browser check pass.
- Limits: Native desktop appearance requires user review.
- Replaces: The 800-millisecond fade rule in the interface guide.
- Update 2026-10-29: The rule stays. The native Background feature implements it ([UI-057](#ui-057--background-replaces-background-image-and-background-slideshow)).
### UI-016 — Translucent code blocks
@@ -442,6 +443,7 @@ Evidence: RuneStone_Git/.audit/git-tooltip-evidence.json and git-tooltip-*.png.
- Shared implementation: The image sidecar API, optional blurredUrl frames, and separate foreground and cover layers.
- Evidence: Host frame and sidecar checks cover layout, cleanup, size limits, and external changes. Plugin checks accompany the card review.
- Limits: Native desktop appearance requires user review.
- Update 2026-10-29: The rule stays. The native Background feature implements it ([UI-057](#ui-057--background-replaces-background-image-and-background-slideshow)).
### UI-021 — Workspace links in document panes
@@ -589,6 +591,7 @@ The overlay retains the source hue. Selected glyph backgrounds stay transparent,
Evidence: RuneStone_Terminal/.audit/terminal-selection-evidence.json records source colors, alpha, composites, and contrast.
Screenshots cover both themes at 620 and 1440 pixels. Measured text contrast is 8.94:1 in dark and 11.80:1 in light.
Native shell, background image, and desktop acceptance remain open.
Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-selection` ([UI-058](#ui-058--settings--terminal-and-theme-colors-in-the-terminal)).
### UI-030 — Settings installation checkbox theme drift
@@ -811,6 +814,7 @@ Native shell, background image, and desktop acceptance remain open.
- Evidence: The applied colors and the Source colors of each tag group are the same as before stage 5a-1, for every built-in theme and a saved schema 2 custom theme. `tests/unit/theme/customThemes.spec.ts` covers schema 3, `base`, and the conversion of old syntax names.
- Replaces / replaced by: The template format of [UI-028](#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes). Its transparency rule remains.
- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open.
- Update 2026-10-29: The native Terminal feature uses the terminal roles ([UI-058](#ui-058--settings--terminal-and-theme-colors-in-the-terminal)).
### UI-043 — Opaque menus
@@ -923,7 +927,7 @@ Native shell, background image, and desktop acceptance remain open.
- Type: Rule change
- Date: 2026-10-28
- Status: Implemented for user review
- Status: Implemented for user review. The names beside the icons are superseded by [UI-056](#ui-056--icon-only-view-control).
- Decision source: Owner decisions 4 and 5 of 2026-10-27 (interface review issues 5 and 7), stage 5-3.
- Previous rule: Two icon-only switchers, "Document view" (Edit, Read, Split) and "Editor layout" (Writer, IDE), showed only the current choice until hover. Hover widened them, so the target moved. The same views had other names in the tab menu ("Reading view", "Source mode") and in the status bar ("IDE"). The file name showed in the tab, in the breadcrumb as a full path, as a title, and in the status bar.
- New rule: One radio group shows Write, Source, and Read at all times, with an icon and a name. Narrow panes show only the icons. The arrow keys move the choice, and the group has one Tab stop. The current choice gets the selection fill and an accent bar. Hover gets only a fill. A separate **Split** toggle shows Read beside Write or Source. Write and Source keep Split, and Read ends it. Ctrl+E switches between Write and Source, and Ctrl+Shift+E switches between Read and the editor. The tab menu, the status bar, the docs, and the code use the same names. "IDE" is not a view name.
@@ -1012,3 +1016,93 @@ Native shell, background image, and desktop acceptance remain open.
- Evidence: `tests/smoke/browser/engine.smoke.mjs`, with screenshots of each state in both themes and a 360-pixel Settings window.
- Replaces / replaced by: The bundled engine.
- Limits: The download does not resume. A failed download starts again from zero. The engine installs for the current Windows account only. Browser checks mock the native download.
### UI-055 — Settings → Features and native Git
- Type: Rule change
- Date: 2026-10-29
- Status: Implemented for user review
- Decision source: The owner decisions "Native features decision" and "Phase 7 replaced" of 2026-10-29, and Phase 7 decisions 1A, 2A, 3A, 4A, and 5C.
- Previous rule: Git was the optional Git plugin. Settings → Plug-ins enabled or disabled it. Its strings were English only, its file rows and buttons drew their own icons, and its status refreshed every 10 seconds. The "Show Git graph" command showed in the **Plug-in views** menu.
- New rule: Git is a native feature. A new Settings page, **Features**, between Appearance and Plug-ins, has one switch for each native feature with its name and one line of description. A feature that is off loads no code and shows no controls. A feature that is on loads its code at first need. Off applies at once in all windows. Source control uses the shared `IconButton`, tooltips, icons, and catalog. Its status refreshes after a workspace change, on window focus, and after each Git action. **Show Git graph** is in the command palette and in Source control. The new shared icons are `toggle`, `minus`, and `upload`.
- Reason: The owner chose response time and memory over the versatility of the plugin API. A switch lets users remove the controls of a feature that they do not use.
- Scope: Settings → Features, the Source control pane, the Git diff and Git graph tabs, the line history in the status bar, and the command palette.
- Shared implementation: `src/lib/features/`, `src/lib/layout/SettingsDialog.svelte`, `src/lib/plugins/external.ts`, and `src-tauri/src/features.rs`.
- Evidence: `tests/smoke/features/settings.smoke.mjs` and `tests/smoke/features/git.smoke.mjs`, with screenshots in both themes and at 360 pixels in `output/smoke/features/`.
- Replaces / replaced by: The Git plugin (`runestone.git` 0.1.10).
- Limits: Code that a window loaded stays in memory until the window reloads. The old package stays installed until the user removes it.
### UI-056 — Icon-only view control
- Type: Rule change
- Date: 2026-10-29
- Status: Implemented for user review
- Decision source: The owner's review of 0.1.50 (2026-10-29): the buttons at the top right of the editor went "from icon only to icon + text".
- Previous rule: [UI-049](#ui-049--one-view-control-and-one-file-name). Write, Source, and Read, and the Split toggle, showed an icon and a name. Panes narrower than 560 pixels showed only the icons.
- New rule: Write, Source, Read, and Split show icons only, at every width. All choices stay visible, so the targets do not move. Each control keeps its accessible name and a tooltip with the name and the shortcut. The current choice keeps the selection fill and the accent bar.
- Reason: The editor header is a compact toolbar of familiar actions, and the other header tools are icon only.
- Scope: The view control and the Split toggle of each document pane.
- Shared implementation: `src/lib/layout/ViewModes.svelte`.
- 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.
### UI-058 — Settings → Terminal and theme colors in the terminal
- Type: Rule change
- Date: 2026-10-29
- Status: Implemented for user review
- Decision source: The owner decisions of Phase 7, stage 7-3 (2026-10-29), and decision 5C. The card "Use the host terminal colors".
- Previous rule: The Terminal plugin (`runestone.terminal` 0.1.11) kept its settings in a modal dialog with **Save settings** and **Cancel**. It saved them in the `runestone.terminal` key of `localStorage`. Its ANSI colors came from the status and accent tokens. Thus blue was the accent color, and most bright colors were the same as the normal colors.
- New rule: Terminal is a native feature with a switch in Settings → Features. **Settings → Terminal** shows only while Terminal is on. It has **Default profile** (a shared action menu without the JavaScript Debug Terminal), **Font size**, **Scrollback lines**, and **Blink cursor**. Each change saves at once to the `terminal` section of `settings.json`. Open terminals take the font, the scrollback, and the cursor. **Terminal settings** in the profile menu opens Settings. The 16 ANSI colors come from the `--rs-ansi-*` tokens. Text is `--rs-text`, the cursor is `--rs-accent` on `--rs-bg`, and the selection is `--rs-selection` with at most 65% alpha. Off asks first when a window runs a shell, with the words of the close guard.
- Reason: The owner chose response time and memory over the plugin API. Settings apply at once on one Settings page, as the [Settings](ui-design.md#settings) rules require. Terminal colors keep their ANSI meaning in every theme.
- Scope: Settings → Terminal, Settings → Features, the terminal panel, terminal windows, and Help.
- Shared implementation: `src/lib/features/terminal/` (`theme.ts` for the colors), `src/lib/features/TerminalSettings.svelte`, `src/lib/features/terminalSettings.ts`, `src/lib/features/terminalKeys.ts`, `src/lib/theme/roles.ts`, and `src-tauri/src/pty.rs`.
- Evidence: `tests/smoke/features/terminal.smoke.mjs` and `tests/unit/features/terminal.spec.ts`, with screenshots in both themes and at 360 pixels in `output/smoke/features/terminal/`.
- Replaces / replaced by: The settings dialog and the ANSI color map of the Terminal plugin. The terminal roles of [UI-042](#ui-042--theme-file-format-3-and-terminal-colors) and the selection cap of [UI-029](#ui-029--text-selection-transparency) stay.
- Limits: The smoke tests use mock shells. Real shells, dictation, and native desktop appearance need user review. The old package stays installed until the user removes it.
### UI-059 — The PDF toolbar on shared controls
- Type: Rule change
- Date: 2026-10-29
- Status: Implemented for user review
- Decision source: The owner decisions of Phase 7, stage 7-4 (2026-10-29), and decision 5C.
- Previous rule: The PDF Viewer plugin (`runestone.pdf-viewer` 0.0.5) drew its own toolbar buttons, tooltip spans, and `title` tooltips. **Fit width** and **Reload PDF** showed a caption. Disabled buttons faded with opacity. Rotation used an icon that the plugin drew. All strings were English only.
- New rule: PDF Viewer is a native feature with a switch in Settings → Features. Each PDF tab has one toolbar of shared `IconButton` controls with the shared tooltip: **Previous page**, the page field, the page count, **Next page**, **Zoom out**, the zoom percent, **Zoom in**, **Fit width**, **Rotate clockwise**, and **Reload PDF**. All buttons are icon only. **Fit width** is a toggle with the selection fill and the accent bar while the page fits the tab. Previous and next page use the `up` and `down` icons of the find panel. The new shared icons are `zoom-in`, `zoom-out`, `fit-width`, and `rotate`. The toolbar wraps in a narrow tab. The page is white paper in both themes. All strings come from the catalog.
- Reason: The owner chose response time and memory over the plugin API. The PDF toolbar is a compact toolbar of familiar actions, so it follows the icon rules of [Icons and labels](ui-design.md#icons-and-labels).
- Scope: The PDF tab, its toolbar, its password form, its status line, the file tree mark of PDF files, and Settings → Features.
- Shared implementation: `src/lib/features/pdf/`, `src/lib/features/pdfDocument.ts`, `src/lib/features/session.ts`, `src/lib/ui/Icon.svelte`, and `src/lib/ui/IconButton.svelte`.
- Evidence: `tests/smoke/features/pdf.smoke.mjs` and `tests/unit/features/pdf.spec.ts`, with screenshots in both themes, at 900 pixels, and with keyboard focus in `output/smoke/features/pdf/`.
- Replaces / replaced by: The toolbar of the PDF Viewer plugin.
- Limits: The tab shows one page at a time. The old package stays installed until the user removes it.
### UI-060 — Native Project Management
- Type: Rule change
- Date: 2026-10-29
- Status: Implemented for user review
- Decision source: The owner decisions of Phase 7, stage 7-5 (2026-10-29), and decision 5C.
- Previous rule: The Project Management plugin (`runestone.pm` 0.2.49) opened from the **Plug-in views** menu. It bundled the tooltip and icon helpers of the SDK, and its strings were English only. Its settings were a settings view of the plugin. It read boards and cards from visible Markdown notes and from `.runestone/pm/`. It offered the boards service to other plugins, and it read board frames through `api.backgrounds`.
- New rule: Project Management is a native feature with a switch in Settings → Features. A ribbon button with the `kanban` icon, after Terminal, opens the default board of the workspace or All tasks. The button is active while a Project Management tab is active. **Plug-in views** does not list Project Management. The board scope, the select choices, and the details pickers use the shared action menu. Icon-only controls use the shared tooltip and the shared action icons. All interface text comes from the catalog. **Settings → Project Management** shows only while the feature is on. It has **Priority levels** and **Default board**, and each change saves at once. **More actions** → **Project Management settings** shows the same component. The feature reads only `.runestone/pm/`. For a workspace with data in visible notes, the **Migrate Project Management data** panel names the data. It offers **Migrate** and **Not now**. The migration keeps exact backups and does not change the original files. **Migration complete** lists the original files for the user to remove.
- Reason: The owner chose response time and memory over the plugin API. One ribbon button is easier to find than a menu entry. A migration that the user starts keeps the original notes safe.
- Scope: The ribbon button, the board tabs, All tasks, Settings → Project Management, the migration panel, and the Background board list.
- Shared implementation: `src/lib/features/pm/`, `src/lib/features/pmSettings.ts`, `src/lib/features/pmBoards.ts`, `src/lib/features/ProjectManagementSettings.svelte`, `src/lib/layout/PluginRibbon.svelte`, and `src/lib/features/session.ts`.
- Evidence: `tests/smoke/features/pm*.smoke.mjs` and `tests/unit/features/pm/`, with screenshots in both themes in `output/smoke/features/`. `pmLanguage.smoke.mjs` shows a board in French.
- Replaces / replaced by: The Project Management plugin, its settings view, the boards service, and `api.backgrounds`. The rules of [UI-033](#ui-033--list-capacity-and-a-frozen-all-tasks-overview) through [UI-038](#ui-038--fixed-workspace-default-board) stay.
- Limits: **More actions**, the card actions, and the list actions stay popup panels of the feature. The old package stays installed until the user removes it.
+58 -14
View File
@@ -62,10 +62,11 @@ Windows is the primary platform. macOS and Linux builds are experimental.
| `workspace.rs` | The workspace root of each window, path checks, atomic saves, the file watcher, search |
| `plugins.rs` | Plugin package review, installation, enable state, removal, and recovery |
| `plugin_sources.rs` | Plugin downloads from Gitea releases |
| `git.rs` | The Git service for the Git plugin. It runs the `git` program. |
| `pty.rs`, `terminal_platform.rs` | Pseudo-terminals for the Terminal plugin |
| `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 first-start migration. It changes no plugin file. |
| `pty.rs`, `terminal_platform.rs` | The shell sessions of the Terminal feature, the shell search, and terminal windows. A session belongs to the window and the page that opened it. |
| `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. |
@@ -87,7 +88,9 @@ 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 |
| `completion/`, `git/` | Contracts and services that plugins use |
| `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, and the Background settings (`backgroundSettings.ts`). Each feature has a folder: `git/`, `background/`, `terminal/`, `pdf/`, and `pm/`. The main-bundle files of Terminal are `terminalKeys.ts`, `terminalSettings.ts`, `terminalHost.ts`, `TerminalHost.svelte`, and `TerminalSettings.svelte`. The main-bundle files of Project Management are `pmSettings.ts`, `pmBoards.ts`, and `ProjectManagementSettings.svelte`. 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`) |
| `ui/` | Shared menus, pickers, and action icons |
| `i18n/` | Interface text in English, French, Japanese, and Simplified Chinese |
@@ -111,11 +114,12 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command
| Data | Location |
| --- | --- |
| Documents | Ordinary files in the workspace folder |
| Workspace state: tab order, pins, bookmarks, templates, Project Management boards | `.runestone/` in the workspace |
| Workspace state: tab order, pins, bookmarks, templates, and the boards, cards, labels, and images of Project Management (`.runestone/pm/`) | `.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, Terminal, Project Management | `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. |
| Window layout, the open tabs of each workspace, and the view state of each Project Management tab (`runestone.pm.viewStates`) | The WebView storage (`localStorage`) of the app. RuneStone can lose these values without harm. |
#### The settings file
@@ -131,13 +135,17 @@ On macOS, it is `~/Library/Application Support/<identifier>/`. On Linux, it is `
"appearance": { "theme": "default", "mode": "dark" },
"customThemes": [],
"customThemesLegacy": [],
"language": "en"
"language": "en",
"features": { "git": true, "background": true, "terminal": true, "pdf": true, "pm": true },
"background": { "source": "folder", "seconds": 60, "order": "name", "paused": false, "targets": ["app"], "overlay": 0, "position": "center", "size": "cover" },
"terminal": { "defaultProfile": "", "fontSize": 13, "scrollback": 10000, "cursorBlink": true },
"projectManagement": { "priorityLevels": 3 }
}
```
| Rule | Detail |
| --- | --- |
| Sections | `general`, `appearance`, `customThemes`, `customThemesLegacy` (the original version 1 themes), and `language`. 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), `background` (the source, the timing, the targets, and the folder layout of Background), and `terminal` (the default profile, the font size, the scrollback, and the cursor of Terminal). `projectManagement` holds the priority levels of Project Management. The host does not interpret their values. The frontend normalizes each section. |
| Size | At most 8 MiB in total. The appearance can hold an image data URL of up to 3,000,000 characters. |
| Writes | `settings_write` replaces one section. The host writes a complete temporary file and renames it. Then it sends `settings-changed` to all windows with the section, the revision, and the value. |
| Damaged file | The host moves the file to `settings.corrupt-<seconds>.json` and writes a new file with the defaults. The first window that reads the settings shows a message one time. |
@@ -152,7 +160,7 @@ After that, `src/lib/settings/store.ts` reads the sections from memory and tells
- Workspace documents stay ordinary local files. Users keep access to them when plugins are disabled.
- The core includes Markdown table editing, rendering, and table formulas.
- Native file access, file watching, search, Git, and terminals belong in Rust.
- Optional features ship as plugins. The [plugin development reference](plugin-development.md) defines the package format and the API.
- Built-in features with an off switch live in `src/lib/features/`. Other optional features ship as plugins. The [plugin development reference](plugin-development.md) defines the package format and the API.
- For sync, prefer a local Git clone. Do not use a live network share as the sync path.
These stay outside the product:
@@ -177,6 +185,7 @@ Run these commands from the repository folder. They do not need an installer.
| `pnpm smoke` | Browser smoke tests. See [Browser smoke tests](#browser-smoke-tests). |
| `pnpm build` | The production frontend build |
| `pnpm check:menus` | The inventory of menu surfaces. See [Interface design](ui-design.md). |
| `pnpm check:features` | A full build. It fails when a native feature module loads at start. See [Native features](#native-features). |
To run one test file, use `node --experimental-strip-types --import ./tests/unit/_svelte/register.mjs --test tests/unit/tables/selection.spec.ts`.
The `--import` hook compiles `.svelte.ts` modules, so a test can import them.
@@ -199,6 +208,42 @@ All text that a user reads goes through the catalog in `src/lib/i18n/messages.ts
Errors of the plugin API stay in English, because they are for plugin developers.
`pnpm check` runs `scripts/i18nAudit.mjs`. It fails for a key that the catalog does not have, a catalog key that the code does not use, and a row without all translations.
## Native features
Git, Background, Terminal, PDF Viewer, and Project Management 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, commands, and document types | `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, 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, commands, and document tabs in the workbench | `src/lib/features/session.ts` and `src/lib/plugins/external.ts` |
| The feature code | `src/lib/features/<feature>/index.ts` and its components |
- The 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.
- Terminal has no view and no launch rule. `TerminalHost.svelte` puts the panel in the workbench and in the terminal window, and the first use loads the module. `terminalKeys.ts` holds the shortcuts and the Help rows. Settings → Terminal (`TerminalSettings.svelte`) loads no xterm.
- `@xterm/xterm` and `@xterm/addon-fit` are host dependencies. `pnpm check:features` keeps them out of the start chunks.
- PDF Viewer has a document type and no view. The file tree marks PDF files through `identifyPdf` in `src/lib/features/pdfDocument.ts`, in the main bundle. The first PDF tab loads the module and calls `FeatureInstance.mountDocument`. Each tab reads its file with `workspace_read_bytes` and starts its own PDF.js worker. Closing the tab, or Off, stops the worker.
- `pdfjs-dist` is a host dependency. `src/lib/features/pdf/engine.ts` loads the minified build. The worker, the character maps, the standard fonts, and the image decoders are Vite assets of the app, so PDF.js makes no network request. `build.assetsInlineLimit` in `vite.config.js` keeps these files out of the code.
- Project Management has one editor view, `planning`, with `launch: true`. The view pattern `board-<hex of the board ID>` gives each board its own tab. Its ribbon button in `PluginRibbon.svelte` calls the launch, which opens the default board of the workspace or All tasks. It has no command.
- Project Management reads and writes only `.runestone/pm/`. `storage/legacy.ts` finds data in the old format of visible notes. The interface then offers the migration, with backups in `.runestone/pm/backups/`. It migrates only after the user chooses it.
- `pm/storage/` and `pm/model/` stay pure TypeScript without host modules, so the `runestone-project-management` skill can bundle them. They mark their user-visible text with `message()` from `storage/message.ts` and keep it in English. The interface translates that text with `localize()` in `pm/ui/text.ts`.
- The `projectManagement` section holds the priority levels (`pmSettings.ts`). The default board is `defaultBoardId` in `.runestone/pm/workspace.json`, so each workspace has its own. Appearance → Background reads the board list from the same file through `pmBoards.ts`, without the feature code.
- The first start makes the `projectManagement` section from the kept settings of the Project Management plugin. When `localStorage` has no view states, it also copies the view states of the plugin.
- `yaml` is a host dependency of Project Management. The card descriptions use the markdown-it of the host.
- [THIRD_PARTY_NOTICES.md](../THIRD_PARTY_NOTICES.md) gives the version, license, and source of each third-party package that a feature includes. Update it when you add or update such a package.
- The first start makes the `terminal` section from the `runestone.terminal` key of `localStorage`, which the Terminal plugin wrote. The old key stays.
- Before Terminal goes off, Settings asks `pty_running` for the shells of all windows. Off closes the sessions of each window.
- Host code never imports a feature folder statically. `pnpm check:features` builds the app. It fails when a feature module, or a library that only a feature needs, is in a chunk that loads at start.
- 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`. Add a launch rule only when the feature must run without a view.
## Plugin SDK
The plugin SDK in `packages/plugin-sdk/` is the only source of the public plugin types.
@@ -240,8 +285,7 @@ A test states what it needs near its top. The runner skips the test, with the re
| Line | Requirement |
| --- | --- |
| `// @requires plugin:terminal` | The compiled Terminal plugin |
| `// @requires repo:RuneStone_Git/dist` | A file or folder in a sibling plugin checkout |
| `// @requires repo:RuneStone_Local_Autocomplete/src` | A file or folder in a sibling plugin checkout |
| `// @requires electron` | The browser engine dependencies. Run `npm ci --prefix browser-runtime`. |
| `// @known-issue <defect>` | The test fails because of a known app defect. The run reports it as `known`. If the test passes, the run fails, so that someone removes the line. |
@@ -249,14 +293,14 @@ A test states what it needs near its top. The runner skips the test, with the re
| --- | --- |
| `SMOKE_URL` | The frontend address. The default is `http://127.0.0.1:1420`. When the runner starts Vite, it uses the port of this address, so two checkouts can run tests at the same time. |
| `RUNESTONE_PLUGIN_REPOS` | The folder of the sibling plugin checkouts. The default is the parent folder of this repository. |
| `RUNESTONE_TERMINAL_DIST` | The compiled Terminal plugin. The default is `RuneStone_Terminal/dist` in that folder. |
| `RUNESTONE_CSP` | `1` sends and checks the content security policy. `--csp` sets it. |
| `CHROME_PATH` | A Chromium browser for Playwright |
| `PLAYWRIGHT_MODULE` | A different Playwright package |
To write a smoke test, start from an existing test in the same area. The harness in `tests/smoke/_harness/index.mjs` starts the browser, mocks the Tauri commands, and gives an in-memory workspace.
The harness also has default handlers for the settings file and for tab transfers. All pages of one browser context share them.
The harness also has default handlers for the settings file, for tab transfers, and for the `pty_*` shells of Terminal. All pages of one browser context share them.
The mock shell sends its output through the channel of `pty_open`. To send more, use `window.__TEST__.pty.output(id, text)` and `window.__TEST__.pty.exit(id, code)`.
To seed preferences, set the old `localStorage` keys before the first load. The app then migrates them.
To read or change a section later, use `window.__TEST__.settings(section)` and `window.__TEST__.writeSettings(section, value)`.
A failed test saves `failure.png` in its output folder and prints the page console errors and warnings.
+53
View File
@@ -0,0 +1,53 @@
# Git guide
[RuneStone](../../README.md) · [User guide](../user-guide.md)
This guide explains how to review changes, stage files, commit, push, and pull with Git in RuneStone.
Git is part of RuneStone and is on by default. It needs the `git` program on the system path. To turn it off, see [Turn features on or off](../user-guide.md#turn-features-on-or-off).
## Review and stage changes
1. Open the root folder of the repository as the workspace.
2. Select **Source control** in the navigation buttons at the top of the side pane.
3. Select a file to open its diff in an editor tab. **Open file** in that tab opens the file in the editor.
4. Select the plus button beside a file to stage it, or the minus button to unstage it. The button beside a group stages or unstages all files in that group.
Source control shows the current branch and the **Changes** section with two groups. **Staged changes** go into the next commit. **Unstaged changes** holds the files that still need review or staging.
A file shows in both groups when only part of its content is staged. Unstage keeps the content of the working file.
Source control reads the repository again after each change in the workspace, also in the `.git` folder, and when the window gets focus. **Refresh source control** reads it at once.
A diff tab shows the file as it was when you selected it. Select the file again to update the diff. Git reads the files on disk, so save your edits first.
## Commit
1. Stage the files for the commit.
2. Enter a commit message.
3. Select **Commit staged**, or press Ctrl+Enter (⌘+Enter on macOS).
A commit contains only the staged changes. Git hooks and signing settings apply as usual. Set your author name, email, and signing tools in Git outside RuneStone.
If a hook stops the commit, the error stays visible, and the message stays in the field.
## Push and pull
**Push to the upstream branch** and **Pull from the upstream branch** use the upstream branch of the current branch and your current Git sign-in.
Pull accepts only a fast-forward update. It stops when local changes or diverging commits prevent that update. RuneStone never forces a push, and it does not set an upstream branch.
## Commit graph
Select **Show Git graph** in Source control, or run **Show Git graph** from the command palette (Ctrl+Shift+P). The graph opens in an editor tab.
The graph shows the latest 100 commits with their branches, tags, IDs, authors, dates, and messages. Dashed lines continue to parents outside these 100 commits.
Select a commit to see its changed files, then select a file to see its diff. The arrow keys, Home, and End move through the commits.
## Line history
While a saved text file is open, the status bar shows the author and the date of the last commit for the line of the cursor. A new or changed line can show no author until you commit it.
## Limits
- Parent repositories and linked worktrees with their metadata outside the workspace do not work. Open the repository root.
- RuneStone does not include a Git program.
- Create repositories, switch branches, resolve conflicts, and set remotes with Git outside RuneStone. RuneStone has no discard, reset, or force push.
- A Git operation stops after 30 seconds or 2 MiB of output. If an operation stops, refresh to see its result before you do it again.
- The diff of a new text file shows at most 512 KiB. A binary file shows a notice instead of a diff.
+168
View File
@@ -0,0 +1,168 @@
# Project Management guide
[RuneStone](../../README.md) · [User guide](../user-guide.md)
This guide explains how to plan work with boards, lists, and cards in RuneStone. It also explains the timeline and calendar views of the same cards.
Project Management is part of RuneStone and is on by default. To turn it off, see [Turn Project Management off](#turn-project-management-off).
## Open Project Management
Select **Project Management** (the board icon) in the left ribbon. It opens the default board of the workspace, or **All tasks** when the workspace has no default board. See [Choose the default board](#choose-the-default-board).
Each board opens in its own tab. To open another board in the same tab, select the board name in the toolbar. Then select a board or **All tasks**.
A workspace without boards shows **Create your first board**. Select it and enter a name.
## Boards and lists
A board holds lists, and a list holds cards. A new board starts with the lists **To do**, **In progress**, and **Done**.
| Action | How |
| --- | --- |
| Create a board | **More actions** (the three dots) → **New board** |
| Rename a board | **Rename board** beside the board name, or **More actions** → **Rename board** |
| Archive or restore a board | **More actions** → **Archive board** or **Restore board** |
| Delete a board | **More actions** → **Delete board**. The cards stay in All tasks. You cannot undo this action. |
| Add a list | **Add a list** in the toolbar of a board |
| Rename a list, or set its status | List actions (the button in the list header) → **Edit list** |
| Move a list | Drag its header, or use **Move left** and **Move right** in the list actions |
| Set a card limit | List actions → **Set list limit**. A warning shows at the limit. Cards can still go into the list. |
| Archive all cards of a list | List actions → **Archive all cards** |
| Delete a list | List actions → **Delete list**. Its cards go to **Unlisted**. Their status does not change. |
| Collapse or expand a list | The collapse button in the list header. A collapsed list is a narrow strip with its name and card count. |
**Status when a card enters this list** sets the status of each card that you move into the list. Choose **Do not change status** to keep the status of the card.
## Cards
| Action | How |
| --- | --- |
| Create a card | **Add a card** at the bottom of a list, or **More actions** → **New card** |
| Open the card details | Select the card |
| Move a card on the board | Drag the card, or use **Move to list**, **Move up**, and **Move down** in the card actions |
| Put a card on another board | Card actions → **Move to board** |
| Take a card off this board | Card actions → **Remove from board**. The card stays in All tasks and on its other boards. |
| Archive or restore a card | Card actions → **Archive** or **Restore**. **More actions** → **Show archived** shows the archived cards. |
| Delete a card | Card actions → **Delete card**. It removes the card from all boards. You cannot undo this action. |
| Work with more than one card | **Select cards** in the toolbar. Then move the selected cards to a list or a board, or delete them. |
| Find a card | **Search tasks** in the toolbar. The search looks in titles, descriptions, tags, labels, assignments, and custom fields. |
A card can be on more than one board, with a different list on each board.
The card details have the title, the labels, and the description in Markdown.
A change to the description stays a draft until you select **Save**. **Cancel** restores the saved text. When you close the card with a draft, the card shows an unsaved marker.
Board and list changes save at once. Other fields save when you close the card details.
### Card details
Select **Add details** in the card details to add one of these fields:
| Field | Use |
| --- | --- |
| **Priority** | The urgency of the card, apart from its labels |
| **Labels** | Colored labels that all boards of the workspace share |
| **Tags** | Plain words for the search |
| **Planned dates** | The first and the last day of the work. The Gantt view shows them as a bar. |
| **Deadline** | The due date. Gantt and Calendar show it with ◆. |
| **Work session** | A start time and an end time. The Calendar view shows the session. |
| **Assignments** | People, teams, or customers |
| **Color** | The color of the card |
| **Custom field** | A name and a value of your choice |
| **Subtasks and linked cards** | Smaller tasks of the card, and other cards that block it, that it blocks, or that relate to it |
| **Card cover** | An image of the card that shows on the board |
**More actions** → **Add existing note** makes a new card from a Markdown note of the workspace. The card gets the file name as its title and the note text as its description.
The note does not change. Later edits to the note do not change the card.
## Labels and priority
Select **Manage labels** (the tag icon) in the toolbar to add, rename, recolor, or delete labels.
All boards of the workspace share the labels. A change of name or color applies to each card with the label. When you delete a label, RuneStone removes it from all cards.
Priority has two, three, or five levels. To change the number of levels, see [Change the Project Management settings](#change-the-project-management-settings).
## Views
The buttons at the left of the toolbar change the view of the board.
| View | Shows |
| --- | --- |
| **Kanban** | The lists and their cards |
| **Gantt** | Each card with its planned dates as a bar and its deadline as ◆, for 28 days from the visible date |
| **Calendar** | Deadlines and work sessions by **Day**, **Week**, or **Month**, in the time zone of your computer |
**Previous**, **Today**, **Next**, and the date field change the visible dates of Gantt and Calendar.
In Calendar, you can create a card from a date:
- In **Month**, select the number of a day to create a card with that deadline.
- In **Day** or **Week**, select an hour to create a card with a one-hour work session.
Gantt and Calendar do not move a card when you drag it. To change dates, open the card and edit **Planned dates**, **Deadline**, or **Work session**.
## All tasks
**All tasks** shows the cards of all boards of the workspace in one view.
- Lists with the same name on different boards share one column. The match ignores uppercase and lowercase letters.
- In each column, the cards show below the name of their board. Cards without an active board show below **No active board**.
- You cannot drag cards between columns. To move a card, open it and change **Board** or **List**, or open its board.
- A new card in All tasks needs a board. Choose the board and the list in the card details.
## Images
To add an image to a card, paste it or drop it into the description, or select **Add image**.
Use a PNG, JPEG, GIF, or WebP image of at most 50 MiB.
To show an image on the board, add **Card cover** and choose one of the images of the card.
**More actions** → **Customize background** sets an image behind the open board, or behind All tasks.
To show the Background slideshow on the boards, see [Choose where the background shows](themes.md#choose-where-the-background-shows).
## Choose the default board
1. Open **Settings → Project Management**, or select **More actions** → **Project Management settings**.
2. Select **Default board**.
3. Select a board, or **All tasks**.
Each workspace has its own default board. The ribbon button then opens that board. Restored tabs keep their board.
An archived or deleted default board opens All tasks.
## Change the Project Management settings
Open **Settings → Project Management**. The page shows only while Project Management is on. Each change saves at once.
| Setting | Values |
| --- | --- |
| **Priority levels** | **2** (High and Low), **3** (High, Medium, and Low), or **5** (Highest through Lowest). The default is 3. The priorities of existing cards do not change. |
| **Default board** | **All tasks** or one board of the current workspace. See [Choose the default board](#choose-the-default-board). |
After an update, the first start copies the priority levels of the old Project Management plugin.
## Where the boards are
The boards, cards, labels, and images of a workspace are in `.runestone/pm/` in the workspace folder.
To see this folder in the file tree, turn on **Show .runestone folder** in Settings → General.
Git ignores `.runestone/pm/`, because RuneStone puts a `.gitignore` file there. To keep a copy of your boards, back up this folder separately.
## Move old Project Management notes
Early versions of the Project Management plugin kept boards and cards in visible Markdown notes, and labels in `runestone-pm-labels.json`.
RuneStone reads only `.runestone/pm/`. When a workspace has data in the old format, Project Management shows **Migrate Project Management data**.
1. Read the list of boards, task notes, and label files.
2. If the offer names notes with invalid properties, repair these notes first.
3. Select **Migrate**. RuneStone copies the data to `.runestone/pm/` and keeps exact backups in `.runestone/pm/backups/`.
4. Examine the boards.
5. Remove the original files that **Migration complete** lists, then select **Done**.
The migration does not change or remove the original files. **Not now** hides the offer in this tab.
## Turn Project Management off
1. Open **Settings → Features**.
2. Clear **Project Management**.
Off closes the Project Management tabs and removes the ribbon button and the settings page in all windows.
Your boards stay in `.runestone/pm/`, and your settings stay. Turn Project Management on again in the same place.
+47 -20
View File
@@ -1,29 +1,30 @@
# Terminal guide
[RuneStone](../../README.md) · [User guide](../user-guide.md) · [Install a plugin](../plugins.md#install-a-plugin)
[RuneStone](../../README.md) · [User guide](../user-guide.md)
This guide explains how to use shells, scripts, and workspace tasks with the optional Terminal plugin.
This guide explains how to use shells, scripts, and workspace tasks in the terminal of RuneStone.
Install and enable the Terminal plugin first. The shells and script runtimes that you use must be installed on your computer.
Terminal is part of RuneStone and is on by default. The shells and script runtimes that you use must be installed on your computer. To turn Terminal off, see [Turn Terminal off](#turn-terminal-off).
## Open and arrange terminals
| Action | How |
| --- | --- |
| Show or hide the terminal panel | Ctrl+` or Ctrl+J. Sessions and scrollback stay. |
| Show or hide the terminal panel | **Terminal** in the left ribbon, Ctrl+`, or Ctrl+J. Sessions and scrollback stay. |
| New terminal | Ctrl+Shift+` or the + button |
| Split the active terminal | Ctrl+Shift+5. The new pane uses the same folder and profile. |
| New terminal window | Ctrl+Shift+Alt+` |
| Split the active terminal | Ctrl+Shift+5 or **Split terminal**. The new pane uses the same folder and profile. |
| New terminal window | Ctrl+Shift+Alt+`, or **New terminal window** in the profile menu |
| End the active session | **Kill terminal**, or Delete while an entry in the terminal list has focus |
| Change the panel size | **Maximize panel** or **Restore panel**. Shells do not restart. |
| End all sessions in the panel | **Close terminal (end all sessions)** |
The terminal list shows only when more than one session is open.
Closing a separate terminal window ends its sessions.
Closing a terminal window ends its sessions. When you close a workspace window with running sessions, RuneStone asks first.
You can type before a shell starts. RuneStone sends the text when the shell is ready.
## Choose a shell
Open the menu beside the + button to start a terminal with a specific profile.
Open **Terminal profiles and tasks** (the arrow beside the + button) to start a terminal with a specific profile.
| System | Profiles |
| --- | --- |
@@ -31,10 +32,26 @@ Open the menu beside the + button to start a terminal with a specific profile.
| macOS and Linux | Bash and PowerShell |
The menu shows only the shells that RuneStone finds on your computer.
The same menu has **Split Terminal with Profile**, **Select Default Profile**, **Configure Terminal Settings**, and the task commands.
Terminal settings set the font size, scrollback lines, cursor blink, and default profile. RuneStone keeps them on this computer.
The same menu has **Split terminal with profile**, **Terminal settings**, **Select the default profile**, and the task commands.
New terminals get the RuneStone environment, including `PATH`.
## Change the terminal settings
Open **Settings → Terminal**, or choose **Terminal settings** in the profile menu. The page shows only while Terminal is on.
| Setting | Values |
| --- | --- |
| **Default profile** | The shell of a new terminal. The JavaScript Debug Terminal is not a choice. |
| **Font size** | 9 to 28 pixels. The default is 13. |
| **Scrollback lines** | 100 to 100,000 lines. The default is 10,000. |
| **Blink cursor** | The cursor blinks in the focused terminal. On by default. |
A change saves at once and applies to all windows. Open terminals take the new font size, scrollback, and cursor. The default profile applies to new terminals.
After an update, the first start copies the settings of the old Terminal plugin.
The terminal colors come from the color theme. The text, the cursor, and the selection use the theme colors. The 16 ANSI colors use the `ansi-*` keys of the theme.
To change them, see [Edit a theme](themes.md#edit-a-theme) and [Color keys](themes.md#color-keys).
## Copy and paste
- Drag across terminal text to select it.
@@ -48,24 +65,25 @@ Open **More terminal actions** for these commands:
| Command | Result |
| --- | --- |
| **Run Active File** | Saves and runs the active file in the terminal. |
| **Run Selected Text** | Sends the text that is selected in the editor to the terminal. |
| **Clear Terminal** | Clears the scrollback. |
| **Run Recent Command…** (Ctrl+Alt+R) | Runs a command from this session again. |
| **Go to Recent Directory…** (Ctrl+G) | Changes to a recent folder. |
| **Scroll to Previous Command** / **Next Command** (Ctrl+Up / Ctrl+Down) | Moves between command prompts. |
| **Scroll to the previous command** / **Scroll to the next command** (Ctrl+Up / Ctrl+Down) | Moves between command prompts. |
| **Clear the terminal** | Clears the scrollback. |
| **Run the active file** | Saves and runs the active file in the terminal. |
| **Run selected text** | Sends the text that is selected in the editor to the terminal. |
| **Start dictation** | Starts Windows voice typing. See [Debug JavaScript and use dictation](#debug-javascript-and-use-dictation). |
| **Go to a recent folder…** (Ctrl+G) | Changes to a recent folder. |
| **Run a recent command…** (Ctrl+Alt+R) | Runs a command from this session again. |
**Run Active File** supports Python, JavaScript, PowerShell, Bash, Ruby, Windows batch files, and executables.
**Run the active file** supports Python, JavaScript, PowerShell, Bash, Ruby, Windows batch files, and executables.
The terminal keeps command history in memory only. PowerShell and Bash record a command after it finishes. Command Prompt records the text that you submit.
## Configure workspace tasks
A task is a named command that you can start from a menu.
1. Choose **Configure Tasks…**. RuneStone creates or opens `.runestone/tasks.json`.
1. Choose **Configure tasks…**. RuneStone creates or opens `.runestone/tasks.json`.
2. Add an object to the `tasks` array with `label` and `command`.
3. Optionally, add `profile` with one of these IDs: `powershell`, `pwsh`, `git-bash`, `cmd`, or `bash`.
4. Choose **Run Task…** and select the task.
4. Choose **Run a task…** and select the task.
Example (`.runestone/tasks.json`):
@@ -84,5 +102,14 @@ Each task runs in its own terminal at the workspace root. Tasks run only when yo
**JavaScript Debug Terminal** in the profile menu starts a Node.js REPL with a local inspector on a free port.
Attach an external debugger to the address that the terminal shows. RuneStone does not include a debugger.
**Start Dictation** starts Windows voice typing (Win+H) in the focused terminal. Set up the microphone and voice typing in Windows first.
**Start dictation** starts Windows voice typing (Win+H) in the focused terminal. Set up the microphone and voice typing in Windows first.
On other systems, use the dictation shortcut of the operating system.
## Turn Terminal off
1. Open **Settings → Features**.
2. Clear **Terminal**.
3. If a window runs a shell, RuneStone asks "Terminal sessions will end. Turn off Terminal?". Confirm to continue.
Off ends the terminal sessions of every window. The Terminal buttons, shortcuts, and Help rows do not show. A terminal window shows "Terminal is off. Turn it on in Settings → Features."
Your terminal settings and `.runestone/tasks.json` stay. Turn Terminal on again in the same place.
+61 -9
View File
@@ -2,7 +2,7 @@
[RuneStone](../../README.md) · [User guide](../user-guide.md)
This guide explains how to choose colors, set a background image, and edit, create, or share a custom theme.
This guide explains how to choose colors, show a background, and edit, create, or share a custom theme.
Open **Settings → Appearance**. Appearance settings apply to all workspaces on this computer and to all open windows.
@@ -21,20 +21,72 @@ Each named theme has its own fonts and syntax colors. Fonts come from your compu
## Adjust transparency
**Transparent surfaces** tints work areas with a background image and compatible plugin surfaces.
**Transparent surfaces** tints work areas with a [background](#show-a-background) and compatible plugin surfaces.
Menus stay opaque. With a background image, menus are at least 92% opaque and blur the image.
Set **Transparency amount** from 0% to 100%. The default is 18%.
Turn off **Transparent surfaces** for opaque surfaces. Text and icons stay opaque in both cases.
## Set a background image
## Show a background
1. Choose **Choose image…** and select a PNG, JPEG, WebP, or GIF file up to 50 MiB.
2. Set **Image size** to **Fill**, **Fit**, or **Actual size**.
3. Set **Image position**.
4. Set **Image overlay** from -100% to 100%. Negative values lighten the image, and positive values darken it.
The **Background** section shows a folder of images as a slideshow, or one image, behind the workspace.
Set **Background source** to **Folder**, **Image**, or **None**.
The image shows in new tabs. RuneStone keeps it on this computer.
The Project Management plugin can keep a separate image for a board. The Background Slideshow plugin can replace the image for a time.
### Show a folder as a slideshow
1. Set **Background source** to **Folder**, or choose **Choose folder…**.
2. Select a folder with PNG, JPEG, GIF, or WebP images. Each image can be up to 64 MiB.
3. Set **Seconds per image** from 1 to 86,400.
4. Set **Image order** to **File name** or **Random**.
**File name** uses natural order, so `2.png` comes before `10.png`. **Random** does not repeat the current image when the folder has other images.
Images fade over two seconds. When your system reduces motion, the images change without a fade.
RuneStone reads the folder again when a window gets the focus, after a settings change, and after every 10 images.
Subfolders, links, and unreadable files do not show. When no image loads, the background goes away, and RuneStone tries again after the image time, at least 5 seconds.
**Remove folder** forgets the folder. It changes no file.
### Show one image
1. Set **Background source** to **Image**, or choose **Choose image…**.
2. Select a PNG, JPEG, WebP, or GIF file up to 50 MiB.
RuneStone keeps the image on this computer. **Remove image** deletes the saved copy. It does not change your file.
### Set the layout
- **Image size**: **Fill**, **Fit**, or **Actual size**.
- **Image position**: one of nine positions.
- **Image overlay**: from -100% to 100%. Negative values lighten the image, and positive values darken it.
The folder and the image keep separate layouts.
### Change one image of the folder
Portrait images show in full over a blurred fill by default. To change one image:
1. Open **Per-image appearance**.
2. Choose the image in **Image**. Type part of its name to find it.
3. Set **Fit**, **Position**, and **Overlay**. The preview shows the result.
4. Choose **Save image appearance**.
**Reset image appearance** returns the image to the folder layout.
RuneStone keeps these settings in `.runestone-backgrounds.json` in the image folder. When another program changed the file, choose **Reload image settings** and make the change again.
### Choose where the background shows
Under **Show the background in**, select **The workspace and new tabs**, **All Project Management boards**, or one board.
The board list shows the Project Management boards 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
+2 -2
View File
@@ -70,10 +70,10 @@ Voice typing is not part of the Linux checks.
| Editors | Edit Markdown, source code, tables, images, and diagrams. Check undo, keyboard shortcuts, and both themes. |
| Clipboard and dialogs | Copy and paste text, tables, and images. Check folder selection, external links, and file reveal. |
| Plugins | Install plugin ZIPs through Settings, enable them, restart, disable them, and remove them. Check that plugin data stays. |
| Terminal plugin | Install the Terminal ZIP. Bash starts in the workspace, accepts Unicode, resizes, and exits when its session closes. |
| Terminal | Open the terminal panel. Bash starts in the workspace, accepts Unicode, resizes, and exits when its session closes. |
| Settings | Change preferences, restart, and make sure that they stay. Check separate workspace windows. |
For the Terminal ZIP, see [Build examples](plugin-development.md#build-examples) and the [plugin installation guide](plugins.md).
For the use of Terminal, see the [Terminal guide](guides/terminal.md).
Check terminal profiles after a desktop launch too. A desktop launcher can have a different `PATH` from an interactive shell.
Known Linux limits:
+117 -139
View File
@@ -1,13 +1,8 @@
{
"date": "2026-10-15",
"date": "2026-10-29",
"scope": [
"RuneStone",
"RuneStone_Project_Management",
"RuneStone_Terminal",
"RuneStone_Background_Slideshow",
"RuneStone_Local_Autocomplete",
"RuneStone_Git",
"RuneStone_PDF_Viewer",
"RuneStone_CSV_Viewer"
],
"limits": [
@@ -94,6 +89,13 @@
"design": "Shared action menu",
"check": "tests/smoke/menus/consistency.smoke.mjs"
},
"RuneStone/src/lib/features/git/GitGraph.svelte": {
"counts": {
"picker": 1
},
"design": "Commit history listbox of the native Git feature, not a popup menu",
"check": "tests/smoke/features/git.smoke.mjs"
},
"RuneStone/src/lib/layout/CommandPalette.svelte": {
"counts": {
"picker": 1,
@@ -153,14 +155,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,
@@ -176,120 +170,6 @@
"design": "Shared action menu",
"check": "tests/smoke/menus/consistency.smoke.mjs"
},
"RuneStone_Project_Management/src/choices-ui.ts": {
"counts": {
"action": 1
},
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_Project_Management/src/details-ui.ts": {
"counts": {
"picker": 1,
"localPopup": 4
},
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_Project_Management/src/labels-ui.ts": {
"counts": {
"picker": 1,
"localPopup": 3
},
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_Project_Management/src/preferences.ts": {
"counts": {
"action": 1,
"nativeChoice": 1
},
"design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained",
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_Project_Management/src/priority-ui.ts": {
"counts": {
"action": 1,
"picker": 1,
"localPopup": 3
},
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_Project_Management/src/relations-ui.ts": {
"counts": {
"nativeChoice": 1,
"picker": 1,
"localPopup": 5
},
"design": "Shared relationship choice and direct searchable picker rows; older-host choice fallback retained",
"check": "RuneStone_Project_Management/tests/relations-menu.spec.ts; tests/menu-audit.spec.ts; tests/related-cards.spec.ts"
},
"RuneStone_Project_Management/src/tags.ts": {
"counts": {
"picker": 2,
"localPopup": 2
},
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
},
"RuneStone_Project_Management/src/ui.ts": {
"counts": {
"action": 4,
"nativeChoice": 13,
"picker": 1,
"localPopup": 1
},
"design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained",
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts; tests/list-limits.spec.ts; tests/all-tasks.spec.ts; tests/card-board-details.spec.ts"
},
"RuneStone_Terminal/src/TerminalDock.svelte": {
"counts": {
"action": 1
},
"design": "Synchronized shared action menu snapshot",
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
},
"RuneStone_Terminal/src/TerminalPicker.svelte": {
"counts": {
"picker": 2,
"localPopup": 3
},
"design": "Shared searchable picker",
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
},
"RuneStone_Terminal/src/TerminalSettings.svelte": {
"counts": {
"action": 1,
"localPopup": 1
},
"design": "Synchronized shared action menu snapshot",
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
},
"RuneStone_Background_Slideshow/src/contracts.ts": {
"counts": {
"action": 1
},
"design": "API type declaration, no renderer",
"check": "pnpm check"
},
"RuneStone_Background_Slideshow/src/image-settings-ui.ts": {
"counts": {
"action": 1,
"nativeChoice": 1,
"picker": 2,
"localPopup": 3
},
"design": "Host action menus and shared searchable image picker; native image select only on older hosts",
"check": "RuneStone_Background_Slideshow/tests/settings.smoke.mjs"
},
"RuneStone_Background_Slideshow/src/settings.ts": {
"counts": {
"action": 1
},
"design": "Host action menus and shared searchable image picker; native image select only on older hosts",
"check": "RuneStone_Background_Slideshow/tests/settings.smoke.mjs"
},
"RuneStone_Local_Autocomplete/src/main.mjs": {
"counts": {
"action": 1,
@@ -298,13 +178,6 @@
"design": "Host radio menu; native server select only on older hosts",
"check": "tests/smoke/plugins/choiceMenus.smoke.mjs"
},
"RuneStone_Git/src/view.js": {
"counts": {
"picker": 1
},
"design": "Commit history listbox, not a popup menu",
"check": "Source inspection: persistent history list retains its own layout"
},
"RuneStone_CSV_Viewer/src/index.js": {
"counts": {
"action": 1,
@@ -322,12 +195,117 @@
"design": "Shared action menu for interface language; settings retain ordinary controls",
"check": "tests/smoke/settings/displayLanguage.smoke.mjs; tests/smoke/menus/consistency.smoke.mjs"
},
"RuneStone_Project_Management/src/workspace-default.ts": {
"RuneStone/src/lib/features/background/BackgroundSettings.svelte": {
"counts": {
"nativeChoice": 1
"action": 1,
"localPopup": 4
},
"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"
"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"
},
"RuneStone/src/lib/features/terminal/TerminalDock.svelte": {
"counts": {
"action": 1
},
"design": "Shared action menu through showActionMenu",
"check": "tests/smoke/features/terminal.smoke.mjs"
},
"RuneStone/src/lib/features/terminal/TerminalPicker.svelte": {
"counts": {
"picker": 2,
"localPopup": 3
},
"design": "Shared searchable picker",
"check": "tests/smoke/features/terminal.smoke.mjs"
},
"RuneStone/src/lib/features/TerminalSettings.svelte": {
"counts": {
"action": 1,
"localPopup": 1
},
"design": "Shared action menu for the default profile in Settings → Terminal",
"check": "tests/smoke/features/terminal.smoke.mjs"
},
"RuneStone/src/lib/features/pm/ui/host.ts": {
"counts": {
"action": 2
},
"design": "The host layer of Project Management: showActionMenu of managedActionMenu.ts and the shared tooltip",
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
},
"RuneStone/src/lib/features/pm/ui/choices-ui.ts": {
"counts": {
"action": 1
},
"design": "Shared choice adapter: the native selects stay hidden for their values, and the host action menu shows the choices",
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
},
"RuneStone/src/lib/features/pm/ui/priority-ui.ts": {
"counts": {
"action": 1
},
"design": "Shared action menu for the card priority",
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
},
"RuneStone/src/lib/features/pm/ui/details-ui.ts": {
"counts": {
"picker": 1,
"localPopup": 4
},
"design": "Shared searchable picker classes (rs-picker) for the optional card details",
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
},
"RuneStone/src/lib/features/pm/ui/labels-ui.ts": {
"counts": {
"picker": 1,
"localPopup": 3
},
"design": "Shared searchable picker classes (rs-picker) for labels",
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
},
"RuneStone/src/lib/features/pm/ui/relations-ui.ts": {
"counts": {
"nativeChoice": 1,
"picker": 1,
"localPopup": 5
},
"design": "Shared relationship choice through the choice adapter and direct searchable picker rows",
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
},
"RuneStone/src/lib/features/pm/ui/tags.ts": {
"counts": {
"picker": 2,
"localPopup": 2
},
"design": "Shared searchable picker classes (rs-picker) for tag suggestions",
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
},
"RuneStone/src/lib/features/pm/ui/ui.ts": {
"counts": {
"action": 3,
"nativeChoice": 12,
"picker": 1,
"localPopup": 1
},
"design": "Board, list, card, scope, and background menus use the host action menu. Native selects stay hidden behind the shared choice adapter",
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
},
"RuneStone/src/lib/features/ProjectManagementSettings.svelte": {
"counts": {
"action": 1,
"localPopup": 2
},
"design": "Shared action menu for the priority levels and the default board in Settings → Project Management",
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
}
}
}
+25 -144
View File
@@ -11,11 +11,8 @@ This reference gives the package contract, the build procedure, and the API for
- [Versions and releases](#versions-and-releases)
- [Plugin API](#plugin-api)
- [Use the SDK instead of native calls](#use-the-sdk-instead-of-native-calls)
- [Terminal API](#terminal-api)
- [Folder grants](#folder-grants)
- [Plugin services](#plugin-services)
- [Git API](#git-api)
- [Background API](#background-api)
## Install the SDK
@@ -147,22 +144,21 @@ In user instructions, do not tell users to load JSON, select a build folder, ren
Each example is specific to one plugin. Read the package scripts of a plugin before you build it.
For the RuneStone source setup, see [Run from source](development.md#run-from-source).
### Example: Terminal
### Example: CSV Viewer
Source: [Terminal repository](https://git.knottywyvern.com/kwyvern/RuneStone_Terminal), its `package.json`, and its `scripts/build.mjs`.
Source: [CSV Viewer repository](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer), its `package.json`, `plugin.json`, `scripts/build.mjs`, and `README.md`.
| Item | Value |
| --- | --- |
| Prerequisites | Node.js 24 and pnpm 10. Run `pnpm install --frozen-lockfile` in the Terminal folder. |
| Working folder | The Terminal repository root |
| Prerequisites | Node.js 24 or later and pnpm. Run `pnpm install --frozen-lockfile` in the CSV Viewer folder. Put the RuneStone source checkout beside it, in a folder with the name `RuneStone`. The source imports shared interface files from `../../RuneStone/src/lib/ui/`. |
| Working folder | The CSV Viewer repository root |
| Command | `pnpm build` |
| Output | `releases/runestone.terminal-<version>.zip` in the Terminal folder |
| Output | `releases/runestone.csv-viewer-<version>.zip` in the CSV Viewer folder. `<version>` is the `version` of `plugin.json`, for example `0.1.3`. |
The build compiles the Svelte interface and its dependencies into `dist/` (`main.js`, `style.css`, `plugin.json`, and `README.md`). Then it makes the ZIP.
The build stops when the versions in `package.json` and `plugin.json` are different.
To compile into `dist/` without a ZIP, run `node scripts/build.mjs --no-package`.
RuneStone supplies the native terminal sessions. The plugin supplies the interface, shortcuts, and session controls.
For use of the terminal, see the [Terminal guide](guides/terminal.md).
The build compiles `src/index.js` with esbuild into a readable `dist/main.js`. It copies `plugin.json` and `README.md` into `dist/` and writes `dist/build.json`.
Then it runs `scripts/packagePlugin.mjs` of the RuneStone checkout on `dist/`. Set `RUNESTONE_ROOT` to use another RuneStone checkout for this step.
The build stops when the versions in `package.json` and `plugin.json` are different. It also stops when the release ZIP of the version exists. Set the next version in both files first.
To compile into `dist/` without a ZIP, run `pnpm compile`.
### Example: Workspace overview
@@ -217,8 +213,8 @@ The SDK feature checks do this. Their error names each missing feature and tells
```ts
import { hasFeature, requireFeature, requireFeatures } from "@runestone/plugin-sdk";
requireFeatures(api, ["pty", "workspace.readBytes"]);
const pty = requireFeature(api, "pty");
requireFeatures(api, ["files", "workspace.readBytes"]);
const files = requireFeature(api, "files");
if (hasFeature(api, "settings.subscribe")) watchSettings();
```
@@ -226,6 +222,8 @@ Without the SDK, examine the member directly: `if (!api.workspace.readBytes) thr
Older hosts ignore unknown fields in objects that you pass to the host, such as a view `icon` or `launch` handler.
The host has no `api.backgrounds`. Only the native Background feature shows images behind the interface, and plugins cannot set or read its frames.
### Activation and cleanup
- The host limits activation, each view mount, and each cleanup callback to five seconds. A timeout reports an error.
@@ -233,7 +231,7 @@ Older hosts ignore unknown fields in objects that you pass to the host, such as
- Plugins activate in every RuneStone window except browser windows.
- `api.signal` aborts when shutdown starts. Use it to stop pending work.
- After shutdown starts, every API call throws an error. Ignore results that arrive after shutdown.
- On disable, the host removes contributions, commands, views, and background frames first. Then it runs view cleanups and `onDispose` callbacks in reverse order.
- On disable, the host removes contributions, commands, and views first. Then it runs view cleanups and `onDispose` callbacks in reverse order.
- Remove timers, listeners, and other resources in cleanup. Closing a view and disabling the plugin share the same cleanup promise.
- Plugins have full application access. The SDK does not isolate plugin JavaScript.
@@ -265,11 +263,8 @@ Older hosts ignore unknown fields in objects that you pass to the host, such as
| `assets.read(path)` | | Read a package file as a `Uint8Array`. |
| `ui.showActionMenu(options)` | yes | Open the shared RuneStone action menu. See [Menus](#menus). |
| `completion` | yes | Autocomplete fields and providers. See the [completion API](completion.md). |
| `git` | yes | Git operations for the active workspace. See [Git API](#git-api). |
| `pty` | yes | Terminal sessions. See [Terminal API](#terminal-api). |
| `files` | yes | Folders outside the workspace that the user granted to the plugin. See [Folder grants](#folder-grants). |
| `services` | yes | Data that one plugin offers to other plugins. See [Plugin services](#plugin-services). |
| `backgrounds` | yes | Background image frames. See [Background API](#background-api). |
### Commands
@@ -311,7 +306,6 @@ Closing an editor tab or disabling the plugin disposes the view.
A `launch()` handler can select a default target and call `api.openView(id)`.
Explicit `api.openView` calls and restored tabs do not call `launch()`.
Example: [Project Management](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/development.md#workspace-default-board) uses `launch()` to open the default board of the workspace.
### Navigation buttons
@@ -387,11 +381,9 @@ Only one enabled plugin can own each key. The host removes contributions before
| Key | Purpose | Owner |
| --- | --- | --- |
| `terminal` | Mounts terminal controls in a host element. Returns update, command, and dispose functions. | Terminal plugin |
| `git` | Supplies line blame for the editor. | Git plugin |
| `browser` | The built-in browser. `newTab(url?)` opens a browser tab. `open(url)` returns false when the system browser must open a web link, for example before the engine is installed. | RuneStone |
A terminal contribution must stop its controls and native sessions before its cleanup finishes.
Earlier hosts also had `api.pty` and a `terminal` key for the Terminal plugin. They are gone, because RuneStone now includes Terminal as a native feature.
### Theme tokens
@@ -426,49 +418,12 @@ The window sends a `runestone-theme-changed` event after each theme change. A pl
## Use the SDK instead of native calls
Do not call `invoke`, `listen`, or other `@tauri-apps/api` functions from a plugin. Do not read the private files of other plugins.
Use the `api` members below. They check plugin shutdown, and they will stay available when a later host runs each plugin in its own isolated context.
Make sure that an optional member exists before you use it. Keep the native call only as a fallback for older hosts.
Use the `api` members of the [API reference](#api-reference). They check plugin shutdown, and they will stay available when a later host runs each plugin in its own isolated context.
Make sure that an optional member exists before you use it.
The host still accepts the native calls of released plugins. A later host can remove them.
| Plugin | Current call | Purpose | Use instead |
| --- | --- | --- | --- |
| Terminal | `invoke("pty_open")`, `listen("pty-data")`, `listen("pty-exit")` | Start a shell and receive its output and exit code | `api.pty.open({ ..., onData, onExit })` |
| Terminal | `invoke("pty_write")`, `invoke("pty_resize")`, `invoke("pty_close")` | Send input, change the size, stop the shell | `write`, `resize`, and `close` of the session from `api.pty.open` |
| Terminal | `invoke("pty_profiles")` | List the installed shells | `api.pty.profiles()` |
| 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 Git, Project Management, Local Autocomplete, PDF Viewer, and CSV Viewer plugins make no native calls.
The Local Autocomplete and CSV Viewer plugins make no native calls.
Their test scripts replace `window.__TAURI_INTERNALS__` with a test double. That is test code and does not go into the package.
## Terminal API
`api.pty` (`version: 1`) starts shells in pseudo terminals. The SDK types are `PtyApi` and `PtySession`.
| Member | Contract |
| --- | --- |
| `profiles()` | Returns the installed shells as `{ id, title, kind }`. |
| `open(options)` | Starts a shell and returns a session. See the options below. |
| `openWindow()` | Opens a terminal window for the workspace of the current window. |
| `dictation()` | Starts Windows voice typing. Focus the terminal first. Fails on other systems. |
| Option | Rule |
| --- | --- |
| `cwd` | Required. The workspace root of the window. The start fails when the workspace changed. |
| `cols`, `rows` | Required. Positive integers. |
| `profile` | A profile `id` from `profiles()`. Without it, the host uses the first installed shell. |
| `directory` | A start folder other than the workspace root. |
| `onData(data)` | Required. Receives the output as a `Uint8Array`. A UTF-8 character can be split between two calls. |
| `onExit(code)` | Receives the exit code, or `null`. |
A session has `id`, `write(text)`, `resize(cols, rows)`, and `close()`. `close()` stops the shell, and more calls return the same promise.
Output goes only to the session that started the shell, as raw bytes.
When the plugin stops, the host stops the output, runs the plugin cleanup, and then closes the sessions that are still open.
## Folder grants
`api.files` (`version: 1`) gives access to folders outside the workspace. The user selects each folder. The plugin cannot supply a path.
@@ -494,6 +449,13 @@ A sidecar holds valid JSON of at most 1 MiB. The host writes no other files in a
Store the grant `id` in the plugin settings. Before you use a saved grant, look for it in `grants()`.
### Example: the per-image settings of Background
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.
## Plugin services
`api.services` (`version: 1`) lets a plugin offer data to other plugins in the same window. The host passes the calls, so no plugin reads the private files of another plugin.
@@ -508,84 +470,3 @@ A service name uses lowercase letters, digits, dots, and hyphens, and starts wit
Each method call returns a promise. The host copies the arguments and the result with `structuredClone`. Use only data that this function can copy, not functions or DOM nodes.
When the provider stops, the host removes its services and notifies the subscribers. Calls through an old service object then fail. Call `get` again after a notification.
Make the data of a service a documented contract of the provider. Give its name, methods, and result shapes in the documentation of the provider plugin.
## Git API
`api.git` gives Git operations for the active workspace of the window. The host runs the `git` command, one operation at a time.
The SDK type is `GitApi`. Every method checks for plugin shutdown first.
| Method | Contract |
| --- | --- |
| `status()` | Returns `{ available, repository, branch, changes }`. Each change has `path`, `originalPath?`, `index`, and `worktree`. |
| `diff(path, staged)` | Returns the diff text of one file. |
| `stage(paths)` / `unstage(paths)` | Change the index for 1 to 10,000 paths. |
| `commit(message)` | Commit the staged changes. The message has 1 to 65,536 bytes. |
| `push()` / `pull()` | Push or pull the current branch. |
| `graph()` | Returns `{ commits }` with at most 100 commits from all refs. |
| `commitDetails(commit)` | Returns `{ id, parents, author, date, message, files }` for a full commit ID. |
| `commitDiff(commit, path)` | Returns the diff of one file in a commit, compared to the first parent. |
| `blame(path, line)` | Returns `{ commit, author, date, summary }` for one line, or `null`. `date` is ISO 8601. |
Each graph commit is `{ id, parents, refs, summary, author, date }`. Parent IDs can refer to commits outside the 100 returned commits.
Older hosts can have `git` without `push`, `pull`, `graph`, `commitDetails`, or `commitDiff`. Make sure that a method exists before you call it.
Example: the [Git plugin](https://git.knottywyvern.com/kwyvern/RuneStone_Git/src/branch/main/docs/usage.md#commit-graph) draws the graph from these commits.
For its native service and test setup, see the [Git plugin development guide](https://git.knottywyvern.com/kwyvern/RuneStone_Git/src/branch/main/docs/development.md).
## Background API
`api.backgrounds` (`version: 1`) lets a plugin show image frames behind the RuneStone interface.
Frames stay in the current window and do not change the saved appearance settings.
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 | 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.
### Targets and frames
| Target | Use |
| --- | --- |
| `app` | The host shows this frame behind the app. |
| `pm-all` | Read by Project Management for all boards. |
| `pm-board:<board UUID>` | Read by Project Management for one board. |
| Frame field | Rule |
| --- | --- |
| `url` | Required `blob:` URL. |
| `blurredUrl` | Optional `blob:` URL for a blurred layer. Each target scales it separately from the foreground. |
| `overlay` | From -1 to 1. Negative values make the image lighter. Positive values make it darker. |
| `position` | `center`, `top left`, `top`, `top right`, `left`, `right`, `bottom left`, `bottom`, or `bottom right`. |
| `size` | `cover`, `contain`, or `auto`. |
| `previous` | Optional earlier frame with the same fields, without `previous` or `transitionMs`. |
| `transitionMs` | Optional fade time from 0 to 5,000 milliseconds. |
The host fades from `previous` to the new frame, unless the user turns on reduced motion.
The plugin owns all frame URLs. Keep them valid until a new frame replaces them or the plugin stops, then release them.
When more than one plugin sets a frame for a target, the most recent frame is shown. When it is removed, the host shows the earlier frame or the saved background.
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: [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.
+20 -20
View File
@@ -33,6 +33,8 @@ 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, Terminal, and Project Management, do not use the plugin API. `syncFeatures` in `external.ts` gives each feature that is on a feature session (`src/lib/features/session.ts`) under the ID of its old package, so that its views and document types share the tab model of plugin views. A view pattern in the catalog gives a feature many editor views, for example one for each board (`board-<hex>`). A tab transfer of such a view works before the feature loads. The file tree identifies the files of a feature document type, such as PDF files, without the feature code. A launch rule (`src/lib/features/launch.ts`) can start a feature at once: Background starts when a folder or an image is selected. Browser windows start only the features with a browser window rule, which is Background. See [Native features](development.md#native-features).
`features_legacy` (`src-tauri/src/features.rs`) reads the catalog row and the kept `plugin-data/<id>/settings.json` of an old package. It accepts only the IDs of native features and changes no file.
### Scans
@@ -106,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
@@ -157,12 +159,12 @@ The policy stops a script that comes in through rendered content, for example a
| Directive | Sources | Reason |
| --- | --- | --- |
| `default-src` | `'self'` | All other types come only from the app. |
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: the PDF Viewer decodes JPEG 2000 and JBIG2 images and color profiles with WebAssembly in its worker. It does not permit `eval`. |
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, the Vite dev server, and plugins (Terminal, CSV Viewer, PDF Viewer, Background Slideshow). |
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: PDF.js in the PDF Viewer feature decodes JPEG 2000 and JBIG2 images and compiles PostScript functions with WebAssembly. Its worker is a file of the app and gets no policy, so this source applies only to PDF.js code on the page. It does not permit `eval`. |
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, xterm in the Terminal feature, the Vite dev server, and plugins (CSV Viewer). |
| `img-src` | `'self' data: blob: https: http:` | `data:`: workspace images, browser frames, tab and site icons, and icons in CSS. `blob:`: background images. `https:` and `http:`: remote images in Markdown previews. |
| `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: fonts that the PDF Viewer embeds. |
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the Background Slideshow worker reads its image from a Blob URL. |
| `worker-src` | `'self' blob:` | `'self'`: workers that the app serves. The app starts no worker now. `blob:`: the PDF Viewer and Background Slideshow workers. |
| `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: PDF.js can load the embedded fonts of a PDF from data addresses. |
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the blur worker of the Background feature reads its image from a Blob URL. |
| `worker-src` | `'self' blob:` | `'self'`: workers that the app serves, such as the PDF.js worker of each PDF tab. `blob:`: the blur worker of the Background feature. |
| `object-src` | `'none'` | RuneStone uses no plugins of the web view. |
| `base-uri` | `'self'` | |
| `form-action` | `'none'` | No form sends data to an address. |
@@ -184,18 +186,19 @@ Workers that the app loads from its own files get no policy. Workers from Blob U
| Capability | Windows | Plugins | Commands |
| --- | --- | --- | --- |
| `default.json` | `main`, `workspace-*`, `terminal-*` | All enabled plugins | All app commands |
| `settings.json` | `settings-main`, `settings-workspace-*` | All enabled plugins | Settings, plugins, backgrounds, completion, browser |
| `browser.json` | `browser-*` | Only the built-in browser (`builtInModules` in `src/lib/plugins/external.ts`) | Browser, `plugins_snapshot`, settings, spelling, and window controls |
| `settings.json` | `settings-main`, `settings-workspace-*` | All enabled plugins | Settings, plugins, the Background folder, folder grants, completion, browser, `pty_profiles`, and `pty_running` |
| `browser.json` | `browser-*` | Only the built-in browser (`builtInModules` in `src/lib/plugins/external.ts`) | Browser, `plugins_snapshot`, settings, spelling, window controls, and the read commands of the Background folder (`background_folder`, `background_list`, `background_read`, `background_read_sidecar`) |
A browser window loads no installed plugin, so its capability has no workspace, file, Git, terminal, or plugin package commands. `tests/unit/plugins/windowCapabilities.spec.ts` and `tests/smoke/browser/window.smoke.mjs` check this.
A browser window loads no installed plugin, so its capability has no workspace, file, Git, terminal, or plugin package commands. The Background feature runs there to show the background behind a blank tab, so the window can read the Background folder. `tests/unit/plugins/windowCapabilities.spec.ts` and `tests/smoke/browser/window.smoke.mjs` check this.
The other windows load every enabled plugin. A smaller command set for them would limit only the app code, not the plugins. That split belongs to the plugin isolation work. Findings for that work:
- Terminal windows use the plugin host commands, `pty_*` through the Terminal plugin, and `core:window:allow-destroy`. Other plugins in the same window expect the full host API.
- Settings windows use no `workspace_*`, `git_*`, or `pty_*` commands, but plugin settings views run there.
- Terminal windows use the `pty_*` commands of the Terminal feature, the plugin host commands, and `core:window:allow-destroy`. Other plugins in the same window expect the full host API.
- Settings windows use no `workspace_*` or `git_*` commands, but plugin settings views run there. Of the `pty_*` commands, they use only `pty_profiles` for Settings → Terminal and `pty_running` before Terminal goes off.
- Commands that need a workspace (`workspace_*`, `git_*`, `pty_open`, `pty_new_window`) fail in a window without a bound workspace.
- `pty_write`, `pty_resize`, and `pty_close` do not check the window that opened the terminal.
- `backgrounds_*` need a plugin lease of the calling window.
- `pty_write`, `pty_resize`, and `pty_close` act only on the sessions of the calling window. A session of another window counts as a missing session.
- `pty_open` needs an output channel and a page ID. The first open of a new page in a window, after a reload, closes the sessions of the earlier page. The host refuses a late open from an old page.
- `folders_*` need a plugin lease of the calling window. The `background_*` commands of the Background feature need no lease. They take no path: the host keeps the folder that the folder dialog gave.
- `browser_request` needs the session token that `browser_connect` gives the window. A plugin lease does not replace it.
- A new command for plugins goes in `default.json` and, if settings views need it, in `settings.json`. Add it to `browser.json` only when the built-in browser needs it.
@@ -205,9 +208,9 @@ The other windows load every enabled plugin. A smaller command set for them woul
| --- | --- |
| `src-tauri/src/plugins.rs` | Package checks, discovery, installation, updates, persistence, removal, leases, settings, and assets |
| `src-tauri/src/plugin_sources.rs` | Gitea link parsing and release downloads |
| `src-tauri/src/backgrounds.rs` | Background folder and image commands. Deprecated for plugins: use folder grants |
| `src-tauri/src/backgrounds.rs` | The image folder of the native Background feature. Plugins use folder grants |
| `src-tauri/src/folders.rs` | Folder grants for `api.files`: the picker, stored grants, listing, reads, and settings files beside the images |
| `src-tauri/src/pty.rs` | Terminal sessions for `api.pty`. A session with an IPC channel gets raw output bytes; a session without one gets the older window events |
| `src-tauri/src/pty.rs` | The shell sessions of the Terminal feature. Output goes as raw bytes through the channel of `pty_open`, in messages of up to 64 KiB or 8 ms. `pty_running` counts the sessions of all windows |
| `src/lib/plugins/sdk.ts` | The public package API types |
| `src/lib/plugins/externalSession.ts` | Activation, API checks, contributions, mounts, and shutdown |
| `src/lib/plugins/external.ts` | Native state sync, module loading, scans, views, tabs, and document types |
@@ -216,8 +219,8 @@ The other windows load every enabled plugin. A smaller command set for them woul
| `src/lib/plugins/PluginManager.svelte` | Settings → Plug-ins: review, switches, Gitea form, and uninstall dialog |
| `src/lib/plugins/PluginSettings.svelte` | Plugin configuration pages in Settings |
| `src/lib/plugins/PluginTools.svelte` / `PluginEditor.svelte` | Dialog views and editor views |
| `src/lib/plugins/backgrounds.ts` | Background frames |
| `src/lib/plugins/nativeServices.ts` | The host side of `api.pty` and `api.files`. It binds the plugin ID; the plugin never sends it |
| `src/lib/plugins/backgrounds.ts` | The background frames of one window. The Background feature sets them, and Project Management reads the board targets. Plugins have no access. |
| `src/lib/plugins/nativeServices.ts` | The host side of `api.files`. It binds the plugin ID. The plugin never sends it |
| `src/lib/plugins/services.ts` | `api.services`: services that one plugin offers to another in the same window |
| `src/lib/completion/` | The [completion API](completion.md) |
| `scripts/packagePlugin.mjs` | The packager for plugin authors |
@@ -227,9 +230,6 @@ The other windows load every enabled plugin. A smaller command set for them woul
Run these commands from the RuneStone repository root.
For the general checks, see [Checks](development.md#checks). For the browser setup, see [Browser smoke tests](development.md#browser-smoke-tests).
The feature smoke tests read the compiled Terminal plugin from `../RuneStone_Terminal/dist/`.
To make it without a release ZIP, run `node scripts/build.mjs --no-package` in the Terminal folder. Set `RUNESTONE_TERMINAL_DIST` to use another folder.
Unit tests:
```powershell
+8 -8
View File
@@ -2,15 +2,15 @@
[RuneStone](../README.md) · [User guide](user-guide.md)
This guide explains how to install, enable, update, and remove optional plugins such as Terminal, Git, and PDF Viewer.
This guide explains how to install, enable, update, and remove optional plugins such as CSV Viewer and Local Autocomplete.
Manage all plugins in **Settings → Plug-ins**. The built-in browser and table formulas are part of RuneStone and are not plugins.
Manage all plugins in **Settings → Plug-ins**. The built-in browser, table formulas, Git, Background, Terminal, PDF Viewer, and Project Management are not plugins. To turn Git, Background, Terminal, PDF Viewer, or Project Management off, see [Turn features on or off](user-guide.md#turn-features-on-or-off).
Plugins run with the full access of RuneStone, including your files. There is no permission sandbox, and the author field does not prove who published the plugin. Enable only code that you trust.
## Install a plugin
Get the release ZIP of the plugin, such as `runestone.terminal-<version>.zip`. Do not extract it.
Get the release ZIP of the plugin, such as `runestone.csv-viewer-<version>.zip`. Do not extract it.
1. Open **Settings → Plug-ins**.
2. Choose **Install plugin ZIP**.
@@ -75,12 +75,7 @@ RuneStone uses the token for this request only and does not save it.
| Plugin | Guide |
| --- | --- |
| Terminal | [Terminal guide](guides/terminal.md) |
| Git | [Git usage](https://git.knottywyvern.com/kwyvern/RuneStone_Git/src/branch/main/docs/usage.md) |
| Project Management | [Project Management guide](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/project-management.md) |
| Background Slideshow | [Background Slideshow usage](https://git.knottywyvern.com/kwyvern/RuneStone_BG_Slideshow/src/branch/main/docs/usage.md) |
| Local Autocomplete | [Local Autocomplete trial guide](https://git.knottywyvern.com/kwyvern/RuneStone_LocalModel/src/branch/main/docs/trial-guide.md) |
| PDF Viewer | [PDF Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_PDFViewer/src/branch/master/README.md) |
| CSV Viewer | [CSV Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer/src/branch/main/README.md) |
## Plugin help
@@ -95,6 +90,11 @@ RuneStone uses the token for this request only and does not save it.
| The plugin shows **Removal incomplete** | Choose **Retry cleanup** to finish the removal. If the error names changed files, check that path first. |
| A Gitea release has no usable package | Check the release tag. Ask the publisher for a release with one attached plugin ZIP. |
| An old Browser plugin shows in the list | Uninstall it. The built-in browser keeps your profiles and bookmarks. |
| An old Git plugin shows in the list | Uninstall it. RuneStone includes Git, and the first start after the update kept the plugin state. See [Turn features on or off](user-guide.md#turn-features-on-or-off). |
| An old Background Slideshow plugin shows in the list | Uninstall it. RuneStone includes Background, and the first start after the update took the folder and the settings of the plugin. See [Show a background](guides/themes.md#show-a-background). |
| An old Terminal plugin shows in the list | RuneStone includes Terminal. The plugin stays inactive and shows **Included with RuneStone**. Uninstall it. The first start after the update kept the plugin state and its terminal settings. See the [Terminal guide](guides/terminal.md). |
| An old PDF Viewer plugin shows in the list | RuneStone includes PDF Viewer. The plugin stays inactive and shows **Included with RuneStone**. Uninstall it. The first start after the update kept the plugin state. See [Read PDF files](user-guide.md#read-pdf-files). |
| An old Project Management plugin shows in the list | RuneStone includes Project Management. The plugin stays inactive and shows **Included with RuneStone**. Uninstall it. The first start after the update kept the plugin state and its priority levels. Your boards in `.runestone/pm/` stay. If the workspace has boards in old visible notes, Project Management offers a migration. See [Move old Project Management notes](guides/project-management.md#move-old-project-management-notes). |
| An old Table Formulas plugin shows in the list | Uninstall it. RuneStone does not run it. Your formulas stay in your files. See [Calculate with table formulas](guides/document-tools.md#calculate-with-table-formulas). |
To see the installed files of a plugin, choose **Show files** beside it. **Open plugins folder** opens the folder for all plugins.
+3 -1
View File
@@ -27,7 +27,7 @@ Correct a wrong color in the theme data or in the derivation rule. Do not add lo
| --- | --- | --- |
| Theme identity | `--rs-accent`, `--rs-accent-2` | Keep the characteristic hues of the reference at their strength. |
| Status | `--rs-error`, `--rs-warn`, `--rs-warn-hot`, `--rs-ok` | Use clear, assertive colors. Pair color with a shape or text. |
| Priority (Project Management) | `--pm-priority-color` in the plugin `src/style.css` | Full saturation and value, with opaque symbols and readable text. |
| Priority (Project Management) | `--pm-priority-color` in `src/lib/features/pm/ui/style.css` | Full saturation and value, with opaque symbols and readable text. |
| Links and actions | `--rs-link` (from `--rs-accent` unless the theme sets it) | Keep actionable text distinct and readable on its actual surface. |
| Text on an accent fill | `--rs-on-accent` (black or white, whichever is more readable) | Readable text and icons on accent buttons and badges. |
| Focus | `--rs-focus` (from `--rs-accent` unless the theme sets it) | A visible outline on every surface. |
@@ -38,6 +38,8 @@ Correct a wrong color in the theme data or in the derivation rule. Do not add lo
| Surfaces and dividers | `--rs-bg`, `--rs-bg-elevated`, `--rs-bg-active`, `--rs-border`, `--rs-line-highlight`, `--rs-scrim`, `--rs-image-*` tints | Support the content. Choose their strength by function. |
| Disabled states | Role tokens of the control | Keep labels readable. Do not apply disabled opacity to enabled content. |
The Terminal feature uses these tokens directly (`src/lib/features/terminal/theme.ts`). Text is `--rs-text`, the cursor is `--rs-accent` on `--rs-bg`, and the selection is `--rs-selection` with at most 65% alpha. The 16 ANSI colors are the `--rs-ansi-*` tokens. The terminal reads them again after each theme change.
Do not fade a whole badge, row, or container when only its background needs transparency.
Plugins use the same tokens. [Theme tokens](plugin-development.md#theme-tokens) lists them for plugin authors.
+24 -14
View File
@@ -148,12 +148,12 @@ Decisions: [UI-002](design-decisions.md#ui-002--share-the-requested-dropdown-des
- The main header holds navigation, document tabs, Save, the outline toggle, and window controls. The other tools are in the left ribbon, so the tabs keep their room. A detached tab window has no ribbon, so its header keeps those tools.
- A bar at the bottom of the side pane holds the workspace switcher, Help, and Settings, as in Obsidian. The switcher names the workspace and opens the workspace list above it.
- The left ribbon is always present. It holds the tools (New browser tab, Terminal, Plug-in views, and Commands), then a line, then the plugin view shortcuts. Its menus open at its right. While the side pane is closed, the workspace switcher, Help, and Settings move to the bottom of the ribbon, so they stay reachable.
- The left ribbon is always present. It holds the tools, then a line, then the plugin view shortcuts. The tools are New browser tab, Terminal, Project Management, Plug-in views, and Commands. A tool of an off feature does not show. Its menus open at its right. While the side pane is closed, the workspace switcher, Help, and Settings move to the bottom of the ribbon, so they stay reachable.
- Tabs keep a minimum width of 120 pixels and scroll. Fades show tabs out of view, and ⌄ lists all tabs. A drag area of 120 pixels sits after the tabs. In a narrow header, the tabs shrink first, and the drag area keeps at least 48 pixels.
- Windows and Linux title bars use square caption buttons, 46 pixels wide and full height. Rest the pointer on maximize for Snap Layouts on Windows 11. macOS keeps its native traffic lights, and title bars leave `--rs-titlebar-inset-start` free for them.
- Files, Search, Bookmarks, and installed sidebar views such as Git share the top navigation group. The active navigation button shows which view fills the left pane.
- Files, Search, Bookmarks, Source control (while Git is on), and the sidebar views of installed plugins share the top navigation group. The active navigation button shows which view fills the left pane.
- Plugin editor views can use the left ribbon.
- The built-in browser opens from its own ribbon action. Project Management opens from Plug-in views. Keep Plug-in views in the ribbon, away from the new-tab button.
- The built-in browser and Project Management open from their own ribbon buttons. The Project Management button is active while a board tab or All tasks is the active tab. Plug-in views lists only plugin views. Keep Plug-in views in the ribbon, away from the new-tab button.
- Document and plugin tabs share the tab bar. The new-tab button follows the tabs. Tabs keep their order and pin state when a plugin replaces its view.
- The main window keeps an empty New tab after its last tab closes. A secondary window closes with its last tab. The unsaved-edit and active-terminal confirmations still apply, and Cancel keeps the tab open.
- Sidebar widths and visibility persist across window sessions. A different editor does not restore a hidden outline.
@@ -172,17 +172,21 @@ Decisions: [UI-004](design-decisions.md#ui-004--detached-tab-work-area), [UI-039
- Put related plugin metadata and actions in compact rows.
- Controls wrap at narrow widths, and the content area scrolls. Long navigation must leave room for the selected page.
- General offers the interface language through the shared action menu.
- **Features** lists each native feature in one card: its name, one line of description, and a switch. The page sits between Appearance and Plug-ins, and the `toggle` icon marks it. A failed load shows its cause under the switch in the error color.
- A feature that is off shows no controls: no navigation button, ribbon button, command, or tab. A settings section of an off feature shows one line that names Settings → Features.
- **Terminal** is a Settings page with the `terminal` icon, after Plug-ins and Browser. It shows only while Terminal is on. **Terminal settings** in the profile menu of the terminal panel opens it. No dialog of the panel holds terminal settings.
- **Project Management** is a Settings page with the `kanban` icon, after Terminal. It shows only while Project Management is on. It holds **Priority levels** and **Default board**, with pickers on the shared action menu. **More actions** → **Project Management settings** on a board shows the same component in a popup.
- The transparency slider covers 0% to 100% and uses the accent and surface tokens of the current theme.
- Appearance shows a preview card for each theme. The arrow keys move between the cards and select a theme. The current card has the selection outline and a check mark.
- **Edit theme** opens the theme editor as a workbench tab in the window that opened Settings. The editor shows every color role in groups, with a swatch, a hex field, the lowest contrast result, and a reset button. Each change shows at once in that window. Save writes a short schema 3 theme with a base.
- Custom theme files use schema 3: one `mode`, an optional built-in `base` theme, the `colors` that differ from the base, and `fonts` stacks for interface, prose, headings, and code. The export writes every color and font. Schema 1 and 2 imports convert to schema 3. A schema 1 import selects the palette of the current appearance.
Decisions: [UI-028](design-decisions.md#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes), [UI-042](design-decisions.md#ui-042--theme-file-format-3-and-terminal-colors), [UI-047](design-decisions.md#ui-047--theme-editor-tab-and-theme-cards).
Decisions: [UI-028](design-decisions.md#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes), [UI-042](design-decisions.md#ui-042--theme-file-format-3-and-terminal-colors), [UI-047](design-decisions.md#ui-047--theme-editor-tab-and-theme-cards), [UI-055](design-decisions.md#ui-055--settings--features-and-native-git), [UI-057](design-decisions.md#ui-057--background-replaces-background-image-and-background-slideshow), [UI-058](design-decisions.md#ui-058--settings--terminal-and-theme-colors-in-the-terminal), [UI-060](design-decisions.md#ui-060--native-project-management).
## Typography and tables
- The interface uses `--rs-font-ui`. Prose uses `--rs-font-prose`. Headings use `--rs-font-heading`.
- Source and Terminal share `--rs-font-mono` and `--rs-code-font-weight` (default 300). The monospace stack starts with Cascadia Mono, then Cascadia Code, JetBrains Mono, Fira Code, and Consolas. Terminal font size is a separate setting.
- Source and Terminal share `--rs-font-mono` and `--rs-code-font-weight` (default 300). The monospace stack starts with Cascadia Mono, then Cascadia Code, JetBrains Mono, Fira Code, and Consolas. Terminal font size is a separate setting in Settings → Terminal.
- Document headings use space between sections, not separator lines. Heading fold controls use the shared chevron and take keyboard focus.
- Tables use shared cell padding and line height. Entering a cell does not change its row height.
- A table row needs an unescaped pipe. Write and Read use the same row rule. A paragraph after a table stays a paragraph when the separator line is removed.
@@ -192,6 +196,8 @@ Decisions: [UI-005](design-decisions.md#ui-005--heading-spacing).
## Themes and background images
Background images come from the native Background feature (`src/lib/features/background/`). Appearance → Background holds its settings: the source (a folder, one image, or none), the layout, the per-image editor, and the targets.
### Palettes
- Color choices obey [Functional color](ui-color.md).
@@ -219,15 +225,16 @@ Decisions: [UI-009](design-decisions.md#ui-009--character-theme-appearances), [U
- Code blocks in Write and Read use `--rs-code-block-bg`.
- New-tab buttons use `--rs-image-control-bg` and `--rs-image-control-hover-bg`. Their tint keeps labels readable while the image stays visible. The new-tab screen shows only its action buttons, with icons, labels, and shortcuts.
- Headers and dialogs keep their own surfaces.
- The app work area and Project Management keep separate images and settings in every theme. An image can be up to 50 MiB. Image bytes stay in IndexedDB, and settings keep a small reference.
- Each image has a size, nine alignment positions, and an overlay from -100% (darker) to 100% (lighter), set with a slider or a typed value.
- The app work area and Project Management keep separate images and settings in every theme. The one image of Background can be up to 50 MiB. Its bytes stay in IndexedDB, and the appearance settings keep a small reference.
- The folder and the one image each have a size, nine alignment positions, and an overlay from -100% (lighter) to 100% (darker), set with a slider or a typed value.
- Without a background frame, every surface and menu is opaque. With Background off, no image shows.
Decisions: [UI-010](design-decisions.md#ui-010--background-surface-visibility), [UI-011](design-decisions.md#ui-011--backgrounds-across-the-work-area), [UI-016](design-decisions.md#ui-016--translucent-code-blocks).
### Project Management surfaces
- Without its own image, Project Management shows the host image through a transparent root. A saved or temporary board image keeps its own area.
- The host gives `--rs-workarea-plugin-bg` and `--rs-workarea-surface-opacity` for saved images and slideshow frames.
- The host gives `--rs-workarea-plugin-bg` and `--rs-workarea-surface-opacity` for saved board images and slideshow frames.
- With an image, lists, cards, card details, and search fields share the 82% tint. Gantt and calendar views use one tinted panel, and their date cells show the image.
- Selected cards use the shared selection treatment. Nested surfaces keep their own tint.
- Card detail buttons have a transparent resting background. Hover, pressed, and focus states stay visible.
@@ -236,13 +243,15 @@ Decisions: [UI-014](design-decisions.md#ui-014--readable-project-management-surf
### Slideshow
- A slideshow frame overrides the saved board image while it is active. A temporary board frame comes before the all-board frame. Removal restores the saved image.
- A folder of the Background feature is a slideshow. Its frame overrides the saved board image while it is active. A temporary board frame comes before the all-board frame. Removal restores the saved image.
- When the app and Project Management show the same frame, the host draws it once across both sidebars and the board. Distinct board frames keep their own area.
- Images fade over two seconds. Reduced motion removes the fade. Short intervals and manual Next can interrupt it.
- Portrait images show in full over a blurred cover layer by default. The image editor previews a per-image fit, position, and overlay, and saves or resets the override. Global settings apply to other images. The [plugin API](plugin-development.md#plugin-api) defines the storage.
- A new browser tab on `about:blank` shows the host background. A loaded page keeps its own rendering, even when it is empty.
- The next image loads and decodes before its fade starts. A new frame changes only the custom properties with a new value.
- Portrait images show in full over a blurred cover layer by default. The image editor previews a per-image fit, position, and overlay, and saves or resets the override. The folder layout applies to other images. The sidecar file `.runestone-backgrounds.json` in the folder keeps the overrides.
- **Next background image** and **Pause background** are in the command palette. Next reaches every window. Pause keeps the current image and stops the timer.
- A new browser tab on `about:blank` shows the host background, also in a browser window. A loaded page keeps its own rendering, even when it is empty.
Decisions: [UI-015](design-decisions.md#ui-015--slower-slideshow-fades), [UI-020](design-decisions.md#ui-020--per-image-slideshow-layout).
Decisions: [UI-015](design-decisions.md#ui-015--slower-slideshow-fades), [UI-020](design-decisions.md#ui-020--per-image-slideshow-layout), [UI-057](design-decisions.md#ui-057--background-replaces-background-image-and-background-slideshow).
## Tooltips and text selection
@@ -284,10 +293,11 @@ Decisions: [UI-021](design-decisions.md#ui-021--workspace-links-in-document-pane
- A description edit stays a draft until Save. Cancel restores the saved text. Closing card details keeps the draft, and the card then shows an unsaved marker. Edit opens the draft. Use the labels Save and Cancel, and leave readable space below long descriptions.
- Board and list changes save at once. Close and an outside click use the same save path for other fields.
- Each workspace can set a fixed default view: All tasks or one board. Restored tabs and explicit links keep their targets. An unavailable default returns to All tasks. A workspace without boards shows a New board action.
- Each workspace can set a fixed default view: All tasks or one board. Restored tabs and explicit links keep their targets. An unavailable default returns to All tasks. A workspace without boards shows **Create your first board**.
- Project Management is host code (`src/lib/features/pm/ui/`). The board scope, the select choices, and the details pickers use the shared action menu. Icon-only controls use the shared tooltip and the shared action icons. All interface text comes from the catalog.
- New cards record their creation time, and card details show it. Existing cards show Unknown when no reliable time exists. Moves and edits do not change it. Board cards do not show timestamps.
Decisions: [UI-033](design-decisions.md#ui-033--list-capacity-and-a-frozen-all-tasks-overview), [UI-034](design-decisions.md#ui-034--find-scope-and-shared-list-names), [UI-035](design-decisions.md#ui-035--board-dividers-in-all-tasks), [UI-036](design-decisions.md#ui-036--compact-list-collapse-and-assigned-creation), [UI-037](design-decisions.md#ui-037--saved-metadata-and-explicit-description-drafts), [UI-038](design-decisions.md#ui-038--fixed-workspace-default-board).
Decisions: [UI-033](design-decisions.md#ui-033--list-capacity-and-a-frozen-all-tasks-overview), [UI-034](design-decisions.md#ui-034--find-scope-and-shared-list-names), [UI-035](design-decisions.md#ui-035--board-dividers-in-all-tasks), [UI-036](design-decisions.md#ui-036--compact-list-collapse-and-assigned-creation), [UI-037](design-decisions.md#ui-037--saved-metadata-and-explicit-description-drafts), [UI-038](design-decisions.md#ui-038--fixed-workspace-default-board), [UI-060](design-decisions.md#ui-060--native-project-management).
## Review checklist
+48 -4
View File
@@ -10,11 +10,15 @@ This guide explains how to work with files, documents, tabs, settings, and the b
| Create, find, or organize files | [Create and find files](#create-and-find-files) |
| Write, read, or follow a link | [Edit documents](#edit-documents) |
| Work with images, diagrams, or tables | [Images, diagrams, and tables](guides/document-tools.md) |
| Read a PDF file | [Read PDF files](#read-pdf-files) |
| Start a note from a template | [Use note templates](#use-note-templates) |
| Arrange tabs and windows | [Manage tabs](#manage-tabs) |
| Save, or recover from a changed file | [Save your work](#save-your-work) and [Resolve file conflicts](#resolve-file-conflicts) |
| Change the language or colors | [Change settings](#change-settings) and [Appearance](guides/themes.md) |
| Add Terminal, Git, or other features | [Install and manage plugins](plugins.md) |
| Review changes and commit with Git | [Git guide](guides/git.md) |
| Plan work on boards, a timeline, and a calendar | [Project Management guide](guides/project-management.md) |
| Turn a built-in feature on or off | [Turn features on or off](#turn-features-on-or-off) |
| Add plugins | [Install and manage plugins](plugins.md) |
| Browse websites | [Use the built-in browser](#use-the-built-in-browser) |
| Run commands or scripts | [Terminal guide](guides/terminal.md) |
@@ -81,7 +85,7 @@ Each document pane has one view control with three choices, and a **Split** butt
| **Split** | Read beside Write or Source. Narrow panes stack the two views. Select **Split** again to close it. Markdown files only. |
Press Ctrl+E to switch between Write and Source. Press Ctrl+Shift+E to switch between Read and the editor. The tab menu has the same choices under **View**.
In a narrow pane, the control shows only icons. Hover over an icon, or focus it with the keyboard, to see its name. The arrow keys move the choice.
The control shows icons only. Hover over an icon, or focus it with the keyboard, to see its name and shortcut. The arrow keys move the choice.
The status bar shows the save state, the line and column of the cursor, the word count, the line endings (LF or CRLF), and the current view. For a folder on a network drive, it also shows **Polling for changes**. A tab without a document, such as the theme editor, has no outline and no document facts. The bar above the document shows the folder of the file, and the tab shows the file name.
Write keeps your Markdown source, frontmatter, and Windows line endings. Read shows frontmatter in a collapsed **Properties** section.
Select a checkbox to complete a task. Copy code blocks without their Markdown fences with the **Copy code** button.
@@ -126,6 +130,26 @@ In Write, these shortcuts format the selected text:
The menu also has link, search, extraction, and clipboard actions. RuneStone has no formatting toolbar.
Right-click a misspelled word to see spelling suggestions from the operating system.
## Read PDF files
Select a PDF file in the file tree. It opens in its own tab. The file tree marks PDF files with a document icon.
| Action | How |
| --- | --- |
| Change the page | Select **Previous page** or **Next page**. Or type a number in the page field and press Enter. With the page area focused, press Page Up or Page Down. |
| Zoom | Select **Zoom in** or **Zoom out**, from 25% to 400%. **Fit width** fits the page to the tab again. |
| Rotate | Select **Rotate clockwise**. Each click turns the page by 90 degrees. |
| Copy text | Select text on the page with the pointer, then press Ctrl+C. |
| Show changes from another program | Select **Reload PDF**. The tab stays on the same page. |
| Open a protected PDF | Type the password, then select **Unlock**. RuneStone does not save the password. |
- A PDF file must be in the workspace and at most 64 MiB.
- The tab shows one page at a time. It does not edit PDF files, fill forms, open links, run scripts in a PDF, or print.
- Scanned pages show as images, so you cannot select their text.
- If a PDF does not open, the tab shows the error. Select **Reload PDF**, or try another copy of the file.
PDF Viewer is a built-in feature. To turn it off, see [Turn features on or off](#turn-features-on-or-off).
## Use note templates
A template is a Markdown file in the workspace folder `.runestone/templates/`.
@@ -156,7 +180,7 @@ RuneStone moves the current text of the tab, also unsaved text. It closes the so
If the move fails, the source tab stays open.
When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab.
This includes plugin tabs that show a file, such as a PDF. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening.
This includes PDF tabs and plugin tabs that show a file. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening.
## Save your work
@@ -197,9 +221,29 @@ Settings apply at once to all workspaces on this computer and update all open wi
| Category | Settings |
| --- | --- |
| General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save |
| Appearance | Color theme, transparency, background image, and custom themes. See [Appearance and custom themes](guides/themes.md). |
| Appearance | Color theme, transparency, background (a folder slideshow or one image), and custom themes. See [Appearance and custom themes](guides/themes.md). |
| Features | Turn Git, Background, Terminal, PDF Viewer, and Project Management on or off. See [Turn features on or off](#turn-features-on-or-off). |
| Plug-ins | Install, enable, update, and remove plugins. See [Install and manage plugins](plugins.md). |
| Browser | Homepage, search engine, profiles, ad blocking, and web data |
| Terminal | Default profile, font size, scrollback lines, and cursor blink. The page shows only while Terminal is on. See [Change the terminal settings](guides/terminal.md#change-the-terminal-settings). |
| Project Management | Priority levels and the default board of the workspace. The page shows only while Project Management is on. See [Change the Project Management settings](guides/project-management.md#change-the-project-management-settings). |
### Turn features on or off
Git, Background, Terminal, PDF Viewer, and Project Management are built-in features with an off switch. Open **Settings → Features** and use the switch beside the feature.
- A feature that is on uses no extra memory until you first use it. Examples are Source control, a terminal, a PDF file, or a board. Background loads at the start only when you selected a folder or an image.
- A feature that is off does not load. Its buttons, commands, and tabs do not show.
- Terminal off ends the terminal sessions of every window. When a window runs a shell, RuneStone asks first.
- A change applies at once in all windows. The code that a window loaded stays in memory until you restart RuneStone.
After an update, Git takes the state of its old plugin package: on when the package was enabled, off when it was disabled. Without an old package, Git starts on.
Terminal does the same with the old Terminal plugin, and it copies the terminal settings of that plugin. PDF Viewer does the same with the old PDF Viewer plugin.
Project Management does the same with the old Project Management plugin, and it copies the priority levels of that plugin.
Background starts on for every user. It takes the folder, the timing, and the targets of the Background Slideshow plugin when that plugin was on. Otherwise it shows your old background image, if you had one. See [Show a background](guides/themes.md#show-a-background).
Settings → Plug-ins shows an old package as **Included with RuneStone**. You can uninstall it.
### Display language
**Display language** sets the RuneStone controls to English, Français, 日本語, or 简体中文.
It does not translate documents, plugin content, or operating system messages. Some error messages stay in English.
+7 -2
View File
@@ -1,6 +1,6 @@
{
"name": "runestone",
"version": "0.1.49",
"version": "0.1.51",
"description": "Desktop editor for a local workspace",
"type": "module",
"scripts": {
@@ -12,6 +12,7 @@
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tests/tsconfig.json && tsc -p packages/plugin-sdk/tsconfig.json --noEmit && tsc -p fixtures/plugins/tsconfig.json && node scripts/i18nAudit.mjs",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"check:menus": "node scripts/menuSurfaceAudit.mjs",
"check:features": "node scripts/featureChunks.mjs",
"tauri": "tauri",
"test": "node --experimental-strip-types --import ./tests/unit/_svelte/register.mjs --test \"tests/unit/**/*.spec.ts\"",
"smoke": "node scripts/smoke.mjs",
@@ -53,8 +54,12 @@
"@tiptap/extension-link": "^3.31.3",
"@tiptap/pm": "^3.31.3",
"@tiptap/starter-kit": "^3.31.3",
"@xterm/addon-fit": "0.11.0",
"@xterm/xterm": "6.0.0",
"markdown-it": "^15.0.2",
"mermaid": "^12.0.0"
"mermaid": "^12.0.0",
"pdfjs-dist": "6.4.299",
"yaml": "2.9.1"
},
"devDependencies": {
"@sveltejs/adapter-static": "^3.0.10",
+4 -4
View File
@@ -66,7 +66,7 @@ A type-only import, such as `import type { PluginApi }`, adds no code to the bun
## Check for features
Members marked optional in `PluginApi` can be absent on older RuneStone versions. Examples are `api.pty`, `api.files`, and `api.workspace.readBytes`.
Members marked optional in `PluginApi` can be absent on older RuneStone versions. Examples are `api.files`, `api.services`, and `api.workspace.readBytes`.
Make sure that a member exists before you use it.
```ts
@@ -74,8 +74,8 @@ import { hasFeature, requireFeature, requireFeatures, type PluginApi } from "@ru
export function activate(api: PluginApi) {
// Stop the activation with one message that names each missing feature.
requireFeatures(api, ["pty", "workspace.readOptional"]);
const pty = requireFeature(api, "pty");
requireFeatures(api, ["files", "workspace.readOptional"]);
const files = requireFeature(api, "files");
// Hide a control when the feature is absent.
if (hasFeature(api, "ui.showActionMenu")) showMenuButton();
@@ -91,7 +91,7 @@ export function activate(api: PluginApi) {
When a feature is missing, `requireFeature` and `requireFeatures` throw a `MissingFeatureError`. Its `features` property lists the feature names.
Its message names each feature and its API path, and tells the user to update RuneStone. For example:
`This plugin needs the terminal API (api.pty). Update RuneStone to a version that has this feature.`
`This plugin needs the folder grant API (api.files). Update RuneStone to a version that has this feature.`
`pluginFeatures` lists all the feature names. The checks examine only whether the member exists.
-33
View File
@@ -1,7 +1,5 @@
import type { BackgroundApi } from "./backgrounds.ts";
import type { CompletionApi } from "./completion.ts";
import type { Contributions } from "./contributions.ts";
import type { GitApi } from "./git.ts";
import type { ActionIcon } from "./icons.ts";
import type { ActionMenuItem, ActionMenuOptions } from "./menu.ts";
@@ -21,34 +19,6 @@ export interface PluginDocumentType {
create?: { label: string; defaultName: string; extension: string; contents(): string };
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
}
export interface PtyProfile { id: string; title: string; kind: string }
export interface PtyOpenOptions {
/** The workspace root of the window. The host rejects the request when the workspace changed. */
cwd: string;
cols: number;
rows: number;
profile?: string;
/** A start folder other than the workspace root. */
directory?: string;
/** Receives raw terminal output. UTF-8 characters can be split between two calls. */
onData(data: Uint8Array): void;
onExit?(code: number | null): void;
}
export interface PtySession {
readonly id: string;
write(data: string): Promise<void>;
resize(cols: number, rows: number): Promise<void>;
/** Stops the shell. Repeated calls return the same promise. */
close(): Promise<void>;
}
/** Terminal sessions. The host closes the sessions of a plugin when the plugin stops. */
export interface PtyApi {
readonly version: 1;
profiles(): Promise<PtyProfile[]>;
open(options: PtyOpenOptions): Promise<PtySession>;
openWindow(): Promise<void>;
dictation(): Promise<void>;
}
export interface FolderGrant { id: string; path: string; name: string }
export interface FolderEntry { name: string; size: number }
/** Folders outside the workspace that the user granted to this plugin. */
@@ -90,12 +60,9 @@ export interface AssetsApi { read(path: string): Promise<Uint8Array> }
/** Interface parts that the host draws. */
export interface UiApi { showActionMenu(options: ActionMenuOptions): { close(): void } }
export interface PluginApi {
pty?: PtyApi;
files?: FilesApi;
services?: ServicesApi;
backgrounds?: BackgroundApi;
ui?: UiApi;
git?: GitApi;
completion?: CompletionApi;
readonly id: string;
readonly signal: AbortSignal;
-24
View File
@@ -1,24 +0,0 @@
/** Background image frames behind the RuneStone interface. */
export interface BackgroundFrame {
url: string;
blurredUrl?: string;
overlay: number;
position: 'center' | 'top left' | 'top' | 'top right' | 'left' | 'right' | 'bottom left' | 'bottom' | 'bottom right';
size: 'cover' | 'contain' | 'auto';
previous?: Omit<BackgroundFrame, 'previous' | 'transitionMs'>;
transitionMs?: number;
}
/** The folder methods are deprecated. Use `FilesApi` folder grants in new code. */
export interface BackgroundApi {
readonly version: 1;
chooseFolder(): Promise<string | null>;
defaultFolder?(): Promise<string>;
list(folder: string): Promise<{ name: string }[]>;
read(folder: string, name: string): Promise<Uint8Array>;
readImageSettings?(folder: string): Promise<string | null>;
writeImageSettings?(folder: string, contents: string, expected: string | null): Promise<void>;
set(target: string, frame: BackgroundFrame | null): void;
get(target: string): BackgroundFrame | null;
subscribe(listener: (target: string) => void): () => void;
}
-17
View File
@@ -1,20 +1,7 @@
import type { Dispose } from "./api.ts";
import type { GitLineInfo } from "./git.ts";
export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories";
export interface TerminalProps {
cwd: string; visible: boolean; maximized?: boolean; standalone?: boolean;
onClose: () => void; onMaximize?: () => void; activeFile?: boolean;
onRunFile?: () => Promise<string | null>; getSelection?: () => string; onConfigureTasks?: () => Promise<void>;
}
export interface TerminalMount {
update(props: TerminalProps): void;
command(action: Exclude<TerminalAction, "toggle">): void | Promise<void>;
dispose: Dispose;
}
/** Host features that `api.contribute(key, value)` registers. Only one enabled plugin can own each key. */
export interface Contributions {
git: { blame(path: string, line: number): Promise<GitLineInfo | null> };
browser: {
/** Opens a browser tab, with `url` when it is given. */
newTab?(url?: string): Promise<void>;
@@ -23,8 +10,4 @@ export interface Contributions {
/** Opens a web link from a document. False means that the system browser opens it. */
open(url: string): Promise<boolean>;
};
terminal: {
mount(container: HTMLElement, props: TerminalProps): TerminalMount;
shortcut(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">): TerminalAction | null;
};
}
+1 -19
View File
@@ -1,23 +1,13 @@
import type { FilesApi, PluginApi, PtyApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts";
import type { BackgroundApi } from "./backgrounds.ts";
import type { FilesApi, PluginApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts";
import type { CompletionApi } from "./completion.ts";
import type { GitApi } from "./git.ts";
/**
* The optional members of `PluginApi`, by path, and the type that `requireFeature` returns for each path.
* Older RuneStone hosts can omit these members. Required members, such as `workspace.read`, are not listed.
*/
export interface PluginFeatures {
pty: PtyApi;
files: FilesApi;
services: ServicesApi;
backgrounds: BackgroundApi;
git: GitApi;
"git.push": GitApi["push"];
"git.pull": GitApi["pull"];
"git.graph": GitApi["graph"];
"git.commitDetails": GitApi["commitDetails"];
"git.commitDiff": GitApi["commitDiff"];
completion: CompletionApi;
"completion.transport": NonNullable<CompletionApi["transport"]>;
"ui.showActionMenu": UiApi["showActionMenu"];
@@ -40,16 +30,8 @@ export interface PluginFeatures {
export type PluginFeature = keyof PluginFeatures;
const descriptions: { [K in PluginFeature]: string } = {
pty: "the terminal API",
files: "the folder grant API",
services: "the plugin service API",
backgrounds: "the background API",
git: "the Git API",
"git.push": "Git push",
"git.pull": "Git pull",
"git.graph": "the Git commit graph",
"git.commitDetails": "Git commit details",
"git.commitDiff": "Git commit diffs",
completion: "the completion API",
"completion.transport": "the completion model transport",
"ui.showActionMenu": "the shared action menu",
-64
View File
@@ -1,64 +0,0 @@
/** Git types. The host runs the `git` program for the active workspace. */
export interface GitChange {
path: string;
originalPath?: string;
index: string;
worktree: string;
}
export interface GitStatus {
available: boolean;
repository: boolean;
branch: string | null;
changes: GitChange[];
}
export interface GitLineInfo {
commit: string;
author: string;
/** The author date in ISO 8601 format. */
date: string;
summary: string;
}
/** Older hosts can have `git` without `push`, `pull`, `graph`, `commitDetails`, or `commitDiff`. Use `hasFeature` first. */
export interface GitApi {
status(): Promise<GitStatus>;
diff(path: string, staged: boolean): Promise<string>;
stage(paths: string[]): Promise<void>;
unstage(paths: string[]): Promise<void>;
commit(message: string): Promise<void>;
push(): Promise<void>;
pull(): Promise<void>;
graph(): Promise<GitGraph>;
commitDetails(commit: string): Promise<GitCommitDetails>;
commitDiff(commit: string, path: string): Promise<string>;
blame(path: string, line: number): Promise<GitLineInfo | null>;
}
export interface GitGraphCommit {
id: string;
parents: string[];
refs: string[];
summary: string;
author: string;
date: string;
}
export interface GitGraph {
commits: GitGraphCommit[];
}
export interface GitCommitFile {
path: string;
originalPath?: string;
status: string;
}
export interface GitCommitDetails {
id: string;
parents: string[];
author: string;
date: string;
message: string;
files: GitCommitFile[];
}
-2
View File
@@ -1,10 +1,8 @@
// The public types and helpers of the RuneStone plugin API.
// The icon and tooltip helpers use the DOM. Import them from "@runestone/plugin-sdk/icons" and "@runestone/plugin-sdk/tooltip".
export type * from "./api.ts";
export type * from "./backgrounds.ts";
export type * from "./completion.ts";
export type * from "./contributions.ts";
export type * from "./git.ts";
export type * from "./menu.ts";
export type { ActionIcon } from "./icons.ts";
export { API_VERSION, type PluginManifest } from "./manifest.ts";
+176 -15
View File
@@ -89,22 +89,34 @@ importers:
'@tiptap/starter-kit':
specifier: ^3.31.3
version: 3.31.3
'@xterm/addon-fit':
specifier: 0.11.0
version: 0.11.0
'@xterm/xterm':
specifier: 6.0.0
version: 6.0.0
markdown-it:
specifier: ^15.0.2
version: 15.0.2
mermaid:
specifier: ^12.0.0
version: 12.0.0
pdfjs-dist:
specifier: 6.4.299
version: 6.4.299
yaml:
specifier: 2.9.1
version: 2.9.1
devDependencies:
'@sveltejs/adapter-static':
specifier: ^3.0.10
version: 3.0.10(@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected])))
version: 3.0.10(@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected])))
'@sveltejs/kit':
specifier: ^2.65.1
version: 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected]))
version: 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected]))
'@sveltejs/vite-plugin-svelte':
specifier: ^7.1.2
version: 7.3.0([email protected])([email protected](@types/[email protected]))
version: 7.3.0([email protected])([email protected](@types/[email protected])([email protected]))
'@tauri-apps/cli':
specifier: ^2
version: 2.11.4
@@ -125,7 +137,7 @@ importers:
version: 6.0.3
vite:
specifier: ^8.0.16
version: 8.3.0(@types/[email protected])
version: 8.3.0(@types/[email protected])([email protected])
packages:
@@ -272,6 +284,81 @@ packages:
resolution: {integrity: sha512-K8BeapFUfrfxbRAUQAG5oBOCwo1+bNWzaVnPxTCutkfrTBn6T/j91FIhqxWJ32SUeQ9T3iy1zcmPZ5ROZEvDrg==}
engines: {node: '>=22.12.0'}
'@napi-rs/[email protected]':
resolution: {integrity: sha512-trn7AaDzQ+yeeA0ezhkC7cB1ZDPtp4UYk0EvB5F8qtYL9jEVWtVrU30WOpI52DszoTxaTsCgf5PP4ZVaOlOIHQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [android]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-6Y2djEetL8copxfNK6hg7oig/xqTwOchv19hBOm+zBNdKc/02Z3kjZN5wrLzv/l5O04/bAQS6I/AlQpwBlXgPg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-OZoPwwu4TMMg8GTCFBrg8UFExwQTU/55i3uTC/izDat6PHE+ro9dimyQoOboFf91+NY7Pnn70ScR8f8I8+eZXw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-dZSYaKROuswU2eUWG5aBKndNVe68elo1YX93xtRax7q658tj8rYE+HwduovWJgs6qwv1r1/CLR60nDeBbyjvyg==}
engines: {node: '>= 10'}
cpu: [arm]
os: [linux]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-W6FzYE8ADHI93In1vi80KBL6btDtAMuj50Ch5ptkWS8xuntyzbR4h5JDUmXoakxZn2yMInksudTEqVSWoFqFGg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-+6fQ+rR49hkAa4voh2stLIwQ+4t+gmoseM8Bc53/DlMXb73IKymDPWK9A/NtWeqTW4ijWppYuyuxS2hPI8tzNA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-17XEMO3t9RW/TtHtSFf2AkaSWuCWdzbPeidz7zrOFawHxoLSJCnpTI1hN5aUvrZNnkNNmt/vZVJCh0ryUaik3A==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-lc48IwknVHBsNzXn9Xs5OkUsRX38Ml3Z1aOybQ51mMEzZckm8+4A0qROlyYHEoBPzr1kL3IU8ZUAqDb7wtdX8w==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-bGY1r26S2bs8UNFJcPWcCSNdCFbKep5PATsvtgtC9A5u6SRgr2/jJE/RlhHL5m9ZpixNDhVkLY/5h16Kx5V9YA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-2vRPBZoaIvJrUkDhZTE2Hn0YrnpJRCWVM3EJACoBKjuWI6WgPxGtUoRMsxRviCsyks8bKTSFdyw14CellnG2qA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-DUlW3lZPz63kYsf8mxgyyZuevhlH0T3/BGP9l+NazhB0F1+gL6D4hqZdnhZpw24DlWmTpATDcyYSZlJOi+DdfQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
'@napi-rs/[email protected]':
resolution: {integrity: sha512-b87ugZpQ5ViwqVBkjervxpwa0GmJPsKHLBNoZN6GpjWeHzTbDUGryriq+2DYW2XbB+xCqSIINQysC0/I87nPbw==}
engines: {node: '>= 10'}
'@oxc-project/[email protected]':
resolution: {integrity: sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==}
@@ -750,6 +837,12 @@ packages:
'@upsetjs/[email protected]':
resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}
'@xterm/[email protected]':
resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==}
'@xterm/[email protected]':
resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==}
[email protected]:
resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==}
engines: {node: '>=0.4.0'}
@@ -1183,6 +1276,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==}
[email protected]:
resolution: {integrity: sha512-AVl138zALtfaAPvADulE0PZThbYzCBS79nL4pOSL/6Sm/4AH5A21BD9VHt97OlCuzJuCpmeZtAtkinisF4Vb1g==}
engines: {node: '>=22.13.0 || >=24'}
[email protected]:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -1395,6 +1492,11 @@ packages:
[email protected]:
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
[email protected]:
resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==}
engines: {node: '>= 14.6'}
hasBin: true
[email protected]:
resolution: {integrity: sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==}
@@ -1661,6 +1763,54 @@ snapshots:
dependencies:
'@chevrotain/types': 11.1.2
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optional: true
'@napi-rs/[email protected]':
optionalDependencies:
'@napi-rs/canvas-android-arm64': 1.0.13
'@napi-rs/canvas-darwin-arm64': 1.0.13
'@napi-rs/canvas-darwin-x64': 1.0.13
'@napi-rs/canvas-linux-arm-gnueabihf': 1.0.13
'@napi-rs/canvas-linux-arm64-gnu': 1.0.13
'@napi-rs/canvas-linux-arm64-musl': 1.0.13
'@napi-rs/canvas-linux-riscv64-gnu': 1.0.13
'@napi-rs/canvas-linux-x64-gnu': 1.0.13
'@napi-rs/canvas-linux-x64-musl': 1.0.13
'@napi-rs/canvas-win32-arm64-msvc': 1.0.13
'@napi-rs/canvas-win32-x64-msvc': 1.0.13
optional: true
'@oxc-project/[email protected]': {}
'@polka/[email protected]': {}
@@ -1718,15 +1868,15 @@ snapshots:
dependencies:
acorn: 8.18.0
'@sveltejs/[email protected](@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected])))':
'@sveltejs/[email protected](@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected])))':
dependencies:
'@sveltejs/kit': 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected]))
'@sveltejs/kit': 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected]))
'@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected]))':
'@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected]))':
dependencies:
'@standard-schema/spec': 1.1.0
'@sveltejs/acorn-typescript': 1.0.13([email protected])
'@sveltejs/vite-plugin-svelte': 7.3.0([email protected])([email protected](@types/[email protected]))
'@sveltejs/vite-plugin-svelte': 7.3.0([email protected])([email protected](@types/[email protected])([email protected]))
'@types/cookie': 0.6.0
acorn: 8.18.0
cookie: 0.6.0
@@ -1738,20 +1888,20 @@ snapshots:
set-cookie-parser: 3.1.2
sirv: 3.0.2
svelte: 5.57.1
vite: 8.3.0(@types/[email protected])
vite: 8.3.0(@types/[email protected])([email protected])
optionalDependencies:
typescript: 6.0.3
'@sveltejs/[email protected]': {}
'@sveltejs/[email protected]([email protected])([email protected](@types/[email protected]))':
'@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected]))':
dependencies:
deepmerge: 4.3.1
magic-string: 1.4.1
obug: 2.2.1
svelte: 5.57.1
vite: 8.3.0(@types/[email protected])
vitefu: 1.1.3([email protected](@types/[email protected]))
vite: 8.3.0(@types/[email protected])([email protected])
vitefu: 1.1.3([email protected](@types/[email protected])([email protected]))
'@tauri-apps/[email protected]': {}
@@ -2095,6 +2245,10 @@ snapshots:
d3-selection: 3.0.0
d3-transition: 3.0.1([email protected])
'@xterm/[email protected]': {}
'@xterm/[email protected]': {}
[email protected]: {}
[email protected]: {}
@@ -2503,6 +2657,10 @@ snapshots:
[email protected]: {}
[email protected]:
optionalDependencies:
'@napi-rs/canvas': 1.0.13
[email protected]: {}
[email protected]: {}
@@ -2710,7 +2868,7 @@ snapshots:
[email protected]: {}
[email protected](@types/[email protected]):
[email protected](@types/[email protected])([email protected]):
dependencies:
lightningcss: 1.33.0
picomatch: 4.0.7
@@ -2720,11 +2878,14 @@ snapshots:
optionalDependencies:
'@types/node': 24.19.2
fsevents: 2.3.3
yaml: 2.9.1
[email protected]([email protected](@types/[email protected])):
[email protected]([email protected](@types/[email protected])([email protected])):
optionalDependencies:
vite: 8.3.0(@types/[email protected])
vite: 8.3.0(@types/[email protected])([email protected])
[email protected]: {}
[email protected]: {}
[email protected]: {}
+80
View File
@@ -0,0 +1,80 @@
// Check the build output for the native features (src/lib/features/).
// Each feature module must load only through its dynamic import in `src/lib/features/loader.ts`.
// The check fails when a feature folder, or a library that only a feature needs, is in an entry chunk
// or in a chunk that an entry chunk imports statically. It also reports the size of each feature chunk.
//
// Usage: node scripts/featureChunks.mjs (also `pnpm check:features`)
// It runs a full build with Vite, so it takes about a minute.
import { execFileSync } from "node:child_process";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
/** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */
export const FEATURE_FOLDERS = ["git", "background", "terminal", "pdf", "pm"];
/** Libraries that only features need. */
export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"];
const normal = id => id.replaceAll("\\", "/");
/** The chunk names that the entry chunks load, directly or through static imports. */
export function staticClosure(chunks) {
const byName = new Map(chunks.map(chunk => [chunk.fileName, chunk]));
const seen = new Set();
const queue = chunks.filter(chunk => chunk.isEntry).map(chunk => chunk.fileName);
while (queue.length) {
const name = queue.pop();
if (seen.has(name)) continue;
seen.add(name);
for (const next of byName.get(name)?.imports ?? []) queue.push(next);
}
return seen;
}
/** True when a module belongs to a feature folder or to a feature library. */
export function featureModule(id, folders = FEATURE_FOLDERS, libraries = FEATURE_LIBRARIES) {
const path = normal(id);
return folders.some(folder => path.includes(`/src/lib/features/${folder}/`))
|| libraries.some(library => path.includes(`/node_modules/${library}/`) || path.includes(`/node_modules/.pnpm/${library.replace("/", "+")}`));
}
/**
* Check the chunks of one client build. `chunks` has the Rollup fields `fileName`, `isEntry`, `isDynamicEntry`,
* `facadeModuleId`, `imports`, `moduleIds`, and `size`. Returns the problems and the size of each feature chunk.
*/
export function checkChunks(chunks, folders = FEATURE_FOLDERS) {
const problems = [];
const closure = staticClosure(chunks);
for (const chunk of chunks) {
if (!closure.has(chunk.fileName)) continue;
for (const id of chunk.moduleIds ?? []) {
if (featureModule(id, folders)) problems.push(`${chunk.fileName} loads at start and contains ${normal(id).replace(/^.*?\/(src|node_modules)\//, "$1/")}`);
}
}
const sizes = {};
for (const folder of folders) {
const entry = chunks.find(chunk => chunk.facadeModuleId && normal(chunk.facadeModuleId).endsWith(`/src/lib/features/${folder}/index.ts`));
if (!entry) { problems.push(`No chunk starts at src/lib/features/${folder}/index.ts.`); continue; }
if (!entry.isDynamicEntry || entry.isEntry) problems.push(`src/lib/features/${folder}/index.ts must be a dynamic entry only.`);
sizes[folder] = entry.size;
}
return { problems, sizes };
}
async function main() {
// The client build of SvelteKit runs as a nested Vite build, so the report comes from a plugin in vite.config.js.
const report = path.join(mkdtempSync(path.join(tmpdir(), "runestone-chunks-")), "chunks.json");
const vite = fileURLToPath(new URL("../node_modules/vite/bin/vite.js", import.meta.url));
execFileSync(process.execPath, [vite, "build", "--logLevel", "warn"], { stdio: ["ignore", "ignore", "inherit"], env: { ...process.env, RUNESTONE_FEATURE_CHUNKS: report } });
const chunks = JSON.parse(readFileSync(report, "utf8"));
rmSync(path.dirname(report), { recursive: true, force: true });
const { problems, sizes } = checkChunks(chunks);
for (const [folder, size] of Object.entries(sizes)) console.log(`${folder}: ${(size / 1024).toFixed(1)} KiB in its own chunk`);
if (problems.length) {
for (const problem of problems) console.error(`FAIL: ${problem}`);
process.exitCode = 1;
} else console.log(`PASS: ${FEATURE_FOLDERS.length} feature module(s) load only at first need.`);
}
if (process.argv[1] === fileURLToPath(import.meta.url)) await main();
+145
View File
@@ -0,0 +1,145 @@
// Start the test build, attach to its WebView2 through CDP, read the metrics, and stop only the started process tree.
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import path from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { playwright } from "../../tests/smoke/_harness/index.mjs";
import { processTree } from "./core.mjs";
import { listProcesses, stopTree } from "./processes.mjs";
import { TABLE } from "./scenarios.mjs";
const isMainPage = page => { try { const url = new URL(page.url()); return url.pathname === "/" && !url.search && url.protocol.startsWith("http"); } catch { return false; } };
async function cdpResponds(port) {
try {
const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) });
return response.ok;
} catch { return false; }
}
/** Call a Rust command from the page. */
export function invoke(page, command, args = {}) {
return page.evaluate(([command, args]) => window.__TAURI_INTERNALS__.invoke(command, args), [command, args]);
}
/**
* Start `exe` with remote debugging on `port` and attach to its main page.
* Refuse when another program already answers on the port, because the tool must not drive a foreign browser.
*/
export async function launch({ exe, port, timeout = 90000 }) {
if (await cdpResponds(port)) throw new Error(`Port ${port} already answers CDP requests. Stop that program or choose another --port.`);
const env = { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}`, NO_PROXY: "127.0.0.1,localhost", no_proxy: "127.0.0.1,localhost" };
const started = performance.now();
const startedAt = Date.now();
const child = spawn(exe, [], { env, cwd: path.dirname(exe), stdio: "ignore", windowsHide: false });
let exited = null;
child.on("exit", code => { exited = code ?? -1; });
child.on("error", error => { exited = String(error); });
await new Promise(resolve => child.once("spawn", resolve).once("error", resolve));
const app = { child, pid: child.pid, started, startedAt, browser: null, page: null, cdpMs: null };
if (!app.pid) throw new Error(`Cannot start ${exe}: ${exited}`);
try {
const { chromium } = playwright();
while (!app.browser) {
if (exited !== null) throw new Error(`The app stopped during the start (exit ${exited}).`);
if (performance.now() - started > timeout) throw new Error("CDP did not answer during the start.");
if (await cdpResponds(port)) app.browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`, { timeout: 10000 });
else await sleep(50);
}
app.cdpMs = performance.now() - started;
while (!app.page) {
if (performance.now() - started > timeout) throw new Error("The main window page did not open.");
app.page = app.browser.contexts().flatMap(context => context.pages()).find(isMainPage) ?? null;
if (!app.page) await sleep(50);
}
app.page.setDefaultTimeout(30000);
return app;
} catch (error) {
await stop(app);
throw error;
}
}
/** Wait for the known tree row. Return the start time in milliseconds from the spawn, and page timing values. */
export async function waitForWorkbench(app, timeout = 60000) {
await app.page.locator(TABLE.knownRow).waitFor({ state: "visible", timeout });
const startMs = performance.now() - app.started;
const timing = await app.page.evaluate(() => ({ timeOrigin: performance.timeOrigin, domContentLoaded: performance.getEntriesByType("navigation")[0]?.domContentLoadedEventEnd ?? null, tabs: document.querySelectorAll('[role="tab"]').length }));
return { startMs, navigationMs: timing.timeOrigin - app.startedAt, domContentLoadedMs: timing.domContentLoaded === null ? null : timing.timeOrigin + timing.domContentLoaded - app.startedAt, tabsAtStart: timing.tabs };
}
/** Start a long task observer in the page. */
export function observeLongTasks(page) {
return page.evaluate(() => {
const state = { count: 0, max: 0 };
const record = entries => { for (const entry of entries) { state.count++; state.max = Math.max(state.max, entry.duration); } };
const observer = new PerformanceObserver(list => record(list.getEntries()));
observer.observe({ type: "longtask" });
window.__rsLongTasks = { state, observer, record };
});
}
/** Stop the long task observer. Return the count and the longest duration. */
export function collectLongTasks(page) {
return page.evaluate(() => {
const tasks = window.__rsLongTasks;
if (!tasks) return null;
tasks.record(tasks.observer.takeRecords());
tasks.observer.disconnect();
return { count: tasks.state.count, maxMs: Math.round(tasks.state.max) };
});
}
/** Collect garbage in the main page, wait, and read the heap and the process tree. */
export async function readMemory(app, { settleMs = 5000 } = {}) {
const cdp = await app.page.context().newCDPSession(app.page);
try {
await cdp.send("HeapProfiler.collectGarbage");
await sleep(settleMs);
const heap = await cdp.send("Runtime.getHeapUsage");
const tree = processTree(await listProcesses(), app.pid);
return {
heapMB: heap.usedSize / 1048576,
heapTotalMB: heap.totalSize / 1048576,
privateMB: tree.privateBytes / 1048576,
workingSetMB: tree.workingSet / 1048576,
processCount: tree.count,
processNames: tree.names,
processes: tree.processes.map(item => ({ pid: item.ProcessId, parent: item.ParentProcessId, name: item.Name, privateMB: +(item.PrivatePageCount / 1048576).toFixed(1), workingSetMB: +(item.WorkingSetSize / 1048576).toFixed(1), created: item.Created })),
};
} finally { await cdp.detach().catch(() => {}); }
}
/**
* Clear the open tabs and the layout in the page storage, so the next start restores no tab and shows the file tree.
* Chromium writes local storage to disk after a delay, so the function waits before it returns.
*/
export async function clearViewState(page, flushMs = 6000) {
await page.evaluate(layout => {
for (const key of Object.keys(localStorage)) if (key.startsWith("runestone.document-session.")) localStorage.removeItem(key);
localStorage.setItem("runestone.workbenchLayout", JSON.stringify(layout));
}, TABLE.layout);
await sleep(flushMs);
}
/** Stop the started process tree and make sure that none of its processes remain. */
export async function stop(app) {
if (!app?.pid) return { stopped: false };
const before = processTree(await listProcesses().catch(() => []), app.pid).processes;
const result = await stopTree(app.pid);
await app.browser?.close().catch(() => {});
for (let attempt = 0; attempt < 50; attempt++) {
const now = await listProcesses().catch(() => []);
const left = before.filter(item => now.some(other => other.ProcessId === item.ProcessId && other.Created === item.Created));
if (!left.length) return { ...result, remaining: [] };
if (attempt === 10) for (const item of left) await stopTree(item.ProcessId);
await sleep(200);
}
throw new Error(`Processes of the stopped app remain: ${before.map(item => item.ProcessId).join(", ")}.`);
}
/** The WebView2 folder of the test identity. It exists after the first start of a build with that identifier. */
export function webviewFolder(localData) {
return path.join(localData, "EBWebView");
}
export const hasWebviewFolder = localData => existsSync(webviewFolder(localData));
+157
View File
@@ -0,0 +1,157 @@
// Pure parts of the feature measurement tool: arguments, safety refusals, statistics, the process tree, and the report table.
import path from "node:path";
export const FEATURES = ["git", "background", "terminal", "pdf", "pm"];
export const MODES = ["plugin", "native"];
export const SCENARIOS = ["on-idle", "in-use", "after-off"];
/** The app that the owner installed. The tool never starts it, stops it, or touches its data. */
export const INSTALLED_EXE = "D:\\Users\\KnottyWyvern\\AppData\\Local\\RuneStone\\runestone.exe";
export const INSTALLED_IDENTIFIER = "com.runestone.app";
export const USAGE = "Usage: node scripts/measureFeatures.mjs --exe <path> --identifier com.runestone.<name> --stage <name> --mode plugin|native --features git,background,terminal,pdf,pm [--runs 3] [--port 9241] [--fresh-fixture] [--only base,<feature>:<scenario>,...] [--skip-base]";
/** Read the command line. Throw an error with the usage text for a missing or unknown argument. */
export function parseArguments(args) {
const options = { exe: undefined, identifier: undefined, stage: undefined, mode: undefined, features: undefined, runs: 3, port: 9241, freshFixture: false, only: undefined, skipBase: false };
const values = { "--exe": "exe", "--identifier": "identifier", "--stage": "stage", "--mode": "mode", "--features": "features", "--runs": "runs", "--port": "port", "--only": "only" };
const seen = new Set();
for (let index = 0; index < args.length; index++) {
const arg = args[index];
if (arg === "--fresh-fixture") { options.freshFixture = true; continue; }
if (arg === "--skip-base") { options.skipBase = true; continue; }
const key = values[arg];
if (!key) throw new Error(`Unknown argument ${arg}. ${USAGE}`);
if (seen.has(arg)) throw new Error(`Give ${arg} one time only. ${USAGE}`);
seen.add(arg);
const value = args[++index];
if (value === undefined || value.startsWith("--")) throw new Error(`${arg} needs a value. ${USAGE}`);
options[key] = value;
}
for (const key of ["exe", "identifier", "stage", "mode", "features"]) if (options[key] === undefined) throw new Error(`--${key} is required. ${USAGE}`);
if (!MODES.includes(options.mode)) throw new Error(`--mode must be plugin or native. ${USAGE}`);
if (!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(options.stage)) throw new Error("--stage must be a simple folder name.");
const features = options.features.split(",").map(feature => feature.trim()).filter(Boolean);
const unknown = features.filter(feature => !FEATURES.includes(feature));
if (!features.length || unknown.length) throw new Error(`Unknown feature ${unknown.join(", ") || "(none)"}. Use ${FEATURES.join(", ")}.`);
options.features = [...new Set(features)];
for (const key of ["runs", "port"]) {
const number = Number(options[key]);
if (typeof options[key] === "string" && !/^\d+$/.test(options[key])) throw new Error(`--${key} must be a whole number.`);
options[key] = number;
}
if (options.runs < 1 || options.runs > 20) throw new Error("--runs must be from 1 to 20.");
if (options.port < 1024 || options.port > 65535) throw new Error("--port must be from 1024 to 65535.");
if (options.only !== undefined) {
options.only = options.only.split(",").map(item => item.trim()).filter(Boolean);
for (const item of options.only) {
const [feature, scenario] = item.split(":");
if (!(item === "base" || (options.features.includes(feature) && SCENARIOS.includes(scenario)))) throw new Error(`--only takes base or <feature>:<scenario>, not ${item}.`);
}
}
return options;
}
function samePath(a, b) {
return path.win32.resolve(a).toLowerCase() === path.win32.resolve(b).toLowerCase();
}
/**
* Refuse an unsafe target. The executable must not be the installed app or be in its folder.
* The identifier must start with `com.runestone.` and must not be the identifier of the installed app.
* `env` supplies LOCALAPPDATA and APPDATA. Return the two data folders that the tool may reset.
*/
export function checkTarget({ exe, identifier }, env = process.env) {
const installed = [INSTALLED_EXE];
if (env.LOCALAPPDATA) installed.push(path.win32.join(env.LOCALAPPDATA, "RuneStone", "runestone.exe"));
const resolved = path.win32.resolve(exe);
for (const target of installed) {
if (samePath(resolved, target) || samePath(path.win32.dirname(resolved), path.win32.dirname(target)))
throw new Error(`Refusing to run the installed RuneStone (${target}). Give a copy of a test build.`);
}
if (typeof identifier !== "string" || identifier.toLowerCase() === INSTALLED_IDENTIFIER)
throw new Error(`Refusing the identifier ${identifier}. It belongs to the installed RuneStone.`);
if (!/^com\.runestone\.[a-z0-9][a-z0-9-]*$/.test(identifier))
throw new Error(`Refusing the identifier ${identifier}. A test identifier starts with com.runestone. and has lowercase letters, digits, and hyphens.`);
if (!env.APPDATA || !env.LOCALAPPDATA) throw new Error("APPDATA and LOCALAPPDATA must be set.");
return { roaming: path.win32.join(env.APPDATA, identifier), local: path.win32.join(env.LOCALAPPDATA, identifier) };
}
/** The median of the finite numbers in `values`, or null when there is none. */
export function median(values) {
const numbers = values.filter(value => typeof value === "number" && Number.isFinite(value)).sort((a, b) => a - b);
if (!numbers.length) return null;
const middle = Math.floor(numbers.length / 2);
return numbers.length % 2 ? numbers[middle] : (numbers[middle - 1] + numbers[middle]) / 2;
}
/**
* Walk the descendants of `rootPid` in a process list from Win32_Process.
* A child counts only when it started after its parent, so a reused parent process ID does not add a stranger.
* Return the processes of the tree, with the root first, and the sums of the private bytes and the working sets.
*/
export function processTree(list, rootPid) {
const byParent = new Map();
for (const item of list) {
if (!byParent.has(item.ParentProcessId)) byParent.set(item.ParentProcessId, []);
byParent.get(item.ParentProcessId).push(item);
}
const root = list.find(item => item.ProcessId === rootPid);
if (!root) return { processes: [], privateBytes: 0, workingSet: 0, count: 0, names: {} };
const processes = [root];
const seen = new Set([rootPid]);
for (let index = 0; index < processes.length; index++) {
const parent = processes[index];
for (const child of byParent.get(parent.ProcessId) ?? []) {
if (seen.has(child.ProcessId)) continue;
if (typeof child.Created === "number" && typeof parent.Created === "number" && child.Created < parent.Created) continue;
seen.add(child.ProcessId);
processes.push(child);
}
}
const names = {};
for (const item of processes) names[item.Name] = (names[item.Name] ?? 0) + 1;
return {
processes,
privateBytes: processes.reduce((sum, item) => sum + Number(item.PrivatePageCount ?? 0), 0),
workingSet: processes.reduce((sum, item) => sum + Number(item.WorkingSetSize ?? 0), 0),
count: processes.length,
names,
};
}
export const METRICS = ["privateMB", "workingSetMB", "heapMB", "startMs", "firstNeedMs", "longTaskCount", "longTaskMaxMs", "processCount"];
/** The median of each metric over the samples that did not fail. */
export function summarize(samples) {
const good = samples.filter(sample => !sample.error);
const result = { runs: samples.length, failed: samples.length - good.length };
for (const metric of METRICS) result[metric] = median(good.map(sample => sample[metric]));
return result;
}
const fixed = (value, digits = 1) => value === null || value === undefined ? "–" : Number(value).toFixed(digits);
/** The Markdown report: one table row for each feature and scenario. */
export function markdownTable(report) {
const lines = [
`# Feature memory: ${report.stage}`,
"",
`Build: \`${report.build}\` (${report.identifier}), mode ${report.mode}, ${report.runs} runs for each scenario, ${report.date}.`,
`Machine: ${report.machine.cpu}, ${fixed(report.machine.ramGB)} GB RAM, ${report.machine.windows}.`,
"Each value is the median of the runs. Private and working set are sums over the process tree of the app.",
"",
"| Feature | Scenario | Private MB | Working set MB | JS heap MB | Start ms | First need ms | Long tasks (count / longest ms) |",
"| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |",
];
for (const row of report.rows) {
const m = row.median;
if (!m || m.runs === m.failed) {
lines.push(`| ${row.feature} | ${row.scenario} | failed | | | | | ${row.reason ? row.reason.replace(/\|/g, "/").slice(0, 160) : ""} |`);
continue;
}
const failed = m.failed ? ` (${m.failed} of ${m.runs} runs failed)` : "";
lines.push(`| ${row.feature} | ${row.scenario}${failed} | ${fixed(m.privateMB)} | ${fixed(m.workingSetMB)} | ${fixed(m.heapMB)} | ${fixed(m.startMs, 0)} | ${fixed(m.firstNeedMs, 0)} | ${fixed(m.longTaskCount, 0)} / ${fixed(m.longTaskMaxMs, 0)} |`);
}
if (report.notes?.length) lines.push("", "Notes:", "", ...report.notes.map(note => `- ${note}`));
return lines.join("\n") + "\n";
}
+201
View File
@@ -0,0 +1,201 @@
// The fixture workspace: a Git repository with history and changes, a 50-page PDF, background images, and a Project Management store.
// It lives in the system temporary folder, outside the repository, so the file watcher of the app does not see the worktree.
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, realpathSync } from "node:fs";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { encodePng, gradientPixel } from "./png.mjs";
import { writePdf } from "./pdf.mjs";
const run = promisify(execFile);
export const FIXTURE_VERSION = 1;
export const COMMITS = 30;
export const TEXT_FILES = 50;
export const PDF_PAGES = 50;
export const BOARDS = 8;
export const CARDS_PER_BOARD = 50;
export const IMAGES = 5;
export const IMAGE_SIZE = { width: 1920, height: 1080 };
/** A file at the workspace root that the tree shows at once. The start time waits for its row. */
export const KNOWN_ROW = "sample.pdf";
export const fixtureRoot = () => path.join(tmpdir(), "runestone-phase7-fixture");
/** A UUID with the version 4 layout, made from `seed`, so each fixture build has the same IDs. */
export function seededUuid(seed) {
const hex = createHash("sha256").update(seed).digest("hex");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${"89ab"[parseInt(hex[16], 16) % 4]}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
}
/** The card file name: the hex of the UTF-8 card ID, then `.md`. */
export const cardFileName = id => `${Buffer.from(id, "utf8").toString("hex")}.md`;
/** An order key that sorts in the same order as `index`. */
const orderKey = index => `a${String.fromCharCode(97 + Math.floor(index / 26))}${String.fromCharCode(97 + (index % 26))}`;
const textName = index => `note-${String(index + 1).padStart(2, "0")}.txt`;
function git(cwd, args, env = {}) {
const config = ["-c", "user.name=RuneStone Fixture", "-c", "[email protected]", "-c", "commit.gpgsign=false", "-c", "core.autocrlf=false", "-c", "init.defaultBranch=main"];
return run("git", ["-C", cwd, ...config, ...args], { env: { ...process.env, GIT_TERMINAL_PROMPT: "0", ...env }, windowsHide: true, maxBuffer: 16 * 1024 * 1024 });
}
const LISTS = [
{ id: "backlog", name: "Backlog", status: null },
{ id: "todo", name: "To do", status: "todo" },
{ id: "doing", name: "In progress", status: "doing" },
{ id: "done", name: "Done", status: "done" },
];
/** The Project Management store: `workspace.json`, the card files, and the two `.gitignore` files. */
export function pmFiles() {
const files = new Map();
files.set(".runestone/pm/.gitignore", "# RuneStone PM local data\n*\n");
files.set(".runestone/pm/cards/.gitignore", "*\n");
const boards = [];
for (let b = 0; b < BOARDS; b++) {
const id = seededUuid(`board-${b}`);
boards.push({
name: `Fixture board ${b + 1}`,
value: {
schema: 1, kind: "board", id,
lists: LISTS.map(list => ({ id: list.id, name: list.name, status: list.status, collapsed: false })),
defaults: { todo: "todo", doing: "doing", done: "done" },
},
});
for (let c = 0; c < CARDS_PER_BOARD; c++) {
const cardId = seededUuid(`card-${b}-${c}`);
const list = LISTS[c % LISTS.length];
const status = list.status ?? "todo";
const source = [
"---",
"runestone_pm:",
" schema: 1",
` id: ${cardId}`,
" kind: task",
` status: ${status}`,
" tags: []",
" sessions: []",
" archived: false",
` order: ${orderKey(b * CARDS_PER_BOARD + c)}`,
" placements:",
` ${id}:`,
` listId: ${list.id}`,
` order: ${orderKey(c)}`,
` title: Fixture card ${c + 1} on board ${b + 1}`,
` priority: ${["low", "medium", "high"][c % 3]}`,
"---",
"",
`This card is fixture data for the memory measurement. Board ${b + 1}, card ${c + 1}.`,
"",
].join("\n");
files.set(`.runestone/pm/cards/${cardFileName(cardId)}`, source);
}
}
files.set(".runestone/pm/workspace.json", JSON.stringify({ schema: 1, boards, deletedBoardIds: [] }, null, 2) + "\n");
return files;
}
const COLORS = [
[[16, 42, 120], [220, 90, 40], 0.3],
[[10, 110, 80], [240, 220, 60], 1.2],
[[120, 20, 90], [40, 200, 230], 2.1],
[[30, 30, 30], [200, 200, 210], 0],
[[200, 40, 40], [20, 60, 160], Math.PI / 2],
];
async function writeFiles(root, files) {
for (const [rel, contents] of files) {
const target = path.join(root, ...rel.split("/"));
await mkdir(path.dirname(target), { recursive: true });
await writeFile(target, contents);
}
}
/** Build the fixture in `root`. The caller removes an old fixture first. */
export async function buildFixture(root) {
const workspace = path.join(root, "workspace");
const backgrounds = path.join(root, "backgrounds");
await mkdir(workspace, { recursive: true });
await mkdir(backgrounds, { recursive: true });
for (const [index, [from, to, angle]] of COLORS.entries()) {
const { width, height } = IMAGE_SIZE;
await writeFile(path.join(backgrounds, `background-${index + 1}.png`), encodePng(width, height, gradientPixel(width, height, from, to, angle)));
}
await git(workspace, ["init", "-q"]);
await writeFile(path.join(workspace, ".gitignore"), ".runestone/\n");
await writeFile(path.join(workspace, "sample.pdf"), writePdf(Array.from({ length: PDF_PAGES }, (_, index) => `Page ${index + 1}`)));
const line = (file, version) => `Fixture file ${file + 1}, version ${version}.\n`;
const versions = Array(TEXT_FILES).fill(0);
for (let file = 0; file < TEXT_FILES; file++) await writeFile(path.join(workspace, textName(file)), line(file, 0));
for (let commit = 0; commit < COMMITS; commit++) {
if (commit > 0) {
// Each later commit changes five files, so the graph and the diffs have content.
for (let k = 0; k < 5; k++) {
const file = (commit * 7 + k * 11) % TEXT_FILES;
versions[file]++;
await writeFile(path.join(workspace, textName(file)), Array.from({ length: versions[file] + 1 }, (_, v) => line(file, v)).join(""));
}
}
await git(workspace, ["add", "-A"]);
const date = new Date(Date.UTC(2026, 0, 1 + commit, 12)).toISOString();
await git(workspace, ["commit", "-q", "--no-verify", "-m", commit === 0 ? "Add the fixture files" : `Change fixture files, step ${commit}`], { GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date });
}
for (let file = 0; file < TEXT_FILES; file++) {
const target = path.join(workspace, textName(file));
await writeFile(target, (await readFile(target, "utf8")) + `Changed after the last commit (file ${file + 1}).\n`);
}
await writeFiles(workspace, pmFiles());
await writeFile(path.join(root, "fixture.json"), JSON.stringify({ version: FIXTURE_VERSION, commits: COMMITS, changes: TEXT_FILES, pages: PDF_PAGES, boards: BOARDS, cards: BOARDS * CARDS_PER_BOARD, images: IMAGES }, null, 2) + "\n");
}
/** Check that the fixture in `root` is complete and unchanged. Return a list of problems, empty when it matches. */
export async function checkFixture(root) {
const problems = [];
const workspace = path.join(root, "workspace");
try {
const record = JSON.parse(await readFile(path.join(root, "fixture.json"), "utf8"));
if (record.version !== FIXTURE_VERSION) problems.push(`fixture version ${record.version}`);
} catch { problems.push("no fixture.json"); return problems; }
for (let index = 0; index < IMAGES; index++) if (!existsSync(path.join(root, "backgrounds", `background-${index + 1}.png`))) problems.push(`no background ${index + 1}`);
if (!existsSync(path.join(workspace, "sample.pdf"))) problems.push("no sample.pdf");
try {
const status = (await git(workspace, ["status", "--porcelain"])).stdout.split("\n").filter(Boolean);
if (status.length !== TEXT_FILES || status.some(entry => !entry.startsWith(" M "))) problems.push(`git status shows ${status.length} entries, not ${TEXT_FILES} changed files`);
const count = Number((await git(workspace, ["rev-list", "--count", "HEAD"])).stdout.trim());
if (count !== COMMITS) problems.push(`${count} commits, not ${COMMITS}`);
} catch (error) { problems.push(`git: ${error.message}`); }
for (const [rel, contents] of pmFiles()) {
const target = path.join(workspace, ...rel.split("/"));
if (!existsSync(target)) { problems.push(`no ${rel}`); break; }
if (rel.endsWith("workspace.json") && (await readFile(target, "utf8")) !== contents) problems.push("workspace.json changed");
}
return problems;
}
/** Reuse the fixture when it matches, or build it again. Return the canonical paths. */
export async function prepareFixture({ fresh = false, root = fixtureRoot(), log = () => {} } = {}) {
let problems = fresh ? ["--fresh-fixture"] : await checkFixture(root);
if (problems.length) {
log(`Building the fixture in ${root} (${problems.join(", ")}).`);
// The fixture folder belongs to this tool. It is in the system temporary folder.
if (path.basename(root) !== "runestone-phase7-fixture") throw new Error(`Refusing to remove ${root}.`);
await rm(root, { recursive: true, force: true });
await buildFixture(root);
problems = await checkFixture(root);
if (problems.length) throw new Error(`The new fixture does not match: ${problems.join(", ")}.`);
} else log(`Reusing the fixture in ${root}.`);
// The canonical path expands short 8.3 names, so the app and the grants see the same path.
const real = realpathSync.native(root);
return { root: real, workspace: path.join(real, "workspace"), backgrounds: path.join(real, "backgrounds") };
}
/** Run the read-only Project Management helper of the skill. Return the number of boards that it lists. */
export async function inspectPmBoards(workspace, helper = path.join(process.env.USERPROFILE ?? "", ".claude", "skills", "runestone-project-management", "scripts", "inspect.mjs")) {
if (!existsSync(helper)) return { checked: false, reason: `no helper at ${helper}` };
const { stdout } = await run(process.execPath, [helper, "boards", "--workspace", workspace], { windowsHide: true, maxBuffer: 16 * 1024 * 1024 });
return { checked: true, output: stdout };
}
+47
View File
@@ -0,0 +1,47 @@
// A local fake Gitea release server. The host installs plugin ZIPs through its Gitea path from this server.
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import path from "node:path";
/**
* Serve the releases in `packages`: a list of `{ repo, tag, file }`, with `file` the path of a plugin ZIP.
* The server answers `GET /api/v1/repos/test/<repo>/releases/tags/<tag>` and serves the ZIP at its download link.
* Return the base URL, the repository link of each package, the request log, and `close`.
*/
export async function startGiteaServer(packages, owner = "test") {
const bodies = new Map();
for (const item of packages) bodies.set(item.repo, { ...item, name: path.basename(item.file), bytes: await readFile(item.file) });
const requests = [];
const server = createServer((request, response) => {
const url = new URL(request.url, "http://127.0.0.1");
requests.push(`${request.method} ${url.pathname}`);
const release = /^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/releases\/tags\/([^/]+)$/.exec(url.pathname);
const download = /^\/download\/([^/]+)\/([^/]+)$/.exec(url.pathname);
if (request.method === "GET" && release && release[1] === owner && bodies.get(release[2])?.tag === decodeURIComponent(release[3])) {
const item = bodies.get(release[2]);
const body = JSON.stringify({
tag_name: item.tag, draft: false,
assets: [{ name: item.name, size: item.bytes.length, browser_download_url: `${base}/download/${item.repo}/${encodeURIComponent(item.name)}` }],
});
response.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body) });
response.end(body);
return;
}
if (request.method === "GET" && download && bodies.get(download[1])?.name === decodeURIComponent(download[2])) {
const item = bodies.get(download[1]);
response.writeHead(200, { "content-type": "application/zip", "content-length": item.bytes.length });
response.end(item.bytes);
return;
}
response.writeHead(404, { "content-type": "text/plain" });
response.end("not found");
});
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); });
const base = `http://127.0.0.1:${server.address().port}`;
return {
base,
requests,
repository: repo => `${base}/${owner}/${repo}`,
close: () => new Promise(resolve => server.close(() => resolve())),
};
}
+45
View File
@@ -0,0 +1,45 @@
// A small PDF writer for the fixture document: one page for each text, in Helvetica, with a correct cross-reference table.
function escapeText(text) {
return text.replace(/[\\()]/g, match => `\\${match}`);
}
/** Write a PDF with one US Letter page for each entry of `texts`. Return the bytes. */
export function writePdf(texts) {
if (!texts.length) throw new Error("A PDF needs at least one page.");
// Object numbers: 1 catalog, 2 page tree, 3 font, then a page and its content stream for each text.
const pageIds = texts.map((_, index) => 4 + index * 2);
const objects = [
"<< /Type /Catalog /Pages 2 0 R >>",
`<< /Type /Pages /Kids [${pageIds.map(id => `${id} 0 R`).join(" ")}] /Count ${texts.length} >>`,
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
];
for (const [index, text] of texts.entries()) {
const stream = `BT /F1 48 Tf 72 680 Td (${escapeText(text)}) Tj ET\nBT /F1 14 Tf 72 640 Td (RuneStone measurement fixture, page ${index + 1} of ${texts.length}) Tj ET\n`;
objects.push(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents ${pageIds[index] + 1} 0 R >>`);
objects.push(`<< /Length ${Buffer.byteLength(stream, "latin1")} >>\nstream\n${stream}endstream`);
}
let body = "%PDF-1.4\n%\xe2\xe3\xcf\xd3\n";
const offsets = [];
for (const [index, object] of objects.entries()) {
offsets.push(Buffer.byteLength(body, "latin1"));
body += `${index + 1} 0 obj\n${object}\nendobj\n`;
}
const xref = Buffer.byteLength(body, "latin1");
// Each entry is exactly 20 bytes, with a space and a line feed at the end.
body += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
for (const offset of offsets) body += `${String(offset).padStart(10, "0")} 00000 n \n`;
body += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
return Buffer.from(body, "latin1");
}
/** Read the cross-reference table of a PDF from `writePdf`. Return `startxref` and the offsets of the objects in use. */
export function readPdfXref(bytes) {
const text = bytes.toString("latin1");
const start = Number(/startxref\n(\d+)\n%%EOF\n?$/.exec(text)?.[1]);
if (!Number.isInteger(start) || !text.startsWith("xref\n", start)) throw new Error("The startxref offset does not point to the xref table.");
const lines = text.slice(start).split("\n");
const [, count] = lines[1].split(" ").map(Number);
const entries = lines.slice(2, 2 + count).map(line => ({ line, offset: Number(line.slice(0, 10)), used: line.slice(17, 18) === "n" }));
return { start, count, entries };
}
+80
View File
@@ -0,0 +1,80 @@
// A small PNG encoder for the fixture images. It writes 8-bit RGB images without a dependency.
import { deflateSync } from "node:zlib";
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c >>> 0;
}
return table;
})();
/** The CRC-32 of `bytes`, as PNG and ZIP use it. */
export function crc32(bytes) {
let crc = 0xffffffff;
for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
return (crc ^ 0xffffffff) >>> 0;
}
export const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
function chunk(type, data) {
const length = Buffer.alloc(4);
length.writeUInt32BE(data.length);
const body = Buffer.concat([Buffer.from(type, "ascii"), data]);
const crc = Buffer.alloc(4);
crc.writeUInt32BE(crc32(body));
return Buffer.concat([length, body, crc]);
}
/** Encode an RGB image. `pixel(x, y)` returns `[r, g, b]` with values from 0 to 255. */
export function encodePng(width, height, pixel) {
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) throw new Error("The image size must be positive whole numbers.");
const stride = width * 3 + 1;
const raw = Buffer.alloc(stride * height);
for (let y = 0; y < height; y++) {
const row = y * stride;
raw[row] = 0; // Filter type None.
for (let x = 0; x < width; x++) {
const [r, g, b] = pixel(x, y);
const at = row + 1 + x * 3;
raw[at] = r; raw[at + 1] = g; raw[at + 2] = b;
}
}
const header = Buffer.alloc(13);
header.writeUInt32BE(width, 0);
header.writeUInt32BE(height, 4);
header[8] = 8; // Bit depth.
header[9] = 2; // Color type RGB.
header[10] = 0; header[11] = 0; header[12] = 0;
return Buffer.concat([PNG_SIGNATURE, chunk("IHDR", header), chunk("IDAT", deflateSync(raw, { level: 6 })), chunk("IEND", Buffer.alloc(0))]);
}
/** Read the chunks of a PNG file. Each chunk has its type, data, stored CRC, and computed CRC. */
export function readPngChunks(bytes) {
if (!bytes.subarray(0, 8).equals(PNG_SIGNATURE)) throw new Error("The file has no PNG signature.");
const chunks = [];
let at = 8;
while (at < bytes.length) {
const length = bytes.readUInt32BE(at);
const type = bytes.toString("ascii", at + 4, at + 8);
const data = bytes.subarray(at + 8, at + 8 + length);
const stored = bytes.readUInt32BE(at + 8 + length);
chunks.push({ type, data, stored, computed: crc32(bytes.subarray(at + 4, at + 8 + length)) });
at += 12 + length;
}
return chunks;
}
/** A diagonal gradient between two colors. Each fixture image uses a different pair and angle. */
export function gradientPixel(width, height, from, to, angle) {
const dx = Math.cos(angle), dy = Math.sin(angle);
const span = Math.abs(dx) * width + Math.abs(dy) * height;
const origin = Math.min(0, dx * width) + Math.min(0, dy * height);
return (x, y) => {
const t = (x * dx + y * dy - origin) / span;
return [0, 1, 2].map(i => Math.round(from[i] + (to[i] - from[i]) * t));
};
}
+25
View File
@@ -0,0 +1,25 @@
// Process sampling and the stop of one process tree. The tool never stops a process by its image name.
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const run = promisify(execFile);
const LIST = "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,PrivatePageCount,WorkingSetSize,@{n='Created';e={if ($_.CreationDate) { $_.CreationDate.ToFileTimeUtc() } else { $null }}} | ConvertTo-Json -Compress";
/** List all processes one time, with the private bytes and the working set of each. */
export async function listProcesses() {
const { stdout } = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", LIST], { maxBuffer: 64 * 1024 * 1024, windowsHide: true });
const value = JSON.parse(stdout);
return (Array.isArray(value) ? value : [value]).map(item => ({ ...item, PrivatePageCount: Number(item.PrivatePageCount ?? 0), WorkingSetSize: Number(item.WorkingSetSize ?? 0) }));
}
/** Stop the process tree of `pid` with taskkill. Errors are returned, not thrown, because the tree can be gone already. */
export async function stopTree(pid) {
if (!Number.isInteger(pid) || pid <= 4) throw new Error(`Refusing to stop process ID ${pid}.`);
try {
const { stdout } = await run("taskkill.exe", ["/PID", String(pid), "/T", "/F"], { windowsHide: true });
return { stopped: true, output: stdout.trim() };
} catch (error) {
return { stopped: false, output: String(error.stderr || error.message).trim() };
}
}
+187
View File
@@ -0,0 +1,187 @@
// The scenario table: the selectors, names, and feature switches of both modes, and the in-use action of each feature.
// A value with `plugin` and `native` keys differs between the modes. Change the table when a stage changes a name.
const PLUGIN_RELEASES = "D:/Users/KnottyWyvern/Documents";
export const TABLE = {
/** The start time ends when this tree row is visible. */
knownRow: '[data-tree-rel="sample.pdf"]',
/** The command palette. */
palette: { shortcut: "Control+Shift+P", input: "Find a command" },
/** The layout that the cleanup writes, so each start shows the file tree. */
layout: { leftOpen: true, rightOpen: true, leftWidth: 260, rightWidth: 240, leftView: "files" },
/** The settings section of the native feature switches. */
featuresSection: "features",
features: {
git: {
plugin: { id: "runestone.git", repo: "runestone-git", tag: "v0.1.10", zip: `${PLUGIN_RELEASES}/RuneStone_Git/releases/runestone.git-0.1.10.zip` },
nativeKey: "git",
navigation: "Source control",
changeRow: { plugin: ".rs-git-row", native: ".source-control .row" },
changeCount: 50,
changeFile: { plugin: ".rs-git-file", native: ".source-control .file" },
diffTab: "Git diff",
diffText: "Changed after the last commit",
graphCommand: "Show Git graph",
/** Where the command is: `palette`, or `menu:<ribbon menu name>`. Master lists plugin view commands only in the Plug-in views menu. */
graphCommandIn: { plugin: "menu:Plug-in views", native: "palette" },
graphTab: "Git graph",
graphText: "Change fixture files, step 29",
},
background: {
plugin: { id: "runestone.bg-slideshow", repo: "runestone-bg-slideshow", tag: "v0.0.11", zip: `${PLUGIN_RELEASES}/RuneStone_Background_Slideshow/releases/runestone.bg-slideshow-0.0.11.zip` },
nativeKey: "background",
/**
* The style property of the body that holds the current background image. The action counts its changes.
* Native: `backgroundHub.applyApp` (src/lib/plugins/backgrounds.ts) sets it for each new image of Background.
*/
imageProperty: { plugin: "--rs-background-image", native: "--rs-background-image" },
changes: 3,
seconds: 10,
},
terminal: {
plugin: { id: "runestone.terminal", repo: "runestone-terminal", tag: "v0.1.11", zip: `${PLUGIN_RELEASES}/RuneStone_Terminal/releases/runestone.terminal-0.1.11.zip` },
nativeKey: "terminal",
/**
* Both modes use the same names. Native: the ribbon button comes from the feature switch, and the first click loads
* the Terminal feature and xterm (src/lib/features/TerminalHost.svelte), so the action includes that load.
*/
ribbon: ".plugin-ribbon",
button: "Terminal",
surface: ".xterm",
rows: ".xterm-rows",
prompt: "PS [A-Za-z]:\\\\",
command: '1..10000 | % { "line $_" }',
readyText: "line 10000",
},
pdf: {
plugin: { id: "runestone.pdf-viewer", repo: "runestone-pdf-viewer", tag: "v0.0.5", zip: `${PLUGIN_RELEASES}/RuneStone_PDF_Viewer/releases/runestone.pdf-viewer-0.0.5.zip` },
nativeKey: "pdf",
/**
* Both modes use the same names. Native: the tree row opens a PDF tab, and the first tab loads the PDF Viewer feature
* and PDF.js (src/lib/features/pdf/), so the action includes that load. Each page canvas is an image named "PDF page N",
* and the page field is a spin button named "Page number". Enter in the field goes to the page.
*/
row: '[data-tree-rel="sample.pdf"]',
firstPage: "PDF page 1",
pageInput: "Page number",
target: 25,
targetPage: "PDF page 25",
},
pm: {
plugin: { id: "runestone.pm", repo: "runestone-pm", tag: "v0.2.49", zip: `${PLUGIN_RELEASES}/RuneStone_Project_Management/releases/runestone.pm-0.2.49.zip` },
nativeKey: "pm",
/**
* Where the view opens: `palette`, `menu:<ribbon menu name>`, or `ribbon:<ribbon button name>`. Native: the static
* ribbon button opens the default board or All tasks, and the first click loads the feature (src/lib/features/pm/).
*/
openIn: { plugin: "menu:Plug-in views", native: "ribbon:Project Management" },
title: "Project Management",
card: { plugin: ".pm-card", native: ".pm-card" },
minCards: 50,
},
},
};
/** The value of a table entry for `mode`. */
export const pick = (value, mode) => value && typeof value === "object" && !Array.isArray(value) && ("plugin" in value || "native" in value) ? value[mode] : value;
const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const starts = text => new RegExp(`^${escape(text)}`);
/** Wait until the page has at least `count` elements for `selector`. The predicate is synchronous on purpose. */
export function waitForCount(page, selector, count, timeout = 60000) {
return page.waitForFunction(([selector, count]) => document.querySelectorAll(selector).length >= count, [selector, count], { timeout, polling: 100 });
}
/** Open a command from the command palette by its exact title. */
export async function runPaletteCommand(page, title) {
await page.keyboard.press(TABLE.palette.shortcut);
const input = page.getByRole("textbox", { name: TABLE.palette.input, exact: true });
await input.waitFor({ timeout: 10000 });
await input.fill(title);
await page.getByRole("button", { name: starts(title) }).first().waitFor({ timeout: 10000 });
await input.press("Enter");
}
/**
* Run a command from the palette, from a ribbon menu, or from a ribbon button.
* `where` is `palette`, `menu:<menu name>`, or `ribbon:<button name>`.
*/
export async function runCommand(page, where, title) {
if (where === "palette") return runPaletteCommand(page, title);
const button = /^ribbon:(.+)$/.exec(where)?.[1];
if (button) return page.locator(".plugin-ribbon").getByRole("button", { name: button, exact: true }).click();
const menu = /^menu:(.+)$/.exec(where)?.[1];
if (!menu) throw new Error(`Unknown command place ${where}.`);
await page.locator(".plugin-ribbon").getByRole("button", { name: menu, exact: true }).click();
await page.getByRole("menuitem", { name: starts(title) }).first().click();
}
/**
* The in-use action of each feature. Each action returns when its ready condition is true.
* `ctx` has `mode` and `log`. Some actions return details for the sample.
*/
export const ACTIONS = {
async git(page, { mode }) {
const git = TABLE.features.git;
await page.getByRole("button", { name: git.navigation, exact: true }).first().click();
await waitForCount(page, pick(git.changeRow, mode), git.changeCount);
await page.locator(pick(git.changeFile, mode)).first().click();
await page.getByRole("tab", { name: starts(git.diffTab) }).first().waitFor({ timeout: 30000 });
await page.getByText(git.diffText).first().waitFor({ timeout: 30000 });
await runCommand(page, pick(git.graphCommandIn, mode), git.graphCommand);
await page.getByRole("tab", { name: starts(git.graphTab) }).first().waitFor({ timeout: 30000 });
await page.getByText(git.graphText, { exact: true }).first().waitFor({ timeout: 30000 });
return { changeRows: await page.locator(pick(git.changeRow, mode)).count() };
},
async background(page, { mode }) {
const background = TABLE.features.background;
const property = pick(background.imageProperty, mode);
const started = Date.now();
// Count the changes in the page, so a short image does not slip between two Node polls.
await page.evaluate(property => {
const state = { values: [], times: [] };
const sample = () => {
const value = document.body.style.getPropertyValue(property);
if (value && value !== state.values.at(-1)) { state.values.push(value); state.times.push(performance.now()); }
};
sample();
state.timer = setInterval(sample, 100);
window.__rsBackgroundProbe = state;
}, property);
const timeout = (background.changes + 2) * background.seconds * 1000 + 30000;
await page.waitForFunction(changes => (window.__rsBackgroundProbe?.values.length ?? 0) >= changes + 1, background.changes, { timeout, polling: 250 });
const result = await page.evaluate(() => {
const state = window.__rsBackgroundProbe;
clearInterval(state.timer);
return { images: state.values.length, intervalsMs: state.times.slice(1).map((time, index) => Math.round(time - state.times[index])) };
});
return { ...result, waitedMs: Date.now() - started };
},
async terminal(page) {
const terminal = TABLE.features.terminal;
await page.locator(terminal.ribbon).getByRole("button", { name: terminal.button, exact: true }).click();
await page.locator(terminal.surface).first().waitFor({ timeout: 30000 });
await page.waitForFunction(([rows, prompt]) => new RegExp(prompt).test((document.querySelector(rows)?.textContent ?? "").replace(/\u00a0/g, " ")), [terminal.rows, terminal.prompt], { timeout: 60000, polling: 100 });
await page.locator(terminal.surface).first().click();
await page.keyboard.type(terminal.command);
await page.keyboard.press("Enter");
await page.waitForFunction(([rows, text]) => (document.querySelector(rows)?.textContent ?? "").replace(/\u00a0/g, " ").includes(text), [terminal.rows, terminal.readyText], { timeout: 120000, polling: 100 });
},
async pdf(page) {
const pdf = TABLE.features.pdf;
await page.locator(pdf.row).click();
await page.getByRole("img", { name: pdf.firstPage, exact: true }).waitFor({ timeout: 60000 });
const input = page.getByRole("textbox", { name: pdf.pageInput, exact: true }).or(page.getByRole("spinbutton", { name: pdf.pageInput, exact: true })).first();
await input.fill(String(pdf.target));
await input.press("Enter");
await page.getByRole("img", { name: pdf.targetPage, exact: true }).waitFor({ timeout: 60000 });
},
async pm(page, { mode }) {
const pm = TABLE.features.pm;
await runCommand(page, pick(pm.openIn, mode), pm.title);
await waitForCount(page, pick(pm.card, mode), pm.minCards);
return { cards: await page.locator(pick(pm.card, mode)).count() };
},
};
+279
View File
@@ -0,0 +1,279 @@
#!/usr/bin/env node
// Measure the RAM and the response times of the optional features, each feature off and on.
// The tool starts a test build with an isolated identifier, drives it through CDP, and stops only the process tree that it started.
// Run `node scripts/measureFeatures.mjs --help` for the arguments. The results go to output/phase-7/<stage>/.
import { existsSync } from "node:fs";
import { realpathSync } from "node:fs";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { fileURLToPath, pathToFileURL } from "node:url";
import { checkTarget, FEATURES, markdownTable, parseArguments, SCENARIOS, summarize, USAGE } from "./measure/core.mjs";
import { inspectPmBoards, prepareFixture } from "./measure/fixture.mjs";
import { startGiteaServer } from "./measure/giteaServer.mjs";
import { ACTIONS, TABLE } from "./measure/scenarios.mjs";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const IDLE_MS = 15000;
const GC_SETTLE_MS = 5000;
// Plugins load after the workbench shows. Each run waits this long after the start, so the action measures the feature and not the plugin load.
const START_SETTLE_MS = 5000;
const log = message => console.log(`[${new Date().toISOString().slice(11, 19)}] ${message}`);
async function machine() {
return { cpu: os.cpus()[0]?.model?.trim() ?? "unknown", cores: os.cpus().length, ramGB: os.totalmem() / 1024 ** 3, windows: `${os.version()} ${os.release()}`, node: process.version };
}
/** Remove the data folders of the test identity. `checkTarget` made the paths from the test identifier. */
async function resetData(folders, identifier) {
for (const folder of [folders.roaming, folders.local]) {
if (path.win32.basename(folder) !== identifier) throw new Error(`Refusing to remove ${folder}.`);
for (let attempt = 0; ; attempt++) {
try { await rm(folder, { recursive: true, force: true }); break; } catch (error) {
if (attempt >= 20) throw new Error(`Cannot reset ${folder}: ${error.message}`);
await sleep(500);
}
}
}
}
/** Write the folder grant and the settings of Background Slideshow before the first start. */
async function seedBackgroundPlugin(folders, backgrounds) {
const id = TABLE.features.background.plugin.id;
const folder = path.join(folders.roaming, "plugin-data", id);
await mkdir(folder, { recursive: true });
const grant = "6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90";
await writeFile(path.join(folder, "folder-grants.json"), JSON.stringify({ schema: 1, grants: [{ id: grant, path: backgrounds }] }, null, 2));
await writeFile(path.join(folder, "settings.json"), JSON.stringify({ grant, folder: backgrounds, seconds: TABLE.features.background.seconds, order: "name", enabled: true, targets: ["app"], overlay: 0, position: "center", size: "cover" }));
}
/**
* Write the `background` settings and the host folder file of the native Background before the first start
* (src/lib/features/backgroundSettings.ts and src-tauri/src/backgrounds.rs). The settings file has no other section,
* so the first start keeps it and migrates only the feature switches.
*/
async function seedBackgroundNative(folders, backgrounds) {
await mkdir(folders.roaming, { recursive: true });
const background = { source: "folder", seconds: TABLE.features.background.seconds, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover" };
await writeFile(path.join(folders.roaming, "settings.json"), JSON.stringify({ schema: 1, revision: 1, background }, null, 2) + "\n");
// The host accepts the folder only at its resolved path.
await writeFile(path.join(folders.roaming, "background-folder.json"), JSON.stringify({ schema: 1, path: realpathSync.native(backgrounds) }, null, 2));
}
/** The features that are on in the running app. */
async function readState(app, mode, invoke) {
if (mode === "plugin") {
const snapshot = await invoke(app.page, "plugins_snapshot");
return new Set(FEATURES.filter(feature => snapshot.plugins.some(row => row.manifest.id === TABLE.features[feature].plugin.id && row.enabled)));
}
const file = await invoke(app.page, "settings_read");
const section = file?.sections?.[TABLE.featuresSection] ?? {};
return new Set(FEATURES.filter(feature => section[TABLE.features[feature].nativeKey] === true));
}
/** Turn on exactly the features in `enabled`, and turn off the others. */
async function applyState(app, mode, enabled, invoke) {
if (mode === "plugin") {
const snapshot = await invoke(app.page, "plugins_snapshot");
for (const row of snapshot.plugins) {
const feature = FEATURES.find(item => TABLE.features[item].plugin.id === row.manifest.id);
const want = feature ? enabled.has(feature) : false;
if (row.enabled !== want) await invoke(app.page, "plugins_set_enabled", { id: row.manifest.id, enabled: want, hash: want ? row.hash : null });
}
return;
}
const file = await invoke(app.page, "settings_read");
const value = { ...(file?.sections?.[TABLE.featuresSection] ?? {}) };
for (const feature of FEATURES) value[TABLE.features[feature].nativeKey] = enabled.has(feature);
await invoke(app.page, "settings_write", { section: TABLE.featuresSection, value });
}
const sameSet = (a, b) => a.size === b.size && [...a].every(item => b.has(item));
/** Install the plugins of `features` from the fake Gitea server. */
async function installPlugins(app, features, invoke) {
const packages = features.map(feature => TABLE.features[feature].plugin);
for (const item of packages) if (!existsSync(item.zip)) throw new Error(`No plugin ZIP at ${item.zip}.`);
const server = await startGiteaServer(packages.map(item => ({ repo: item.repo, tag: item.tag, file: item.zip })));
try {
for (const item of packages) {
const rows = await invoke(app.page, "plugins_from_git", { url: server.repository(item.repo), tag: item.tag, token: null });
if (rows.length !== 1 || rows[0].error || !rows[0].token) throw new Error(`plugins_from_git for ${item.repo}: ${JSON.stringify(rows)}`);
if (rows[0].manifest?.id !== item.id) throw new Error(`The ZIP of ${item.repo} has the ID ${rows[0].manifest?.id}, not ${item.id}.`);
const results = await invoke(app.page, "plugins_install", { tokens: [rows[0].token], enabled: true });
if (results.some(result => result.error)) throw new Error(`plugins_install for ${item.id}: ${JSON.stringify(results)}`);
log(`Installed ${item.id} from ${server.repository(item.repo)}.`);
}
} finally { await server.close(); }
const snapshot = await invoke(app.page, "plugins_snapshot");
const missing = packages.filter(item => !snapshot.plugins.some(row => row.manifest.id === item.id && !row.error));
if (missing.length) throw new Error(`Plugins missing after the install: ${missing.map(item => item.id).join(", ")}.`);
return snapshot.plugins.map(row => ({ id: row.manifest.id, version: row.manifest.version, hash: row.hash }));
}
export async function main(argv = process.argv.slice(2)) {
if (argv.includes("--help")) { console.log(USAGE); return; }
const options = parseArguments(argv);
const exe = path.resolve(options.exe);
const folders = checkTarget({ exe, identifier: options.identifier });
if (!existsSync(exe)) throw new Error(`No executable at ${exe}.`);
// Load the app module after the refusals, so the refusals work without Playwright.
const app = await import("./measure/app.mjs");
const output = path.join(repoRoot, "output", "phase-7", options.stage);
await mkdir(output, { recursive: true });
const fixture = await prepareFixture({ fresh: options.freshFixture, log });
const pm = await inspectPmBoards(fixture.workspace);
if (pm.checked && JSON.parse(pm.output).workspaces[0].boards.length !== 8) throw new Error("The Project Management fixture does not show 8 boards.");
const reportPath = path.join(output, "memory.json");
const previous = options.only && existsSync(reportPath) ? JSON.parse(await readFile(reportPath, "utf8")) : null;
const report = {
stage: options.stage, mode: options.mode, build: exe, identifier: options.identifier, date: new Date().toISOString(), runs: options.runs,
machine: await machine(), fixture, method: {
idleMs: IDLE_MS, gcSettleMs: GC_SETTLE_MS, startSettleMs: START_SETTLE_MS,
action: "Each run waits startSettleMs after the start, then starts the action. First need is the time from the start of the action to its ready condition.",
memory: "Win32_Process PrivatePageCount and WorkingSetSize, summed over the descendants of the started process.",
heap: "CDP Runtime.getHeapUsage usedSize of the main page after HeapProfiler.collectGarbage. Workers and other pages are not included.",
start: `From the spawn to the visible tree row ${TABLE.knownRow}.`,
longTasks: "PerformanceObserver longtask in the main page, from the start of the action to its end. For on-idle and base, over the idle wait.",
},
plugins: previous?.plugins ?? null, setup: {}, rows: previous?.rows ?? [], notes: previous?.notes ?? [],
};
const save = async () => {
report.date = new Date().toISOString();
await writeFile(reportPath, JSON.stringify(report, null, 2) + "\n");
await writeFile(path.join(output, "memory.md"), markdownTable(report));
};
const wanted = (feature, scenario) => !options.only || options.only.includes(feature === "base" ? "base" : `${feature}:${scenario}`);
// The plan: base runs with every feature off, then each feature scenario with only that feature on.
const plan = [];
if (wanted("base") && !options.skipBase) for (let run = 1; run <= options.runs; run++) plan.push({ feature: "base", scenario: "base", run, enabled: new Set() });
const featurePlan = [];
for (const feature of options.features) for (const scenario of SCENARIOS) if (wanted(feature, scenario)) for (let run = 1; run <= options.runs; run++) featurePlan.push({ feature, scenario, run, enabled: new Set([feature]) });
log(`Resetting ${folders.roaming} and ${folders.local}.`);
await resetData(folders, options.identifier);
if (options.mode === "plugin" && options.features.includes("background")) await seedBackgroundPlugin(folders, fixture.backgrounds);
if (options.mode === "native" && options.features.includes("background")) await seedBackgroundNative(folders, fixture.backgrounds);
// The setup start opens the workspace. It also proves the test identity.
let session = await app.launch({ exe, port: options.port });
try {
if (!app.hasWebviewFolder(folders.local)) throw new Error(`${app.webviewFolder(folders.local)} does not exist. The executable does not use the identifier ${options.identifier}.`);
const snapshot = await app.invoke(session.page, "plugins_snapshot");
if (!path.resolve(snapshot.root).toLowerCase().startsWith(path.resolve(folders.roaming).toLowerCase())) throw new Error(`The app data folder ${snapshot.root} is not in ${folders.roaming}.`);
report.setup.identity = { webview: app.webviewFolder(folders.local), pluginRoot: snapshot.root };
await app.invoke(session.page, "workspace_open", { path: fixture.workspace });
await session.page.evaluate(layout => localStorage.setItem("runestone.workbenchLayout", JSON.stringify(layout)), TABLE.layout);
await session.page.reload();
await session.page.locator(TABLE.knownRow).waitFor({ timeout: 60000 });
if (options.mode === "native") await applyState(session, "native", new Set(), app.invoke);
await app.clearViewState(session.page);
} finally { await app.stop(session); }
log("Setup done: workspace open, identity confirmed.");
const rowFor = (feature, scenario) => {
let row = report.rows.find(item => item.feature === feature && item.scenario === scenario);
if (!row) { row = { feature, scenario, samples: [], median: null }; report.rows.push(row); }
return row;
};
for (const item of [...plan, ...featurePlan]) {
const row = rowFor(item.feature, item.scenario);
if (item.run === 1) { row.samples = []; row.median = null; delete row.reason; }
}
// Keep the row order stable: base first, then each feature in the order of FEATURES and SCENARIOS.
const rank = row => row.feature === "base" ? -1 : FEATURES.indexOf(row.feature) * 10 + SCENARIOS.indexOf(row.scenario);
report.rows.sort((a, b) => rank(a) - rank(b));
await save();
let installed = options.mode === "native";
const runAll = async list => {
for (const [index, item] of list.entries()) {
const next = list[index + 1];
const row = rowFor(item.feature, item.scenario);
log(`${item.feature} ${item.scenario}, run ${item.run} of ${options.runs}.`);
const sample = await measure(item, next, options.mode).catch(error => ({ run: item.run, error: String(error?.stack ?? error).split("\n").slice(0, 3).join(" | ") }));
if (sample.error) log(` failed: ${sample.error}`);
else log(` private ${sample.privateMB.toFixed(1)} MB, working set ${sample.workingSetMB.toFixed(1)} MB, heap ${sample.heapMB.toFixed(1)} MB, start ${Math.round(sample.startMs)} ms, first need ${sample.firstNeedMs === null ? "–" : Math.round(sample.firstNeedMs)} ms`);
row.samples.push(sample);
row.median = summarize(row.samples);
if (row.median.failed === row.median.runs) row.reason = row.samples.find(item => item.error)?.error;
else delete row.reason;
await save();
}
};
/** One measured run in a new app process. Before the stop, it prepares the feature state of `next`. */
async function measure(item, next, mode, retry = true) {
const session = await app.launch({ exe, port: options.port });
const sample = { run: item.run, pid: session.pid, cdpMs: Math.round(session.cdpMs) };
let prepared = false;
try {
Object.assign(sample, await app.waitForWorkbench(session));
const state = await readState(session, mode, app.invoke);
if (!sameSet(state, item.enabled)) {
// A failed run can leave another state. Fix it and start again.
if (!retry) throw new Error(`The feature state is ${[...state].join(",") || "none"}, not ${[...item.enabled].join(",") || "none"}.`);
await applyState(session, mode, item.enabled, app.invoke);
await app.clearViewState(session.page);
prepared = true;
await app.stop(session);
return measure(item, next, mode, false);
}
await sleep(START_SETTLE_MS);
await app.observeLongTasks(session.page);
sample.firstNeedMs = null;
if (item.scenario === "in-use" || item.scenario === "after-off") {
const begin = performance.now();
sample.details = await ACTIONS[item.feature](session.page, { mode, log }) ?? null;
sample.firstNeedMs = performance.now() - begin;
if (item.scenario === "after-off") await applyState(session, mode, new Set(), app.invoke);
const tasks = await app.collectLongTasks(session.page);
await sleep(IDLE_MS);
Object.assign(sample, { longTaskCount: tasks?.count ?? null, longTaskMaxMs: tasks?.maxMs ?? null });
} else {
await sleep(IDLE_MS);
const tasks = await app.collectLongTasks(session.page);
Object.assign(sample, { longTaskCount: tasks?.count ?? null, longTaskMaxMs: tasks?.maxMs ?? null });
}
Object.assign(sample, await app.readMemory(session, { settleMs: GC_SETTLE_MS }));
return sample;
} catch (error) {
const shot = path.join(output, `failure-${item.feature}-${item.scenario}-${item.run}.png`);
await session.page.screenshot({ path: shot }).catch(() => {});
throw error;
} finally {
if (!prepared) {
try {
await applyState(session, mode, next?.enabled ?? new Set(), app.invoke);
await app.clearViewState(session.page);
} catch (error) { log(` cleanup: ${error.message}`); }
await app.stop(session);
}
}
}
await runAll(plan);
if (featurePlan.length && !installed) {
session = await app.launch({ exe, port: options.port });
try {
await session.page.locator(TABLE.knownRow).waitFor({ timeout: 60000 });
report.plugins = await installPlugins(session, options.features, app.invoke);
await session.page.reload();
await session.page.locator(TABLE.knownRow).waitFor({ timeout: 60000 });
await applyState(session, "plugin", featurePlan[0].enabled, app.invoke);
await app.clearViewState(session.page);
} finally { await app.stop(session); }
installed = true;
await save();
}
await runAll(featurePlan);
await save();
log(`Wrote ${reportPath} and ${path.join(output, "memory.md")}.`);
}
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
main().catch(error => { console.error(error?.stack ?? String(error)); process.exitCode = 1; });
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
const root = fileURLToPath(new URL('../', import.meta.url));
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..');
export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Terminal', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_Git', 'RuneStone_PDF_Viewer', 'RuneStone_CSV_Viewer'];
export const projects = ['RuneStone', 'RuneStone_Local_Autocomplete', 'RuneStone_CSV_Viewer'];
const patterns = {
action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
svelteMenu: /<ContextMenu\b/g,
-2
View File
@@ -1,2 +0,0 @@
// RuneStone_Terminal imports this path for its smoke test. The helper lives in the shared smoke harness.
export * from "../tests/smoke/_harness/pluginMocks.mjs";
+1 -5
View File
@@ -6,7 +6,7 @@
// After the parallel run, the runner runs each failed test again, one at a time (--retries, default 1).
// A test that passes on a retry counts as "flaky". The summary lists it, but the run does not fail.
// A test declares what it needs on a line near the top:
// // @requires plugin:terminal repo:RuneStone_Git/dist electron
// // @requires repo:RuneStone_Local_Autocomplete/src electron
// The runner skips a test, with the reason, when a requirement is missing.
// A test that fails because of a known app defect states it near the top:
// // @known-issue <the defect>
@@ -67,10 +67,6 @@ async function header(file) {
function missing(requirement) {
const [kind, value = ""] = requirement.split(/:(.*)/s);
if (kind === "plugin" && value === "terminal") {
const dist = env.RUNESTONE_TERMINAL_DIST || path.join(pluginRepos, "RuneStone_Terminal", "dist");
return existsSync(path.join(dist, "main.js")) ? null : `the Terminal plugin is not built at ${dist}`;
}
if (kind === "repo") {
const target = path.join(pluginRepos, value);
return existsSync(target) ? null : `${target} is missing; set RUNESTONE_PLUGIN_REPOS to the folder of the plugin checkouts`;
+1 -1
View File
@@ -3130,7 +3130,7 @@ dependencies = [
[[package]]
name = "runestone"
version = "0.1.49"
version = "0.1.51"
dependencies = [
"base64 0.23.1",
"dunce",
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "runestone"
version = "0.1.49"
version = "0.1.51"
description = "Writing workspace plus script editor"
authors = ["Knotty Wyvern"]
edition = "2021"
@@ -46,4 +46,4 @@ opt-level = 3
strip = true
[package.metadata.runestone]
version = "0.1.49"
version = "0.1.51"
+10 -6
View File
@@ -3,12 +3,14 @@ fn main() {
tauri_build::Attributes::new().app_manifest(
tauri_build::AppManifest::new().commands(&[
"theme_export",
"backgrounds_choose_folder",
"backgrounds_default_folder",
"backgrounds_list",
"backgrounds_read",
"backgrounds_read_image_settings",
"backgrounds_write_image_settings",
"background_choose_folder",
"background_folder",
"background_clear_folder",
"background_list",
"background_read",
"background_read_sidecar",
"background_write_sidecar",
"background_migrate",
"folders_choose",
"folders_picture",
"folders_grants",
@@ -17,6 +19,7 @@ fn main() {
"folders_read",
"folders_read_sidecar",
"folders_write_sidecar",
"features_legacy",
"spelling_suggestions",
"spelling_menu_install",
"spelling_menu_select",
@@ -95,6 +98,7 @@ fn main() {
"pty_profiles",
"pty_new_window",
"pty_dictation",
"pty_running",
]),
),
)
+4
View File
@@ -13,6 +13,10 @@
"allow-browser-engine-install",
"allow-browser-engine-cancel",
"allow-plugins-snapshot",
"allow-background-folder",
"allow-background-list",
"allow-background-read",
"allow-background-read-sidecar",
"allow-settings-read",
"allow-window-snap-layouts",
"allow-settings-write",
+10 -6
View File
@@ -18,6 +18,7 @@
"allow-settings-read",
"allow-settings-write",
"allow-settings-migrate",
"allow-features-legacy",
"allow-tab-transfer-offer",
"allow-tab-transfer-take",
"allow-tab-transfer-finish",
@@ -95,13 +96,16 @@
"allow-pty-profiles",
"allow-pty-new-window",
"allow-pty-dictation",
"allow-pty-running",
"opener:allow-reveal-item-in-dir",
"allow-backgrounds-choose-folder",
"allow-backgrounds-default-folder",
"allow-backgrounds-list",
"allow-backgrounds-read",
"allow-backgrounds-read-image-settings",
"allow-backgrounds-write-image-settings",
"allow-background-choose-folder",
"allow-background-folder",
"allow-background-clear-folder",
"allow-background-list",
"allow-background-read",
"allow-background-read-sidecar",
"allow-background-write-sidecar",
"allow-background-migrate",
"allow-folders-choose",
"allow-folders-picture",
"allow-folders-grants",
+11 -6
View File
@@ -12,6 +12,9 @@
"allow-window-snap-layouts",
"allow-settings-write",
"allow-settings-migrate",
"allow-features-legacy",
"allow-pty-running",
"allow-pty-profiles",
"core:default",
"core:window:allow-close",
"core:window:allow-minimize",
@@ -42,12 +45,14 @@
"allow-browser-engine-remove",
"allow-completion-request",
"allow-completion-cancel",
"allow-backgrounds-choose-folder",
"allow-backgrounds-default-folder",
"allow-backgrounds-list",
"allow-backgrounds-read",
"allow-backgrounds-read-image-settings",
"allow-backgrounds-write-image-settings",
"allow-background-choose-folder",
"allow-background-folder",
"allow-background-clear-folder",
"allow-background-list",
"allow-background-read",
"allow-background-read-sidecar",
"allow-background-write-sidecar",
"allow-background-migrate",
"allow-folders-choose",
"allow-folders-picture",
"allow-folders-grants",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-choose-folder"
description = "Enables the background_choose_folder command without any pre-configured scope."
commands.allow = ["background_choose_folder"]
[[permission]]
identifier = "deny-background-choose-folder"
description = "Denies the background_choose_folder command without any pre-configured scope."
commands.deny = ["background_choose_folder"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-clear-folder"
description = "Enables the background_clear_folder command without any pre-configured scope."
commands.allow = ["background_clear_folder"]
[[permission]]
identifier = "deny-background-clear-folder"
description = "Denies the background_clear_folder command without any pre-configured scope."
commands.deny = ["background_clear_folder"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-folder"
description = "Enables the background_folder command without any pre-configured scope."
commands.allow = ["background_folder"]
[[permission]]
identifier = "deny-background-folder"
description = "Denies the background_folder command without any pre-configured scope."
commands.deny = ["background_folder"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-list"
description = "Enables the background_list command without any pre-configured scope."
commands.allow = ["background_list"]
[[permission]]
identifier = "deny-background-list"
description = "Denies the background_list command without any pre-configured scope."
commands.deny = ["background_list"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-migrate"
description = "Enables the background_migrate command without any pre-configured scope."
commands.allow = ["background_migrate"]
[[permission]]
identifier = "deny-background-migrate"
description = "Denies the background_migrate command without any pre-configured scope."
commands.deny = ["background_migrate"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-read"
description = "Enables the background_read command without any pre-configured scope."
commands.allow = ["background_read"]
[[permission]]
identifier = "deny-background-read"
description = "Denies the background_read command without any pre-configured scope."
commands.deny = ["background_read"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-read-sidecar"
description = "Enables the background_read_sidecar command without any pre-configured scope."
commands.allow = ["background_read_sidecar"]
[[permission]]
identifier = "deny-background-read-sidecar"
description = "Denies the background_read_sidecar command without any pre-configured scope."
commands.deny = ["background_read_sidecar"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-background-write-sidecar"
description = "Enables the background_write_sidecar command without any pre-configured scope."
commands.allow = ["background_write_sidecar"]
[[permission]]
identifier = "deny-background-write-sidecar"
description = "Denies the background_write_sidecar command without any pre-configured scope."
commands.deny = ["background_write_sidecar"]
@@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-choose-folder"
description = "Enables the backgrounds_choose_folder command without any pre-configured scope."
commands.allow = ["backgrounds_choose_folder"]
[[permission]]
identifier = "deny-backgrounds-choose-folder"
description = "Denies the backgrounds_choose_folder command without any pre-configured scope."
commands.deny = ["backgrounds_choose_folder"]
@@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-default-folder"
description = "Enables the backgrounds_default_folder command without any pre-configured scope."
commands.allow = ["backgrounds_default_folder"]
[[permission]]
identifier = "deny-backgrounds-default-folder"
description = "Denies the backgrounds_default_folder command without any pre-configured scope."
commands.deny = ["backgrounds_default_folder"]
@@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-list"
description = "Enables the backgrounds_list command without any pre-configured scope."
commands.allow = ["backgrounds_list"]
[[permission]]
identifier = "deny-backgrounds-list"
description = "Denies the backgrounds_list command without any pre-configured scope."
commands.deny = ["backgrounds_list"]
@@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-read"
description = "Enables the backgrounds_read command without any pre-configured scope."
commands.allow = ["backgrounds_read"]
[[permission]]
identifier = "deny-backgrounds-read"
description = "Denies the backgrounds_read command without any pre-configured scope."
commands.deny = ["backgrounds_read"]
@@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-read-image-settings"
description = "Enables the backgrounds_read_image_settings command without any pre-configured scope."
commands.allow = ["backgrounds_read_image_settings"]
[[permission]]
identifier = "deny-backgrounds-read-image-settings"
description = "Denies the backgrounds_read_image_settings command without any pre-configured scope."
commands.deny = ["backgrounds_read_image_settings"]
@@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-backgrounds-write-image-settings"
description = "Enables the backgrounds_write_image_settings command without any pre-configured scope."
commands.allow = ["backgrounds_write_image_settings"]
[[permission]]
identifier = "deny-backgrounds-write-image-settings"
description = "Denies the backgrounds_write_image_settings command without any pre-configured scope."
commands.deny = ["backgrounds_write_image_settings"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-features-legacy"
description = "Enables the features_legacy command without any pre-configured scope."
commands.allow = ["features_legacy"]
[[permission]]
identifier = "deny-features-legacy"
description = "Denies the features_legacy command without any pre-configured scope."
commands.deny = ["features_legacy"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-pty-running"
description = "Enables the pty_running command without any pre-configured scope."
commands.allow = ["pty_running"]
[[permission]]
identifier = "deny-pty-running"
description = "Denies the pty_running command without any pre-configured scope."
commands.deny = ["pty_running"]
+391 -301
View File
@@ -1,99 +1,46 @@
//! The image folder of the Background feature (`src/lib/features/background/`).
//!
//! The host keeps one folder in `background-folder.json` in the app data folder. Only the folder dialog
//! sets it, so the interface never sends a folder path. The commands read the image files directly in
//! that folder and the sidecar file `.runestone-backgrounds.json` with the per-image settings.
//! They use the rules of the plugin folder grants (`folders.rs`): plain file names only, no links,
//! raster images up to 64 MiB, a sidecar up to 1 MiB, and at most 10,000 files in the folder.
use crate::error::{Error, Result};
use crate::folders;
use crate::fsutil::{self, is_link};
use crate::plugins::PluginState;
use base64::Engine;
use serde::Serialize;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use tauri::{AppHandle, Manager, Window};
use tauri_plugin_dialog::DialogExt;
const IMAGE_LIMIT: u64 = 50 * 1024 * 1024;
const SETTINGS_LIMIT: u64 = 1024 * 1024;
const SETTINGS_FILE: &str = ".runestone-backgrounds.json";
const FOLDER_FILE: &str = "background-folder.json";
const SIDECAR: &str = ".runestone-backgrounds.json";
/// The old plugin whose folder grant the migration takes.
const LEGACY_PLUGIN: &str = "runestone.bg-slideshow";
const FOLDER_FILE_LIMIT: u64 = 64 * 1024;
#[derive(Debug, Serialize)]
pub struct BackgroundFile {
name: String,
/// Serializes changes to the folder file.
static LOCK: Mutex<()> = Mutex::new(());
#[derive(Debug, Serialize, Deserialize)]
struct FolderFile {
schema: u32,
path: PathBuf,
}
fn require_plugin(app: &AppHandle, label: &str, id: &str) -> Result<()> {
app.state::<PluginState>().require_lease(app, label, id)
/// The folder file and the plugin data of one app data folder.
struct Host {
data: PathBuf,
}
/// Check the lease on a blocking worker, because the plugin lock can wait for package work.
async fn check_plugin(app: &AppHandle, window: &Window, id: &str) -> Result<()> {
let (app, label, id) = (app.clone(), window.label().to_owned(), id.to_owned());
tauri::async_runtime::spawn_blocking(move || require_plugin(&app, &label, &id)).await?
}
fn folder_root(folder: &Path) -> Result<PathBuf> {
if !folder.is_absolute()
|| folder
.components()
.any(|part| matches!(part, Component::ParentDir))
{
return Err("Supply an absolute background folder path without parent segments.".into());
}
let root = dunce::canonicalize(folder)?;
if !root.is_dir() {
return Err("The background folder does not exist.".into());
}
Ok(root)
}
fn supported(name: &str) -> bool {
fn raster(name: &str) -> bool {
Path::new(name)
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
matches!(
extension.to_ascii_lowercase().as_str(),
"png" | "jpg" | "jpeg" | "gif" | "webp"
)
})
}
fn image_path(root: &Path, name: &str) -> Result<PathBuf> {
if name.is_empty()
|| name.contains(['/', '\\', ':'])
|| name.ends_with(['.', ' '])
|| !supported(name)
|| Path::new(name).components().count() != 1
|| !matches!(
Path::new(name).components().next(),
Some(Component::Normal(_))
)
{
return Err("Supply one PNG, JPEG, GIF, or WebP filename.".into());
}
let path = root.join(name);
let metadata = fs::symlink_metadata(&path)?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Background images must be ordinary files, not links.".into());
}
let resolved = dunce::canonicalize(&path)?;
if resolved.parent() != Some(root) {
return Err("The background image is outside its folder.".into());
}
Ok(path)
}
fn list_images(folder: &Path) -> Result<Vec<BackgroundFile>> {
let root = folder_root(folder)?;
let mut images = Vec::new();
for entry in fs::read_dir(&root)? {
let entry = entry?;
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
if supported(&name) && image_path(&root, &name).is_ok() {
images.push(BackgroundFile { name });
}
}
images.sort_by(|a, b| a.name.cmp(&b.name));
Ok(images)
.is_some_and(|extension| matches!(extension.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "gif" | "webp"))
}
fn raster_signature(bytes: &[u8]) -> bool {
@@ -104,176 +51,205 @@ fn raster_signature(bytes: &[u8]) -> bool {
|| (bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP")
}
fn read_image(folder: &Path, name: &str) -> Result<Vec<u8>> {
let root = folder_root(folder)?;
let path = image_path(&root, name)?;
// Open the entry itself so a replaced link cannot redirect the read.
let file = fsutil::open_entry(&path)?;
let metadata = file.metadata()?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Background images must be ordinary files, not links.".into());
}
if metadata.len() > IMAGE_LIMIT {
return Err("The background image exceeds 50 MiB.".into());
}
image_path(&root, name)?;
let Some(bytes) = fsutil::read_to_limit(file, IMAGE_LIMIT)? else {
return Err("The background image exceeds 50 MiB.".into());
/// Read a small JSON file. A missing file gives `None`. A link or a folder is an error.
fn read_json<T: for<'de> Deserialize<'de>>(path: &Path, limit: u64) -> Result<Option<T>> {
let metadata = match fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error.into()),
};
if !metadata.is_file() || is_link(&metadata) {
return Err(Error::new(format!("{} must be an ordinary file.", path.display())));
}
let Some(bytes) = fsutil::read_to_limit(fsutil::open_entry(path)?, limit)? else {
return Err(Error::new(format!("{} is too large.", path.display())));
};
Ok(Some(serde_json::from_slice(&bytes)?))
}
impl Host {
fn file(&self) -> PathBuf {
self.data.join(FOLDER_FILE)
}
fn stored(&self) -> Result<Option<PathBuf>> {
let Some(file) = read_json::<FolderFile>(&self.file(), FOLDER_FILE_LIMIT)? else { return Ok(None) };
if file.schema != 1 {
return Err("Unknown background folder file schema.".into());
}
Ok(Some(file.path))
}
fn save(&self, path: &Path) -> Result<()> {
fs::create_dir_all(&self.data)?;
let bytes = serde_json::to_vec_pretty(&FolderFile { schema: 1, path: path.to_path_buf() })?;
let temp = self.data.join(format!("{FOLDER_FILE}.{}.tmp", uuid::Uuid::new_v4()));
Ok(fsutil::replace_file(&self.file(), &temp, &bytes)?)
}
/// Keep `folder` as the background folder. It must be an existing folder, not a whole drive.
fn choose(&self, folder: &Path) -> Result<String> {
let root = folders::granted_root(folder)?;
let _lock = LOCK.lock()?;
self.save(&root)?;
Ok(root.to_string_lossy().into_owned())
}
/// The kept folder for display, or `None`.
fn folder(&self) -> Result<Option<String>> {
Ok(self.stored()?.map(|path| path.to_string_lossy().into_owned()))
}
fn clear(&self) -> Result<()> {
let _lock = LOCK.lock()?;
match fs::remove_file(self.file()) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()),
_ => Ok(()),
}
}
/// The kept folder, still an ordinary folder at the same resolved path.
/// A folder that became a link or a file does not redirect the access.
fn root(&self) -> Result<PathBuf> {
let path = self.stored()?.ok_or_else(|| Error::new("Choose a background folder first."))?;
let metadata = fs::symlink_metadata(&path).map_err(|_| Error::new("The background folder is missing. Choose the folder again."))?;
if !metadata.is_dir() || is_link(&metadata) || dunce::canonicalize(&path)? != path {
return Err("The background folder changed into a link or a file. Choose the folder again.".into());
}
Ok(path)
}
/// The names of the raster images directly in the folder.
fn list(&self) -> Result<Vec<String>> {
Ok(folders::list_files(&self.root()?)?
.into_iter()
.map(|entry| entry.name)
.filter(|name| raster(name))
.collect())
}
fn read(&self, name: &str) -> Result<Vec<u8>> {
if !raster(name) {
return Err("Supply one PNG, JPEG, GIF, or WebP file name.".into());
}
let bytes = folders::read_file(&self.root()?, name)?;
if !raster_signature(&bytes) {
return Err("The file is not a supported raster image.".into());
}
Ok(bytes)
}
#[tauri::command]
pub async fn backgrounds_default_folder(
app: AppHandle,
window: Window,
id: String,
) -> Result<String> {
check_plugin(&app, &window, &id).await?;
let pictures = app.path().picture_dir()?;
let folder = pictures.join("RuneStone Backgrounds");
let created = folder.clone();
tauri::async_runtime::spawn_blocking(move || fs::create_dir_all(created)).await??;
check_plugin(&app, &window, &id).await?;
folder_root(&folder).map(|root| root.to_string_lossy().into_owned())
fn read_sidecar(&self) -> Result<Option<String>> {
folders::read_sidecar(&self.root()?, SIDECAR)
}
#[tauri::command]
pub async fn backgrounds_choose_folder(
app: AppHandle,
window: Window,
id: String,
) -> Result<Option<String>> {
check_plugin(&app, &window, &id).await?;
let picker_app = app.clone();
let picker_window = window.clone();
let selected = tauri::async_runtime::spawn_blocking(move || {
picker_app
.dialog()
.file()
.set_parent(&picker_window)
.set_title("Choose background image folder")
.blocking_pick_folder()
})
.await?;
check_plugin(&app, &window, &id).await?;
selected
.map(|source| {
let path = source.into_path().map_err(Error::from_display)?;
folder_root(&path).map(|root| root.to_string_lossy().into_owned())
})
.transpose()
}
#[tauri::command]
pub async fn backgrounds_list(
app: AppHandle,
window: Window,
id: String,
folder: String,
) -> Result<Vec<BackgroundFile>> {
check_plugin(&app, &window, &id).await?;
let result = tauri::async_runtime::spawn_blocking(move || list_images(Path::new(&folder)))
.await??;
check_plugin(&app, &window, &id).await?;
Ok(result)
}
#[tauri::command]
pub async fn backgrounds_read(
app: AppHandle,
window: Window,
id: String,
folder: String,
name: String,
) -> Result<String> {
check_plugin(&app, &window, &id).await?;
let result =
tauri::async_runtime::spawn_blocking(move || read_image(Path::new(&folder), &name))
.await??;
check_plugin(&app, &window, &id).await?;
Ok(base64::engine::general_purpose::STANDARD.encode(result))
}
fn read_image_settings(folder: &Path) -> Result<Option<String>> {
let root = folder_root(folder)?;
let path = root.join(SETTINGS_FILE);
let metadata = match fs::symlink_metadata(&path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(Error::from(error)),
};
if !metadata.is_file() || is_link(&metadata) || metadata.len() > SETTINGS_LIMIT {
return Err("Image settings must be an ordinary file within 1 MiB.".into());
}
let file = fsutil::open_entry(&path)?;
let metadata = file.metadata()?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Image settings must be an ordinary file, not a link.".into());
}
let Some(bytes) = fsutil::read_to_limit(file, SETTINGS_LIMIT)? else {
return Err("Image settings exceed 1 MiB.".into());
};
String::from_utf8(bytes).map(Some).map_err(Error::from)
}
fn write_image_settings(folder: &Path, contents: &str, expected: Option<&str>) -> Result<()> {
static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _lock = WRITE_LOCK.lock()?;
if contents.len() as u64 > SETTINGS_LIMIT {
return Err("Image settings exceed 1 MiB.".into());
}
/// Save the per-image settings only if the file still holds `expected` (`None` when it does not exist).
fn write_sidecar(&self, contents: &str, expected: Option<&str>) -> Result<()> {
let value: serde_json::Value = serde_json::from_str(contents)?;
if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1)
|| !value.get("images").is_some_and(serde_json::Value::is_object)
{
if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1) || !value.get("images").is_some_and(serde_json::Value::is_object) {
return Err("Use image settings with schema 1 and an images object.".into());
}
let root = folder_root(folder)?;
if read_image_settings(&root)?.as_deref() != expected {
return Err("Image settings changed. Reload them before saving.".into());
folders::write_sidecar(&self.root()?, SIDECAR, contents, expected)
}
let path = root.join(SETTINGS_FILE);
if expected.is_some() {
fsutil::write_text(&path, contents, expected)
} else {
// Publish a complete new file without replacing a file created by another process.
let temp = root.join(format!(".runestone-backgrounds-{}.tmp", uuid::Uuid::new_v4()));
Ok(fsutil::create_file(&path, &temp, contents.as_bytes())?)
/// Take the folder of the old Background Slideshow grant when the host has no folder yet.
/// Returns the folder after the migration, or `None`. It changes no plugin file.
fn migrate(&self) -> Result<Option<String>> {
let _lock = LOCK.lock()?;
if let Some(path) = self.stored()? {
return Ok(Some(path.to_string_lossy().into_owned()));
}
let plugin_data = self.data.join("plugin-data");
let settings = plugin_data.join(LEGACY_PLUGIN).join("settings.json");
let Some(value) = read_json::<serde_json::Value>(&settings, 1024 * 1024).ok().flatten() else { return Ok(None) };
let Some(grant) = value.get("grant").and_then(serde_json::Value::as_str).filter(|grant| !grant.is_empty()) else { return Ok(None) };
let Ok(path) = folders::plugin_grant(&plugin_data, LEGACY_PLUGIN, grant) else { return Ok(None) };
self.save(&path)?;
Ok(Some(path.to_string_lossy().into_owned()))
}
}
fn host(app: &AppHandle) -> Result<Host> {
Ok(Host { data: app.path().app_data_dir()? })
}
/// Run `work` on a blocking worker, because the file system calls can wait.
async fn run<T: Send + 'static>(app: &AppHandle, work: impl FnOnce(Host) -> Result<T> + Send + 'static) -> Result<T> {
let host = host(app)?;
tauri::async_runtime::spawn_blocking(move || work(host)).await?
}
/// Show the folder dialog and keep the chosen folder. Returns the folder for display, or `None` after Cancel.
#[tauri::command]
pub async fn backgrounds_read_image_settings(app: AppHandle, window: Window, id: String, folder: String) -> Result<Option<String>> {
check_plugin(&app, &window, &id).await?;
let result = tauri::async_runtime::spawn_blocking(move || read_image_settings(Path::new(&folder))).await??;
check_plugin(&app, &window, &id).await?;
Ok(result)
pub async fn background_choose_folder(app: AppHandle, window: Window, title: Option<String>) -> Result<Option<String>> {
let (picker_app, picker_window) = (app.clone(), window.clone());
let title = title.filter(|title| !title.trim().is_empty() && title.len() <= 200).unwrap_or_else(|| "Choose the background folder".into());
let selected = tauri::async_runtime::spawn_blocking(move || {
picker_app.dialog().file().set_parent(&picker_window).set_title(title).blocking_pick_folder()
})
.await?;
let Some(selected) = selected else { return Ok(None) };
let folder = selected.into_path().map_err(Error::from_display)?;
run(&app, move |host| host.choose(&folder)).await.map(Some)
}
#[tauri::command]
pub async fn backgrounds_write_image_settings(app: AppHandle, window: Window, id: String, folder: String, contents: String, expected: Option<String>) -> Result<()> {
check_plugin(&app, &window, &id).await?;
// Check the lease again immediately before the write on the blocking worker.
tauri::async_runtime::spawn_blocking(move || {
require_plugin(&app, window.label(), &id)?;
write_image_settings(Path::new(&folder), &contents, expected.as_deref())
}).await?
pub async fn background_folder(app: AppHandle) -> Result<Option<String>> {
run(&app, |host| host.folder()).await
}
#[tauri::command]
pub async fn background_clear_folder(app: AppHandle) -> Result<()> {
run(&app, |host| host.clear()).await
}
#[tauri::command]
pub async fn background_list(app: AppHandle) -> Result<Vec<String>> {
run(&app, |host| host.list()).await
}
/// Return the bytes as an `ArrayBuffer`, not as JSON or base64 text.
#[tauri::command]
pub async fn background_read(app: AppHandle, name: String) -> Result<tauri::ipc::Response> {
Ok(tauri::ipc::Response::new(run(&app, move |host| host.read(&name)).await?))
}
#[tauri::command]
pub async fn background_read_sidecar(app: AppHandle) -> Result<Option<String>> {
run(&app, |host| host.read_sidecar()).await
}
#[tauri::command]
pub async fn background_write_sidecar(app: AppHandle, contents: String, expected: Option<String>) -> Result<()> {
run(&app, move |host| host.write_sidecar(&contents, expected.as_deref())).await
}
#[tauri::command]
pub async fn background_migrate(app: AppHandle) -> Result<Option<String>> {
run(&app, |host| host.migrate()).await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::folders::LIST_LIMIT;
const PNG: &[u8] = b"\x89PNG\r\n\x1a\n";
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let root = std::env::temp_dir()
.join(format!("runestone-backgrounds-{}", uuid::Uuid::new_v4()));
let root = std::env::temp_dir().join(format!("runestone-background-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
Self(root)
Self(dunce::canonicalize(root).unwrap())
}
fn folder(&self, name: &str) -> PathBuf {
let path = self.0.join(name);
fs::create_dir_all(&path).unwrap();
path
}
fn host(&self) -> Host {
Host { data: self.folder("app") }
}
}
impl Drop for Fixture {
@@ -282,103 +258,217 @@ mod tests {
}
}
#[test]
fn image_settings_preserve_external_changes_and_validate_file_limits() {
let fixture = Fixture::new();
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
let next = r#"{"schema":1,"images":{}}"#;
assert_eq!(read_image_settings(&fixture.0).unwrap(), None);
write_image_settings(&fixture.0, first, None).unwrap();
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
assert!(write_image_settings(&fixture.0, next, None).is_err());
assert!(write_image_settings(&fixture.0, next, Some("stale")).is_err());
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
write_image_settings(&fixture.0, next, Some(first)).unwrap();
assert!(write_image_settings(&fixture.0, r#"{"schema":2,"images":{}}"#, Some(next)).is_err());
assert!(write_image_settings(&fixture.0, &"x".repeat(SETTINGS_LIMIT as usize + 1), Some(next)).is_err());
fs::File::create(fixture.0.join(SETTINGS_FILE)).unwrap().set_len(SETTINGS_LIMIT + 1).unwrap();
assert!(read_image_settings(&fixture.0).is_err());
/// Make a link, or return `false` when Windows does not allow links for this user.
fn link(original: &Path, link: &Path, folder: bool) -> bool {
#[cfg(unix)]
{
let _ = folder;
std::os::unix::fs::symlink(original, link).unwrap();
true
}
#[cfg(windows)]
{
let result = if folder { std::os::windows::fs::symlink_dir(original, link) } else { std::os::windows::fs::symlink_file(original, link) };
match result {
Ok(()) => true,
Err(error) if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => {
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
false
}
Err(error) => panic!("{error}"),
}
}
}
#[test]
fn listing_is_nonrecursive_and_filters_extensions() {
fn the_host_keeps_one_folder_until_it_is_cleared() {
let fixture = Fixture::new();
fs::write(fixture.0.join("a.PNG"), b"\x89PNG\r\n\x1a\n").unwrap();
fs::write(fixture.0.join("b.jpg"), b"\xff\xd8\xff").unwrap();
fs::write(fixture.0.join("text.svg"), b"<svg />").unwrap();
fs::create_dir(fixture.0.join("nested.gif")).unwrap();
fs::write(fixture.0.join("nested.gif/hidden.png"), b"png").unwrap();
let names: Vec<_> = list_images(&fixture.0)
.unwrap()
.into_iter()
.map(|image| image.name)
.collect();
assert_eq!(names, vec!["a.PNG", "b.jpg"]);
assert_eq!(
read_image(&fixture.0, "a.PNG").unwrap(),
b"\x89PNG\r\n\x1a\n"
);
let images = fixture.folder("images");
let other = fixture.folder("other");
let host = fixture.host();
assert_eq!(host.folder().unwrap(), None);
assert!(host.list().unwrap_err().to_string().contains("Choose a background folder"));
assert_eq!(host.choose(&images).unwrap(), images.to_string_lossy());
// A new host reads the kept folder, as after a restart.
assert_eq!(fixture.host().folder().unwrap(), Some(images.to_string_lossy().into_owned()));
host.choose(&other).unwrap();
assert_eq!(host.folder().unwrap(), Some(other.to_string_lossy().into_owned()));
host.clear().unwrap();
host.clear().unwrap();
assert_eq!(host.folder().unwrap(), None);
}
#[test]
fn reads_reject_traversal_invalid_images_and_oversized_files() {
fn the_chosen_folder_must_be_an_existing_folder() {
let fixture = Fixture::new();
for name in [
"../escape.png",
"nested/image.png",
"nested\\image.png",
"C:\\image.png",
"image.png:stream",
"image.svg",
] {
assert!(read_image(&fixture.0, name).is_err(), "{name}");
}
assert!(list_images(Path::new("relative")).is_err());
fs::write(fixture.0.join("invalid.png"), b"<svg />").unwrap();
assert!(read_image(&fixture.0, "invalid.png")
.unwrap_err()
.to_string()
.contains("raster"));
let file = fs::File::create(fixture.0.join("large.png")).unwrap();
file.set_len(IMAGE_LIMIT + 1).unwrap();
assert!(read_image(&fixture.0, "large.png")
.unwrap_err()
.to_string()
.contains("50 MiB"));
let host = fixture.host();
let images = fixture.folder("images");
assert!(host.choose(Path::new("relative")).is_err());
assert!(host.choose(&images.join("..").join("images")).is_err());
assert!(host.choose(&fixture.0.join("missing")).is_err());
fs::write(fixture.0.join("file.txt"), "x").unwrap();
assert!(host.choose(&fixture.0.join("file.txt")).is_err());
let drive = images.ancestors().last().unwrap().to_path_buf();
assert!(host.choose(&drive).is_err());
assert_eq!(host.folder().unwrap(), None);
// A damaged folder file is an error, not a silent reset.
fs::write(host.file(), "{damaged").unwrap();
assert!(host.folder().is_err());
fs::write(host.file(), r#"{"schema":2,"path":"C:\\"}"#).unwrap();
assert!(host.folder().is_err());
}
#[test]
fn raster_types_are_recognized() {
for bytes in [
b"\x89PNG\r\n\x1a\n".as_slice(),
b"\xff\xd8\xff",
b"GIF87a",
b"GIF89a",
b"RIFF0000WEBP",
] {
assert!(raster_signature(bytes));
fn the_listing_has_only_the_raster_files_directly_in_the_folder() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let host = fixture.host();
host.choose(&images).unwrap();
fs::write(images.join("b.PNG"), PNG).unwrap();
fs::write(images.join("a.jpg"), b"\xff\xd8\xff").unwrap();
fs::write(images.join("c.webp"), b"RIFF0000WEBP").unwrap();
fs::write(images.join("text.svg"), b"<svg />").unwrap();
fs::write(images.join("notes.md"), b"# notes").unwrap();
fs::write(images.join(SIDECAR), b"{}").unwrap();
fixture.folder("images/nested.gif");
fs::write(images.join("nested.gif/hidden.png"), PNG).unwrap();
assert_eq!(host.list().unwrap(), vec!["a.jpg", "b.PNG", "c.webp"]);
assert_eq!(host.read("b.PNG").unwrap(), PNG);
}
assert!(!raster_signature(b"RIFF0000WAVE"));
#[test]
fn reads_reject_other_names_other_types_and_large_files() {
let fixture = Fixture::new();
let images = fixture.folder("images");
fs::write(fixture.0.join("outside.png"), PNG).unwrap();
let host = fixture.host();
host.choose(&images).unwrap();
for name in ["../outside.png", "nested/image.png", "nested\\image.png", "C:\\image.png", "image.png:stream", "image.svg", "notes.md", "", "nul.png"] {
assert!(host.read(name).is_err(), "{name}");
}
fs::write(images.join("fake.png"), b"<svg />").unwrap();
assert!(host.read("fake.png").unwrap_err().to_string().contains("raster"));
fs::File::create(images.join("large.png")).unwrap().set_len(folders::READ_LIMIT + 1).unwrap();
assert!(host.read("large.png").unwrap_err().to_string().contains("64 MiB"));
}
#[test]
fn the_listing_has_a_size_limit() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let host = fixture.host();
host.choose(&images).unwrap();
for index in 0..=LIST_LIMIT {
fs::write(images.join(format!("{index}.png")), b"").unwrap();
}
assert!(host.list().unwrap_err().to_string().contains("10000"));
}
#[test]
fn links_cannot_escape_the_folder() {
let fixture = Fixture::new();
let outside = Fixture::new();
let original = outside.0.join("outside.png");
fs::write(&original, b"\x89PNG\r\n\x1a\n").unwrap();
let link = fixture.0.join("link.png");
#[cfg(unix)]
std::os::unix::fs::symlink(&original, &link).unwrap();
#[cfg(windows)]
if let Err(error) = std::os::windows::fs::symlink_file(&original, &link) {
if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) {
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
let images = fixture.folder("images");
let outside = fixture.folder("outside");
fs::write(outside.join("secret.png"), PNG).unwrap();
let host = fixture.host();
host.choose(&images).unwrap();
if !link(&outside.join("secret.png"), &images.join("link.png"), false) {
return;
}
panic!("{error}");
assert!(host.list().unwrap().is_empty());
assert!(host.read("link.png").is_err());
// A kept folder that is replaced by a link loses its access.
let moved = fixture.folder("moved");
host.choose(&moved).unwrap();
fs::remove_dir(&moved).unwrap();
assert!(link(&outside, &moved, true));
assert!(host.list().unwrap_err().to_string().contains("Choose the folder again"));
}
assert!(list_images(&fixture.0).unwrap().is_empty());
assert!(read_image(&fixture.0, "link.png").is_err());
#[test]
fn the_sidecar_keeps_external_changes_and_needs_schema_one() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let host = fixture.host();
host.choose(&images).unwrap();
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
let next = r#"{"schema":1,"images":{}}"#;
assert_eq!(host.read_sidecar().unwrap(), None);
host.write_sidecar(first, None).unwrap();
assert_eq!(host.read_sidecar().unwrap().as_deref(), Some(first));
assert!(host.write_sidecar(next, None).is_err());
assert!(host.write_sidecar(next, Some("stale")).is_err());
host.write_sidecar(next, Some(first)).unwrap();
assert_eq!(fs::read_to_string(images.join(SIDECAR)).unwrap(), next);
for bad in [r#"{"schema":2,"images":{}}"#, r#"{"schema":1,"images":[]}"#, "not json"] {
assert!(host.write_sidecar(bad, Some(next)).is_err(), "{bad}");
}
assert!(host.write_sidecar(&format!(r#"{{"schema":1,"images":{{}},"x":"{}"}}"#, "x".repeat(folders::SIDECAR_LIMIT as usize)), Some(next)).is_err());
fs::File::create(images.join(SIDECAR)).unwrap().set_len(folders::SIDECAR_LIMIT + 1).unwrap();
assert!(host.read_sidecar().is_err());
}
fn seed_plugin(fixture: &Fixture, folder: &Path, settings: &str) -> String {
let grant = uuid::Uuid::new_v4().to_string();
let data = fixture.folder(&format!("app/plugin-data/{LEGACY_PLUGIN}"));
fs::write(data.join("folder-grants.json"), serde_json::to_vec(&serde_json::json!({ "schema": 1, "grants": [{ "id": grant, "path": folder }] })).unwrap()).unwrap();
fs::write(data.join("settings.json"), settings.replace("GRANT", &grant)).unwrap();
grant
}
#[test]
fn the_migration_takes_the_folder_of_the_old_grant() {
let fixture = Fixture::new();
let images = fixture.folder("images");
seed_plugin(&fixture, &images, r#"{"grant":"GRANT","enabled":true}"#);
let data = fixture.0.join("app/plugin-data").join(LEGACY_PLUGIN);
let before = (fs::read(data.join("folder-grants.json")).unwrap(), fs::read(data.join("settings.json")).unwrap());
let host = fixture.host();
assert_eq!(host.migrate().unwrap(), Some(images.to_string_lossy().into_owned()));
assert_eq!(host.folder().unwrap(), Some(images.to_string_lossy().into_owned()));
assert_eq!((fs::read(data.join("folder-grants.json")).unwrap(), fs::read(data.join("settings.json")).unwrap()), before, "The migration changes no plugin file.");
}
#[test]
fn the_migration_keeps_an_existing_host_folder() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let chosen = fixture.folder("chosen");
seed_plugin(&fixture, &images, r#"{"grant":"GRANT"}"#);
let host = fixture.host();
host.choose(&chosen).unwrap();
assert_eq!(host.migrate().unwrap(), Some(chosen.to_string_lossy().into_owned()));
assert_eq!(host.folder().unwrap(), Some(chosen.to_string_lossy().into_owned()));
}
#[test]
fn the_migration_without_a_usable_grant_keeps_no_folder() {
// No plugin data.
let fixture = Fixture::new();
assert_eq!(fixture.host().migrate().unwrap(), None);
// Settings without a grant, with an unknown grant, and with damaged JSON.
for settings in [r#"{"folder":"D:\\Pictures"}"#, r#"{"grant":"6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90"}"#, r#"{"grant":"not-a-uuid"}"#, "{damaged"] {
let fixture = Fixture::new();
let images = fixture.folder("images");
seed_plugin(&fixture, &images, settings);
let host = fixture.host();
assert_eq!(host.migrate().unwrap(), None, "{settings}");
assert_eq!(host.folder().unwrap(), None);
}
// A granted folder that no longer exists.
let fixture = Fixture::new();
let images = fixture.folder("images");
seed_plugin(&fixture, &images, r#"{"grant":"GRANT"}"#);
fs::remove_dir(&images).unwrap();
assert_eq!(fixture.host().migrate().unwrap(), None);
}
#[test]
fn raster_types_are_recognized() {
for bytes in [PNG, b"\xff\xd8\xff", b"GIF87a", b"GIF89a", b"RIFF0000WEBP"] {
assert!(raster_signature(bytes));
}
assert!(!raster_signature(b"RIFF0000WAVE"));
assert!(raster("A.JPEG") && raster("b.gif") && !raster("c.svg") && !raster("png"));
}
}
+49
View File
@@ -0,0 +1,49 @@
//! The old plugin packages of the native features. The frontend reads them one time for each feature,
//! when the `features` settings section has no switch for it (`src/lib/features/migration.ts`).
//! Nothing here changes plugin files.
use tauri::AppHandle;
use crate::error::{Error, Result};
use crate::plugins::{legacy_packages, LegacyPackage};
/// The packages that native features replace. A request for another ID fails.
pub const LEGACY_PACKAGES: [&str; 5] = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm"];
fn check(ids: &[String]) -> Result<()> {
if ids.len() > LEGACY_PACKAGES.len() {
return Err(Error::new("Too many feature packages."));
}
match ids.iter().find(|id| !LEGACY_PACKAGES.contains(&id.as_str())) {
Some(id) => Err(Error::new(format!("Unknown feature package: {id}"))),
None => Ok(()),
}
}
#[tauri::command]
pub async fn features_legacy(app: AppHandle, ids: Vec<String>) -> Result<Vec<LegacyPackage>> {
check(&ids)?;
legacy_packages(&app, ids).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_packages_of_native_features_are_read() {
assert!(check(&["runestone.git".into()]).is_ok());
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into()]).is_ok());
assert!(check(&["runestone.terminal".into()]).is_ok());
assert!(check(&["runestone.pdf-viewer".into()]).is_ok());
assert!(check(&["runestone.pm".into()]).is_ok());
assert!(check(&LEGACY_PACKAGES.map(String::from)).is_ok());
assert!(check(&[]).is_ok());
for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] {
assert!(check(&[id.into()]).is_err(), "{id}");
}
let too_many = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm", "runestone.git"].map(String::from);
assert!(too_many.len() > LEGACY_PACKAGES.len());
assert!(check(&too_many).is_err());
}
}
+16 -10
View File
@@ -18,9 +18,9 @@ use tauri_plugin_dialog::DialogExt;
const GRANTS_FILE: &str = "folder-grants.json";
const GRANT_LIMIT: usize = 64;
const READ_LIMIT: u64 = 64 * 1024 * 1024;
const SIDECAR_LIMIT: u64 = 1024 * 1024;
const LIST_LIMIT: usize = 10_000;
pub(crate) const READ_LIMIT: u64 = 64 * 1024 * 1024;
pub(crate) const SIDECAR_LIMIT: u64 = 1024 * 1024;
pub(crate) const LIST_LIMIT: usize = 10_000;
/// Serializes changes to grant files and sidecar files.
static LOCK: Mutex<()> = Mutex::new(());
@@ -47,7 +47,7 @@ pub struct FolderGrant {
#[derive(Debug, Serialize, PartialEq)]
pub struct FolderEntry {
name: String,
pub(crate) name: String,
size: u64,
}
@@ -172,7 +172,7 @@ impl Grants {
}
/// Resolve a chosen folder. Reject relative paths, parent segments, files, and whole drives.
fn granted_root(folder: &Path) -> Result<PathBuf> {
pub(crate) fn granted_root(folder: &Path) -> Result<PathBuf> {
if !folder.is_absolute() || folder.components().any(|part| matches!(part, Component::ParentDir)) {
return Err("Supply an absolute folder path without parent segments.".into());
}
@@ -200,7 +200,7 @@ fn file_path(root: &Path, name: &str) -> Result<PathBuf> {
}
/// Open one ordinary file. Reject links, also a link that replaces the file after the check.
fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
pub(crate) fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Granted folder access is limited to ordinary files, not links or folders.".into());
@@ -213,7 +213,7 @@ fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
Ok((file, opened.len()))
}
fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
pub(crate) fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
let mut entries = Vec::new();
for entry in fs::read_dir(root)? {
let entry = entry?;
@@ -232,7 +232,7 @@ fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
Ok(entries)
}
fn read_file(root: &Path, name: &str) -> Result<Vec<u8>> {
pub(crate) fn read_file(root: &Path, name: &str) -> Result<Vec<u8>> {
let path = file_path(root, name)?;
let (file, size) = open_plain(root, &path)?;
if size > READ_LIMIT {
@@ -251,7 +251,7 @@ fn sidecar_path(root: &Path, name: &str) -> Result<PathBuf> {
file_path(root, name)
}
fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
pub(crate) fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
let path = sidecar_path(root, name)?;
match fs::symlink_metadata(&path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
@@ -267,7 +267,7 @@ fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
}
/// Save a sidecar only if it still holds `expected` (`None` when the file does not exist).
fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>) -> Result<()> {
pub(crate) fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>) -> Result<()> {
let path = sidecar_path(root, name)?;
if contents.len() as u64 > SIDECAR_LIMIT {
return Err("The sidecar file exceeds 1 MiB.".into());
@@ -285,6 +285,12 @@ fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>
}
}
/// The folder of one grant of `plugin` in the plugin data folder `data`, with the checks of a normal access.
/// The Background feature uses it to take the folder of the old Background Slideshow plugin. It changes no file.
pub(crate) fn plugin_grant(data: &Path, plugin: &str, id: &str) -> Result<PathBuf> {
Grants { data: data.to_path_buf() }.resolve(plugin, id)
}
fn grants(app: &AppHandle) -> Result<Grants> {
Ok(Grants { data: app.path().app_data_dir()?.join("plugin-data") })
}
+11 -6
View File
@@ -16,6 +16,7 @@ mod spelling;
mod theme;
mod backgrounds;
mod folders;
mod features;
mod window_frame;
use pty::PtyState;
@@ -37,12 +38,14 @@ pub fn run() {
.manage(preferences::PreferencesState::default())
.manage(tab_transfer::TabTransferState::default())
.invoke_handler(tauri::generate_handler![
backgrounds::backgrounds_choose_folder,
backgrounds::backgrounds_default_folder,
backgrounds::backgrounds_list,
backgrounds::backgrounds_read,
backgrounds::backgrounds_read_image_settings,
backgrounds::backgrounds_write_image_settings,
backgrounds::background_choose_folder,
backgrounds::background_folder,
backgrounds::background_clear_folder,
backgrounds::background_list,
backgrounds::background_read,
backgrounds::background_read_sidecar,
backgrounds::background_write_sidecar,
backgrounds::background_migrate,
folders::folders_choose,
folders::folders_picture,
folders::folders_grants,
@@ -51,6 +54,7 @@ pub fn run() {
folders::folders_read,
folders::folders_read_sidecar,
folders::folders_write_sidecar,
features::features_legacy,
theme::theme_export,
spelling::spelling_menu_install,
spelling::spelling_suggestions,
@@ -130,6 +134,7 @@ pub fn run() {
pty::pty_profiles,
pty::pty_new_window,
pty::pty_dictation,
pty::pty_running,
])
.build(tauri::generate_context!())
.expect("error while building tauri application")
+58
View File
@@ -1466,6 +1466,39 @@ pub async fn plugins_reveal(
app.opener().reveal_item_in_dir(path).map_err(Error::from)
}
}
/// What the feature migration (`features.rs`) reads about an old package. Nothing changes.
#[derive(Serialize, Debug, PartialEq)]
pub struct LegacyPackage {
pub id: String,
pub installed: bool,
pub enabled: bool,
/// The kept plugin settings. Missing, damaged, or linked settings count as none.
pub settings: Option<serde_json::Value>,
}
impl Service {
/// A package that is in removal, or whose removal did not finish, counts as not installed.
fn legacy(&self, id: &str) -> LegacyPackage {
let record = self.catalog.plugins.get(id).filter(|record| record.removal.is_none() && !self.removing.contains_key(id));
let settings = self.directory("plugin-data").ok().and_then(|parent| {
let dir = parent.join(id);
let path = dir.join("settings.json");
if !path.exists() || safe_child(&parent, &dir).is_err() {
return None;
}
serde_json::from_slice(&bounded(&path, 1024 * 1024).ok()?).ok()
});
LegacyPackage {
id: id.to_owned(),
installed: record.is_some(),
enabled: record.is_some_and(|record| record.enabled),
settings,
}
}
}
/// Read the old packages for the feature migration. The caller checks the IDs.
pub async fn legacy_packages(app: &AppHandle, ids: Vec<String>) -> Result<Vec<LegacyPackage>> {
PluginState::run(app, move |service| Ok(ids.iter().map(|id| service.legacy(id)).collect())).await
}
#[tauri::command]
pub async fn plugins_data(
app: AppHandle,
@@ -1863,6 +1896,31 @@ mod tests {
assert!(f.service.inspect("main", f.source.clone()).error.is_none());
}
#[test]
fn legacy_packages_report_state_and_kept_settings_without_changes() {
let mut disabled = Fixture::new();
let missing = disabled.service.legacy("org.test.demo");
assert_eq!(missing, LegacyPackage { id: "org.test.demo".into(), installed: false, enabled: false, settings: None });
let id = disabled.install(false);
assert_eq!(disabled.service.legacy(&id), LegacyPackage { id: id.clone(), installed: true, enabled: false, settings: None });
let mut f = Fixture::new();
let id = f.install(true);
let data = f.service.directory("plugin-data").unwrap().join(&id);
fs::create_dir(&data).unwrap();
fs::write(data.join("settings.json"), r#"{"fontSize":15}"#).unwrap();
let state = fs::read(f.root.join("app/plugin-state.json")).unwrap();
assert_eq!(f.service.legacy(&id), LegacyPackage { id: id.clone(), installed: true, enabled: true, settings: Some(serde_json::json!({ "fontSize": 15 })) });
fs::write(data.join("settings.json"), "{damaged").unwrap();
assert_eq!(f.service.legacy(&id).settings, None);
assert_eq!(fs::read(f.root.join("app/plugin-state.json")).unwrap(), state, "The read must not change the catalog.");
// Settings stay after an uninstall, and the package then counts as not installed.
fs::write(data.join("settings.json"), r#"{"kept":true}"#).unwrap();
let plan = f.service.prepare("main", &id).unwrap();
f.service.begin_remove("main", &plan.token).unwrap();
assert!(!f.service.legacy(&id).installed, "A package in removal is not an installed package.");
f.service.finish_remove(&id).unwrap();
assert_eq!(f.service.legacy(&id), LegacyPackage { id, installed: false, enabled: false, settings: Some(serde_json::json!({ "kept": true })) });
}
#[test]
fn feature_packages_use_the_standard_install_and_remove_lifecycle() {
for id in ["runestone.terminal", "runestone.table-formulas"] {
let mut f = Fixture::new();
+2 -1
View File
@@ -20,7 +20,8 @@ use crate::fsutil;
pub const FILE_NAME: &str = "settings.json";
pub const SCHEMA: u64 = 1;
/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion.
pub const SECTIONS: [&str; 5] = ["general", "appearance", "customThemes", "customThemesLegacy", "language"];
/// `features` holds the switches of the native features. `background` and `terminal` hold the settings of the Background and Terminal features.
pub const SECTIONS: [&str; 9] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background", "terminal", "projectManagement"];
/// The appearance section can hold an image data URL of up to 3,000,000 characters.
pub const MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
pub const CHANGED_EVENT: &str = "settings-changed";
+411 -104
View File
@@ -1,24 +1,54 @@
use std::collections::HashMap;
//! Shell sessions for the native Terminal feature of RuneStone (`src/lib/features/terminal/`).
use std::collections::{HashMap, VecDeque};
use std::io::{Read, Write};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, RecvTimeoutError};
use std::sync::Mutex;
use std::thread;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
use serde::Serialize;
use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId};
use tauri::{AppHandle, Emitter, Manager, State};
use tauri::{AppHandle, Manager, State};
use crate::error::{Error, Result};
use crate::workspace::{current_root, WorkspaceState};
use crate::terminal_platform::find_executable;
/// The largest output message in bytes.
const BATCH_BYTES: usize = 64 * 1024;
/// The longest time that output waits for more output before it goes to the webview.
const BATCH_WAIT: Duration = Duration::from_millis(8);
/// The number of retired page IDs that each window keeps.
const RETIRED_PAGES: usize = 16;
const NOT_OPEN: &str = "terminal is not open";
const RETIRED_PAGE: &str = "terminal page is no longer active";
pub struct PtyState {
inner: Mutex<HashMap<String, OpenPty>>,
inner: Mutex<Sessions>,
}
#[derive(Default)]
struct Sessions {
open: HashMap<String, OpenPty>,
/// The page IDs of each window, by window label.
pages: HashMap<String, Pages>,
}
/// The page loads of one window. Each page load of the frontend makes a new page ID.
#[derive(Default)]
struct Pages {
current: String,
retired: VecDeque<String>,
}
struct OpenPty {
owner: String,
/// A unique number for this session. A session ID can come back after a reload.
serial: u64,
integration_file: Option<PathBuf>,
master: Box<dyn MasterPty + Send>,
writer: std::sync::Arc<Mutex<Box<dyn Write + Send>>>,
@@ -33,12 +63,13 @@ impl Drop for OpenPty {
}
impl PtyState {
/// Close the window's terminals. Remove them under the lock, then stop the shells outside it.
/// Close the window's terminals and forget its pages. Remove the terminals under the lock,
/// then stop the shells outside it.
pub fn close_window(&self, label: &str) {
let closed: Vec<OpenPty> = match self.inner.lock() {
Ok(mut sessions) => {
let ids: Vec<String> = sessions.iter().filter(|(_, session)| session.owner == label).map(|(id, _)| id.clone()).collect();
ids.iter().filter_map(|id| sessions.remove(id)).collect()
sessions.pages.remove(label);
take_window(&mut sessions.open, label)
}
Err(_) => return,
};
@@ -55,22 +86,51 @@ impl PtyState {
pub fn new() -> Self {
Self {
inner: Mutex::new(HashMap::new()),
inner: Mutex::new(Sessions::default()),
}
}
}
#[derive(Clone, Serialize)]
pub struct PtyData {
pub id: String,
// xterm owns UTF-8 decoding so multibyte characters split across reads survive.
pub data: Vec<u8>,
/// Remove the sessions of one window from the map. The caller stops them outside the lock.
fn take_window(open: &mut HashMap<String, OpenPty>, owner: &str) -> Vec<OpenPty> {
let ids: Vec<String> = open.iter().filter(|(_, session)| session.owner == owner).map(|(id, _)| id.clone()).collect();
ids.iter().filter_map(|id| open.remove(id)).collect()
}
#[derive(Clone, Serialize)]
pub struct PtyExit {
pub id: String,
pub code: Option<u32>,
/// The number of open sessions of all windows.
fn running(pty: &PtyState) -> Result<usize> {
Ok(pty.inner.lock().map_err(|_| Error::new("pty lock"))?.open.len())
}
/// A page ID has 1 to 64 ASCII letters, digits, and hyphens.
fn check_page(page: &str) -> Result<()> {
if page.is_empty() || page.len() > 64 || !page.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
return Err(Error::new("Invalid terminal page ID"));
}
Ok(())
}
/// Apply the page rule to an open request of the window `owner`. A new page is a reload of
/// the window. It retires the current page and returns the sessions of the earlier page.
/// The caller stops them outside the lock. A retired page gets an error, so a late request
/// of an old page cannot close the sessions of the new page.
fn enter_page(sessions: &mut Sessions, owner: &str, page: &str) -> Result<Vec<OpenPty>> {
let Some(pages) = sessions.pages.get_mut(owner) else {
sessions.pages.insert(owner.to_owned(), Pages { current: page.to_owned(), retired: VecDeque::new() });
return Ok(Vec::new());
};
if pages.current == page {
return Ok(Vec::new());
}
if pages.retired.iter().any(|retired| retired == page) {
return Err(Error::new(RETIRED_PAGE));
}
let earlier = std::mem::replace(&mut pages.current, page.to_owned());
pages.retired.push_back(earlier);
while pages.retired.len() > RETIRED_PAGES {
pages.retired.pop_front();
}
Ok(take_window(&mut sessions.open, owner))
}
/// The destination of the output and the exit status of one terminal session.
@@ -79,24 +139,6 @@ trait PtyOutput: Send {
fn exit(&self, code: Option<u32>);
}
/// Window events for the released Terminal plugin, which listens for `pty-data` and `pty-exit`.
/// The events go to the window that opened the session. A global `listen` in that window
/// receives them. Tauri 2 also delivers an addressed event to a global `listen` in other windows.
struct EventOutput {
app: AppHandle,
owner: String,
id: String,
}
impl PtyOutput for EventOutput {
fn data(&self, bytes: &[u8]) {
let _ = self.app.emit_to(self.owner.as_str(), "pty-data", PtyData { id: self.id.clone(), data: bytes.to_vec() });
}
fn exit(&self, code: Option<u32>) {
let _ = self.app.emit_to(self.owner.as_str(), "pty-exit", PtyExit { id: self.id.clone(), code });
}
}
/// A channel to the webview that opened the session. Output goes as raw bytes (an
/// `ArrayBuffer` in JavaScript). The exit status goes as `{ "exit": code }`.
struct ChannelOutput(Channel<InvokeResponseBody>);
@@ -110,23 +152,58 @@ impl PtyOutput for ChannelOutput {
}
}
/// Use the channel when the caller supplies one. Without a channel, use window events.
fn output(channel: Option<Channel<InvokeResponseBody>>, events: impl FnOnce() -> Box<dyn PtyOutput>) -> Box<dyn PtyOutput> {
match channel {
Some(channel) => Box::new(ChannelOutput(channel)),
None => events(),
}
}
/// Send the output until the reader reaches EOF. Then send the exit status.
fn pump(mut reader: impl Read, exit: std::sync::mpsc::Receiver<Option<u32>>, output: &dyn PtyOutput) {
let mut buf = [0u8; 4096];
/// Read the PTY until EOF and send each read to `chunks`.
fn read_chunks(mut reader: impl Read, chunks: std::sync::mpsc::Sender<Vec<u8>>) {
let mut buf = vec![0u8; 16 * 1024];
loop {
match reader.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => output.data(&buf[..n]),
Ok(n) => {
if chunks.send(buf[..n].to_vec()).is_err() { break; }
}
}
}
}
/// Join the output chunks into messages, then send the exit status. A message starts with
/// the first chunk that arrives. It collects more chunks until `wait` after that chunk or
/// until `max_bytes`. A chunk that does not fit starts the next message. A chunk larger than
/// `max_bytes` goes in parts. When the reader stops, the loop sends the rest of the output
/// and then the exit status.
fn pump(chunks: Receiver<Vec<u8>>, exit: Receiver<Option<u32>>, output: &dyn PtyOutput, max_bytes: usize, wait: Duration) {
let max_bytes = max_bytes.max(1);
let mut next: Option<Vec<u8>> = None;
loop {
let mut message = match next.take() {
Some(chunk) => chunk,
None => match chunks.recv() {
Ok(chunk) => chunk,
Err(_) => break,
},
};
let deadline = Instant::now() + wait;
let mut ended = false;
while message.len() < max_bytes {
let now = Instant::now();
if now >= deadline { break; }
match chunks.recv_timeout(deadline - now) {
Ok(chunk) if message.len() + chunk.len() > max_bytes => {
next = Some(chunk);
break;
}
Ok(chunk) => message.extend(chunk),
Err(RecvTimeoutError::Timeout) => break,
Err(RecvTimeoutError::Disconnected) => {
ended = true;
break;
}
}
}
for part in message.chunks(max_bytes) {
output.data(part);
}
if ended { break; }
}
output.exit(exit.recv().ok().flatten());
}
@@ -246,7 +323,7 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
integration_file = Some(rc);
}
// The cmd prompt cannot encode base64, so it reports the folder as plain text with `Cwd`.
// The Terminal plugin reads both `Cwd` (plain) and `RSCwd` (base64). A Windows path
// The Terminal feature reads both `Cwd` (plain) and `RSCwd` (base64). A Windows path
// cannot contain the escape or bell characters that end the sequence.
"cmd" => { cmd.args(["/D", "/K", "prompt $E]633;Cwd;$P$E\\$E]133;A$E\\$P$G$E]133;B$E\\"]); }
"node" => { cmd.args(["--inspect=127.0.0.1:0", "-i"]); }
@@ -265,8 +342,10 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
.spawn_command(cmd)
.map_err(Error::from_display)?;
drop(pair.slave);
static NEXT_SERIAL: AtomicU64 = AtomicU64::new(0);
let session = OpenPty {
owner: owner.into(),
serial: NEXT_SERIAL.fetch_add(1, Ordering::Relaxed),
integration_file,
master: pair.master,
writer: std::sync::Arc::new(Mutex::new(writer)),
@@ -284,77 +363,103 @@ pub async fn pty_open(
webview: tauri::Webview,
workspace: State<'_, WorkspaceState>,
id: String,
page: String,
cols: u16,
rows: u16,
cwd: String,
profile: Option<String>,
directory: Option<String>,
channel: Option<JavaScriptChannelId>,
channel: JavaScriptChannelId,
) -> Result<()> {
check_page(&page)?;
let root = current_root(&workspace, window.label())?;
if root.to_string_lossy() != cwd {
return Err(Error::new("workspace changed before the terminal started"));
}
let owner = window.label().to_owned();
// A session with a channel sends no `pty-data` or `pty-exit` events.
let channel = channel.map(|channel| channel.channel_on(webview));
tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory, channel)).await?
let output = ChannelOutput(channel.channel_on(webview));
let request = OpenRequest { owner, page, id, cols, rows, profile, directory: directory.map(PathBuf::from).unwrap_or(root) };
tauri::async_runtime::spawn_blocking(move || open(app, request, output)).await?
}
#[allow(clippy::too_many_arguments)]
fn open(
app: AppHandle,
struct OpenRequest {
owner: String,
root: PathBuf,
page: String,
id: String,
cols: u16,
rows: u16,
profile: Option<String>,
directory: Option<String>,
channel: Option<Channel<InvokeResponseBody>>,
) -> Result<()> {
let pty = app.state::<PtyState>();
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
if guard.contains_key(&id) {
return Err(Error::new("terminal already exists"));
directory: PathBuf,
}
let directory = directory.map(PathBuf::from).unwrap_or(root);
if !directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
let (session, reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?;
guard.insert(id.clone(), session);
drop(guard);
/// Apply the page rule and start the shell under one lock, so two opens cannot race.
fn open(app: AppHandle, request: OpenRequest, output: impl PtyOutput + 'static) -> Result<()> {
let pty = app.state::<PtyState>();
let (left, started) = {
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
let left = enter_page(&mut guard, &request.owner, &request.page)?;
(left, start(&mut guard, &request))
};
// A reload left these sessions. Stop their shells outside the lock.
drop(left);
let (serial, reader, mut child) = started?;
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
let wait_app = app.clone();
let wait_id = id.clone();
let wait_id = request.id;
thread::spawn(move || {
let code = child.wait().ok().map(|status| status.exit_code());
// Close ConPTY after the shell exits so the output reader reaches EOF.
// A later session can use the same ID, so remove only this session.
let session = wait_app
.state::<PtyState>()
.inner
.lock()
.ok()
.and_then(|mut sessions| sessions.remove(&wait_id));
.and_then(|mut sessions| match sessions.open.get(&wait_id) {
Some(session) if session.serial == serial => sessions.open.remove(&wait_id),
_ => None,
});
drop(session);
let _ = exit_tx.send(code);
});
let output = output(channel, || Box::new(EventOutput { app: app.clone(), owner, id }));
thread::spawn(move || pump(reader, exit_rx, output.as_ref()));
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
thread::spawn(move || read_chunks(reader, chunk_tx));
thread::spawn(move || pump(chunk_rx, exit_rx, &output, BATCH_BYTES, BATCH_WAIT));
Ok(())
}
/// Write input on a blocking worker. A shell that does not read its input can fill the pipe,
/// and the write then waits. The Terminal plugin waits for each write before the next one.
#[tauri::command]
pub async fn pty_write(app: AppHandle, id: String, data: String) -> Result<()> {
tauri::async_runtime::spawn_blocking(move || write(&app.state::<PtyState>(), &id, &data)).await?
type StartedShell = (u64, Box<dyn Read + Send>, Box<dyn portable_pty::Child + Send + Sync>);
/// Start the shell and insert its session. The caller holds the lock.
fn start(sessions: &mut Sessions, request: &OpenRequest) -> Result<StartedShell> {
if sessions.open.contains_key(&request.id) {
return Err(Error::new("terminal already exists"));
}
if !request.directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
let (session, reader, child) = spawn_shell(&request.directory, request.cols, request.rows, request.profile.as_deref(), &request.owner)?;
let serial = session.serial;
sessions.open.insert(request.id.clone(), session);
Ok((serial, reader, child))
}
fn write(pty: &PtyState, id: &str, data: &str) -> Result<()> {
/// Find a session of the window `owner`. A session of another window gives the same error
/// as a missing session.
fn owned<'a>(sessions: &'a Sessions, owner: &str, id: &str) -> Result<&'a OpenPty> {
sessions.open.get(id).filter(|session| session.owner == owner).ok_or_else(|| Error::new(NOT_OPEN))
}
/// Write input on a blocking worker. A shell that does not read its input can fill the pipe,
/// and the write then waits. The Terminal feature waits for each write before the next one.
#[tauri::command]
pub async fn pty_write(app: AppHandle, window: tauri::Window, id: String, data: String) -> Result<()> {
let owner = window.label().to_owned();
tauri::async_runtime::spawn_blocking(move || write(&app.state::<PtyState>(), &owner, &id, &data)).await?
}
fn write(pty: &PtyState, owner: &str, id: &str, data: &str) -> Result<()> {
let writer = {
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
let session = guard.get(id).ok_or_else(|| Error::new("terminal is not open"))?;
session.writer.clone()
owned(&guard, owner, id)?.writer.clone()
};
// Other terminals stay usable while this write waits.
let mut writer = writer.lock().map_err(|_| Error::new("pty writer lock"))?;
@@ -366,10 +471,13 @@ fn write(pty: &PtyState, id: &str, data: &str) -> Result<()> {
}
#[tauri::command]
pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> Result<()> {
pub fn pty_resize(pty: State<PtyState>, window: tauri::Window, id: String, cols: u16, rows: u16) -> Result<()> {
resize(&pty, window.label(), &id, cols, rows)
}
fn resize(pty: &PtyState, owner: &str, id: &str, cols: u16, rows: u16) -> Result<()> {
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
let session = guard.get(&id).ok_or_else(|| Error::new("terminal is not open"))?;
session
owned(&guard, owner, id)?
.master
.resize(PtySize {
rows: rows.max(2),
@@ -382,19 +490,34 @@ pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> Res
}
/// Stop a shell on a blocking worker. Closing a pseudo console can wait for its output.
/// A missing session and a session of another window are not an error. Neither one closes.
#[tauri::command]
pub async fn pty_close(app: AppHandle, id: String) -> Result<()> {
pub async fn pty_close(app: AppHandle, window: tauri::Window, id: String) -> Result<()> {
let owner = window.label().to_owned();
tauri::async_runtime::spawn_blocking(move || {
let pty = app.state::<PtyState>();
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
let session = guard.remove(&id);
drop(guard);
let session = close(&app.state::<PtyState>(), &owner, &id)?;
drop(session);
Ok(())
})
.await?
}
/// Remove a session of the window `owner` under the lock. The caller stops it outside the lock.
fn close(pty: &PtyState, owner: &str, id: &str) -> Result<Option<OpenPty>> {
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
if owned(&guard, owner, id).is_err() {
return Ok(None);
}
Ok(guard.open.remove(id))
}
/// The number of open terminals of all windows. The Settings window asks before Terminal
/// goes off when shells run.
#[tauri::command]
pub fn pty_running(pty: State<PtyState>) -> Result<usize> {
running(&pty)
}
#[tauri::command]
pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> Result<()> {
let root = current_root(&workspace, window.label())?;
@@ -436,28 +559,111 @@ mod tests {
use std::sync::Arc;
use std::time::{Duration, Instant};
/// Records the window events that a session would send.
struct FakeEvents(Arc<Mutex<Vec<String>>>);
impl PtyOutput for FakeEvents {
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(format!("pty-data {}", String::from_utf8_lossy(bytes))); }
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(format!("pty-exit {code:?}")); }
#[derive(Debug, PartialEq)]
enum Sent {
Data(Vec<u8>),
Exit(Option<u32>),
}
fn run_pump(channel: Option<Channel<InvokeResponseBody>>, events: Arc<Mutex<Vec<String>>>) {
/// Records the messages that a session sends.
#[derive(Clone, Default)]
struct Recorder(Arc<Mutex<Vec<Sent>>>);
impl PtyOutput for Recorder {
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(Sent::Data(bytes.to_vec())); }
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(Sent::Exit(code)); }
}
impl Recorder {
fn take(&self) -> Vec<Sent> { std::mem::take(&mut *self.0.lock().unwrap()) }
}
type Pump = (std::sync::mpsc::Sender<Vec<u8>>, std::sync::mpsc::Sender<Option<u32>>, Recorder, thread::JoinHandle<()>);
/// Run the batch loop on its own thread. The test sends the chunks and the exit status.
fn start_pump(max_bytes: usize, wait: Duration) -> Pump {
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
exit_tx.send(Some(3)).unwrap();
let output = output(channel, move || Box::new(FakeEvents(events)));
pump(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), exit_rx, output.as_ref());
let recorder = Recorder::default();
let output = recorder.clone();
let handle = thread::spawn(move || pump(chunk_rx, exit_rx, &output, max_bytes, wait));
(chunk_tx, exit_tx, recorder, handle)
}
fn data_sizes(sent: &[Sent]) -> Vec<usize> {
sent.iter().filter_map(|message| match message { Sent::Data(bytes) => Some(bytes.len()), Sent::Exit(_) => None }).collect()
}
#[test]
fn a_channel_session_sends_raw_bytes_and_no_window_events() {
let events = Arc::new(Mutex::new(Vec::new()));
fn small_chunks_within_the_wait_become_one_message() {
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5));
for _ in 0..100 { chunks.send(b"ab".to_vec()).unwrap(); }
drop(chunks);
exit.send(Some(0)).unwrap();
handle.join().unwrap();
assert_eq!(recorder.take(), vec![Sent::Data(b"ab".repeat(100)), Sent::Exit(Some(0))]);
}
#[test]
fn output_larger_than_the_limit_becomes_several_messages() {
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5));
let mut expected: Vec<u8> = Vec::new();
for index in 0..40u8 {
let chunk = vec![index; 4000];
expected.extend(&chunk);
chunks.send(chunk).unwrap();
}
// One chunk larger than the limit goes in parts.
let large = vec![b'x'; BATCH_BYTES + 100];
expected.extend(&large);
chunks.send(large).unwrap();
drop(chunks);
exit.send(None).unwrap();
handle.join().unwrap();
let sent = recorder.take();
let sizes = data_sizes(&sent);
assert!(sizes.len() > 1, "{sizes:?}");
assert!(sizes.iter().all(|&size| size > 0 && size <= BATCH_BYTES), "{sizes:?}");
let joined: Vec<u8> = sent.iter().flat_map(|message| match message { Sent::Data(bytes) => bytes.clone(), Sent::Exit(_) => Vec::new() }).collect();
assert_eq!(joined, expected);
assert_eq!(sent.last(), Some(&Sent::Exit(None)));
}
#[test]
fn a_chunk_after_a_pause_goes_in_a_new_message() {
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_millis(20));
chunks.send(b"first".to_vec()).unwrap();
thread::sleep(Duration::from_millis(300));
chunks.send(b"second".to_vec()).unwrap();
drop(chunks);
exit.send(Some(1)).unwrap();
handle.join().unwrap();
assert_eq!(recorder.take(), vec![Sent::Data(b"first".to_vec()), Sent::Data(b"second".to_vec()), Sent::Exit(Some(1))]);
}
#[test]
fn the_exit_comes_after_all_output() {
let (chunks, exit, recorder, handle) = start_pump(16, Duration::from_secs(5));
// The exit status is ready before the output ends.
exit.send(Some(9)).unwrap();
for _ in 0..10 { chunks.send(b"0123456789".to_vec()).unwrap(); }
drop(chunks);
handle.join().unwrap();
let sent = recorder.take();
assert_eq!(data_sizes(&sent).iter().sum::<usize>(), 100);
assert!(data_sizes(&sent).iter().all(|&size| size <= 16));
assert_eq!(sent.iter().position(|message| matches!(message, Sent::Exit(_))), Some(sent.len() - 1));
assert_eq!(sent.last(), Some(&Sent::Exit(Some(9))));
}
#[test]
fn a_channel_session_sends_raw_bytes_then_the_json_exit() {
let received = Arc::new(Mutex::new(Vec::new()));
let sink = received.clone();
let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) });
run_pump(Some(channel), events.clone());
assert!(events.lock().unwrap().is_empty(), "a channel session must not send pty-data or pty-exit events");
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
exit_tx.send(Some(3)).unwrap();
read_chunks(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), chunk_tx);
pump(chunk_rx, exit_rx, &ChannelOutput(channel), BATCH_BYTES, BATCH_WAIT);
let received = received.lock().unwrap();
assert_eq!(received.len(), 2);
match &received[0] {
@@ -470,11 +676,112 @@ mod tests {
}
}
/// Start a real shell for `owner`. A thread reads its output until EOF.
fn shell(owner: &str) -> OpenPty {
let root = std::env::current_dir().unwrap();
let (session, mut reader, _child) = spawn_shell(&root, 80, 24, None, owner).unwrap();
thread::spawn(move || {
let _ = std::io::copy(&mut reader, &mut std::io::sink());
});
session
}
fn ids(pty: &PtyState) -> Vec<String> {
let mut ids: Vec<String> = pty.inner.lock().unwrap().open.keys().cloned().collect();
ids.sort();
ids
}
#[test]
fn a_session_without_a_channel_keeps_the_window_events() {
let events = Arc::new(Mutex::new(Vec::new()));
run_pump(None, events.clone());
assert_eq!(*events.lock().unwrap(), vec!["pty-data hello λ".to_owned(), "pty-exit Some(3)".to_owned()]);
fn only_the_owner_window_can_use_a_session() {
let pty = PtyState::new();
pty.inner.lock().unwrap().open.insert("t1".into(), shell("a"));
assert_eq!(write(&pty, "b", "t1", "\r").unwrap_err().to_string(), NOT_OPEN);
assert_eq!(resize(&pty, "b", "t1", 100, 40).unwrap_err().to_string(), NOT_OPEN);
assert!(close(&pty, "b", "t1").unwrap().is_none());
assert_eq!(ids(&pty), vec!["t1"]);
// A missing session gives the same results.
assert_eq!(write(&pty, "a", "t2", "\r").unwrap_err().to_string(), NOT_OPEN);
assert_eq!(resize(&pty, "a", "t2", 100, 40).unwrap_err().to_string(), NOT_OPEN);
assert!(close(&pty, "a", "t2").unwrap().is_none());
write(&pty, "a", "t1", "\r").unwrap();
resize(&pty, "a", "t1", 100, 40).unwrap();
let session = close(&pty, "a", "t1").unwrap();
assert!(session.is_some());
assert!(ids(&pty).is_empty());
drop(session);
}
#[test]
fn a_new_page_closes_the_sessions_of_its_window_only() {
let pty = PtyState::new();
let enter = |owner: &str, page: &str| enter_page(&mut pty.inner.lock().unwrap(), owner, page);
// The first page of each window becomes current.
assert!(enter("a", "page-1").unwrap().is_empty());
assert!(enter("b", "page-b").unwrap().is_empty());
{
let mut sessions = pty.inner.lock().unwrap();
sessions.open.insert("a1".into(), shell("a"));
sessions.open.insert("b1".into(), shell("b"));
}
// A second dock of the same page keeps the sessions.
assert!(enter("a", "page-1").unwrap().is_empty());
assert_eq!(ids(&pty), vec!["a1", "b1"]);
// A reload of window "a" closes its sessions. The session of window "b" stays.
let left = enter("a", "page-2").unwrap();
assert_eq!(left.iter().map(|session| session.owner.as_str()).collect::<Vec<_>>(), vec!["a"]);
drop(left);
assert_eq!(ids(&pty), vec!["b1"]);
// A late open of the old page is refused and closes nothing.
pty.inner.lock().unwrap().open.insert("a2".into(), shell("a"));
assert_eq!(enter("a", "page-1").err().map(|error| error.to_string()).as_deref(), Some(RETIRED_PAGE));
assert_eq!(ids(&pty), vec!["a2", "b1"]);
// The window forgets its pages when it closes.
pty.close_window("a");
assert_eq!(ids(&pty), vec!["b1"]);
assert!(!pty.inner.lock().unwrap().pages.contains_key("a"));
assert!(enter("a", "page-1").unwrap().is_empty());
pty.close_all();
assert!(ids(&pty).is_empty());
assert!(pty.inner.lock().unwrap().pages.is_empty());
}
#[test]
fn a_window_keeps_a_limited_number_of_retired_pages() {
let mut sessions = Sessions::default();
for index in 0..=RETIRED_PAGES + 4 {
assert!(enter_page(&mut sessions, "a", &format!("page-{index}")).unwrap().is_empty());
}
let pages = &sessions.pages["a"];
assert_eq!(pages.retired.len(), RETIRED_PAGES);
assert_eq!(pages.current, format!("page-{}", RETIRED_PAGES + 4));
assert!(enter_page(&mut sessions, "a", &format!("page-{}", RETIRED_PAGES + 3)).is_err());
}
#[test]
fn page_ids_are_checked() {
assert!(check_page("0f3c-9a1b").is_ok());
assert!(check_page(&"a".repeat(64)).is_ok());
for page in ["", "a b", "../page", "page_1", "λ"] {
assert!(check_page(page).is_err(), "{page}");
}
assert!(check_page(&"a".repeat(65)).is_err());
}
#[test]
fn running_counts_the_sessions_of_all_windows() {
let pty = PtyState::new();
assert_eq!(running(&pty).unwrap(), 0);
{
let mut sessions = pty.inner.lock().unwrap();
sessions.open.insert("a1".into(), shell("a"));
sessions.open.insert("b1".into(), shell("b"));
}
assert_eq!(running(&pty).unwrap(), 2);
pty.close_window("a");
assert_eq!(running(&pty).unwrap(), 1);
pty.close_all();
assert_eq!(running(&pty).unwrap(), 0);
}
#[test]
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "RuneStone",
"version": "0.1.49",
"version": "0.1.51",
"identifier": "com.runestone.app",
"build": {
"beforeDevCommand": "pnpm dev",
+1
View File
@@ -3,6 +3,7 @@
@import "./lib/ui/menu.css";
@import "./lib/ui/switch.css";
@import "./lib/theme/base.css";
@import "./lib/theme/background.css";
@import "./lib/ui/tooltip.css";
@import "./lib/layout/reading.css";
@import "./lib/editor/noteTitle.css";
@@ -0,0 +1,123 @@
<!--
Settings → Project Management, and the Project Management settings of the board menu. It is in the main bundle and
loads no feature code: the priority levels are in the `projectManagement` settings section (`pmSettings.ts`), and
the default board is in `.runestone/pm/workspace.json` of the workspace (`pmBoards.ts`). It shows only while
Project Management is on. Each change saves at once.
-->
<script lang="ts">
import { onDestroy, onMount } from "svelte";
import { message, t } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte";
import { showActionMenu } from "$lib/ui/managedActionMenu";
import { PRIORITY_LEVELS, onProjectManagementChange, readProjectManagement, writeProjectManagement, type PriorityLevels, type ProjectManagementSettings } from "./pmSettings";
import { readBoardCatalog, writeDefaultBoard, type BoardSummary } from "./pmBoards";
let { compact = false }: { compact?: boolean } = $props();
// The errors here are catalog keys without values (pmBoards.ts) or host text. The full `errorText()` of the feature
// (pm/ui/text.ts) is not necessary, and this component must load no feature module.
const errorText = (reason: unknown) => $t(reason instanceof Error ? reason.message : String(reason));
const levelNames: Record<PriorityLevels, string> = { 2: message("2 — High and Low"), 3: message("3 — High, Medium, and Low"), 5: message("5 — Highest through Lowest") };
let settings = $state<ProjectManagementSettings>(readProjectManagement());
let boards = $state<BoardSummary[]>([]);
let defaultBoard = $state("");
let boardsReady = $state(false);
let boardNote = $state("");
let saving = $state(false);
let notice = $state("");
let error = $state("");
let closeMenu = () => {};
let disposed = false;
const active = $derived(boards.filter(board => !board.archived));
const boardName = $derived(defaultBoard ? active.find(board => board.id === defaultBoard)?.name ?? $t("Unavailable board (opens All tasks)") : $t("All tasks"));
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
closeMenu();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
}
function saveLevels(priorityLevels: PriorityLevels) {
error = "";
settings = { ...settings, priorityLevels };
writeProjectManagement(settings).then(() => { notice = $t("Changes saved."); })
.catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); notice = ""; settings = readProjectManagement(); });
}
async function saveDefault(id: string) {
const previous = defaultBoard;
error = ""; saving = true; defaultBoard = id;
try { await writeDefaultBoard(id || null); if (!disposed) notice = $t("Changes saved."); }
catch (reason) { if (!disposed) { defaultBoard = previous; notice = ""; error = errorText(reason); } }
finally { saving = false; }
}
async function readBoards() {
try {
const catalog = await readBoardCatalog();
if (disposed) return;
boards = catalog.boards;
defaultBoard = catalog.defaultBoardId ?? "";
boardsReady = true;
boardNote = "";
} catch (reason) {
if (!disposed) boardNote = /no workspace/i.test(String(reason)) ? $t("Open a workspace to choose its default board.") : errorText(reason);
}
}
onMount(() => {
void readBoards();
return onProjectManagementChange(() => { settings = readProjectManagement(); });
});
onDestroy(() => { disposed = true; closeMenu(); });
</script>
<div class="pm-settings">
{#if !compact}
<h2>{$t("Project Management")}</h2>
<p class="intro">{$t("The boards of each workspace stay in {folder} in the workspace.", { folder: ".runestone/pm" })}</p>
{/if}
<div class="card">
<div class="setting-row">
<div><span class="name" id="pm-priority-label">{$t("Priority levels")}</span><p id="pm-priority-description">{$t("Existing card priorities stay unchanged when you change this setting.")}</p></div>
<button class="picker" type="button" aria-label={$t("Priority levels")} aria-describedby="pm-priority-description" aria-haspopup="menu"
onclick={event => picker(event, $t("Priority levels"), PRIORITY_LEVELS.map(levels => ({ label: $t(levelNames[levels]), checked: settings.priorityLevels === levels, run: () => saveLevels(levels) })))}>
{$t(levelNames[settings.priorityLevels])}<Icon icon="chevron-down" />
</button>
</div>
<div class="setting-row">
<div><span class="name" id="pm-default-label">{$t("Default board")}</span><p id="pm-default-description">{boardNote || $t("Choose the board that opens in this workspace. Restored tabs keep their board.")}</p></div>
<button class="picker" type="button" aria-label={$t("Default board")} aria-describedby="pm-default-description" aria-haspopup="menu" disabled={!boardsReady || saving}
onclick={event => picker(event, $t("Default board"), [
{ label: $t("All tasks"), checked: !defaultBoard, run: () => void saveDefault("") },
...active.map(board => ({ label: board.name, checked: defaultBoard === board.id, run: () => void saveDefault(board.id) })),
])}>
{boardName}<Icon icon="chevron-down" />
</button>
</div>
</div>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<p class="saved" role="status">{notice}</p>
</div>
<style>
.pm-settings { min-width: 0; }
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
.name { font-weight: 500; color: var(--rs-text); }
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); box-sizing: border-box; max-width: 100%; min-width: 160px; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: left; cursor: pointer; }
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
.picker:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
.error { color: var(--rs-error); margin-top: 10px; }
</style>
+39
View File
@@ -0,0 +1,39 @@
<script lang="ts">
// The place of the terminal panel in the workbench and in the terminal window. It is in the main bundle.
// The first mount loads the Terminal feature (xterm included). An unmount closes the sessions of this panel.
import { onMount } from "svelte";
import { t } from "$lib/i18n";
import { terminalInstance, type TerminalAction, type TerminalMount, type TerminalProps } from "./terminalHost";
let props: TerminalProps = $props();
let container: HTMLDivElement;
let mounted = $state.raw<TerminalMount>();
let loading = $state(true);
let error = $state("");
let ready: Promise<TerminalMount | undefined> = Promise.resolve(undefined);
onMount(() => {
let disposed = false;
ready = terminalInstance().then(instance => {
if (disposed) return undefined;
mounted = instance.mountDock(container, { ...props });
return mounted;
}).catch(reason => { if (!disposed) error = String(reason); return undefined; }).finally(() => { loading = false; });
return () => {
disposed = true;
const current = mounted;
mounted = undefined;
void current?.dispose().catch(reason => console.error("The terminal panel did not close cleanly.", reason));
};
});
$effect(() => { mounted?.update({ ...props }); });
/** Run a terminal action. It waits for the first load. */
export async function command(action: Exclude<TerminalAction, "toggle">) { await (await ready)?.command(action); }
</script>
{#if error}<p class="error" role="alert">{$t("The terminal could not start: {error}", { error })}</p>{/if}
{#if loading}<p class="loading">{$t("Loading the terminal…")}</p>{/if}
<div class="terminal-host" bind:this={container}></div>
<style>
.terminal-host { display: flex; flex-direction: column; flex: 1; height: 100%; min-height: 0; min-width: 0; }
.error, .loading { margin: 0; padding: 7px 12px; font-size: 12px; }
.error { color: var(--rs-error); }
.loading { color: var(--rs-text-dim); }
</style>
+113
View File
@@ -0,0 +1,113 @@
<!--
Settings → Terminal. It is in the main bundle and loads no feature code, so it does not load xterm.
It shows only while Terminal is on. Each change saves at once to the `terminal` section, and open terminals take it.
-->
<script lang="ts">
import { onDestroy, onMount } from "svelte";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { t, tr } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte";
import { showActionMenu } from "$lib/ui/managedActionMenu";
import { FONT_SIZE, SCROLLBACK, onTerminalChange, readTerminal, writeTerminal, type TerminalSettings } from "./terminalSettings";
type Profile = { id: string; title: string; kind: string };
const initial = readTerminal();
let settings = $state<TerminalSettings>(initial);
let fontSize = $state<number | undefined>(initial.fontSize);
let scrollback = $state<number | undefined>(initial.scrollback);
let profiles = $state<Profile[]>([]);
let profileNote = $state("");
let message = $state("");
let error = $state("");
let closeMenu = () => {};
/** The shells that a new terminal can use. The Node.js debug terminal is not a default. */
const shells = $derived(profiles.filter(profile => profile.kind !== "node"));
const current = $derived(shells.find(profile => profile.id === settings.defaultProfile) ?? shells[0]);
function read() {
settings = readTerminal();
fontSize = settings.fontSize;
scrollback = settings.scrollback;
}
function save(next: TerminalSettings) {
error = "";
settings = next;
writeTerminal(next).then(() => { message = tr("Changes saved."); })
.catch(() => { error = tr("Could not save these settings. Your previous settings still apply. Try again."); message = ""; });
}
function changeNumber(value: number | undefined, range: { min: number; max: number }, key: "fontSize" | "scrollback") {
if (typeof value !== "number" || !Number.isInteger(value) || value < range.min || value > range.max) {
error = tr("Choose a whole number from {min} to {max}.", { min: range.min.toLocaleString(), max: range.max.toLocaleString() });
message = "";
return;
}
save({ ...settings, [key]: value });
}
function profileMenu(event: MouseEvent) {
closeMenu();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: tr("Default terminal profile"), parent: anchor.closest("dialog") ?? undefined,
items: shells.map(profile => ({ label: profile.title, icon: "code", radio: true, checked: current?.id === profile.id,
run: () => save({ ...settings, defaultProfile: profile.id }) })) }).close;
}
onMount(() => {
const stop = onTerminalChange(read);
if (!isTauri()) profileNote = tr("The desktop app lists the installed shells.");
else invoke<Profile[]>("pty_profiles").then(found => {
profiles = found;
if (!found.some(profile => profile.kind !== "node")) profileNote = tr("RuneStone found no supported shells on PATH.");
}).catch(reason => { profileNote = tr("RuneStone could not list the shells: {error}", { error: String(reason) }); });
return stop;
});
onDestroy(() => closeMenu());
</script>
<div class="terminal-settings">
<h2>{$t("Terminal")}</h2>
<p class="intro">{$t("Font, scrollback, and cursor apply to open terminals. The default profile applies to new terminals.")}</p>
<div class="card">
<div class="setting-row">
<div><span class="name" id="terminal-profile-label">{$t("Default profile")}</span><p id="terminal-profile-description">{profileNote || $t("The shell of a new terminal.")}</p></div>
<button class="picker" type="button" aria-label={$t("Default profile")} aria-describedby="terminal-profile-description" aria-haspopup="menu" disabled={!shells.length} onclick={profileMenu}>
{current?.title ?? $t("No shell")}<Icon icon="chevron-down" />
</button>
</div>
<div class="setting-row">
<div><label for="terminal-font-size">{$t("Font size")}</label><p id="terminal-font-description">{$t("From {min} to {max} pixels.", { min: FONT_SIZE.min, max: FONT_SIZE.max })}</p></div>
<input id="terminal-font-size" type="number" min={FONT_SIZE.min} max={FONT_SIZE.max} step="1" required aria-describedby="terminal-font-description" bind:value={fontSize} onchange={() => changeNumber(fontSize, FONT_SIZE, "fontSize")} />
</div>
<div class="setting-row">
<div><label for="terminal-scrollback">{$t("Scrollback lines")}</label><p id="terminal-scrollback-description">{$t("The lines that a terminal keeps above the screen, from {min} to {max}.", { min: SCROLLBACK.min.toLocaleString(), max: SCROLLBACK.max.toLocaleString() })}</p></div>
<input id="terminal-scrollback" type="number" min={SCROLLBACK.min} max={SCROLLBACK.max} step="100" required aria-describedby="terminal-scrollback-description" bind:value={scrollback} onchange={() => changeNumber(scrollback, SCROLLBACK, "scrollback")} />
</div>
<div class="setting-row">
<div><label for="terminal-cursor-blink">{$t("Blink cursor")}</label><p id="terminal-blink-description">{$t("The cursor blinks in the focused terminal.")}</p></div>
<input id="terminal-cursor-blink" class="rs-switch" type="checkbox" role="switch" aria-describedby="terminal-blink-description" checked={settings.cursorBlink} onchange={event => save({ ...settings, cursorBlink: event.currentTarget.checked })} />
</div>
</div>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<p class="saved" role="status">{message}</p>
</div>
<style>
.terminal-settings { min-width: 0; }
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
.setting-row label, .name { font-weight: 500; color: var(--rs-text); }
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
input[type=number], .picker { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
input[type=number] { width: 96px; }
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); max-width: 100%; min-width: 160px; text-align: left; cursor: pointer; }
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
:is(.picker, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
.error { color: var(--rs-error); margin-top: 10px; }
</style>
@@ -0,0 +1,295 @@
<!--
Appearance → Background. The source is a folder (a slideshow), one image, or none. The folder layout and the order
are in the `background` settings section. The image and its layout stay in `appearance.newTabBackground`.
This component also works in the settings window, where the slideshow does not run. It sends Next to every window.
-->
<script lang="ts">
import { onDestroy, onMount } from "svelte";
import { t, tr } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte";
import { showActionMenu } from "$lib/ui/managedActionMenu";
import { onSettingsChange } from "$lib/settings/store";
import { featureSwitches } from "$lib/features/state";
import { readBoardCatalog } from "../pmBoards";
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, saveAppearance, type Appearance } from "$lib/theme/appearance";
import { removeBackgroundImage, saveBackgroundImage } from "$lib/theme/backgroundImages";
import { hasImage, normalizeLayout, readBackground, writeBackground, type BackgroundLayout, type BackgroundSettings, type BackgroundSource } from "../backgroundSettings";
import { folderHost, readSavedImage, sendBackgroundCommand } from "./sources";
import { imageNames } from "./imageSettings";
import ImageEditor from "./ImageEditor.svelte";
/** The background targets of single boards need a UUID board ID. */
const boardId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
let settings = $state<BackgroundSettings>(readBackground());
let appearance = $state<Appearance>(readAppearance());
let folder = $state<string | null>(null);
let folderNote = $state("");
let boards = $state<{ id: string; name: string }[]>([]);
let boardsNote = $state("");
let previewUrl = $state("");
let error = $state("");
let imageInput: HTMLInputElement;
let imageRevision = 0;
let boardRevision = 0;
let previewKey = "";
let closeMenu = () => {};
let disposed = false;
const image = $derived(appearance.newTabBackground);
const layout = $derived<BackgroundLayout | null>(settings.source === "folder" ? normalizeLayout(settings) : settings.source === "image" && hasImage(appearance) ? normalizeLayout(image) : null);
const sourceLabels = $derived<Record<BackgroundSource, string>>({ folder: $t("Folder"), image: $t("Image"), none: $t("None") });
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
const sizeLabels = $derived([$t("Fill"), $t("Fit"), $t("Actual size")]);
const orderLabels = $derived({ name: $t("File name"), random: $t("Random") });
const targets = $derived([
{ id: "app", name: $t("The workspace and new tabs") },
{ id: "pm-all", name: $t("All Project Management boards") },
...boards.map(board => ({ id: `pm-board:${board.id}`, name: $t("Board: {name}", { name: board.name }) })),
// Keep saved targets without a current board, so that the user can remove them.
...settings.targets.filter(id => id.startsWith("pm-board:") && !boards.some(board => `pm-board:${board.id}` === id))
.map(id => ({ id, name: $t("Unavailable board: {id}", { id: id.slice(9) }) })),
]);
const report = (reason: unknown) => { if (!disposed) error = reason instanceof Error ? reason.message : String(reason); };
function save(next: BackgroundSettings) {
settings = next; error = "";
writeBackground(next).catch(() => report(tr("Could not save the background settings.")));
}
function saveImageAppearance(next: Appearance) {
try {
saveAppearance(next).catch(() => report(tr("Could not save appearance settings.")));
appearance = readAppearance(); error = ""; return true;
} catch { report(tr("Could not save appearance settings.")); return false; }
}
function changeLayout(patch: Partial<BackgroundLayout>) {
if (settings.source === "folder") save({ ...settings, ...patch });
else if (image) saveImageAppearance({ ...appearance, newTabBackground: { ...image, ...patch } });
}
function changeOverlay(input: HTMLInputElement) {
const percent = input.valueAsNumber;
if (!Number.isFinite(percent)) return;
changeLayout({ overlay: Math.round(Math.max(-100, Math.min(100, percent))) / 100 });
}
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
closeMenu();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
}
async function chooseSource(source: BackgroundSource) {
error = "";
if (source === "folder" && !folder) { await chooseFolder(); return; }
if (source === "image" && !hasImage(appearance)) { imageInput.click(); return; }
save({ ...settings, source });
}
async function chooseFolder() {
try {
const chosen = await folderHost.choose(tr("Choose the background folder"));
if (!chosen || disposed) return;
folder = chosen;
save({ ...settings, source: "folder" });
await sendBackgroundCommand("reload");
void inspectFolder();
} catch (reason) { report(reason); }
}
async function removeFolder() {
try {
await folderHost.clear();
folder = null; folderNote = "";
if (settings.source === "folder") save({ ...settings, source: "none" });
await sendBackgroundCommand("reload");
} catch (reason) { report(reason); }
}
/** Count the images of the folder, so that the user sees a problem at once. */
async function inspectFolder() {
if (!folder) { folderNote = ""; return; }
try {
const count = imageNames(await folderHost.list()).length;
if (!disposed) folderNote = count ? tr(count === 1 ? "{count} image." : "{count} images.", { count }) : tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files.");
} catch (reason) { if (!disposed) folderNote = reason instanceof Error ? reason.message : String(reason); }
}
async function importImage(file?: File) {
if (!file) return;
const revision = ++imageRevision;
try {
if (!["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)) throw new Error(tr("Choose a PNG, JPEG, WebP, or GIF image."));
const imageId = await saveBackgroundImage(file);
if (revision !== imageRevision) { await removeBackgroundImage(imageId); return; }
const old = appearance.newTabBackground?.imageId;
if (saveImageAppearance({ ...appearance, newTabBackground: { ...appearance.newTabBackground, image: undefined, imageId, overlay: appearance.newTabBackground?.overlay ?? 0 } })) {
if (settings.source !== "image") save({ ...settings, source: "image" });
if (old) await removeBackgroundImage(old);
} else await removeBackgroundImage(imageId);
} catch (reason) { if (revision === imageRevision) report(reason); }
finally { if (revision === imageRevision) imageInput.value = ""; }
}
async function removeImage() {
imageRevision++;
const old = appearance.newTabBackground?.imageId;
if (saveImageAppearance({ ...appearance, newTabBackground: undefined }) && old) {
try { await removeBackgroundImage(old); } catch { report(tr("Could not remove the saved image from storage.")); }
}
}
function toggleTarget(id: string, on: boolean) {
save({ ...settings, targets: on ? [...new Set([...settings.targets, id])] : settings.targets.filter(target => target !== id) });
}
/** The active boards of `.runestone/pm/workspace.json`. It needs no Project Management code. */
async function discoverBoards(on: boolean) {
const revision = ++boardRevision;
if (!on) {
boards = []; boardsNote = tr("Turn on Project Management to show the background on one board.");
return;
}
try {
const catalog = await readBoardCatalog();
if (disposed || revision !== boardRevision) return;
boards = catalog.boards.filter(board => !board.archived && boardId.test(board.id)).map(board => ({ id: board.id, name: board.name }));
boardsNote = boards.length ? "" : tr("The workspace has no boards.");
} catch (reason) {
if (!disposed && revision === boardRevision) boardsNote = tr("Could not read the workspace boards: {error}", { error: reason instanceof Error ? reason.message : String(reason) });
}
}
/** The preview of the saved image. It uses its own blob URL, so it works in every window. */
async function updatePreview() {
const saved = settings.source === "image" ? appearance.newTabBackground : undefined;
const key = saved && hasImage(appearance) ? saved.imageId ?? `${saved.image?.length}:${saved.image?.slice(-48)}` : "";
if (key === previewKey) return;
previewKey = key;
if (previewUrl) URL.revokeObjectURL(previewUrl);
previewUrl = "";
if (!key || !saved) return;
try {
const url = URL.createObjectURL(await readSavedImage(saved));
if (disposed || previewKey !== key) { URL.revokeObjectURL(url); return; }
previewUrl = url;
} catch (reason) { report(reason); }
}
const overlayShade = $derived(layout ? `linear-gradient(rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}),rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}))` : "none");
$effect(() => { void settings.source; void appearance.newTabBackground; void updatePreview(); });
onMount(() => {
const read = () => { settings = readBackground(); appearance = readAppearance(); };
const stops = [onSettingsChange("background", read), onSettingsChange("appearance", read), featureSwitches.subscribe(switches => { void discoverBoards(switches.pm); })];
void folderHost.current().then(value => { if (!disposed) { folder = value; void inspectFolder(); } }, () => { folder = null; });
return () => stops.forEach(stop => stop());
});
onDestroy(() => { disposed = true; closeMenu(); if (previewUrl) URL.revokeObjectURL(previewUrl); });
</script>
<div class="background-settings">
<div class="card">
<div class="setting-row"><span>{$t("Background source")}</span><button class="picker" aria-label={$t("Background source")} aria-haspopup="menu"
onclick={event => picker(event, $t("Background source"), (["folder", "image", "none"] as const).map(source => ({ label: sourceLabels[source], checked: settings.source === source, run: () => void chooseSource(source) })))}>{sourceLabels[settings.source]}<Icon icon="chevron-down" /></button></div>
{#if settings.source === "folder"}
<div class="setting-row folder-row"><label for="background-folder">{$t("Image folder")}</label><div class="controls folder-controls">
<input id="background-folder" readonly value={folder ?? ""} title={folder ?? ""} placeholder={$t("No folder selected")} />
<button onclick={() => void chooseFolder()}><Icon icon="folder-open" />{$t("Choose folder…")}</button>
{#if folder}<button onclick={() => void removeFolder()}>{$t("Remove folder")}</button>{/if}
</div></div>
<div class="setting-row"><label for="background-seconds">{$t("Seconds per image")}</label><input id="background-seconds" type="number" min="1" max="86400" step="1" value={settings.seconds}
onchange={event => { if (event.currentTarget.reportValidity()) save({ ...settings, seconds: event.currentTarget.valueAsNumber }); }} /></div>
<div class="setting-row"><span>{$t("Image order")}</span><button class="picker" aria-label={$t("Image order")} aria-haspopup="menu"
onclick={event => picker(event, $t("Image order"), (["name", "random"] as const).map(order => ({ label: orderLabels[order], checked: settings.order === order, run: () => save({ ...settings, order }) })))}>{orderLabels[settings.order]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Slideshow")}</span><div class="controls">
<button onclick={() => void sendBackgroundCommand("next").catch(report)}><Icon icon="arrow-right" />{$t("Next image")}</button>
<button aria-pressed={settings.paused} onclick={() => save({ ...settings, paused: !settings.paused })}>{settings.paused ? $t("Resume slideshow") : $t("Pause slideshow")}</button>
</div></div>
{:else if settings.source === "image"}
<div class="background-preview" role="img" aria-label={$t("Background image preview")}
style:background-image={previewUrl ? `${overlayShade}, url("${previewUrl}")` : "none"}
style:background-size={layout ? `100% 100%, ${layout.size}` : undefined}
style:background-position={layout ? `center, ${layout.position}` : undefined}><span>{$t("Background")}</span></div>
<div class="actions">
<button onclick={() => imageInput.click()}>{$t("Choose image…")}</button>
{#if image}<button onclick={() => void removeImage()}>{$t("Remove image")}</button>{/if}
</div>
{/if}
{#if layout}
<div class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("Image position")} aria-haspopup="menu"
onclick={event => picker(event, $t("Image position"), BACKGROUND_POSITIONS.map((value, index) => ({ label: positionLabels[index], checked: layout?.position === value, run: () => changeLayout({ position: value }) })))}>{positionLabels[BACKGROUND_POSITIONS.indexOf(layout.position)]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Image size")}</span><button class="picker" aria-label={$t("Image size")} aria-haspopup="menu"
onclick={event => picker(event, $t("Image size"), BACKGROUND_SIZES.map((value, index) => ({ label: sizeLabels[index], checked: layout?.size === value, run: () => changeLayout({ size: value }) })))}>{sizeLabels[BACKGROUND_SIZES.indexOf(layout.size)]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Image overlay")}</span><div class="controls overlay-controls">
<input type="range" aria-label={$t("Image overlay")} min="-100" max="100" value={Math.round(layout.overlay * 100)} oninput={event => changeOverlay(event.currentTarget)} />
<label class="overlay-value"><input type="number" aria-label={$t("Image overlay percentage")} min="-100" max="100" step="1" value={Math.round(layout.overlay * 100)}
oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((layout?.overlay ?? 0) * 100)); }} /><span>%</span></label>
</div></div>
{/if}
</div>
<input bind:this={imageInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importImage(event.currentTarget.files?.[0])} />
{#if settings.source === "folder"}
<p>{$t("Add PNG, JPEG, GIF, or WebP images to the folder. Portrait images show in full over a blurred fill.")}</p>
{#if folderNote}<p role="status">{folderNote}</p>{/if}
{:else if settings.source === "image"}
<p>{$t("PNG, JPEG, WebP, or GIF, up to 50 MiB. The image stays on this device.")}</p>
{:else}
<p>{$t("Choose a folder for a slideshow, or one image.")}</p>
{/if}
{#if layout}<p>{$t("Move the overlay left to lighten the image or right to darken it.")}</p>{/if}
{#if settings.source === "folder" && folder}
<ImageEditor {settings} />
{/if}
{#if settings.source !== "none"}
<fieldset class="targets">
<legend>{$t("Show the background in")}</legend>
{#each targets as target (target.id)}
<label class="check"><input type="checkbox" checked={settings.targets.includes(target.id)} onchange={event => toggleTarget(target.id, event.currentTarget.checked)} /><span>{target.name}</span></label>
{/each}
{#if boardsNote}<p>{boardsNote}</p>{/if}
</fieldset>
{/if}
{#if error}<p role="alert">{error}</p>{/if}
</div>
<style>
.background-settings { display: grid; gap: var(--rs-settings-gap); min-width: 0; }
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
.card { padding: 0 var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); min-width: 0; }
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; min-width: 0; }
.card > * + * { border-top: 1px solid var(--rs-border); }
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; max-width: 100%; }
.folder-controls { flex: 1 1 320px; justify-content: flex-end; }
.folder-controls input { flex: 1 1 160px; min-width: 120px; width: 0; }
input:not([type=checkbox]):not([type=range]), button { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
button { display: inline-flex; align-items: center; gap: 6px; background: var(--rs-bg-elevated); cursor: pointer; }
button:hover { background: var(--rs-bg-active); }
button[aria-pressed="true"] { border-color: var(--rs-accent); }
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
.picker { max-width: 100%; background: var(--rs-bg); }
input[type=number] { width: 88px; }
:is(button, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
.actions { display: flex; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; }
.background-preview { height: 120px; margin-top: var(--rs-settings-row-padding); background-color: var(--rs-bg); background-repeat: no-repeat; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); display: grid; place-items: center; }
.background-preview span { padding: 8px 14px; background: var(--rs-bg-elevated); border-radius: var(--rs-control-radius); }
.overlay-controls input[type=range] { width: 160px; max-width: 100%; min-width: 0; appearance: none; background: transparent; height: var(--rs-settings-control-height); margin: 0; cursor: pointer; }
.overlay-controls input[type=range]::-webkit-slider-runnable-track { height: 6px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
.overlay-controls input[type=range]::-webkit-slider-thumb { appearance: none; width: 18px; height: 18px; margin-top: -7px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
.overlay-controls input[type=range]::-moz-range-track { height: 4px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
.overlay-controls input[type=range]::-moz-range-thumb { width: 14px; height: 14px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
.overlay-controls input[type=range]:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; border-radius: var(--rs-control-radius); }
.overlay-value { display: flex; align-items: center; gap: 4px; }
.overlay-value input { width: 64px; }
.targets { display: grid; gap: 2px; min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
.targets legend { padding: 0 4px; color: var(--rs-text); }
.check { display: flex; align-items: center; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); overflow-wrap: anywhere; }
.check input { flex-shrink: 0; accent-color: var(--rs-accent); }
[role=alert] { color: var(--rs-error); }
</style>
@@ -0,0 +1,227 @@
<!--
The appearance of one image of the folder: fit, position, and overlay. It saves the sidecar file of the folder
(`.runestone-backgrounds.json`) only when the file did not change since the read. Then every window reads it again.
-->
<script lang="ts">
import { onDestroy, untrack } from "svelte";
import { t, tr } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte";
import { showActionMenu } from "$lib/ui/managedActionMenu";
import { BACKGROUND_POSITIONS } from "$lib/theme/appearance";
import { normalizeLayout, type BackgroundSettings } from "../backgroundSettings";
import { folderHost, sendBackgroundCommand } from "./sources";
import { imageAppearance, imageFits, imageNames, parseImageSettings, sidecarName, type ImageAppearance, type ImageSettings } from "./imageSettings";
let { settings }: { settings: BackgroundSettings } = $props();
let names = $state<string[]>([]);
let selected = $state("");
let query = $state("");
let pickerOpen = $state(false);
let draft = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
let baseline = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
let saved = $state<ImageSettings>({ schema: 1, images: {} });
let source: string | null = null;
let url = $state("");
let portrait = false;
let loaded = $state(false);
let busy = $state(false);
let status = $state({ text: "", error: false });
let generation = 0;
let closed = false;
let closeMenu = () => {};
let trigger: HTMLButtonElement | undefined = $state();
let search: HTMLInputElement | undefined = $state();
const pickerId = $props.id();
const filtered = $derived(names.filter(name => name.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())));
const fitLabels = $derived<Record<string, string>>({ cover: $t("Fill"), contain: $t("Fit"), auto: $t("Actual size"), blurred: $t("Full image with blurred fill") });
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
const changed = $derived(draft.fit !== baseline.fit || draft.position !== baseline.position || draft.overlay !== baseline.overlay);
const report = (reason: unknown) => { if (!closed) status = { text: reason instanceof Error ? reason.message : String(reason), error: true }; };
/** The values that differ from the inherited appearance. Only these go to the file. */
function changes(): Partial<ImageAppearance> {
return {
...(draft.fit !== baseline.fit ? { fit: draft.fit } : {}),
...(draft.position !== baseline.position ? { position: draft.position } : {}),
...(draft.overlay !== baseline.overlay ? { overlay: draft.overlay } : {}),
};
}
async function load() {
const revision = ++generation;
loaded = false; pickerOpen = false; names = [];
if (url) URL.revokeObjectURL(url);
url = "";
try {
const [text, list] = await Promise.all([folderHost.readSidecar(), folderHost.list()]);
if (closed || revision !== generation) return;
saved = parseImageSettings(text); source = text;
names = imageNames(list);
if (!names.includes(selected)) selected = names[0] ?? "";
if (selected) await choose(selected);
else status = { text: tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."), error: false };
} catch (reason) { report(reason); }
}
async function choose(name: string) {
const revision = ++generation;
selected = name; loaded = false;
if (url) URL.revokeObjectURL(url);
url = "";
try {
const next = URL.createObjectURL(await folderHost.read(name));
try {
const image = new Image(); image.src = next; await image.decode();
if (closed || revision !== generation) { URL.revokeObjectURL(next); return; }
portrait = image.naturalHeight > image.naturalWidth;
} catch (error) { URL.revokeObjectURL(next); throw error; }
url = next;
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
baseline = { ...draft };
loaded = true;
status = { text: saved.images[name] ? tr("Saved appearance.") : tr("Default appearance."), error: false };
} catch (reason) { report(reason); }
}
/** A change of the folder layout changes the inherited values. Keep the edits of the user. */
function inherit() {
if (!loaded) return;
const next = imageAppearance(normalizeLayout(settings), saved.images[selected], portrait);
if (next.fit === baseline.fit && next.position === baseline.position && next.overlay === baseline.overlay) return;
const edited = changes();
baseline = next;
draft = { ...next, ...edited };
}
async function write(reset: boolean) {
if (!loaded || busy) return;
const edited = changes();
if (!reset && !Object.keys(edited).length) return;
busy = true;
const revision = generation, name = selected;
try {
const next = structuredClone($state.snapshot(saved)) as ImageSettings;
if (reset) delete next.images[name]; else next.images[name] = { ...next.images[name], ...edited };
const contents = JSON.stringify(next, null, 2) + "\n";
await folderHost.writeSidecar(contents, source);
if (closed || revision !== generation) return;
source = contents; saved = next;
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
baseline = { ...draft };
status = { text: reset ? tr("Default appearance restored.") : tr("Image appearance saved."), error: false };
await sendBackgroundCommand("reload");
} catch (reason) { report(reason); }
finally { busy = false; }
}
function menu(event: MouseEvent, field: "fit" | "position") {
closeMenu();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
const values: readonly string[] = field === "fit" ? imageFits : BACKGROUND_POSITIONS;
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === "fit" ? $t("Image fit") : $t("Position of this image"), parent: anchor.closest("dialog") ?? undefined,
items: values.map((value, index) => ({ label: field === "fit" ? fitLabels[value] : positionLabels[index], radio: true, checked: draft[field] === value,
run: () => { draft = { ...draft, [field]: value }; } })) }).close;
}
function overlay(input: HTMLInputElement) {
if (input.validity.valid && Number.isFinite(input.valueAsNumber)) draft = { ...draft, overlay: Math.round(Math.max(-100, Math.min(100, input.valueAsNumber))) / 100 };
}
function openPicker() {
if (pickerOpen) { pickerOpen = false; return; }
query = ""; pickerOpen = true;
queueMicrotask(() => search?.focus());
}
function pick(name: string) {
pickerOpen = false;
void choose(name).then(() => trigger?.focus());
}
function moveFocus(event: KeyboardEvent, list: HTMLElement) {
const rows = [...list.querySelectorAll<HTMLButtonElement>("button")];
if (!rows.length) return;
const index = rows.indexOf(document.activeElement as HTMLButtonElement);
const next = event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : index < 0 ? (event.key === "ArrowDown" ? 0 : rows.length - 1) : Math.max(0, Math.min(rows.length - 1, index + (event.key === "ArrowDown" ? 1 : -1)));
event.preventDefault();
rows[next].focus();
}
$effect(() => { void settings.size; void settings.position; void settings.overlay; untrack(inherit); });
void load();
onDestroy(() => { closed = true; generation++; closeMenu(); if (url) URL.revokeObjectURL(url); });
</script>
<details class="image-editor">
<summary>{$t("Per-image appearance")}</summary>
<p>{$t("Choose an image to change its fit, position, and overlay. Portrait images show in full over a blurred fill by default.")}</p>
<fieldset disabled={busy}>
<div class="row"><span>{$t("Image")}</span>
<button bind:this={trigger} class="choice" aria-label={$t("Image to change")} aria-expanded={pickerOpen} aria-controls={pickerId} disabled={!names.length} onclick={openPicker}>
<span class="name">{selected || $t("Choose an image")}</span><Icon icon="chevron-down" /></button></div>
{#if pickerOpen}
<!-- svelte-ignore a11y_no_static_element_interactions (Escape closes the picker.) -->
<div id={pickerId} class="rs-picker image-picker" onkeydown={event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); pickerOpen = false; trigger?.focus(); } }}>
<input bind:this={search} type="search" aria-label={$t("Find an image")} placeholder={$t("Find an image")} bind:value={query}
onkeydown={event => { if (event.key === "ArrowDown" || event.key === "ArrowUp") moveFocus(event, event.currentTarget.nextElementSibling as HTMLElement); else if (event.key === "Enter" && filtered[0]) { event.preventDefault(); pick(filtered[0]); } }} />
<div class="options" role="listbox" aria-label={$t("Image files")} tabindex="-1"
onkeydown={event => { if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) moveFocus(event, event.currentTarget); }}>
{#each filtered.slice(0, 100) as name (name)}
<button class="rs-picker-row" role="option" tabindex="-1" aria-selected={name === selected} onclick={() => pick(name)}>{name}</button>
{/each}
</div>
<p role="status">{!filtered.length ? $t("No matching images.") : filtered.length > 100 ? $t("{count} matches. Type more of the name to see other images.", { count: filtered.length }) : $t(filtered.length === 1 ? "{count} image." : "{count} images.", { count: filtered.length })}</p>
</div>
{/if}
<div class="preview" role="img" aria-label={selected ? $t("Selected image preview: {name}", { name: selected }) : $t("Selected image preview")}>
{#if url}
{#if draft.fit === "blurred"}<span class="fill" style:background-image={`url("${url}")`}></span>{/if}
<span class="foreground" style:background-image={`url("${url}")`} style:background-size={draft.fit === "blurred" ? "contain" : draft.fit} style:background-position={draft.position}></span>
{/if}
<span class="shade" style:background={draft.overlay < 0 ? "white" : "black"} style:opacity={String(Math.abs(draft.overlay))}></span>
</div>
<div class="row"><span>{$t("Fit")}</span><button class="choice" aria-label={$t("Image fit")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "fit")}>{fitLabels[draft.fit]}<Icon icon="chevron-down" /></button></div>
<div class="row"><span>{$t("Position")}</span><button class="choice" aria-label={$t("Position of this image")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "position")}>{positionLabels[BACKGROUND_POSITIONS.indexOf(draft.position)]}<Icon icon="chevron-down" /></button></div>
<div class="row"><span>{$t("Overlay")}</span><div class="controls">
<input type="range" min="-100" max="100" aria-label={$t("Overlay of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} />
<input type="number" min="-100" max="100" step="1" required aria-label={$t("Overlay percentage of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} /><span>%</span>
</div></div>
<div class="controls">
<button disabled={!loaded || !changed} onclick={() => void write(false)}><Icon icon="save" />{$t("Save image appearance")}</button>
<button disabled={!loaded || !saved.images[selected]} onclick={() => void write(true)}><Icon icon="undo" />{$t("Reset image appearance")}</button>
<button onclick={() => void load()}><Icon icon="refresh" />{$t("Reload image settings")}</button>
</div>
</fieldset>
{#if status.text}<p role={status.error ? "alert" : "status"} class:error={status.error}>{status.text}</p>{/if}
</details>
<style>
.image-editor { display: grid; gap: var(--rs-settings-gap); min-width: 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
summary { cursor: pointer; min-height: var(--rs-settings-control-height); line-height: var(--rs-settings-control-height); border-radius: var(--rs-control-radius); }
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
.error { color: var(--rs-error); }
fieldset { display: grid; gap: var(--rs-settings-gap); min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: 0; border: 0; }
.row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
button:not(.rs-picker-row), input:not([type=range]) { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
button:not(.rs-picker-row) { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
button:not(.rs-picker-row):hover:not(:disabled) { background: var(--rs-bg-active); }
button:disabled, input:disabled { opacity: .55; cursor: default; }
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
:is(button, input, summary):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
.choice { max-width: 100%; min-width: 0; }
.choice .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
input[type=number] { width: 72px; }
input[type=range] { width: 160px; max-width: 100%; accent-color: var(--rs-accent); }
.image-picker { display: grid; gap: var(--rs-settings-gap); width: 100%; min-width: 0; position: static; }
.image-picker input { width: 100%; min-width: 0; }
.options { display: grid; gap: 2px; max-height: 220px; overflow: auto; min-width: 0; }
.options button { justify-content: flex-start; text-align: left; overflow-wrap: anywhere; }
.preview { position: relative; width: 100%; height: 170px; overflow: hidden; border-radius: var(--rs-control-radius); background-color: var(--rs-bg-active); }
.fill, .foreground, .shade { position: absolute; inset: 0; background-repeat: no-repeat; pointer-events: none; }
.fill { inset: -24px; filter: blur(18px); background-size: cover; background-position: center; }
</style>
+83
View File
@@ -0,0 +1,83 @@
// The blurred fill of a portrait image. One worker does the decode, the resize, and the filter away from the
// input and paint work of the window. It lives as long as the Background instance.
import { tr } from "../../i18n/index.ts";
const workerSource = `
self.onmessage = async ({ data: { id, url, width, height } }) => {
let image;
try {
const source = await (await fetch(url)).blob();
image = await createImageBitmap(source, { resizeWidth: width, resizeHeight: height, resizeQuality: 'high' });
const canvas = new OffscreenCanvas(width, height);
const context = canvas.getContext('2d');
context.filter = 'blur(24px)';
context.drawImage(image, -48, -48, width + 96, height + 96);
self.postMessage({ id, blob: await canvas.convertToBlob({ type: 'image/png' }) });
} catch (error) {
self.postMessage({ id, error: error instanceof Error ? error.message : String(error) });
} finally { image?.close(); }
};`;
/** The size of the blurred copy. Its long side is at most 1024 pixels. */
export function blurSize(width: number, height: number): { width: number; height: number } {
const scale = Math.min(1, 1024 / Math.max(width, height, 1));
return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
}
export class BlurWorker {
private worker?: Worker;
private workerUrl?: string;
private serial = 0;
private pending = new Map<number, { resolve: (blob: Blob) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>();
/** A blob URL of the blurred copy of the image at `url`. The caller releases it. */
async blur(url: string, width: number, height: number): Promise<string> {
const size = blurSize(width, height);
if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined") return URL.createObjectURL(await this.inWindow(url, size));
const worker = this.start();
const id = ++this.serial;
const blob = await new Promise<Blob>((resolve, reject) => {
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(tr("The blurred image took too long to load."))); }, 10000);
this.pending.set(id, { resolve, reject, timer });
worker.postMessage({ id, url, ...size });
});
return URL.createObjectURL(blob);
}
private start(): Worker {
if (this.worker) return this.worker;
this.workerUrl = URL.createObjectURL(new Blob([workerSource], { type: "text/javascript" }));
const worker = this.worker = new Worker(this.workerUrl);
worker.onmessage = ({ data }) => {
const request = this.pending.get(data?.id);
if (!request) return;
this.pending.delete(data.id); clearTimeout(request.timer);
if (data.blob instanceof Blob) request.resolve(data.blob);
else request.reject(new Error(data.error || tr("Cannot create the blurred image.")));
};
worker.onerror = () => this.fail(new Error(tr("Cannot create the blurred image.")));
return worker;
}
/** A fallback for a window without OffscreenCanvas. */
private async inWindow(url: string, size: { width: number; height: number }): Promise<Blob> {
const image = new Image(); image.src = url; await image.decode();
const canvas = document.createElement("canvas");
canvas.width = size.width; canvas.height = size.height;
const context = canvas.getContext("2d")!;
context.filter = "blur(24px)";
context.drawImage(image, -48, -48, size.width + 96, size.height + 96);
return new Promise<Blob>((resolve, reject) => canvas.toBlob(value => value ? resolve(value) : reject(new Error(tr("Cannot create the blurred image."))), "image/png"));
}
private fail(error: Error) {
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
this.pending.clear();
// A failed worker starts again at the next request.
this.worker?.terminate(); this.worker = undefined;
if (this.workerUrl) URL.revokeObjectURL(this.workerUrl);
this.workerUrl = undefined;
}
dispose() { this.fail(new Error(tr("This feature is off."))); }
}
+337
View File
@@ -0,0 +1,337 @@
// The Background engine: it shows the images of a source as background frames, one after the other.
// It comes from the engine of the Background Slideshow plugin, with these changes for the open card
// "Lag before image transition": the next image loads and decodes before its fade, the blurred fills of the
// last images stay in a cache, and the folder list and the sidecar are read again only after a settings change,
// on window focus, or after every 10 images.
import { tr } from "../../i18n/index.ts";
import type { BackgroundFrame } from "../../plugins/backgroundContracts.ts";
import type { BackgroundLayout } from "../backgroundSettings.ts";
import { imageAppearance, imageNames, parseImageSettings, sequence, type ImageAppearance, type ImageSettings } from "./imageSettings.ts";
/** The time of the fade from one image to the next. */
export const transitionMs = 2000;
/** The folder list and the sidecar are read again after this number of images. */
export const RESCAN_SLIDES = 10;
/** The number of blurred fills that stay in the cache. */
export const BLUR_CACHE = 3;
/** The shortest wait before a new try after an error. */
export const RETRY_MS = 5000;
/** Where the images come from: the image folder of the host, or the one saved image. */
export interface ImageSource {
/** A different key means a different folder or image. The engine then starts again. */
readonly key: string;
/** True for a folder: the images change on a timer, and the sidecar and the portrait default apply. */
readonly timed: boolean;
/** The image names. */
list(): Promise<string[]>;
read(name: string): Promise<Blob>;
/** The text of the sidecar file, or null. */
sidecar(): Promise<string | null>;
}
export interface LoadedImage { url: string; width: number; height: number }
/** The browser services of the engine. Tests replace them. */
export interface Runtime {
/** Make a blob URL and decode the image before it shows. */
load(blob: Blob): Promise<LoadedImage>;
/** Make the blurred fill of a loaded image. The engine releases the URL. */
blur(image: LoadedImage): Promise<string>;
release(url: string): void;
later(callback: () => void, milliseconds: number): unknown;
cancel(timer: unknown): void;
random(): number;
now(): number;
}
export interface Frames { set(target: string, frame: BackgroundFrame | null): void }
export interface EngineSettings extends BackgroundLayout {
seconds: number;
order: "name" | "random";
paused: boolean;
targets: string[];
}
export interface Status { message: string; image: string | null; count: number; error: boolean }
interface Shown { name: string; key: string; image: LoadedImage; appearance: ImageAppearance; blurred?: string }
interface Prepared { name: string; key: string; image: LoadedImage }
function toFrame(shown: Shown): BackgroundFrame {
const frame: BackgroundFrame = { url: shown.image.url, overlay: shown.appearance.overlay, position: shown.appearance.position,
size: shown.appearance.fit === "blurred" ? "contain" : shown.appearance.fit };
if (shown.blurred) frame.blurredUrl = shown.blurred;
return frame;
}
const sameAppearance = (a: ImageAppearance, b: ImageAppearance) => a.fit === b.fit && a.position === b.position && a.overlay === b.overlay;
export class Slideshow {
status: Status = { message: "", image: null, count: 0, error: false };
private source: ImageSource | null = null;
private settings: EngineSettings | null = null;
private revision = 0;
private stopped = false;
private timer: unknown;
/** When the current timer fires, or null without a timer. */
private due: number | null = null;
private names: string[] | null = null;
private imageSettings: ImageSettings = { schema: 1, images: {} };
private sidecarError = "";
private stale = true;
private slides = 0;
private shown: Shown | null = null;
/** The image that the current frame fades from. */
private previous: Shown | null = null;
private targets = new Set<string>();
/** The blurred fills, oldest first. */
private blurs = new Map<string, string>();
private prepared: { name: string; work: Promise<Prepared | null>; discarded: boolean } | null = null;
/** Changes at each `clear`, so that a late blurred fill of an old image does not enter the cache. */
private epoch = 0;
private listeners = new Set<() => void>();
private frames: Frames;
private runtime: Runtime;
constructor(frames: Frames, runtime: Runtime) { this.frames = frames; this.runtime = runtime; }
subscribe(listener: () => void) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
private notify() { for (const listener of [...this.listeners]) listener(); }
/** Use a new source or new settings. The current image stays when the source is the same and still has it. */
configure(source: ImageSource | null, settings: EngineSettings): Promise<void> {
if (this.stopped) return Promise.resolve();
if (source?.key !== this.source?.key) {
this.clear();
this.names = null;
}
this.source = source;
this.settings = { ...settings, targets: [...settings.targets] };
this.stale = true;
return this.update(false);
}
/** Read the list and the sidecar again before the next image, for example after a window focus. */
invalidate() { this.stale = true; }
/** Read the list and the sidecar again now, and apply them to the current image. */
reload = () => { this.stale = true; return this.update(false); };
/** Show the next image now. */
next = () => this.update(true);
dispose() {
if (this.stopped) return;
this.stopped = true; this.revision++;
this.runtime.cancel(this.timer); this.timer = undefined;
this.clear(); this.listeners.clear();
}
private async update(advance: boolean): Promise<void> {
if (this.stopped) return;
const revision = ++this.revision;
const remaining = this.due === null ? null : Math.max(0, this.due - this.runtime.now());
this.runtime.cancel(this.timer); this.timer = undefined; this.due = null;
const valid = () => !this.stopped && revision === this.revision;
const source = this.source, settings = this.settings;
try {
if (!source || !settings) { this.clear(); this.setStatus(tr("Choose a folder or an image to show a background.")); return; }
if (!settings.targets.length) { this.clear(); this.setStatus(tr("Select where to show the background.")); return; }
if (this.stale || !this.names) {
const [list, sidecar] = await Promise.all([source.list(), source.timed ? source.sidecar() : Promise.resolve(null)]);
if (!valid()) return;
this.names = source.timed ? imageNames(list) : [...list];
try { this.imageSettings = parseImageSettings(sidecar); this.sidecarError = ""; }
catch (reason) { this.imageSettings = { schema: 1, images: {} }; this.sidecarError = reason instanceof Error ? reason.message : String(reason); }
this.stale = false; this.slides = 0;
if (this.prepared && !this.names.includes(this.prepared.name)) this.discardPrepared();
}
const names = this.names;
this.status.count = names.length;
if (!names.length) throw new Error(tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."));
const shown = this.shown;
if (shown && names.includes(shown.name) && (!advance || names.length === 1)) {
await this.reapply(shown, settings, valid);
if (!valid()) return;
this.schedule(remaining ?? settings.seconds * 1000, revision);
this.prepare();
return;
}
let failures = 0;
const order = sequence(names, shown?.name ?? null, settings.order, this.runtime.random);
const candidates = this.prepared && order.includes(this.prepared.name) ? [this.prepared.name, ...order.filter(name => name !== this.prepared!.name)] : order;
for (const name of candidates) {
let loaded: Prepared | null = null;
let next: Shown;
try {
loaded = await this.load(name);
if (!valid()) { if (loaded) this.runtime.release(loaded.image.url); return; }
if (!loaded) throw new Error(tr("The image cannot be displayed."));
next = { ...loaded, appearance: this.appearanceOf(name, loaded.image, settings) };
if (next.appearance.fit === "blurred") {
next.blurred = await this.blurOf(loaded);
if (!valid()) { this.runtime.release(loaded.image.url); return; }
}
} catch {
if (loaded) this.runtime.release(loaded.image.url);
if (!valid()) return;
failures++; continue;
}
this.publish(next, settings, true);
const message = failures ? tr("{name}: skipped {count} unreadable images.", { name, count: failures }) : name;
this.status = { image: name, count: names.length, error: !!this.sidecarError, message: this.sidecarError ? `${message} ${this.sidecarError}` : message };
this.notify();
if (++this.slides >= RESCAN_SLIDES) this.stale = true;
this.schedule(settings.seconds * 1000, revision);
this.prepare();
return;
}
throw new Error(tr("No readable images in this folder. Check the image files."));
} catch (error) {
if (!valid()) return;
this.clear();
this.status = { ...this.status, image: null, error: true, message: error instanceof Error ? error.message : String(error) };
this.notify();
if (source?.timed && settings) this.schedule(Math.max(RETRY_MS, settings.seconds * 1000), revision, true);
}
}
private setStatus(message: string) {
this.status = { message, image: null, count: 0, error: false };
this.notify();
}
private appearanceOf(name: string, image: LoadedImage, settings: EngineSettings): ImageAppearance {
if (!this.source?.timed) return { fit: settings.size, position: settings.position, overlay: settings.overlay };
return imageAppearance(settings, this.imageSettings.images[name], image.height > image.width);
}
/** The image of `name`: the prepared image when it matches, or a new read. */
private async load(name: string): Promise<Prepared | null> {
const prepared = this.prepared;
if (prepared?.name === name) {
this.prepared = null;
const result = await prepared.work.catch(() => null);
if (result) return result;
}
const source = this.source!;
const blob = await source.read(name);
const image = await this.runtime.load(blob);
return { name, key: `${source.key}\n${name}\n${blob.size}`, image };
}
/** Load and decode the next image of a timed source now, so that its fade starts on time. */
private prepare() {
const source = this.source, settings = this.settings, names = this.names, shown = this.shown;
if (!source?.timed || !settings || settings.paused || !names || names.length < 2 || !shown || this.prepared) return;
const name = sequence(names, shown.name, settings.order, this.runtime.random)[0];
const entry: { name: string; work: Promise<Prepared | null>; discarded: boolean } = { name, work: Promise.resolve(null), discarded: false };
entry.work = (async (): Promise<Prepared | null> => {
const blob = await source.read(name);
const image = await this.runtime.load(blob);
// A prepared image that nobody wants any more goes away at once.
if (this.stopped || entry.discarded) { this.runtime.release(image.url); return null; }
const result = { name, key: `${source.key}\n${name}\n${blob.size}`, image };
const appearance = imageAppearance(settings, this.imageSettings.images[name], image.height > image.width);
if (appearance.fit === "blurred") await this.blurOf(result).catch(() => undefined);
return result;
})();
entry.work.catch(() => undefined);
this.prepared = entry;
}
private discardPrepared() {
const prepared = this.prepared;
this.prepared = null;
if (!prepared) return;
prepared.discarded = true;
void prepared.work.then(result => { if (result) this.runtime.release(result.image.url); }, () => undefined);
}
/** The blurred fill of an image, from the cache when possible. */
private async blurOf(image: Prepared): Promise<string> {
const cached = this.blurs.get(image.key);
if (cached) { this.blurs.delete(image.key); this.blurs.set(image.key, cached); return cached; }
const epoch = this.epoch;
const url = await this.runtime.blur(image.image);
if (this.stopped || epoch !== this.epoch) { this.runtime.release(url); throw new Error(tr("The background changed.")); }
const again = this.blurs.get(image.key);
if (again) { this.runtime.release(url); return again; }
this.blurs.set(image.key, url);
this.trimBlurs(url);
return url;
}
/** Release the oldest blurred fills beyond the cache size. Fills that a frame shows stay. */
private trimBlurs(keep?: string) {
const used = new Set([this.shown?.blurred, this.previous?.blurred, keep]);
for (const [key, url] of this.blurs) {
if (this.blurs.size <= BLUR_CACHE) break;
if (used.has(url)) continue;
this.blurs.delete(key); this.runtime.release(url);
}
}
/** Apply new settings or new image settings to the image that shows, without a fade. */
private async reapply(shown: Shown, settings: EngineSettings, valid: () => boolean) {
const appearance = this.appearanceOf(shown.name, shown.image, settings);
const sameTargets = settings.targets.length === this.targets.size && settings.targets.every(target => this.targets.has(target));
const needsBlur = appearance.fit === "blurred" && !shown.blurred;
if (sameTargets && sameAppearance(appearance, shown.appearance) && !needsBlur) return;
const next: Shown = { ...shown, appearance, blurred: undefined };
if (appearance.fit === "blurred") {
next.blurred = await this.blurOf(shown);
if (!valid()) return;
}
this.publish(next, settings, false);
this.notify();
}
/** Show `next` on every target. With `fade`, the frame fades from the image that showed before. */
private publish(next: Shown, settings: EngineSettings, fade: boolean) {
const old = this.shown;
const frame = toFrame(next);
if (fade && old) { frame.previous = toFrame(old); frame.transitionMs = transitionMs; }
try {
for (const target of this.targets) if (!settings.targets.includes(target)) this.frames.set(target, null);
// Track the new targets before the frames go out, so that a cleanup also clears a partial publish.
for (const target of settings.targets) this.targets.add(target);
for (const target of settings.targets) this.frames.set(target, frame);
} catch (error) {
if (next.image !== old?.image) this.runtime.release(next.image.url);
throw error;
}
this.targets = new Set(settings.targets);
// Keep the image of the fade until the next frame replaces it.
const release = this.previous;
if (release && release.image !== next.image && release.image !== old?.image) this.runtime.release(release.image.url);
this.previous = fade && old && old.image !== next.image ? old : null;
if (!fade && old && old.image !== next.image) this.runtime.release(old.image.url);
this.shown = next;
this.trimBlurs();
}
/** Remove the frames of every target and release every image. */
private clear() {
for (const target of this.targets) { try { this.frames.set(target, null); } catch { /* The window can close before the cleanup. */ } }
this.targets.clear();
const images = new Set([this.shown?.image.url, this.previous?.image.url]);
for (const url of images) if (url) this.runtime.release(url);
for (const url of this.blurs.values()) this.runtime.release(url);
this.blurs.clear();
this.epoch++;
this.discardPrepared();
this.shown = null; this.previous = null;
this.status = { ...this.status, image: null };
}
private schedule(milliseconds: number, revision: number, retry = false) {
const settings = this.settings;
if (this.stopped || this.revision !== revision || !this.source?.timed || !settings) return;
if (settings.paused && !retry) return;
this.due = this.runtime.now() + milliseconds;
this.timer = this.runtime.later(() => { this.timer = undefined; this.due = null; void this.update(true); }, milliseconds);
}
}
@@ -0,0 +1,57 @@
// The per-image settings: the sidecar file `.runestone-backgrounds.json` in the image folder.
// The Background Slideshow plugin used the same file, so the settings of each image stay.
import { BACKGROUND_POSITIONS } from "../../theme/appearance.ts";
import { tr } from "../../i18n/index.ts";
import type { BackgroundLayout, BackgroundPosition } from "../backgroundSettings.ts";
export const sidecarName = ".runestone-backgrounds.json";
/** `blurred` shows the full image over a blurred copy that fills the view. Portrait images use it by default. */
export const imageFits = ["cover", "contain", "auto", "blurred"] as const;
export type ImageFit = typeof imageFits[number];
export interface ImageAppearance { fit: ImageFit; position: BackgroundPosition; overlay: number }
/** Unknown keys of the file and of each image stay when RuneStone saves the file. */
export interface ImageSettings { schema: 1; images: Record<string, Partial<ImageAppearance>>; [key: string]: unknown }
/** Read the sidecar text. `null` (no file) gives empty settings. Invalid settings throw an error. */
export function parseImageSettings(source: string | null): ImageSettings {
if (source === null) return { schema: 1, images: {} };
const value = JSON.parse(source);
if (!value || value.schema !== 1 || !value.images || typeof value.images !== "object" || Array.isArray(value.images)) {
throw new Error(tr("The image settings file must use schema 1 and an images object."));
}
for (const [name, raw] of Object.entries(value.images)) {
const appearance = raw as Partial<ImageAppearance>;
if (!name || /[\\/]/.test(name) || !appearance || typeof appearance !== "object" || Array.isArray(appearance)
|| ("fit" in appearance && !imageFits.includes(appearance.fit!))
|| ("position" in appearance && !BACKGROUND_POSITIONS.includes(appearance.position!))
|| ("overlay" in appearance && (typeof appearance.overlay !== "number" || !Number.isFinite(appearance.overlay) || Math.abs(appearance.overlay) > 1))) {
throw new Error(tr("Invalid image settings for {name}.", { name }));
}
}
return value;
}
/** The appearance of one image: the folder layout, the portrait default, then the saved values of the image. */
export function imageAppearance(layout: BackgroundLayout, override: Partial<ImageAppearance> | undefined, portrait: boolean): ImageAppearance {
return { fit: portrait ? "blurred" : layout.size, position: layout.position, overlay: layout.overlay, ...override };
}
/** The supported image names, without duplicates, in natural order. */
export function imageNames(names: readonly string[]): string[] {
return [...new Set(names.filter(name => !/[\\/]/.test(name) && /\.(png|jpe?g|gif|webp)$/i.test(name)))]
.sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }) || a.localeCompare(b, "en"));
}
/** The order of the next images after `current`. A random order puts the current image last. */
export function sequence(names: readonly string[], current: string | null, order: "name" | "random", random = Math.random): string[] {
if (order === "name") {
const index = current === null ? -1 : names.indexOf(current);
return [...names.slice(index + 1), ...names.slice(0, index + 1)];
}
const rest = names.filter(name => name !== current);
for (let i = rest.length - 1; i > 0; i--) {
const j = Math.min(i, Math.max(0, Math.floor(random() * (i + 1))));
[rest[i], rest[j]] = [rest[j], rest[i]];
}
return current && names.includes(current) ? [...rest, current] : rest;
}
+84
View File
@@ -0,0 +1,84 @@
// The Background feature. `loader.ts` imports this module when a folder or an image is selected (`launch.ts`),
// at a palette command, or when Appearance → Background shows its settings.
// It shows the images through `backgroundHub`, so the workarea, browser tabs, and Project Management boards get the frames.
import { mount, unmount } from "svelte";
import { tr } from "../../i18n/index.ts";
import { backgroundHub } from "../../plugins/backgrounds.ts";
import { readAppearance } from "../../theme/appearance.ts";
import { hasImage, normalizeLayout, onBackgroundChange, readBackground, writeBackground } from "../backgroundSettings.ts";
import type { FeatureContext, FeatureInstance } from "../types.ts";
import { BlurWorker } from "./blur.ts";
import { Slideshow, type ImageSource } from "./engine.ts";
import { browserRuntime, folderHost, folderSource, imageSource, onBackgroundCommand, sendBackgroundCommand } from "./sources.ts";
import BackgroundSettings from "./BackgroundSettings.svelte";
export function start(_context: FeatureContext): FeatureInstance {
const owner = Symbol("background");
const blur = new BlurWorker();
const engine = new Slideshow({ set: (target, frame) => backgroundHub.set(owner, target, frame) }, browserRuntime(blur));
/** The host folder for display. `undefined` until the first read. */
let folder: string | null | undefined;
let generation = 0;
let disposed = false;
/** The last source and settings. A change of another appearance setting, such as the theme, gives the same value. */
let applied = "";
/** Give the engine the current source and settings. `reread` asks the host for its folder again. */
async function apply(reread: boolean) {
const run = ++generation;
const settings = readBackground();
const appearance = readAppearance();
let source: ImageSource | null = null;
let layout = normalizeLayout(settings);
if (settings.source === "folder") {
if (reread || folder === undefined) {
try { folder = await folderHost.current(); } catch { folder = null; }
if (disposed || run !== generation) return;
}
source = folder ? folderSource(folder) : null;
} else if (settings.source === "image" && hasImage(appearance)) {
source = imageSource(appearance.newTabBackground!);
layout = normalizeLayout(appearance.newTabBackground);
}
const next = { ...settings, ...layout };
const signature = JSON.stringify([source?.key ?? null, next]);
if (!reread && signature === applied) return;
applied = signature;
await engine.configure(source, next);
}
const stopSettings = onBackgroundChange(() => { void apply(false); });
const stopCommands = onBackgroundCommand(command => {
if (command === "next") void engine.next();
else { engine.invalidate(); void apply(true); }
});
// Another window or program can change the folder. A focus reads the folder, the list, and the sidecar again.
const focus = () => { engine.invalidate(); void apply(true); };
window.addEventListener("focus", focus);
void apply(true);
return {
mount() { throw new Error(tr("This view is unavailable.")); },
async run(command) {
if (command === "next") await sendBackgroundCommand("next");
else if (command === "pause") {
const settings = readBackground();
await writeBackground({ ...settings, paused: !settings.paused });
} else throw new Error(tr("This command is unavailable."));
},
dispose() {
disposed = true; generation++;
stopSettings(); stopCommands();
window.removeEventListener("focus", focus);
engine.dispose();
blur.dispose();
backgroundHub.removeOwner(owner);
},
};
}
/** The settings of Appearance → Background. They work also in a window where Background does not run. */
export function mountSettings(element: HTMLElement) {
const component = mount(BackgroundSettings, { target: element });
return () => { void unmount(component); };
}
+108
View File
@@ -0,0 +1,108 @@
// The image sources of Background, the host folder commands (`src-tauri/src/backgrounds.rs`), the browser runtime of the
// engine, and the commands that reach the Background instance of every window.
import { invoke, isTauri } from "@tauri-apps/api/core";
import { emit, listen } from "@tauri-apps/api/event";
import { tr } from "../../i18n/index.ts";
import { readBackgroundImage } from "../../theme/backgroundImages.ts";
import type { Appearance } from "../../theme/appearance.ts";
import type { BlurWorker } from "./blur.ts";
import type { ImageSource, LoadedImage, Runtime } from "./engine.ts";
const types: Record<string, string> = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
const typeOf = (name: string) => types[name.split(".").pop()!.toLowerCase()] ?? "application/octet-stream";
/** The host commands of the image folder. The host keeps the folder, so no command takes a path. */
export const folderHost = {
/** Show the folder dialog. Returns the chosen folder for display, or null after Cancel. */
choose: (title: string) => invoke<string | null>("background_choose_folder", { title }),
/** The current folder for display, or null. */
current: () => invoke<string | null>("background_folder"),
clear: () => invoke<void>("background_clear_folder"),
list: () => invoke<string[]>("background_list"),
read: async (name: string): Promise<Blob> => {
const bytes = await invoke<ArrayBuffer | Uint8Array | number[]>("background_read", { name });
return new Blob([bytes instanceof ArrayBuffer ? bytes : Uint8Array.from(bytes)], { type: typeOf(name) });
},
readSidecar: () => invoke<string | null>("background_read_sidecar"),
writeSidecar: (contents: string, expected: string | null) => invoke<void>("background_write_sidecar", { contents, expected }),
};
/** The images of the host folder. `folder` is the path for display. It makes the key, so another folder starts again. */
export function folderSource(folder: string): ImageSource {
return { key: `folder:${folder}`, timed: true, list: folderHost.list, read: folderHost.read, sidecar: folderHost.readSidecar };
}
/** The saved image of Appearance, from IndexedDB or from an old data URL. */
export async function readSavedImage(background: NonNullable<Appearance["newTabBackground"]>): Promise<Blob> {
if (background.imageId) {
const blob = await readBackgroundImage(background.imageId);
if (!blob) throw new Error(tr("The saved background image is missing. Choose the image again."));
return blob;
}
const image = background.image ?? "";
const [header, data] = image.split(",");
const bytes = Uint8Array.from(atob(data ?? ""), character => character.charCodeAt(0));
return new Blob([bytes], { type: header.slice(5, header.indexOf(";")) });
}
/** A short hash of a data URL, so that another old image gets another key. */
function hash(text: string): string {
let value = 0x811c9dc5;
for (let index = 0; index < text.length; index++) value = Math.imul(value ^ text.charCodeAt(index), 0x01000193);
return (value >>> 0).toString(16);
}
/** The one saved image. It has no timer. */
export function imageSource(background: NonNullable<Appearance["newTabBackground"]>): ImageSource {
const id = background.imageId ?? `data:${background.image?.length ?? 0}:${hash(background.image ?? "")}`;
return { key: `image:${id}`, timed: false, list: async () => ["image"], read: () => readSavedImage(background), sidecar: async () => null };
}
/** Make a blob URL and decode the image before it shows, so the fade does not wait for the decode. */
export async function loadImage(blob: Blob): Promise<LoadedImage> {
const url = URL.createObjectURL(blob);
try {
const image = new Image();
let timer: ReturnType<typeof setTimeout> | undefined;
image.src = url;
await Promise.race([image.decode(), new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(tr("The image took too long to load."))), 10000); })])
.finally(() => clearTimeout(timer));
return { url, width: image.naturalWidth, height: image.naturalHeight };
} catch (error) { URL.revokeObjectURL(url); throw error; }
}
export function browserRuntime(blur: BlurWorker): Runtime {
return {
load: loadImage,
blur: image => blur.blur(image.url, image.width, image.height),
release: url => URL.revokeObjectURL(url),
later: (callback, milliseconds) => setTimeout(callback, milliseconds),
cancel: timer => clearTimeout(timer as ReturnType<typeof setTimeout>),
random: Math.random,
now: () => Date.now(),
};
}
/** `next` shows the next image. `reload` reads the folder, the list, and the sidecar again. */
export type BackgroundCommand = "next" | "reload";
const EVENT = "background-command";
/** Send a command to the Background instance of every window, this window too. */
export async function sendBackgroundCommand(command: BackgroundCommand): Promise<void> {
if (isTauri()) await emit(EVENT, command);
else window.dispatchEvent(new CustomEvent(EVENT, { detail: command }));
}
/** Receive the commands of every window. Returns the function that stops it. */
export function onBackgroundCommand(listener: (command: BackgroundCommand) => void): () => void {
const accept = (value: unknown) => { if (value === "next" || value === "reload") listener(value); };
if (!isTauri()) {
const handle = (event: Event) => accept((event as CustomEvent).detail);
window.addEventListener(EVENT, handle);
return () => window.removeEventListener(EVENT, handle);
}
let stopped = false;
let off: (() => void) | undefined;
void listen<unknown>(EVENT, event => accept(event.payload)).then(unlisten => { if (stopped) unlisten(); else off = unlisten; }, () => undefined);
return () => { stopped = true; off?.(); };
}
+119
View File
@@ -0,0 +1,119 @@
// The settings of the Background feature: the `background` section of the settings file.
// This file is in the main bundle, because the launch rule and the first-start migration need it without the feature code.
// The image source keeps its image and its layout in `appearance.newTabBackground`, so an older version still shows it.
// The host keeps the image folder itself (`src-tauri/src/backgrounds.rs`). The interface never sends a folder path.
import { onSettingsChange, readSection, writeSection } from "../settings/store.ts";
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, type Appearance } from "../theme/appearance.ts";
import type { LegacyPlugin } from "./migration.ts";
export const BACKGROUND_SOURCES = ["folder", "image", "none"] as const;
export type BackgroundSource = typeof BACKGROUND_SOURCES[number];
export type BackgroundPosition = typeof BACKGROUND_POSITIONS[number];
export type BackgroundSize = typeof BACKGROUND_SIZES[number];
/** The views that show the background: the workspace, all Project Management boards, or one board. */
export const BACKGROUND_TARGET = /^(?:app|pm-all|pm-board:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
export interface BackgroundLayout {
/** From -1 (white) to 1 (black). */
overlay: number;
position: BackgroundPosition;
size: BackgroundSize;
}
export interface BackgroundSettings extends BackgroundLayout {
source: BackgroundSource;
/** The time of each image of a folder, from 1 to 86,400 seconds. */
seconds: number;
order: "name" | "random";
/** A paused folder keeps its current image. */
paused: boolean;
targets: string[];
}
export const DEFAULT_BACKGROUND: Readonly<BackgroundSettings> = Object.freeze({
source: "none", seconds: 60, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover",
});
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
}
/** The folder layout fields from any value. Invalid fields take the defaults. */
export function normalizeLayout(value: unknown): BackgroundLayout {
const raw = record(value);
return {
overlay: typeof raw.overlay === "number" && Number.isFinite(raw.overlay) ? Math.max(-1, Math.min(1, raw.overlay)) : 0,
position: BACKGROUND_POSITIONS.includes(raw.position as BackgroundPosition) ? raw.position as BackgroundPosition : "center",
size: BACKGROUND_SIZES.includes(raw.size as BackgroundSize) ? raw.size as BackgroundSize : "cover",
};
}
/** Valid settings from any value. Invalid fields take the defaults. */
export function normalizeBackground(value: unknown): BackgroundSettings {
const raw = record(value);
return {
source: BACKGROUND_SOURCES.includes(raw.source as BackgroundSource) ? raw.source as BackgroundSource : "none",
seconds: typeof raw.seconds === "number" && Number.isFinite(raw.seconds) ? Math.max(1, Math.min(86400, Math.round(raw.seconds))) : 60,
order: raw.order === "random" ? "random" : "name",
paused: raw.paused === true,
targets: Array.isArray(raw.targets)
? [...new Set(raw.targets.filter((target): target is string => typeof target === "string" && BACKGROUND_TARGET.test(target)))]
: ["app"],
...normalizeLayout(raw),
};
}
export function readBackground(): BackgroundSettings {
return normalizeBackground(readSection("background"));
}
/** Save the settings. Keys of a newer version stay. */
export function writeBackground(next: BackgroundSettings): Promise<void> {
return writeSection("background", { ...record(readSection("background")), ...normalizeBackground(next) });
}
/** True when the appearance has a saved background image. */
export function hasImage(appearance: Appearance = readAppearance()): boolean {
return !!(appearance.newTabBackground?.image || appearance.newTabBackground?.imageId);
}
/** True when Background has something to show: a folder, or an image that exists. */
export function hasBackgroundSource(settings: BackgroundSettings = readBackground(), appearance: Appearance = readAppearance()): boolean {
return settings.source === "folder" || (settings.source === "image" && hasImage(appearance));
}
/** Run `listener` after each change of the background or appearance settings. Returns the function that stops it. */
export function onBackgroundChange(listener: () => void): () => void {
const stops = [onSettingsChange("background", listener), onSettingsChange("appearance", listener)];
return () => stops.forEach(stop => stop());
}
/** The host side of the first-start migration of the `background` section. */
export interface BackgroundMigrationHost {
/** True when the settings file has no `background` section. */
missing(): boolean;
/** True when the appearance has a saved background image. */
hasImage(): boolean;
/** Copy the folder of the old plugin grant to the host. True when the host has a folder after the call. */
migrateFolder(): Promise<boolean>;
write(value: BackgroundSettings): Promise<void>;
}
/**
* Make the `background` section from the old Background Slideshow plugin and the old background image.
* The source is the folder when the plugin was installed, enabled, and on, and its folder migrated.
* Otherwise it is the image when one exists. The kept plugin settings give the sequence, the targets, and the layout.
*/
export async function migrateBackground(legacy: LegacyPlugin | undefined, host: BackgroundMigrationHost): Promise<BackgroundSettings> {
const kept = record(legacy?.settings);
// Migrate the folder whenever a grant exists, so that a later choice of Folder brings it back.
let folder = false;
if (typeof kept.grant === "string" && kept.grant) {
try { folder = await host.migrateFolder(); } catch (reason) { console.error("RuneStone could not take the old background folder.", reason); }
}
const slideshow = !!legacy?.installed && legacy.enabled && kept.enabled === true && folder;
const copied = Object.fromEntries(["seconds", "order", "targets", "overlay", "position", "size"].filter(key => key in kept).map(key => [key, kept[key]]));
const value = normalizeBackground({ ...copied, source: slideshow ? "folder" : host.hasImage() ? "image" : "none", paused: false });
await host.write(value);
return value;
}
+159
View File
@@ -0,0 +1,159 @@
// The native features of RuneStone. Each feature has an off switch in Settings → Features.
// This file is in the main bundle, so it holds only small static data: names, views, commands, and document types.
// The code of a feature loads with a dynamic import at first need (see `loader.ts`), and never while its switch is off.
import { message, tr } from "../i18n/index.ts";
import type { PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
import { identifyPdf } from "./pdfDocument.ts";
export type FeatureId = "git" | "background" | "terminal" | "pdf" | "pm";
/** 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 {
id: string;
/** Returns the title in the current language. */
title: () => string;
placement: "editor" | "sidebar";
icon?: PluginView["icon"];
/** Show a navigation button for the view. */
navigation?: boolean;
/** True when a launch, such as a ribbon button, asks the feature which view to open (`FeatureInstance.launch`). */
launch?: boolean;
}
/**
* A family of editor views whose IDs follow a pattern, for example one tab for each board. The session answers for each
* matching ID before the feature module loads, so a tab transfer from another window can restore it.
* The feature gives the real title later (`FeatureContext.setViewTitle`).
*/
export interface FeatureViewPattern {
/** Matches the whole view ID. */
match: RegExp;
/** The title until the feature gives one. */
title: () => string;
icon?: PluginView["icon"];
}
/** A command of a feature. The command palette lists it. */
export interface FeatureCommandInfo {
id: string;
title: () => string;
icon?: PluginCommand["icon"];
/** The view that the command opens. Without a view, the command loads the feature and calls `FeatureInstance.run`. */
view?: string;
}
/**
* A document type of a feature. The file tree marks the files of the type, and a click opens them in a tab,
* without the feature code. The first tab of the type loads the feature and calls `FeatureInstance.mountDocument`.
*/
export interface FeatureDocumentInfo {
id: string;
/** Returns the title in the current language. The file tree shows it as the tooltip of the file icon. */
title: () => string;
icon: NonNullable<PluginDocumentType["icon"]>;
/** Lowercase file extensions without the dot. */
extensions: readonly string[];
/** "binary" when `identify` needs no file contents. */
content: "text" | "binary";
/** The document ID of a file, or null when the file is not of this type. */
identify(path: string, source: string): { id: string } | null;
}
export interface FeatureEntry {
id: FeatureId;
/** The ID of the old plugin package. Saved tabs and tab transfers keep it as the owner ID. */
owner: string;
/** Catalog keys for Settings → Features. */
name: string;
description: string;
/** Extra words for the Settings search. */
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[];
/** Editor views with IDs that follow a pattern. */
viewPatterns?: readonly FeatureViewPattern[];
commands: readonly FeatureCommandInfo[];
documentTypes: readonly FeatureDocumentInfo[];
}
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, 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" },
{ id: "graph", title: () => tr("Git graph"), placement: "editor", icon: "git" },
],
commands: [{ id: "graph", title: () => tr("Show Git graph"), icon: "git", view: "graph" }],
documentTypes: [],
},
{
// Background replaces the Background Slideshow plugin and the background image of Appearance. Its settings are in
// 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" },
],
documentTypes: [],
},
{
// Terminal replaces the Terminal plugin. Its panel is not a view: the workbench and the terminal window show it
// (`src/lib/features/TerminalHost.svelte`), and the first use loads the module. Its settings are in Settings → Terminal.
id: "terminal", owner: "runestone.terminal", name: message("Terminal"),
description: message("Run shells, tasks, and the active file in a panel below the editor or in a separate window."),
keywords: "terminal shell console powershell bash cmd command prompt task run pty xterm",
defaultOn: true, followsPackage: true,
views: [],
commands: [],
documentTypes: [],
},
{
// PDF Viewer replaces the PDF Viewer plugin. It has no view: its document type opens each PDF file in its own tab.
// The file tree marks PDF files without the module. The first PDF tab loads the module and PDF.js.
id: "pdf", owner: "runestone.pdf-viewer", name: message("PDF Viewer"),
description: message("Read PDF files of the workspace in tabs, with page controls, zoom, rotation, and text selection."),
keywords: "pdf document viewer page zoom rotate password pdf.js",
defaultOn: true, followsPackage: true,
views: [],
commands: [],
documentTypes: [
{ id: "pdf", title: () => tr("PDF document"), icon: "file", extensions: ["pdf"], content: "binary", identify: identifyPdf },
],
},
{
// Project Management replaces the Project Management plugin. It reads only `.runestone/pm/` in the workspace, so the
// file tree reads no Markdown file for it. Its ribbon button opens `planning`: the default board of the workspace, or
// All tasks. Each board has its own tab, `board-<hex of the board ID>`, as in the plugin, so tab transfers between
// the plugin and the feature work. Its settings are in Settings → Project Management (`ProjectManagementSettings.svelte`).
id: "pm", owner: "runestone.pm", name: message("Project Management"),
description: message("Plan work on Kanban boards, in All tasks, and on Gantt and calendar views. The cards stay in the workspace."),
keywords: "project management kanban board card task list gantt calendar label priority backlog todo plan",
defaultOn: true, followsPackage: true,
views: [{ id: "planning", title: () => tr("Project Management"), placement: "editor", icon: "kanban", launch: true }],
viewPatterns: [{ match: /^board-(?:[0-9a-f]{2})+$/, title: () => tr("Project Management"), icon: "kanban" }],
commands: [],
documentTypes: [],
},
];
export function featureEntry(id: FeatureId): FeatureEntry {
const entry = FEATURES.find(item => item.id === id);
if (!entry) throw new Error(`Unknown feature: ${id}`);
return entry;
}
/** The feature that uses `owner` as its owner ID, if any. */
export function featureOfOwner(owner: string): FeatureEntry | undefined {
return FEATURES.find(item => item.owner === owner);
}
+20
View File
@@ -0,0 +1,20 @@
<script lang="ts">
import { diffLineKind } from "./model";
let { text, error = false, label }: { text: string; error?: boolean; label: string } = $props();
const lines = $derived(text.split("\n"));
</script>
<!-- One block element for each line, so that the add and remove fills cover the full width.
The diff takes focus, so that a keyboard user can scroll it. -->
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<pre class="diff" class:error tabindex="0" aria-label={label}>{#each lines as line, index (index)}<span class="line {diffLineKind(line)}">{line || " "}</span>{/each}</pre>
<style>
.diff { flex: 1; min-height: 0; margin: 0; padding: 8px; overflow: auto; font: 12px/1.6 var(--rs-font-mono); font-weight: var(--rs-code-font-weight); tab-size: 4; background: var(--rs-image-editor-bg, var(--rs-bg)); border-radius: var(--rs-control-radius); }
.diff:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
.line { display: block; min-width: max-content; min-height: 1.6em; }
.add { background: color-mix(in srgb, var(--rs-ok) 18%, transparent); }
.remove { background: color-mix(in srgb, var(--rs-error) 18%, transparent); }
.range { color: var(--rs-accent); }
.error { color: var(--rs-error); }
</style>
+39
View File
@@ -0,0 +1,39 @@
<script lang="ts">
import { t } from "$lib/i18n";
import DiffText from "./DiffText.svelte";
import type { GitState } from "./state.svelte";
let { git, openFile }: { git: GitState; openFile: (path: string) => Promise<void> } = $props();
let error = $state("");
const title = $derived(git.selected
? git.selected.staged ? $t("{path} · Staged", { path: git.selected.path }) : $t("{path} · Working tree", { path: git.selected.path })
: $t("Git diff"));
async function open() {
if (!git.selected) return;
error = "";
try { await openFile(git.selected.path); }
catch (reason) { error = String(reason); }
}
</script>
<section class="git-diff">
<div class="header">
<strong>{title}</strong>
<button class="text-button" type="button" disabled={!git.selected} onclick={open}>{$t("Open file")}</button>
</div>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<DiffText text={git.selected?.text ?? $t("Select a file in Source control to see its diff.")} error={!!git.selected?.error} label={$t("Git diff")} />
</section>
<style>
.git-diff { display: flex; flex-direction: column; gap: 10px; height: 100%; padding: 12px; box-sizing: border-box; overflow: hidden; font-size: 13px; }
.header { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
strong { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
.text-button:hover:not(:disabled) { background: var(--rs-bg-active); }
.text-button:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
.text-button:disabled { color: var(--rs-text-dim); }
.error { margin: 0; color: var(--rs-error); }
</style>
+244
View File
@@ -0,0 +1,244 @@
<script lang="ts">
import { onMount, tick, untrack } from "svelte";
import { t, tr } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte";
import { attachTooltip } from "$lib/ui/tooltip";
import { gitApi } from "$lib/git/service";
import type { GitCommitDetails, GitCommitFile, GitGraph } from "$lib/git/contracts";
import { graphLayout } from "./model";
import DiffText from "./DiffText.svelte";
import type { GitState } from "./state.svelte";
let { git }: { git: GitState } = $props();
const rowHeight = 30;
const x = (lane: number) => 12 + lane * 18;
const y = (row: number) => rowHeight / 2 + row * rowHeight;
let history = $state.raw<GitGraph | null>(null);
let graphMessage = $state(tr("Loading history…"));
let graphError = $state(false);
let refreshing = $state(false);
let detail = $state.raw<GitCommitDetails | null>(null);
let detailMessage = $state(tr("Select a commit."));
let diff = $state<{ text: string; error: boolean } | null>(null);
let list: HTMLOListElement | undefined = $state();
let disposed = false, generation = 0, selection = 0, fileRequest = 0;
const layout = $derived(graphLayout(history));
function tooltip(node: HTMLElement, text: string) {
let current = text;
const dispose = attachTooltip(node, () => current);
return { update(value: string) { current = value; }, destroy: dispose };
}
async function refresh() {
const request = ++generation;
refreshing = true;
try {
const result = await gitApi.graph();
if (disposed || request !== generation) return;
history = result;
graphError = false;
graphMessage = result.commits.length ? "" : tr("No commits yet. Create a commit to start the graph.");
const kept = result.commits.some(commit => commit.id === git.history.selectedId) ? git.history.selectedId : result.commits[0]?.id ?? null;
if (kept) {
if (kept !== detail?.id || kept !== git.history.selectedId) void select(kept);
} else {
git.history.selectedId = null;
++selection; ++fileRequest;
detail = null; diff = null;
detailMessage = tr("No commit is selected.");
}
} catch (reason) {
if (disposed || request !== generation) return;
history = null;
graphError = true;
graphMessage = String(reason);
++selection; ++fileRequest;
detail = null; diff = null;
detailMessage = tr("Select Refresh to try again.");
} finally {
if (!disposed && request === generation) refreshing = false;
}
}
async function select(id: string) {
git.history.selectedId = id;
const request = ++selection;
++fileRequest;
detailMessage = tr("Loading commit…");
try {
const result = await gitApi.commitDetails(id);
if (disposed || request !== selection) return;
detail = result;
diff = null;
const file = result.files.find(item => item.path === git.history.file) ?? result.files[0];
if (file) void selectFile(file, result);
} catch (reason) {
if (disposed || request !== selection) return;
detail = null;
detailMessage = String(reason);
}
}
async function selectFile(file: GitCommitFile, commit: GitCommitDetails) {
git.history.file = file.path;
const request = ++fileRequest;
diff = { text: tr("Loading diff…"), error: false };
try {
const text = await gitApi.commitDiff(commit.id, file.path);
if (disposed || request !== fileRequest || git.history.selectedId !== commit.id) return;
diff = { text: text || tr("No text changes."), error: false };
} catch (reason) {
if (!disposed && request === fileRequest) diff = { text: String(reason), error: true };
}
}
async function keydown(event: KeyboardEvent) {
const commits = layout.nodes;
const index = commits.findIndex(commit => commit.id === git.history.selectedId);
const next = event.key === "ArrowDown" ? Math.min(commits.length - 1, index + 1)
: event.key === "ArrowUp" ? Math.max(0, index - 1)
: event.key === "Home" ? 0 : event.key === "End" ? commits.length - 1 : -1;
if (next < 0 || !commits[next]) return;
event.preventDefault();
void select(commits[next].id);
await tick();
list?.querySelector<HTMLButtonElement>(`[data-commit="${commits[next].id}"]`)?.focus();
}
// The graph reads the history again after a commit, push, or pull, and on window focus.
$effect(() => {
void git.historyVersion;
untrack(() => void refresh());
});
onMount(() => {
const focus = () => void refresh();
window.addEventListener("focus", focus);
return () => { disposed = true; ++generation; ++selection; ++fileRequest; window.removeEventListener("focus", focus); };
});
</script>
<section class="git-graph" aria-label={$t("Git history")}>
<div class="header">
<strong>{$t("Commit graph")}</strong>
<IconButton icon="refresh" label={$t("Refresh commit graph")} disabled={refreshing} onclick={() => void refresh()} />
</div>
<p class="hint">{$t("Latest 100 commits. Select a commit to see its files. Dashed lines continue beyond this history.")}</p>
<div class="body">
<div class="graph" aria-label={$t("Commit graph with branches, authors, and dates")}>
{#if graphMessage}
<p class:error={graphError}>{graphMessage}</p>
{:else}
<div class="canvas">
<svg width={layout.lanes * 18 + 12} height={layout.nodes.length * rowHeight} aria-hidden="true" class="lines">
{#each layout.edges as edge (`${edge.from}:${edge.to}`)}
{@const middle = y(edge.row) + rowHeight / 2}
<path class="edge" class:boundary={edge.outside} style:color={`var(--git-lane-${edge.color + 1})`}
d={`M ${x(edge.lane)} ${y(edge.row)} C ${x(edge.lane)} ${middle} ${x(edge.parentLane)} ${middle} ${x(edge.parentLane)} ${y(edge.row) + rowHeight} L ${x(edge.parentLane)} ${y(edge.endRow)}`} />
{/each}
{#each layout.nodes as commit (commit.id)}
<circle class="node" cx={x(commit.lane)} cy={y(commit.row)} r="4" style:color={`var(--git-lane-${commit.color + 1})`} />
{/each}
</svg>
<ol role="listbox" aria-label={$t("Commits")} bind:this={list} onkeydown={keydown}>
{#each layout.nodes as commit (commit.id)}
{@const selected = commit.id === git.history.selectedId}
<li>
<button type="button" role="option" data-commit={commit.id} aria-selected={selected}
tabindex={selected || (!git.history.selectedId && commit.row === 0) ? 0 : -1}
use:tooltip={`${commit.summary}\n${commit.author} · ${commit.date}\n${commit.id}`}
onclick={() => void select(commit.id)}>
<span class="description">
{#if commit.refs.length}<span class="refs">{commit.refs.join(" · ")}</span>{/if}
<span class="summary">{commit.summary}</span>
</span>
<span class="meta author">{commit.author}</span>
<span class="meta date">{commit.date}</span>
<span class="meta">{commit.id.slice(0, 7)}</span>
<span class="screen-reader">{commit.parents.length ? $t("Parents: {parents}", { parents: commit.parents.join(", ") }) : $t("Root commit")}</span>
</button>
</li>
{/each}
</ol>
</div>
{/if}
</div>
<section class="details" aria-label={$t("Commit details")}>
{#if detail}
<div class="detail-meta">
<strong>{detail.author}</strong>
<time>{detail.date}</time>
<code>{detail.id}</code>
{#if detail.parents.length > 1}<span class="dim">{$t("Changes against the first parent.")}</span>{/if}
</div>
<p class="message">{detail.message}</p>
<strong>{$t("Changed files: {count}", { count: detail.files.length })}</strong>
<div class="files" aria-label={$t("Changed files")}>
{#each detail.files as file (file.path)}
<button type="button" class="file" aria-pressed={file.path === git.history.file}
use:tooltip={file.originalPath ? `${file.originalPath} → ${file.path}` : file.path}
onclick={() => void selectFile(file, detail!)}>
<span>{file.path}</span><span class="dim">{file.status}</span>
</button>
{/each}
</div>
{#if diff}
<DiffText text={diff.text} error={diff.error} label={$t("Commit file diff")} />
{:else}
<p class="dim">{detail.files.length ? $t("Select a file to see its diff.") : $t("This commit contains no file changes.")}</p>
{/if}
{:else}
<p class="dim">{detailMessage}</p>
{/if}
</section>
</div>
</section>
<style>
.git-graph { container-type: inline-size; display: flex; flex-direction: column; gap: 6px; height: 100%; padding: 8px; box-sizing: border-box; overflow: hidden; font-size: 13px;
--git-lane-1: #007fff; --git-lane-2: #ca7000; --git-lane-3: #f000ff; --git-lane-4: #00a000; --git-lane-5: #aa00ff; --git-lane-6: #ff0033; }
.header, .hint { padding: 4px 6px; border-radius: var(--rs-control-radius); background: var(--rs-image-control-bg, var(--rs-bg)); }
.header { display: flex; align-items: center; gap: 6px; }
.header strong { flex: 1; }
.hint { margin: 0; font-size: 11px; color: var(--rs-text-dim); }
.body { display: grid; grid-template-columns: minmax(0, 1fr) minmax(260px, 32%); flex: 1; min-height: 0; min-width: 0; }
.graph { min-height: 0; min-width: 0; padding: 4px; overflow: auto; background: var(--rs-image-editor-bg, var(--rs-bg)); }
.graph p { margin: 8px; color: var(--rs-text-dim); }
.graph p.error { color: var(--rs-error); }
.canvas { display: flex; align-items: flex-start; min-width: 0; }
.lines { flex: 0 0 auto; overflow: hidden; }
.edge { fill: none; stroke: currentColor; stroke-width: 2; }
.boundary { stroke-dasharray: 3 3; }
.node { fill: currentColor; stroke: currentColor; stroke-width: 2; }
ol { flex: 1; min-width: 0; margin: 0; padding: 0; list-style: none; }
li { height: 30px; min-width: 0; }
ol button { display: grid; grid-template-columns: minmax(0, 1fr) 95px 78px 54px; align-items: center; gap: 8px; width: 100%; height: 30px; padding: 0 6px; border: var(--rs-item-selection-width) solid transparent; border-radius: var(--rs-item-selection-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
ol button:hover { background: var(--rs-bg-active); }
ol button[aria-selected="true"], .file[aria-pressed="true"] { background: var(--rs-item-selection-bg); border-color: var(--rs-item-selection-border); }
ol button:focus-visible, .file:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
.description { display: flex; align-items: center; gap: 5px; min-width: 0; }
.summary, .refs, .meta { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.summary { flex: 1; }
.refs { max-width: 45%; padding: 1px 4px; border-radius: var(--rs-control-radius); background: var(--rs-bg-active); color: var(--rs-accent); font-size: 11px; }
.meta, .dim { color: var(--rs-text-dim); font-size: 11px; }
.screen-reader { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
.details { display: flex; flex-direction: column; gap: 8px; min-height: 0; min-width: 0; padding: 10px; overflow: auto; border-left: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-image-editor-bg, var(--rs-bg)); }
.details p { margin: 0; }
.detail-meta { display: flex; flex-direction: column; gap: 3px; overflow-wrap: anywhere; }
time { color: var(--rs-text-dim); }
code { font: 11px var(--rs-font-mono); overflow-wrap: anywhere; }
.message { white-space: pre-wrap; overflow-wrap: anywhere; }
.files { display: flex; flex-direction: column; flex-shrink: 0; max-height: 180px; overflow: auto; }
.file { display: flex; flex-shrink: 0; align-items: center; gap: 6px; min-width: 0; min-height: 28px; padding: 3px 6px; border: var(--rs-item-selection-width) solid transparent; border-radius: var(--rs-item-selection-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
.file:hover { background: var(--rs-bg-active); }
.file span:first-child { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.details :global(.diff) { min-height: 140px; }
@container (max-width: 950px) { ol button { grid-template-columns: minmax(0, 1fr) 54px; } .author, .date { display: none; } }
@container (max-width: 650px) {
.body { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(140px, 45%) minmax(0, 1fr); }
.details { border-left: 0; border-top: 1px solid var(--rs-border); }
}
</style>
+201
View File
@@ -0,0 +1,201 @@
<script lang="ts">
import { onMount } from "svelte";
import { t, tr } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { attachTooltip } from "$lib/ui/tooltip";
import { keys } from "$lib/ui/shortcuts";
import { gitApi } from "$lib/git/service";
import type { GitChange, GitStatus } from "$lib/git/contracts";
import { changeLabel, groups, isConflict, pathsFor } from "./model";
import type { GitState } from "./state.svelte";
let { git, showDiff, showGraph, onWorkspaceChange }: {
git: GitState;
showDiff: (path: string, staged: boolean) => void;
showGraph: () => void;
onWorkspaceChange: (listener: () => void) => () => void;
} = $props();
let snapshot = $state<GitStatus | null>(null);
let busy = $state(false);
let refreshing = $state(false);
let message = $state("");
let notice = $state({ text: tr("Loading repository…"), error: false });
let disposed = false;
let sequence = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const grouped = $derived(snapshot?.repository ? groups(snapshot.changes) : { staged: [], working: [] });
const conflicts = $derived(!!snapshot?.changes.some(isConflict));
const canCommit = $derived(!!snapshot?.repository && grouped.staged.length > 0 && !conflicts && message.trim().length > 0);
function tooltip(node: HTMLElement, text: string) {
let current = text;
const dispose = attachTooltip(node, () => current);
return { update(value: string) { current = value; }, destroy: dispose };
}
function report(text: string, error = false) { notice = { text, error }; }
async function refresh(keepNotice = false) {
if (disposed || busy) return;
const request = ++sequence;
refreshing = true;
try {
const result = await gitApi.status();
if (disposed || request !== sequence) return;
snapshot = result;
if (!result.available) report(tr("Git is not installed. Install Git, then restart RuneStone."));
else if (!result.repository) report(tr("Open a Git repository root as your workspace. Create repositories with Git outside RuneStone."));
else if (result.changes.some(isConflict)) report(tr("Resolve the conflicts, then stage the files before you commit."));
else if (!keepNotice) report(result.changes.length ? "" : tr("No changes. Your working tree is clean."));
} catch (reason) {
if (!disposed && request === sequence) { snapshot = null; report(String(reason), true); }
} finally {
if (request === sequence) refreshing = false;
}
}
/** Run one Git action at a time, then read the status again. */
async function perform(action: () => Promise<void>, changesHistory = false) {
if (busy || disposed) return;
busy = true;
clearTimeout(timer);
++sequence;
report("");
try {
await action();
if (changesHistory) git.historyVersion++;
} catch (reason) {
if (!disposed) report(String(reason), true);
} finally {
busy = false;
if (!disposed) await refresh(true);
}
}
function stage(changes: GitChange[], staged: boolean) {
void perform(() => staged ? gitApi.unstage(pathsFor(changes)) : gitApi.stage(pathsFor(changes)));
}
function commit() {
if (!canCommit) return;
void perform(async () => {
await gitApi.commit(message);
message = "";
report(tr("Commit created."));
}, true);
}
function pull() {
void perform(async () => {
report(tr("Pull in progress…"));
await gitApi.pull();
report(tr("Pull complete. The branch is up to date."));
}, true);
}
function push() {
void perform(async () => {
report(tr("Push in progress…"));
await gitApi.push();
report(tr("Push complete."));
}, true);
}
function rowLabel(change: GitChange, staged: boolean) {
const status = changeLabel(change, staged);
return change.originalPath
? $t("{path} — {status}, from {original}", { path: change.path, status, original: change.originalPath })
: $t("{path} — {status}", { path: change.path, status });
}
// The status refreshes after a workspace change, which includes the `.git` folder, and on window focus.
function schedule() {
clearTimeout(timer);
timer = setTimeout(() => void refresh(), 350);
}
onMount(() => {
const off = onWorkspaceChange(schedule);
window.addEventListener("focus", schedule);
void refresh();
return () => {
disposed = true;
sequence++;
clearTimeout(timer);
off();
window.removeEventListener("focus", schedule);
};
});
</script>
<section class="source-control" aria-label={$t("Git source control")} aria-busy={busy}>
<div class="header">
<span class="branch" use:tooltip={snapshot?.branch ?? $t("Source control")}>{snapshot?.branch ?? $t("Source control")}</span>
{#if snapshot?.repository}
<IconButton icon="git" label={$t("Show Git graph")} disabled={busy} onclick={showGraph} />
<IconButton icon="download" label={$t("Pull from the upstream branch")} disabled={busy} onclick={pull} />
<IconButton icon="upload" label={$t("Push to the upstream branch")} disabled={busy} onclick={push} />
{/if}
<IconButton icon="refresh" label={$t("Refresh source control")} disabled={busy || refreshing} onclick={() => void refresh()} />
</div>
<p class="notice" class:error={notice.error} role="status" hidden={!notice.text}>{notice.text}</p>
{#if snapshot?.repository}
<form class="commit" onsubmit={event => { event.preventDefault(); commit(); }}>
<textarea rows="3" maxlength="65536" placeholder={$t("Commit message")} aria-label={$t("Commit message")} disabled={busy} bind:value={message}
onkeydown={event => { if ((event.ctrlKey || event.metaKey) && event.key === "Enter") { event.preventDefault(); commit(); } }}></textarea>
<button class="primary" type="submit" disabled={busy || !canCommit}><Icon icon="check" /><span>{$t("Commit staged")}</span></button>
<small>{$t("Only staged files enter the commit. Press {shortcut} to commit.", { shortcut: keys("Mod+Enter") })}</small>
</form>
<details class="changes" open>
<summary>{$t("Changes ({count})", { count: snapshot.changes.length })}</summary>
{#each [{ staged: true, changes: grouped.staged }, { staged: false, changes: grouped.working }] as group (group.staged)}
{#if group.changes.length}
<section class="group">
<div class="group-header">
<h3>{group.staged ? $t("Staged changes ({count})", { count: group.changes.length }) : $t("Unstaged changes ({count})", { count: group.changes.length })}</h3>
<IconButton icon={group.staged ? "minus" : "plus"} label={group.staged ? $t("Unstage all") : $t("Stage all")} disabled={busy} onclick={() => stage(group.changes, group.staged)} />
</div>
{#each group.changes as change (change.path)}
<div class="row">
<button class="file" type="button" disabled={busy} aria-label={rowLabel(change, group.staged)} use:tooltip={rowLabel(change, group.staged)} onclick={() => showDiff(change.path, group.staged)}>
<Icon icon="text" /><span>{change.path}</span>
</button>
<span class="status">{changeLabel(change, group.staged)}</span>
<IconButton icon={group.staged ? "minus" : "plus"} label={group.staged ? $t("Unstage {path}", { path: change.path }) : $t("Stage {path}", { path: change.path })} disabled={busy} onclick={() => stage([change], group.staged)} />
</div>
{/each}
</section>
{/if}
{/each}
</details>
{/if}
</section>
<style>
.source-control { display: flex; flex-direction: column; gap: 8px; height: 100%; min-width: 0; padding: 6px; overflow: auto; box-sizing: border-box; font-size: 13px; }
.header { display: flex; align-items: center; gap: 2px; min-width: 0; }
.branch { flex: 1; min-width: 0; padding-left: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
.notice { margin: 0; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; color: var(--rs-text-dim); }
.notice.error { color: var(--rs-error); }
.notice[hidden] { display: none; }
.commit { display: flex; flex-direction: column; gap: 5px; flex: 0 0 auto; }
textarea { box-sizing: border-box; width: 100%; min-height: 60px; resize: vertical; padding: 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
textarea:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; }
.primary { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 28px; padding: 3px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; font-weight: 600; }
.primary:hover:not(:disabled) { background: var(--rs-bg-active); }
.primary:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
.primary:disabled { color: var(--rs-text-dim); }
small { color: var(--rs-text-dim); line-height: 1.5; }
.changes { min-width: 0; border-top: 1px solid var(--rs-border); }
summary { padding: 8px 4px; border-radius: var(--rs-control-radius); cursor: pointer; font-weight: 600; }
summary:hover { background: var(--rs-bg-active); }
summary:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
.group { margin-bottom: 6px; }
.group-header { display: flex; align-items: center; gap: 6px; padding-bottom: 4px; }
h3 { flex: 1; margin: 0; padding-left: 4px; font: inherit; font-weight: 600; }
.row { display: flex; align-items: center; gap: 3px; min-width: 0; }
.file { display: flex; flex: 1; align-items: center; gap: 6px; min-width: 0; min-height: 28px; padding: 4px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); font: inherit; text-align: left; }
.file:hover:not(:disabled) { background: var(--rs-bg-active); }
.file:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; }
.file:disabled { color: var(--rs-text-dim); }
.file span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.status { color: var(--rs-text-dim); font-size: 11px; white-space: nowrap; }
@media (max-width: 450px) { .status { display: none; } }
</style>
+62
View File
@@ -0,0 +1,62 @@
// The Git feature. `loader.ts` imports this module at first need: the Source control pane, a Git tab, or the graph command.
// It uses the host Git service directly. `src-tauri/src/git.rs` runs the `git` program for the workspace of the window.
import { mount, unmount } from "svelte";
import { tr } from "../../i18n/index.ts";
import { gitApi } from "../../git/service.ts";
import type { FeatureContext, FeatureInstance } from "../types.ts";
import { GitState } from "./state.svelte.ts";
import SourceControl from "./SourceControl.svelte";
import GitDiff from "./GitDiff.svelte";
import GitGraph from "./GitGraph.svelte";
export function start(context: FeatureContext): FeatureInstance {
const state = new GitState();
async function loadDiff(path: string, staged: boolean) {
const sequence = ++state.sequence;
state.selected = { path, staged, text: tr("Loading diff…"), error: false };
try {
const text = await gitApi.diff(path, staged);
if (state.disposed || sequence !== state.sequence) return;
state.selected = { path, staged, text: text || tr("No text changes."), error: false };
} catch (reason) {
if (state.disposed || sequence !== state.sequence) return;
state.selected = { path, staged, text: String(reason), error: true };
}
}
const views: Record<string, (target: HTMLElement) => Record<string, unknown>> = {
"source-control": target => mount(SourceControl, { target, props: {
git: state,
showDiff: (path: string, staged: boolean) => { context.openView("diff"); void loadDiff(path, staged); },
showGraph: () => context.openView("graph"),
onWorkspaceChange: context.onWorkspaceChange,
} }),
diff: target => mount(GitDiff, { target, props: { git: state, openFile: context.openFile } }),
graph: target => mount(GitGraph, { target, props: { git: state } }),
};
return {
mount(view, element) {
const create = views[view];
if (!create) throw new Error(tr("This view is unavailable."));
const component = create(element);
return () => unmount(component);
},
saveTabState(view) {
if (view === "diff") return state.selected ? { path: state.selected.path, staged: state.selected.staged } : null;
if (view === "graph") return { selectedId: state.history.selectedId, file: state.history.file };
return undefined;
},
async restoreTabState(view, value) {
const saved = value && typeof value === "object" ? value as Record<string, unknown> : null;
if (!saved) return;
if (view === "diff" && typeof saved.path === "string" && typeof saved.staged === "boolean") await loadDiff(saved.path, saved.staged);
if (view === "graph") {
state.history.selectedId = typeof saved.selectedId === "string" ? saved.selectedId : null;
state.history.file = typeof saved.file === "string" ? saved.file : null;
}
},
dispose() { state.disposed = true; state.sequence++; },
};
}
+86
View File
@@ -0,0 +1,86 @@
// Pure Git helpers of the Git feature: change groups, labels, and the lanes of the commit graph.
import { tr } from "../../i18n/index.ts";
import type { GitChange, GitGraph, GitGraphCommit } from "../../git/contracts.ts";
export function isConflict(change: GitChange): boolean {
return change.index === "U" || change.worktree === "U" || ["AA", "DD"].includes(change.index + change.worktree);
}
/** Staged changes and working tree changes. A conflict shows only with the working tree changes. */
export function groups(changes: GitChange[]): { staged: GitChange[]; working: GitChange[] } {
return {
staged: changes.filter(change => !isConflict(change) && ![" ", "?", "!"].includes(change.index)),
working: changes.filter(change => isConflict(change) || ![" ", "!"].includes(change.worktree)),
};
}
/** The paths to stage or unstage. A rename needs both its old and its new path. */
export function pathsFor(changes: GitChange[]): string[] {
return [...new Set(changes.flatMap(change => change.originalPath ? [change.originalPath, change.path] : [change.path]))];
}
export function changeLabel(change: GitChange, staged: boolean): string {
if (isConflict(change)) return tr("Conflict");
const code = staged ? change.index : change.worktree;
switch (code) {
case "?": return tr("New");
case "A": return tr("Added");
case "M": return tr("Modified");
case "D": return tr("Deleted");
case "R": return tr("Renamed");
case "C": return tr("Copied");
case "T": return tr("Type changed");
default: return code;
}
}
export type DiffLineKind = "add" | "remove" | "range" | "context";
export function diffLineKind(line: string): DiffLineKind {
if (line.startsWith("+") && !line.startsWith("+++")) return "add";
if (line.startsWith("-") && !line.startsWith("---")) return "remove";
return line.startsWith("@@") ? "range" : "context";
}
export interface GraphNode extends GitGraphCommit { row: number; lane: number; color: number }
export interface GraphEdge { from: string; to: string; row: number; lane: number; parentLane: number; color: number; outside: boolean; endRow: number }
/** Lanes and colors for the commit graph. The six colors repeat, and lanes that are in use do not share a color. */
export function graphLayout(history: GitGraph | null | undefined): { nodes: GraphNode[]; edges: GraphEdge[]; lanes: number } {
const commits = history?.commits ?? [];
const lanes: (string | null)[] = [];
const nodes: GraphNode[] = [];
const edges: Omit<GraphEdge, "endRow">[] = [];
const colors = new Map<string, number>();
let nextColor = 0;
const ids = new Set(commits.map(commit => commit.id));
const reserve = (id: string, preferredColor?: number) => {
let lane = lanes.indexOf(id);
if (lane < 0) {
lane = lanes.indexOf(null);
if (lane < 0) lane = lanes.length;
lanes[lane] = id;
if (preferredColor === undefined) {
const activeColors = new Set(lanes.filter(value => value !== id && value !== null).map(value => colors.get(value!)));
preferredColor = nextColor++;
for (let offset = 0; offset < 6 && activeColors.has(preferredColor % 6); offset++) preferredColor = nextColor++;
}
colors.set(id, preferredColor % 6);
}
return lane;
};
let width = 1;
for (const [row, commit] of commits.entries()) {
const lane = reserve(commit.id);
const color = colors.get(commit.id)!;
nodes.push({ ...commit, row, lane, color });
lanes[lane] = null;
for (const [index, parent] of commit.parents.entries()) {
const parentLane = reserve(parent, index === 0 ? color : undefined);
edges.push({ from: commit.id, to: parent, row, lane, parentLane, color: index === 0 ? color : colors.get(parent)!, outside: !ids.has(parent) });
}
width = Math.max(width, lanes.length, lane + 1);
}
const rows = new Map(nodes.map(node => [node.id, node.row]));
return { nodes, edges: edges.map(edge => ({ ...edge, endRow: rows.get(edge.to) ?? nodes.length })), lanes: width };
}
+20
View File
@@ -0,0 +1,20 @@
// The shared state of one Git feature instance. The Source control pane, the diff tab, and the graph tab read it.
export interface DiffSelection {
path: string;
staged: boolean;
text: string;
error: boolean;
}
export class GitState {
/** The file of the diff tab. */
selected = $state<DiffSelection | null>(null);
/** The commit and the file of the graph tab. Tab transfers carry them. */
history = $state<{ selectedId: string | null; file: string | null }>({ selectedId: null, file: null });
/** Grows after each commit, push, or pull, so that the graph reads the history again. */
historyVersion = $state(0);
/** The diff request that may write `selected`. */
sequence = 0;
disposed = false;
}
+32
View File
@@ -0,0 +1,32 @@
// Launch rules: a feature with a rule starts its instance as soon as the rule wants it, without a view or a command.
// A feature without a rule loads at first need. `syncFeatures` in `src/lib/plugins/external.ts` applies the rules.
import type { FeatureId } from "./catalog.ts";
import { hasBackgroundSource, onBackgroundChange } from "./backgroundSettings.ts";
export interface LaunchRule {
/** True when the feature also runs in browser windows. Other features stay out of them. */
browserWindow: boolean;
/** True when the rule also starts the feature in the settings window. */
settingsWindow: boolean;
/** True when the instance must run now. */
wanted(): boolean;
/** Run `listener` after each change that can change `wanted`. Returns the function that stops it. */
subscribe(listener: () => void): () => void;
}
export const LAUNCH_RULES: Partial<Record<FeatureId, LaunchRule>> = {
// Background starts at the start of a window when a folder or an image is selected, and at once when the user selects one.
// The settings window shows the settings only, so the slideshow does not run there.
background: { browserWindow: true, settingsWindow: false, wanted: () => hasBackgroundSource(), subscribe: onBackgroundChange },
};
/** True when a feature runs in a window of this kind. */
export function runsInWindow(id: FeatureId, window: { browserWindow: boolean }): boolean {
return !window.browserWindow || !!LAUNCH_RULES[id]?.browserWindow;
}
/** True when the launch rule of a feature wants its instance now in a window of this kind. */
export function launchWanted(id: FeatureId, window: { settingsWindow: boolean }): boolean {
const rule = LAUNCH_RULES[id];
return !!rule && (!window.settingsWindow || rule.settingsWindow) && rule.wanted();
}
+45
View File
@@ -0,0 +1,45 @@
// Each feature module loads at most one time in each window. The host core never imports a feature module
// statically. `pnpm check:features` makes sure of this in the build output.
import { writable } from "svelte/store";
import type { FeatureId } from "./catalog.ts";
import type { FeatureModule } from "./types.ts";
const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
git: () => import("./git/index.ts"),
background: () => import("./background/index.ts"),
terminal: () => import("./terminal/index.ts"),
pdf: () => import("./pdf/index.ts"),
pm: () => import("./pm/index.ts"),
};
const modules = new Map<FeatureId, Promise<FeatureModule>>();
/** The last load error of each feature, for Settings → Features. */
export const featureErrors = writable<Partial<Record<FeatureId, string>>>({});
function setError(id: FeatureId, message: string | undefined) {
featureErrors.update(errors => {
const next = { ...errors };
if (message) next[id] = message; else delete next[id];
return next;
});
}
/** Import the module of a feature. After a failure, the next call tries again. */
export function loadFeature(id: FeatureId, load: () => Promise<FeatureModule> = imports[id]): Promise<FeatureModule> {
let pending = modules.get(id);
if (!pending) {
pending = load().then(module => { setError(id, undefined); return module; }, reason => {
modules.delete(id);
setError(id, String(reason));
throw reason;
});
modules.set(id, pending);
}
return pending;
}
/** True after the first load started in this window. Tests use it to prove that an off feature never loads. */
export function featureRequested(id: FeatureId): boolean {
return modules.has(id);
}
+101
View File
@@ -0,0 +1,101 @@
// 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`),
// the `terminal` section from the localStorage key of the Terminal plugin (`terminalSettings.ts`), and the
// `projectManagement` section and the tab view states from the kept Project Management settings (`pmSettings.ts`).
import { invoke, isTauri } from "@tauri-apps/api/core";
import { readSection, writeSection } from "../settings/store.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";
import { LEGACY_TERMINAL_KEY, migrateTerminal, writeTerminal, type TerminalMigrationHost } from "./terminalSettings.ts";
import { migrateProjectManagement, writeProjectManagement, type ProjectManagementMigrationHost } from "./pmSettings.ts";
/** What the host reports about one old plugin package. */
export interface LegacyPlugin {
id: string;
installed: boolean;
enabled: boolean;
/** The kept plugin settings, or null. */
settings: unknown;
}
/** 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 entry.followsPackage && legacy?.installed ? legacy.enabled : entry.defaultOn;
}
export interface MigrationHost {
read: () => unknown;
write: (value: unknown) => Promise<void>;
legacy: (ids: string[]) => Promise<LegacyPlugin[]>;
}
const desktopHost: MigrationHost = {
read: () => readSection("features"),
write: value => writeSection("features", value),
legacy: ids => invoke<LegacyPlugin[]>("features_legacy", { ids }),
};
const desktopBackground: BackgroundMigrationHost = {
missing: () => readSection("background") === undefined,
hasImage: () => hasImage(readAppearance()),
migrateFolder: async () => !!await invoke<string | null>("background_migrate"),
write: writeBackground,
};
const desktopProjectManagement: ProjectManagementMigrationHost = {
missing: () => readSection("projectManagement") === undefined,
write: writeProjectManagement,
get storage() { return localStorage; },
};
const desktopTerminal: TerminalMigrationHost = {
missing: () => readSection("terminal") === undefined,
legacy: () => localStorage.getItem(LEGACY_TERMINAL_KEY),
write: writeTerminal,
};
/**
* Give each feature without a stored switch the state of its old package, and make a missing `background`, `terminal`,
* or `projectManagement` section.
* It runs before the first render. When the host cannot report the packages, nothing is written, so the next start tries again.
* The `terminal` section needs no package report, so it migrates also then.
*/
export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground,
terminal: TerminalMigrationHost = desktopTerminal, projectManagement: ProjectManagementMigrationHost = desktopProjectManagement): Promise<FeatureId[]> {
try { await migrateTerminal(terminal); }
catch (reason) { console.error("RuneStone could not copy the old terminal settings.", reason); }
const current = host.read();
const stored = storedSwitches(current);
const missing = FEATURES.filter(entry => stored[entry.id] === undefined);
const backgroundOwner = featureEntry("background").owner;
const backgroundMissing = background.missing();
const pmOwner = featureEntry("pm").owner;
const pmMissing = projectManagement.missing();
const owners = [...new Set([...missing.map(entry => entry.owner), ...backgroundMissing ? [backgroundOwner] : [], ...pmMissing ? [pmOwner] : []])];
if (!owners.length) return [];
let legacy: LegacyPlugin[];
try { legacy = await host.legacy(owners); }
catch (reason) {
console.error("RuneStone could not read the old plugin packages. The feature defaults apply.", reason);
return [];
}
if (missing.length) {
const next: Record<string, unknown> = current && typeof current === "object" && !Array.isArray(current) ? { ...current as Record<string, unknown> } : {};
for (const entry of missing) next[entry.id] = legacySwitch(entry, legacy.find(item => item.id === entry.owner));
await host.write(next);
}
if (backgroundMissing) await migrateBackground(legacy.find(item => item.id === backgroundOwner), background);
if (pmMissing) await migrateProjectManagement(legacy.find(item => item.id === pmOwner), projectManagement);
return missing.map(entry => entry.id);
}
/** Workbench and Settings windows of the desktop app migrate. Browser windows start no feature, and the browser preview keeps the defaults. */
export function migrateFeaturesOnStart(): Promise<unknown> {
const browserWindow = new URLSearchParams(location.search).get("browserWindow") === "true";
if (!isTauri() || browserWindow) return Promise.resolve();
return migrateFeatures().catch(reason => console.error("The feature migration failed.", reason));
}
+239
View File
@@ -0,0 +1,239 @@
<script lang="ts">
// One PDF tab: the toolbar, the status line, the password form, and one page with its text layer.
// The document and its worker live as long as the tab. `close` releases both.
import { onMount } from "svelte";
import { message, t } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte";
import type { PluginDocumentContext } from "$lib/plugins/sdk";
import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine";
import { MAX_ZOOM, MIN_ZOOM, RESIZE_SETTLE_MS, ZOOM_STEP, nextRotation, outputScale, pageNumber, zoomLevel } from "./model";
let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props();
type Status = { key: string; values?: Record<string, string | number>; alert?: boolean };
let page = $state(1);
let count = $state(0);
let zoom = $state(1);
let rotation = $state(0);
let fit = $state(true);
let status = $state<Status>({ key: message("Loading PDF…") });
let asking = $state<"needed" | "incorrect" | null>(null);
let reloading = $state(false);
let failed = $state(false);
let scroller: HTMLDivElement;
let sheet: HTMLDivElement;
let pageInput: HTMLInputElement;
let passwordInput: HTMLInputElement | undefined = $state();
let disposed = false;
let pdf: PDFDocumentProxy | undefined;
let opened: OpenPdf | undefined;
let answer: ((password: string) => void) | undefined;
let render: RenderTask | undefined;
let text: TextLayer | undefined;
let revision = 0;
let queue: Promise<void> = Promise.resolve();
let loading: Promise<void> = Promise.resolve();
let closing: Promise<void> | undefined;
const ready = $derived(count > 0);
function fail(reason: unknown) {
if (disposed) return;
failed = true;
status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true };
}
/** Draw the current page again. A newer request cancels the older one. */
function schedule() {
const request = ++revision;
render?.cancel(); text?.cancel();
if (pdf && !disposed) status = { key: message("Loading page {page}…"), values: { page } };
queue = queue.then(async () => {
if (disposed || request !== revision || !pdf || scroller.clientWidth === 0) return;
const pdfPage = await pdf.getPage(page);
if (disposed || request !== revision) return;
const angle = (pdfPage.rotate + rotation) % 360;
if (fit) zoom = zoomLevel((scroller.clientWidth - 32) / pdfPage.getViewport({ scale: 1, rotation: angle }).width);
const viewport = pdfPage.getViewport({ scale: zoom, rotation: angle });
const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio);
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.floor(viewport.width * scale));
canvas.height = Math.max(1, Math.floor(viewport.height * scale));
canvas.style.width = `${viewport.width}px`;
canvas.style.height = `${viewport.height}px`;
canvas.setAttribute("role", "img");
// The measurement tool and the smoke tests find the page by this English name. Keep "PDF page N".
canvas.setAttribute("aria-label", $t("PDF page {page}", { page }));
const layer = document.createElement("div");
layer.className = "textLayer";
sheet.style.width = `${viewport.width}px`;
sheet.style.height = `${viewport.height}px`;
sheet.style.setProperty("--total-scale-factor", String(zoom));
sheet.replaceChildren(canvas, layer);
render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] });
await render.promise;
if (disposed || request !== revision) return;
text = new TextLayer({ textContentSource: pdfPage.streamTextContent(), container: layer, viewport });
await text.render();
if (disposed || request !== revision) return;
status = { key: message("Page {page} of {count}"), values: { page, count } };
pdfPage.cleanup();
}).catch(reason => { if (!disposed && request === revision) fail(reason); });
}
function go(value: number) {
if (!pdf) return;
page = pageNumber(value, pdf.numPages);
pageInput.value = String(page);
scroller.scrollTop = 0;
schedule();
}
function setZoom(value: number) { fit = false; zoom = zoomLevel(value); schedule(); }
async function load() {
failed = false;
status = { key: message("Loading PDF…") };
const bytes = await readBytes(file.path);
if (disposed) return;
opened = openPdf(bytes, (reason, next) => {
if (disposed) return;
answer = next;
asking = reason;
status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") };
queueMicrotask(() => passwordInput?.focus());
});
pdf = await opened.promise;
if (disposed) return;
page = pageNumber(page, pdf.numPages);
count = pdf.numPages;
schedule();
}
async function release() {
revision++;
render?.cancel(); text?.cancel();
await queue;
const current = opened;
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0;
sheet?.replaceChildren();
await current?.close();
}
async function reload() {
if (reloading || disposed) return;
reloading = true;
try {
await loading;
await release();
if (!disposed) await (loading = load());
} catch (reason) { fail(reason); }
finally { reloading = false; }
}
function unlock(event: SubmitEvent) {
event.preventDefault();
if (!passwordInput || !answer) return;
const value = passwordInput.value;
passwordInput.value = "";
asking = null;
status = { key: message("Loading PDF…") };
const next = answer;
answer = undefined;
next(value);
}
function pageKey(event: KeyboardEvent) {
if (event.ctrlKey || event.metaKey || event.altKey || !ready) return;
if (event.key === "PageDown" || event.key === "PageUp") {
event.preventDefault();
go(page + (event.key === "PageDown" ? 1 : -1));
}
}
/** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */
export function close(): Promise<void> {
if (closing) return closing;
disposed = true;
closing = release().then(() => loading).catch(() => {});
return closing;
}
onMount(() => {
loading = load().catch(fail);
// A fit-width page follows the width of the tab. The first size draws at once. Later sizes wait until the size settles.
let width = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const observer = new ResizeObserver(() => {
const next = scroller.clientWidth;
if (next === 0 || next === width) return;
const first = width === 0;
width = next;
clearTimeout(timer);
if (!fit) return;
if (first) schedule();
else timer = setTimeout(schedule, RESIZE_SETTLE_MS);
});
observer.observe(scroller);
return () => { observer.disconnect(); clearTimeout(timer); void close(); };
});
</script>
<section class="pdf-viewer" aria-label={$t("PDF Viewer")}>
<div class="toolbar" role="group" aria-label={$t("PDF controls")}>
<IconButton icon="up" label={$t("Previous page")} disabled={!ready || page <= 1} onclick={() => go(page - 1)} />
<input bind:this={pageInput} class="page" type="number" min="1" max={Math.max(count, 1)} value={page} disabled={!ready}
aria-label={$t("Page number")} onchange={event => { if (Number(event.currentTarget.value) !== page) go(Number(event.currentTarget.value)); }}
onkeydown={event => { if (event.key === "Enter") go(Number(event.currentTarget.value)); }} />
<span class="count">/ {ready ? count : "—"}</span>
<IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} />
<span class="separator" aria-hidden="true"></span>
<IconButton icon="zoom-out" label={$t("Zoom out")} disabled={!ready || zoom <= MIN_ZOOM} onclick={() => setZoom(zoom / ZOOM_STEP)} />
<span class="zoom">{ready ? `${Math.round(zoom * 100)}%` : "—"}</span>
<IconButton icon="zoom-in" label={$t("Zoom in")} disabled={!ready || zoom >= MAX_ZOOM} onclick={() => setZoom(zoom * ZOOM_STEP)} />
<IconButton icon="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; schedule(); }} />
<IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); schedule(); }} />
<IconButton icon="refresh" label={$t("Reload PDF")} disabled={reloading || (!ready && !failed)} onclick={() => void reload()} />
</div>
<p class="status" class:alert={status.alert} role={status.alert ? "alert" : "status"} aria-live={status.alert ? "assertive" : "polite"}>{$t(status.key, status.values)}</p>
{#if asking}
<form class="password" onsubmit={unlock}>
<label>{$t("PDF password")} <input bind:this={passwordInput} type="password" autocomplete="off" /></label>
<button class="text-button" type="submit">{$t("Unlock")}</button>
</form>
{/if}
<!-- The page area takes focus for Page Up and Page Down. -->
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
<div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF page. Use Page Up and Page Down to change pages.")} onkeydown={pageKey}>
<div bind:this={sheet} class="sheet"></div>
</div>
</section>
<style>
.pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; }
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 8px; border-bottom: 1px solid var(--rs-border); }
.page { box-sizing: border-box; width: 64px; height: 28px; margin-left: 4px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: right; }
.page:disabled { color: var(--rs-text-dim); }
.count { margin: 0 4px; color: var(--rs-text-dim); white-space: nowrap; }
.separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); }
.zoom { min-width: 44px; color: var(--rs-text-dim); text-align: center; white-space: nowrap; }
.status { margin: 0; padding: 4px 12px; font-size: 12px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
.status.alert { color: var(--rs-error); }
.password { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; }
.password input { box-sizing: border-box; height: 28px; margin-left: 4px; padding: 2px 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
.text-button:hover { background: var(--rs-bg-active); }
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; }
.scroll:focus-visible { outline-offset: -2px; }
/* A PDF page is paper: white in both themes. */
.sheet { position: relative; margin: 0 auto; background: white; box-shadow: 0 2px 10px #0003; }
.sheet :global(canvas) { display: block; }
/* The text layer geometry follows the viewer styles of PDF.js 6 (Apache-2.0). See THIRD_PARTY_NOTICES.md. */
.sheet :global(.textLayer) { position: absolute; inset: 0; overflow: clip; text-align: initial; line-height: 1; letter-spacing: normal; word-spacing: normal; text-size-adjust: none; forced-color-adjust: none; transform-origin: 0 0; --min-font-size: 1; --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); --min-font-size-inv: calc(1 / var(--min-font-size)); }
.sheet :global(.textLayer :is(span, br)) { position: absolute; color: transparent; white-space: pre; cursor: text; transform-origin: 0 0; user-select: text; }
.sheet :global(.textLayer > :not(.markedContent)), .sheet :global(.markedContent span:not(.markedContent)) { z-index: 1; --font-height: 0; font-size: calc(var(--text-scale-factor) * var(--font-height)); --scale-x: 1; --rotate: 0deg; transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv)); }
.sheet :global(.markedContent) { display: contents; }
.sheet :global(.textLayer ::selection) { background: color-mix(in srgb, var(--rs-selection) 65%, transparent); color: transparent; }
</style>
+69
View File
@@ -0,0 +1,69 @@
/// <reference types="vite/client" />
// PDF.js for the PDF Viewer feature. The worker, the character maps, the standard fonts, and the WebAssembly image
// decoders come from the app (`'self'`) as Vite assets, so a PDF never causes a network request.
// Each open document has its own worker. `close` stops it.
// The reference to the Vite types serves the unit test type check, which reaches this file through `loader.ts`.
import { getDocument, PDFWorker, PasswordResponses, type PDFDocumentLoadingTask, type PDFDocumentProxy } from "pdfjs-dist/build/pdf.min.mjs";
import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";
export { TextLayer, type PDFDocumentProxy, type RenderTask } from "pdfjs-dist/build/pdf.min.mjs";
// `build.assetsInlineLimit` in vite.config.js keeps these files out of the code, so each one is a file of the app.
// The JPEG 2000 and JBIG2 decoders are the only WebAssembly files that PDF.js asks for with `useWorkerFetch: false`.
// The viewer runs no PDF scripts (quickjs) and uses no ICC color profiles (qcms), as the PDF Viewer plugin did.
const assets = import.meta.glob<string>([
"/node_modules/pdfjs-dist/cmaps/*.bcmap",
"/node_modules/pdfjs-dist/standard_fonts/*.{pfb,ttf}",
"/node_modules/pdfjs-dist/wasm/{jbig2,openjpeg}.wasm",
], { query: "?url", import: "default", eager: true });
const folders: Record<string, string> = { cMapUrl: "cmaps", standardFontDataUrl: "standard_fonts", wasmUrl: "wasm" };
/** The app URL of a PDF.js data file, or undefined for an unknown kind or file. */
export function assetUrl(kind: string, filename: string): string | undefined {
const folder = folders[kind];
if (!folder || !/^[\w.-]+$/.test(filename)) return undefined;
return assets[`/node_modules/pdfjs-dist/${folder}/${filename}`];
}
/** PDF.js asks the window for its data files (`useWorkerFetch: false`). This class reads them from the app. */
class AppBinaryDataFactory {
async fetch({ kind, filename }: { kind: string; filename: string }): Promise<Uint8Array> {
const url = assetUrl(kind, filename);
if (!url) throw new Error(`PDF.js has no data file ${filename}.`);
const response = await fetch(url);
if (!response.ok) throw new Error(`PDF.js could not read ${filename}: ${response.status}.`);
return new Uint8Array(await response.arrayBuffer());
}
}
export interface OpenPdf {
/** Resolves with the document after the password, if the file needs one. */
promise: Promise<PDFDocumentProxy>;
/** Stop the load or release the document, and stop the worker. Later calls return the same promise. */
close(): Promise<void>;
}
/**
* Open the bytes of a PDF in a new worker. PDF.js calls `onPassword` for a protected file, with "incorrect" after a
* wrong password. The viewer calls `answer` with the next password.
*/
export function openPdf(data: Uint8Array, onPassword: (reason: "needed" | "incorrect", answer: (password: string) => void) => void): OpenPdf {
const port = new Worker(workerUrl, { type: "module", name: "PDF.js" });
const worker = PDFWorker.create({ port });
const task: PDFDocumentLoadingTask = getDocument({
data, worker, useWorkerFetch: false, BinaryDataFactory: AppBinaryDataFactory,
useSystemFonts: false, isImageDecoderSupported: false, enableXfa: false,
});
task.onPassword = (answer: (password: string) => void, reason: number) => {
onPassword(reason === PasswordResponses.INCORRECT_PASSWORD ? "incorrect" : "needed", answer);
};
let closing: Promise<void> | undefined;
return {
promise: task.promise,
close: () => closing ??= (async () => {
try { await task.destroy(); }
finally { worker.destroy(); port.terminate(); }
})(),
};
}
+32
View File
@@ -0,0 +1,32 @@
// The PDF Viewer feature. `loader.ts` imports this module when the first PDF tab opens. The file tree marks PDF files
// before that, through the document type of the catalog (`../pdfDocument.ts`).
// Each tab reads its file with `workspace_read_bytes` (64 MiB at most) and has its own PDF.js worker.
import { flushSync, mount, unmount } from "svelte";
import { tr } from "../../i18n/index.ts";
import { workspaceReadBytes } from "../../workspace/api.ts";
import type { FeatureContext, FeatureInstance } from "../types.ts";
import PdfViewer from "./PdfViewer.svelte";
export function start(_context: FeatureContext): FeatureInstance {
const tabs = new Set<() => Promise<void>>();
let stopped = false;
return {
mount() { throw new Error(tr("This view is unavailable.")); },
mountDocument(type, element, file) {
if (type !== "pdf") throw new Error(tr("This view is unavailable."));
if (stopped) throw new Error(tr("This feature is off."));
const viewer = mount(PdfViewer, { target: element, props: { file, readBytes: workspaceReadBytes } });
flushSync();
let closing: Promise<void> | undefined;
// Release the document and stop its worker first. Then remove the component.
const dispose = () => closing ??= viewer.close().then(() => unmount(viewer)).finally(() => { tabs.delete(dispose); });
tabs.add(dispose);
return dispose;
},
/** The host closes the PDF tabs first. Close what is left, so no worker stays. */
async dispose() {
stopped = true;
await Promise.allSettled([...tabs].map(dispose => dispose()));
},
};
}
+31
View File
@@ -0,0 +1,31 @@
// The limits of the PDF Viewer: page numbers, zoom, and the size of the page canvas.
export const MIN_ZOOM = 0.25;
export const MAX_ZOOM = 4;
/** Each zoom step multiplies or divides the zoom by this factor. */
export const ZOOM_STEP = 1.25;
/** A redraw after a resize waits until the size did not change for this time. */
export const RESIZE_SETTLE_MS = 150;
/** A whole page number from 1 to `count`. A value that is not a number gives page 1. */
export function pageNumber(value: number, count: number): number {
return Math.max(1, Math.min(count, Number.isFinite(value) ? Math.trunc(value) : 1));
}
/** A zoom factor from 0.25 to 4. A value that is not a finite number gives 1. */
export function zoomLevel(value: number): number {
return Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, Number.isFinite(value) ? value : 1));
}
/** The next clockwise rotation in degrees: 0, 90, 180, or 270. */
export function nextRotation(rotation: number): number {
return (rotation + 90) % 360;
}
/**
* The pixel scale of the page canvas. It follows the device pixel ratio up to 2, and keeps each side at most
* 8192 pixels and the area at most 16 million pixels, so a large page does not use too much memory.
*/
export function outputScale(width: number, height: number, deviceScale: number): number {
return Math.min(deviceScale || 1, 2, 8192 / width, 8192 / height, Math.sqrt(16_000_000 / (width * height)));
}
+4
View File
@@ -0,0 +1,4 @@
// The minified build of PDF.js has the same exports as the package entry.
declare module "pdfjs-dist/build/pdf.min.mjs" {
export * from "pdfjs-dist";
}
+7
View File
@@ -0,0 +1,7 @@
// The document identification of the PDF Viewer feature. It is in the main bundle, because the file tree marks
// PDF files before the feature module loads. The document ID is the workspace path, so two files never share a tab.
/** The document ID of a PDF file: its path with forward slashes. Any letter case of the extension matches. */
export function identifyPdf(path: string): { id: string } | null {
return /\.pdf$/i.test(path) ? { id: path.replaceAll("\\", "/") } : null;
}
+133
View File
@@ -0,0 +1,133 @@
// The Project Management feature. `loader.ts` imports this module at the first use: the ribbon button, a board tab,
// or a tab transfer from another window. The views are `planning` (All tasks) and `board-<hex of the board ID>`.
// The storage code (`storage/`) and the domain code (`model/`) use no host module, so the skill helper can bundle them.
import { invoke } from "@tauri-apps/api/core";
import { backgroundHub } from "../../plugins/backgrounds.ts";
import { onProjectManagementChange, readProjectManagement, readViewStates, writeProjectManagement, writeViewStates } from "../pmSettings.ts";
import type { FeatureContext, FeatureInstance } from "../types.ts";
import { boardKey, isManagedBoard, readCatalog } from "./storage/catalog.ts";
import { findLegacy, hasLegacy, type LegacyContent } from "./storage/legacy.ts";
import { isHiddenCard } from "./storage/persistence.ts";
import { message } from "./storage/message.ts";
import type { BoardReference } from "./storage/board.ts";
import { TaskStore } from "./model/store.ts";
import { hostMenus } from "./ui/host.ts";
import { mountPM, parseViewState, type PMViewState } from "./ui/ui.ts";
import { hostWorkspace } from "./workspace.ts";
import { boardOfView, boardViewId, PLANNING } from "./views.ts";
export function start(context: FeatureContext): FeatureInstance {
const workspace = hostWorkspace(context.onWorkspaceChange);
const preferences = readProjectManagement();
const stopPreferences = onProjectManagementChange(() => Object.assign(preferences, readProjectManagement()));
const states = new Map<string, PMViewState>(Object.entries(readViewStates()).map(([key, value]) => [key, parseViewState(value)]));
const dirty = new Set<string>();
let saveTimer: ReturnType<typeof setTimeout> | undefined;
let disposed = false;
const mounted = new Set<() => void>();
/** The legacy data of each workspace root. A migration reads it again. */
const legacy = new Map<string, Promise<LegacyContent>>();
const flush = () => {
clearTimeout(saveTimer);
if (!dirty.size) return;
writeViewStates(Object.fromEntries([...dirty].map(key => [key, structuredClone(states.get(key))])));
dirty.clear();
};
const persist = (id: string) => {
if (disposed) return;
dirty.add(id);
clearTimeout(saveTimer);
saveTimer = setTimeout(flush, 200);
};
const root = () => invoke<string | null>("workspace_last_path").catch(() => null);
const legacyContent = async (fresh = false) => {
const key = await root() ?? "";
if (fresh) legacy.delete(key);
let pending = legacy.get(key);
if (!pending) {
pending = findLegacy(workspace, () => { if (disposed) throw new Error(message("Project Management is off.")); });
pending.catch(() => legacy.delete(key));
legacy.set(key, pending);
}
return pending;
};
/** Copy the legacy boards, the root label file, and every legacy task note to `.runestone/pm/`, with backups. */
const migrate = async () => {
const store = new TaskStore(workspace, undefined, { legacy: true });
try {
await store.reload();
const cards = store.tasks.filter(task => !isHiddenCard(task.path)).map(task => task.id);
return await store.migrateStorage(cards);
} finally {
store.dispose();
void legacyContent(true).catch(() => undefined);
}
};
const openBoard = async (path: string, from?: string) => {
const snapshot = await readCatalog(workspace);
const board = isManagedBoard(path) ? snapshot.value.boards.find(item => boardKey(item.value.id) === path) : undefined;
if (!board) throw new Error(message("This board is unavailable. Refresh Project Management."));
const id = boardViewId(board.value.id);
context.setViewTitle(id, board.name);
if (from) context.replaceView(from, id); else context.openView(id);
};
function mountView(view: string, element: HTMLElement) {
const boardId = view === PLANNING ? null : boardOfView(view);
if (view !== PLANNING && !boardId) throw new Error(message("This view is unavailable."));
const reference: BoardReference | undefined = boardId ? { id: boardId, path: boardKey(boardId) } : undefined;
if (!states.has(view)) states.set(view, {});
const store = new TaskStore(workspace, reference, { legacy: false });
if (boardId) {
void readCatalog(workspace).then(snapshot => {
const board = snapshot.value.boards.find(item => item.value.id === boardId);
if (board && !disposed) context.setViewTitle(view, board.name);
}, () => undefined);
}
const cleanup = mountPM(element, store, {
ui: hostMenus,
backgrounds: backgroundHub,
state: states.get(view),
stateChanged: () => persist(view),
preferences,
savePreferences: value => writeProjectManagement(value),
openBoard: (path, replace) => openBoard(path, replace ? view : undefined),
openAll: replace => { if (replace) context.replaceView(view, PLANNING); else context.openView(PLANNING); },
boardRenamed: name => { if (boardId) context.setViewTitle(view, name); },
boardDeleted: () => { if (boardId) context.closeView(view); },
watch: workspace.watch,
legacy: { find: legacyContent, has: hasLegacy, migrate },
});
mounted.add(cleanup);
return () => { mounted.delete(cleanup); cleanup(); };
}
return {
mount: mountView,
async launch(view) {
if (view !== PLANNING) { context.openView(view); return; }
// The default board of the workspace is in the catalog. A missing, archived, or damaged default opens All tasks.
try {
const { value } = await readCatalog(workspace);
const board = value.boards.find(item => item.value.id === value.defaultBoardId && !item.archived);
if (board) { await openBoard(boardKey(board.value.id)); return; }
} catch { /* All tasks shows the storage problem. */ }
context.openView(PLANNING);
},
saveTabState: view => structuredClone(states.get(view) ?? {}),
restoreTabState(view, value) {
if (view !== PLANNING && !boardOfView(view)) throw new Error(message("This view is unavailable."));
states.set(view, parseViewState(value));
persist(view);
},
dispose() {
disposed = true;
flush();
stopPreferences();
for (const cleanup of [...mounted]) cleanup();
mounted.clear();
},
};
}
+77
View File
@@ -0,0 +1,77 @@
import { defaultBoard, type BoardDocument, type BoardList } from "../storage/board.ts";
import type { Task } from "./model.ts";
import { message } from "../storage/message.ts";
export interface TaskColumn {
list?: BoardList;
tasks: Task[];
allowCreate?: boolean;
}
/** Merge equal list names without changing the cards' board placements. */
export function allTaskColumns(boards: BoardDocument[], tasks: Task[]): TaskColumn[] {
const active = boards.filter(board => !board.archived);
const columns = new Map<string, TaskColumn>();
const assigned = new Set<string>();
const append = (list: BoardList | undefined, members: Task[], allowCreate = false) => {
const key = list ? `list:${list.name.trim().toLowerCase()}` : "unlisted";
let column = columns.get(key);
if (!column) {
column = { list: list ? { id: allowCreate ? list.id : key, name: list.name, status: list.status, collapsed: false } : undefined, tasks: [], allowCreate };
columns.set(key, column);
}
const included = new Set(column.tasks.map(task => task.id));
for (const task of members) if (!included.has(task.id)) {
column.tasks.push(task);
included.add(task.id);
}
};
for (const board of active) {
const members = tasks.filter(task => Object.hasOwn(task.placements ?? {}, board.id));
for (const task of members) assigned.add(task.id);
for (const list of board.value.lists)
append(list, members.filter(task => task.placements![board.id].listId === list.id));
const unlisted = members.filter(task => !board.value.lists.some(list => list.id === task.placements![board.id].listId));
if (unlisted.length) append(undefined, unlisted);
}
const standalone = tasks.filter(task => !assigned.has(task.id));
if (standalone.length || !active.length) {
for (const list of defaultBoard("all-tasks").lists)
append(list, standalone.filter(task => task.status === list.status), true);
}
return [...columns.values()];
}
export interface TaskBoardGroup {
boardIds: string[];
name: string;
tasks: Task[];
}
/** Keep shared cards once and name every board represented in this column. */
export function allTaskGroups(boards: BoardDocument[], column: TaskColumn): TaskBoardGroup[] {
const active = boards.filter(board => !board.archived);
const groups = new Map<string, TaskBoardGroup>();
for (const task of column.tasks) {
const owners = active.filter(board => {
const placement = task.placements?.[board.id];
if (!placement) return false;
const list = board.value.lists.find(list => list.id === placement.listId);
return column.list
? list?.name.trim().toLowerCase() === column.list.name.trim().toLowerCase()
: !list;
});
const boardIds = owners.map(board => board.id);
const key = JSON.stringify(boardIds);
let group = groups.get(key);
if (!group) {
group = { boardIds, name: owners.length ? owners.map(board => board.name).join(" · ") : message("No active board"), tasks: [] };
groups.set(key, group);
}
group.tasks.push(task);
}
return [...groups.values()].sort((a, b) => {
const order = (group: TaskBoardGroup) => group.boardIds.length ? active.findIndex(board => board.id === group.boardIds[0]) : active.length;
return order(a) - order(b);
});
}

Some files were not shown because too many files have changed in this diff Show More