Compare commits
3
Commits
135e6d6d92
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1878bcfcf4 | ||
|
|
1f3179facc | ||
|
|
b52eeb14a1 |
@@ -0,0 +1,2 @@
|
|||||||
|
# Tauri writes these files with LF line endings on each build.
|
||||||
|
src-tauri/permissions/autogenerated/*.toml text eol=lf
|
||||||
@@ -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.
|
|
||||||
@@ -2,8 +2,10 @@
|
|||||||
|
|
||||||
RuneStone is a desktop workspace for Markdown notes, code, and project work in ordinary local files.
|
RuneStone is a desktop workspace for Markdown notes, code, and project work in ordinary local files.
|
||||||
A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface (`src/`).
|
A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface (`src/`).
|
||||||
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.
|
The [development guide](docs/development.md#architecture) maps the source folders.
|
||||||
|
The public repository is `https://github.com/KnottyWyvern-GH/RuneStone`. Its releases page holds the installers, the browser engine ZIPs, and the SDK packages.
|
||||||
|
|
||||||
## Skills
|
## Skills
|
||||||
|
|
||||||
@@ -24,6 +26,7 @@ The [development guide](docs/development.md#architecture) maps the source folder
|
|||||||
| `pnpm test` | Unit tests (`tests/unit/`) |
|
| `pnpm test` | Unit tests (`tests/unit/`) |
|
||||||
| `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust tests |
|
| `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust tests |
|
||||||
| `pnpm check:menus` | Menu surface inventory |
|
| `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 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: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). |
|
| `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 +120,5 @@ Rules from the owner:
|
|||||||
|
|
||||||
## Subagents
|
## 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.
|
The `runestone-project-management` skill maps task types to models and lists what each brief must contain.
|
||||||
|
|||||||
@@ -0,0 +1,202 @@
|
|||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
RuneStone
|
||||||
|
Copyright 2026 Knotty Wyvern
|
||||||
|
|
||||||
|
This product includes third-party software. See THIRD_PARTY_NOTICES.md for its licenses.
|
||||||
@@ -4,29 +4,25 @@ RuneStone is a desktop workspace for Markdown notes, code, and project work that
|
|||||||
|
|
||||||
## Install and start
|
## Install and start
|
||||||
|
|
||||||
Download the installer for your computer.
|
On Windows 10 or 11 (x64):
|
||||||
|
|
||||||
| Platform | Installer | Status |
|
1. Download [RuneStone_1.0.0_x64-setup.exe](https://github.com/KnottyWyvern-GH/RuneStone/releases/download/v1.0.0/RuneStone_1.0.0_x64-setup.exe).
|
||||||
| --- | --- | --- |
|
2. Open the installer and complete setup.
|
||||||
| Windows 10 or 11, x64 | [RuneStone_0.1.49_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone_Releases/releases/download/v0.1.49/RuneStone_0.1.49_x64-setup.exe) | Primary platform |
|
3. Open RuneStone from the Start menu.
|
||||||
| macOS, Apple silicon | [RuneStone_0.1.44_aarch64.dmg](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_aarch64.dmg) | Experimental: ad hoc signed, not notarized |
|
|
||||||
| Linux, amd64 | [RuneStone_0.1.44_amd64.deb](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_amd64.deb) | Experimental: built on Ubuntu 26.04.1, needs GLIBC 2.39 or newer |
|
|
||||||
|
|
||||||
- **Windows:** Open the installer and complete setup. Then open RuneStone from the Start menu.
|
The built-in browser needs a separate engine download of about 160 MB. A browser tab offers it on first use.
|
||||||
- **macOS:** Open the disk image and drag RuneStone into Applications. Then open RuneStone from Applications.
|
|
||||||
- **Linux:** Run `sudo apt install ./RuneStone_0.1.44_amd64.deb` in the download folder. Then open RuneStone from your applications menu.
|
|
||||||
|
|
||||||
You do not need developer tools.
|
|
||||||
On Windows, the built-in browser needs a separate engine download of about 160 MB. A browser tab offers it on first use.
|
|
||||||
For checksums, updates, and reinstalls, see [Installation and updates](docs/installation.md).
|
For checksums, updates, and reinstalls, see [Installation and updates](docs/installation.md).
|
||||||
|
|
||||||
|
macOS and Linux have no 1.0.0 package. Build RuneStone from source on these systems. See [Build Linux packages](docs/builds.md#build-linux-packages) or [macOS packages](docs/builds.md#macos-packages).
|
||||||
|
|
||||||
## What you can do
|
## What you can do
|
||||||
|
|
||||||
- Write Markdown with live formatting, editable tables, table formulas, images, and Mermaid diagrams.
|
- Write Markdown with live formatting, editable tables, table formulas, images, and Mermaid diagrams.
|
||||||
- Switch between the Write, Source, Read, and Split views.
|
- Switch between the Write, Source, Read, and Split views.
|
||||||
- Find files, search a workspace, and resolve changes that other tools make to your files.
|
- Find files, search a workspace, and resolve changes that other tools make to your files.
|
||||||
- Open web pages in browser tabs beside your documents.
|
- Open web pages in browser tabs beside your documents.
|
||||||
- Add optional plugins, such as Terminal, Git, Project Management, PDF Viewer, and CSV Viewer.
|
- Use Git source control, a terminal, a PDF viewer, Project Management boards, and a background slideshow. Each one has an off switch in **Settings → Features**.
|
||||||
|
- Add optional plugins from plugin ZIP files.
|
||||||
|
|
||||||
## Find help
|
## Find help
|
||||||
|
|
||||||
@@ -47,6 +43,10 @@ When you report a problem to the maintainer, include the app version, operating
|
|||||||
- Read the [interface design reference](docs/ui-design.md) before you change the interface.
|
- Read the [interface design reference](docs/ui-design.md) before you change the interface.
|
||||||
- See [product boundaries](docs/development.md#product-boundaries) for exclusions and architecture constraints.
|
- See [product boundaries](docs/development.md#product-boundaries) for exclusions and architecture constraints.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
RuneStone uses the [Apache License 2.0](LICENSE). See also [NOTICE](NOTICE) and the [third-party notices](THIRD_PARTY_NOTICES.md).
|
||||||
|
|
||||||
## Maintainer
|
## Maintainer
|
||||||
|
|
||||||
[kwyvern-gh](https://github.com/kwyvern-gh)
|
[KnottyWyvern-GH](https://github.com/KnottyWyvern-GH)
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "runestone-browser",
|
"name": "runestone-browser",
|
||||||
"version": "0.1.8",
|
"version": "0.1.11",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "runestone-browser",
|
"name": "runestone-browser",
|
||||||
"version": "0.1.8",
|
"version": "0.1.11",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ghostery/adblocker": "2.18.2",
|
"@ghostery/adblocker": "2.18.2",
|
||||||
"ipaddr.js": "2.3.0"
|
"ipaddr.js": "2.3.0"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "runestone-browser",
|
"name": "runestone-browser",
|
||||||
"version": "0.1.8",
|
"version": "0.1.11",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Isolated browser runtime included with RuneStone",
|
"description": "Isolated browser runtime included with RuneStone",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
@@ -5,7 +5,27 @@ import os from 'node:os';
|
|||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import electron from 'electron';
|
import electron from 'electron';
|
||||||
const directory = await mkdtemp(path.join(os.tmpdir(), 'runestone-plugin-browser-'));
|
const directory = await mkdtemp(path.join(os.tmpdir(), 'runestone-plugin-browser-'));
|
||||||
|
// A two-frame GIF that the server gives only one time, as some image hosts do.
|
||||||
|
const onceGif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==', 'base64');
|
||||||
|
let onceGifServed = false;
|
||||||
|
// The same GIF with 7 MB of comment blocks, so that Copy image needs more than one part.
|
||||||
|
const comment = Buffer.concat([Buffer.from([255]), Buffer.alloc(255, 0x61)]);
|
||||||
|
const largeGif = Buffer.concat([onceGif.subarray(0, 32), Buffer.from([0x21, 0xfe]), ...Array(28_000).fill(comment), Buffer.from([0]), onceGif.subarray(32)]);
|
||||||
const server = http.createServer((req, res) => {
|
const server = http.createServer((req, res) => {
|
||||||
|
if (req.url === '/direct.gif') {
|
||||||
|
res.writeHead(200, { 'Content-Type': 'image/gif' });
|
||||||
|
return res.end(largeGif);
|
||||||
|
}
|
||||||
|
if (req.url === '/large.gif') {
|
||||||
|
res.writeHead(200, { 'Content-Type': 'image/gif' });
|
||||||
|
return res.end(largeGif);
|
||||||
|
}
|
||||||
|
if (req.url === '/once.gif') {
|
||||||
|
if (onceGifServed) { res.writeHead(200, { 'Content-Type': 'text/html' }); return res.end('Invalid request'); }
|
||||||
|
onceGifServed = true;
|
||||||
|
res.writeHead(200, { 'Content-Type': 'image/gif' });
|
||||||
|
return res.end(onceGif);
|
||||||
|
}
|
||||||
if (req.url === '/picture.png') {
|
if (req.url === '/picture.png') {
|
||||||
res.writeHead(200, { 'Content-Type': 'image/png' });
|
res.writeHead(200, { 'Content-Type': 'image/png' });
|
||||||
return res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII=', 'base64'));
|
return res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII=', 'base64'));
|
||||||
|
|||||||
@@ -31,6 +31,31 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
|
|||||||
pageFocusStates.set(wc, enabled);
|
pageFocusStates.set(wc, enabled);
|
||||||
if (enabled) wc.focus();
|
if (enabled) wc.focus();
|
||||||
}
|
}
|
||||||
|
// The last image that Copy image took from a page. RuneStone gets it in parts when the user pastes.
|
||||||
|
let copied = null;
|
||||||
|
const COPIED_PART = 3_000_000;
|
||||||
|
// The page holds the encoded image. Its bytes keep all frames of a GIF, and the website gets no second request.
|
||||||
|
async function loadedImage(wc, url) {
|
||||||
|
if (!wc.debugger.isAttached()) { wc.debugger.attach('1.3'); pageFocusStates.delete(wc); }
|
||||||
|
await wc.debugger.sendCommand('Page.enable');
|
||||||
|
try {
|
||||||
|
const href = value => { try { return new URL(value).href; } catch { return ''; } };
|
||||||
|
const nodes = [(await wc.debugger.sendCommand('Page.getResourceTree')).frameTree];
|
||||||
|
for (const node of nodes) {
|
||||||
|
// An image that opens as the page itself is the main resource of its frame.
|
||||||
|
const page = href(node.frame.url) === url && /^image\//.test(node.frame.mimeType) ? node.frame : undefined;
|
||||||
|
const resource = page ?? node.resources?.find(item => item.type === 'Image' && href(item.url) === url);
|
||||||
|
if (resource) {
|
||||||
|
const { content, base64Encoded } = await wc.debugger.sendCommand('Page.getResourceContent', { frameId: node.frame.id, url: resource.url });
|
||||||
|
const data = Buffer.from(content, base64Encoded ? 'base64' : 'utf8');
|
||||||
|
const valid = /^image\/(?:gif|png|jpeg|webp|avif|bmp)$/.test(resource.mimeType) && data.length > 0 && data.length <= 20_000_000;
|
||||||
|
return valid ? { mime: resource.mimeType, data } : null;
|
||||||
|
}
|
||||||
|
nodes.push(...(node.childFrames ?? []));
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
} finally { await wc.debugger.sendCommand('Page.disable').catch(() => {}); }
|
||||||
|
}
|
||||||
function emulateViewport(item) {
|
function emulateViewport(item) {
|
||||||
if (!item.viewport) return;
|
if (!item.viewport) return;
|
||||||
const { width, height } = item.viewport, scale = item.scale;
|
const { width, height } = item.viewport, scale = item.scale;
|
||||||
@@ -141,7 +166,9 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
|
|||||||
changed();
|
changed();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
wc.on('did-navigate', (_event, url) => { store.visit(profileId, url, item.title); changed(); });
|
// Each new document gets a renderer widget without device emulation. A page that replaces itself before it finishes
|
||||||
|
// loading, as Google does, otherwise keeps a scale of 1 and grows when the next document finishes.
|
||||||
|
wc.on('did-navigate', (_event, url) => { emulateViewport(item); store.visit(profileId, url, item.title); changed(); });
|
||||||
wc.on('did-navigate-in-page', (_event, _url, main) => { if (main) { item.epoch++; agent.revokeAll(); } changed(); });
|
wc.on('did-navigate-in-page', (_event, _url, main) => { if (main) { item.epoch++; agent.revokeAll(); } changed(); });
|
||||||
wc.on('page-title-updated', (_event, title) => { item.title = title.slice(0, 200); changed(); });
|
wc.on('page-title-updated', (_event, title) => { item.title = title.slice(0, 200); changed(); });
|
||||||
wc.on('page-favicon-updated', (_event, urls) => {
|
wc.on('page-favicon-updated', (_event, urls) => {
|
||||||
@@ -248,7 +275,13 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
|
|||||||
switch (args.action) {
|
switch (args.action) {
|
||||||
case 'copyLink': if (context.linkURL) clipboard.writeText(context.linkURL); break;
|
case 'copyLink': if (context.linkURL) clipboard.writeText(context.linkURL); break;
|
||||||
case 'copyImageAddress': if (context.srcURL) clipboard.writeText(context.srcURL); break;
|
case 'copyImageAddress': if (context.srcURL) clipboard.writeText(context.srcURL); break;
|
||||||
case 'copyImage': if (context.hasImageContents) wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale)); break;
|
case 'copyImage': {
|
||||||
|
if (!context.hasImageContents) break;
|
||||||
|
wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale));
|
||||||
|
const image = context.srcURL ? await loadedImage(wc, context.srcURL).catch(() => null) : null;
|
||||||
|
copied = image && { token: randomUUID(), tabId: current.id, url: context.srcURL, ...image };
|
||||||
|
return copied && { copied: { token: copied.token, url: copied.url, mime: copied.mime, size: copied.data.length } };
|
||||||
|
}
|
||||||
case 'openExternal': if (context.linkURL) await openExternal(context.linkURL); break;
|
case 'openExternal': if (context.linkURL) await openExternal(context.linkURL); break;
|
||||||
case 'saveImage': case 'saveLink': {
|
case 'saveImage': case 'saveLink': {
|
||||||
const url = args.action === 'saveImage' ? context.srcURL : context.linkURL;
|
const url = args.action === 'saveImage' ? context.srcURL : context.linkURL;
|
||||||
@@ -259,6 +292,22 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
case 'linkAt': {
|
||||||
|
// A middle-click on a link opens it in a new tab. The isolated world keeps page scripts from changing the answer.
|
||||||
|
if (![args.x, args.y].every(value => Number.isInteger(value) && value >= 0 && value <= 5120)) throw new Error('Invalid pointer position.');
|
||||||
|
const href = await tab(args.tabId).view.webContents.executeJavaScriptInIsolatedWorld(902, [{
|
||||||
|
code: `document.elementFromPoint(${args.x}, ${args.y})?.closest('a[href], area[href]')?.href ?? ''`,
|
||||||
|
}]).catch(() => '');
|
||||||
|
try { return { url: href ? webUrl(href, { blank: false }) : null }; } catch { return { url: null }; }
|
||||||
|
}
|
||||||
|
case 'copiedImage': {
|
||||||
|
// A part stays below the line limit of the host connection.
|
||||||
|
if (!copied || copied.token !== args.token || copied.tabId !== args.tabId || !Number.isSafeInteger(args.offset) || args.offset < 0 || args.offset >= copied.data.length) {
|
||||||
|
throw new Error('The copied image is no longer available.');
|
||||||
|
}
|
||||||
|
const end = Math.min(copied.data.length, args.offset + COPIED_PART);
|
||||||
|
return { data: copied.data.subarray(args.offset, end).toString('base64'), next: end < copied.data.length ? end : null };
|
||||||
|
}
|
||||||
case 'input': {
|
case 'input': {
|
||||||
const current = tab(args.tabId), wc = current.view.webContents;
|
const current = tab(args.tabId), wc = current.view.webContents;
|
||||||
const input = args.input;
|
const input = args.input;
|
||||||
|
|||||||
@@ -124,6 +124,64 @@ app.whenReady().then(async () => {
|
|||||||
await assert.rejects(engine.command('contextAction', { tabId: first, token: 'expired', action: 'saveImage' }), /no longer available/);
|
await assert.rejects(engine.command('contextAction', { tabId: first, token: 'expired', action: 'saveImage' }), /no longer available/);
|
||||||
await wc.executeJavaScript('document.querySelector("#save-image").remove();true;');
|
await wc.executeJavaScript('document.querySelector("#save-image").remove();true;');
|
||||||
passed.push('Unicode text, native image context menus, saved image bytes and stale menu protection work');
|
passed.push('Unicode text, native image context menus, saved image bytes and stale menu protection work');
|
||||||
|
// Copy image keeps the bytes that the page loaded. The test server gives this GIF only one time.
|
||||||
|
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<img id="copy-image" src="${process.env.RS_TEST_URL}once.gif" style="position:absolute;left:400px;top:40px;width:80px;height:80px">');true;`);
|
||||||
|
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete'));
|
||||||
|
const menus = events.length;
|
||||||
|
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
|
||||||
|
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
|
||||||
|
await until(() => events.slice(menus).some(event => event.event === 'context-menu' && event.hasImageContents));
|
||||||
|
const imageMenu = events.findLast(event => event.event === 'context-menu');
|
||||||
|
const { copied } = await engine.command('contextAction', { tabId: first, token: imageMenu.token, action: 'copyImage' });
|
||||||
|
assert.deepEqual([copied.url, copied.mime, copied.size], [`${process.env.RS_TEST_URL}once.gif`, 'image/gif', 85]);
|
||||||
|
const part = await engine.command('copiedImage', { tabId: first, token: copied.token, offset: 0 });
|
||||||
|
const bytes = Buffer.from(part.data, 'base64');
|
||||||
|
assert.equal(bytes.subarray(0, 6).toString(), 'GIF89a');
|
||||||
|
assert.equal(bytes.length, 85);
|
||||||
|
assert.equal(part.next, null);
|
||||||
|
await assert.rejects(engine.command('copiedImage', { tabId: first, token: copied.token, offset: 85 }), /no longer available/);
|
||||||
|
await assert.rejects(engine.command('copiedImage', { tabId: 'other', token: copied.token, offset: 0 }), /no longer available/);
|
||||||
|
// A large image comes in parts that stay below the line limit of the host.
|
||||||
|
await wc.executeJavaScript(`document.querySelector("#copy-image").src = "${process.env.RS_TEST_URL}large.gif";true;`);
|
||||||
|
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete && document.querySelector("#copy-image").naturalWidth === 1'));
|
||||||
|
const largeMenus = events.length;
|
||||||
|
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
|
||||||
|
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
|
||||||
|
await until(() => events.slice(largeMenus).some(event => event.event === 'context-menu' && event.hasImageContents));
|
||||||
|
const large = (await engine.command('contextAction', { tabId: first, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
|
||||||
|
const parts = [];
|
||||||
|
for (let offset = 0; offset !== null;) {
|
||||||
|
const next = await engine.command('copiedImage', { tabId: first, token: large.token, offset });
|
||||||
|
assert.ok(next.data.length <= 4_000_000);
|
||||||
|
parts.push(Buffer.from(next.data, 'base64')); offset = next.next;
|
||||||
|
}
|
||||||
|
const whole = Buffer.concat(parts);
|
||||||
|
assert.ok(parts.length >= 3);
|
||||||
|
assert.equal(whole.length, large.size);
|
||||||
|
assert.equal(whole.subarray(0, 6).toString(), 'GIF89a');
|
||||||
|
assert.equal(whole.at(-1), 0x3b);
|
||||||
|
await wc.executeJavaScript('document.querySelector("#copy-image").remove();true;');
|
||||||
|
// A middle-click asks for the link under the pointer. Only web links count.
|
||||||
|
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<a id="middle-link" href="${process.env.RS_TEST_URL}linked" style="position:absolute;left:600px;top:40px;width:120px;height:30px;display:block">Linked</a><a id="script-link" href="javascript:void(0)" style="position:absolute;left:600px;top:100px;width:120px;height:30px;display:block">Script</a>');true;`);
|
||||||
|
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 650, y: 50 }), { url: `${process.env.RS_TEST_URL}linked` });
|
||||||
|
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 650, y: 110 }), { url: null });
|
||||||
|
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 900, y: 600 }), { url: null });
|
||||||
|
await assert.rejects(engine.command('linkAt', { tabId: first, x: -1, y: 50 }), /Invalid pointer position/);
|
||||||
|
await wc.executeJavaScript('document.querySelector("#middle-link").remove(); document.querySelector("#script-link").remove();true;');
|
||||||
|
// An image that opens as the page itself is the main resource of the tab.
|
||||||
|
const direct = (await engine.command('newTab', { url: `${process.env.RS_TEST_URL}direct.gif` })).tabId;
|
||||||
|
const directContents = engine.tabs.get(direct).view.webContents;
|
||||||
|
await until(async () => await directContents.executeJavaScript('document.images[0]?.complete === true').catch(() => false));
|
||||||
|
const box = await directContents.executeJavaScript('(({ x, y, width, height }) => ({ x: Math.floor(x + width / 2), y: Math.floor(y + height / 2) }))(document.images[0].getBoundingClientRect())');
|
||||||
|
const directMenus = events.length;
|
||||||
|
await engine.command('input', { tabId: direct, input: { type: 'mouseDown', ...box, button: 'right' } });
|
||||||
|
await engine.command('input', { tabId: direct, input: { type: 'mouseUp', ...box, button: 'right' } });
|
||||||
|
await until(() => events.slice(directMenus).some(event => event.event === 'context-menu' && event.tabId === direct && event.hasImageContents));
|
||||||
|
const directCopy = (await engine.command('contextAction', { tabId: direct, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
|
||||||
|
assert.deepEqual([directCopy.mime, directCopy.size], ['image/gif', large.size]);
|
||||||
|
await engine.command('closeTab', { tabId: direct });
|
||||||
|
passed.push('Copy image keeps the loaded GIF bytes without a second request, also for an image that opens as the page');
|
||||||
|
passed.push('A middle-click finds the web link under the pointer');
|
||||||
await until(async () => await wc.executeJavaScript("getComputedStyle(document.querySelector('.advertisement')).display") === 'none');
|
await until(async () => await wc.executeJavaScript("getComputedStyle(document.querySelector('.advertisement')).display") === 'none');
|
||||||
assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined');
|
assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined');
|
||||||
passed.push('network and cosmetic ad blocking remain active');
|
passed.push('network and cosmetic ad blocking remain active');
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ app.setPath('userData', process.env.RS_INTERACTION_ROOT);
|
|||||||
app.on('window-all-closed', () => {});
|
app.on('window-all-closed', () => {});
|
||||||
app.whenReady().then(async () => {
|
app.whenReady().then(async () => {
|
||||||
let framePending = false;
|
let framePending = false;
|
||||||
const engine = await createEngine({ directory: process.env.RS_INTERACTION_ROOT, canEmitFrame: () => !framePending, emit: value => {
|
// The fixture server of the smoke test is on 127.0.0.1. The engine blocks local addresses for other hosts.
|
||||||
|
const engine = await createEngine({ directory: process.env.RS_INTERACTION_ROOT, allowedTestHosts: new Set(['127.0.0.1']), canEmitFrame: () => !framePending, emit: value => {
|
||||||
if (value.event === 'frame') framePending = true;
|
if (value.event === 'frame') framePending = true;
|
||||||
process.send?.({ event: value }, () => { if (value.event === 'frame') framePending = false; });
|
process.send?.({ event: value }, () => { if (value.event === 'frame') framePending = false; });
|
||||||
} });
|
} });
|
||||||
|
|||||||
@@ -20,4 +20,4 @@ Build procedure: frozen pnpm install; Browser npm ci, checks, tests, engine test
|
|||||||
|
|
||||||
Artifact: `releases/0.1.44/RuneStone_0.1.44_aarch64.dmg`. Logs and packaging scripts remain under `output/macos-installer-0.1.44/`.
|
Artifact: `releases/0.1.44/RuneStone_0.1.44_aarch64.dmg`. Logs and packaging scripts remain under `output/macos-installer-0.1.44/`.
|
||||||
|
|
||||||
Published alongside the existing Windows installer in the [Gitea 0.1.44 release](https://git.knottywyvern.com/kwyvern/RuneStone/releases/tag/v0.1.44), with `macos-release-notes.md` as a separate attachment. The existing release tag was retained.
|
Published alongside the existing Windows installer in the Gitea 0.1.44 release, with `macos-release-notes.md` as a separate attachment. The existing release tag was retained.
|
||||||
|
|||||||
+2
-2
@@ -37,7 +37,7 @@ Output:
|
|||||||
The script prints `Installer available: <path>` when it completes.
|
The script prints `Installer available: <path>` when it completes.
|
||||||
After a successful build, the version fields keep the new version.
|
After a successful build, the version fields keep the new version.
|
||||||
|
|
||||||
Example, from the 0.1.44 download link in the README: version `0.1.44` gives `releases/0.1.44/RuneStone_0.1.44_x64-setup.exe`.
|
Example, from the 1.0.0 download link in the README: version `1.0.0` gives `releases/1.0.0/RuneStone_1.0.0_x64-setup.exe`.
|
||||||
|
|
||||||
### What the script does
|
### What the script does
|
||||||
|
|
||||||
@@ -229,7 +229,7 @@ Procedure, in the RuneStone repository root. The commands use the Tauri CLI from
|
|||||||
|
|
||||||
If the build fails, restore the previous version fields.
|
If the build fails, restore the previous version fields.
|
||||||
|
|
||||||
Example, from the 0.1.44 download link in the README: the x86_64 Debian build of version `0.1.44` is `RuneStone_0.1.44_amd64.deb`.
|
Example, from `productName` and `version` in `src-tauri/tauri.conf.json`: the x86_64 Debian build of version `1.0.0` is `RuneStone_1.0.0_amd64.deb`.
|
||||||
|
|
||||||
`pnpm build:installer` does not build Linux packages. It stops on operating systems other than Windows.
|
`pnpm build:installer` does not build Linux packages. It stops on operating systems other than Windows.
|
||||||
Linux packages do not include the browser engine, and no Linux engine is published yet. The browser tab says that no engine is available for the platform.
|
Linux packages do not include the browser engine, and no Linux engine is published yet. The browser tab says that no engine is available for the platform.
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
313f15e68c3b3a6eec9fb223548c9843e6e87af5566885088ddbf7434742e100 RuneStone_0.1.44_amd64.deb
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
72b17356fdb42a58051a84961e36fdd893ff26e210e7f855b8a96cde69ce946e RuneStone_1.0.0_x64-setup.exe
|
||||||
+1
-1
@@ -114,4 +114,4 @@ Abort stops the display at once. A blocked network read can continue until the r
|
|||||||
Plugins keep full application access. This API does not add a permission sandbox.
|
Plugins keep full application access. This API does not add a permission sandbox.
|
||||||
The API does not include context sources, remote model servers, or credential storage.
|
The API does not include context sources, remote model servers, or credential storage.
|
||||||
|
|
||||||
For tests, see `tests/unit/plugins/completion.spec.ts`. For a provider plugin, see the [Local Autocomplete trial guide](https://git.knottywyvern.com/kwyvern/RuneStone_LocalModel/src/branch/main/docs/trial-guide.md).
|
For tests, see `tests/unit/plugins/completion.spec.ts`.
|
||||||
|
|||||||
+164
-2
@@ -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.
|
- Evidence: All 11 slideshow unit tests, TypeScript checks, and the settings browser check pass.
|
||||||
- Limits: Native desktop appearance requires user review.
|
- Limits: Native desktop appearance requires user review.
|
||||||
- Replaces: The 800-millisecond fade rule in the interface guide.
|
- 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
|
### 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.
|
- 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.
|
- 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.
|
- 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
|
### 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.
|
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.
|
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.
|
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
|
### 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.
|
- 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.
|
- 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.
|
- 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
|
### UI-043 — Opaque menus
|
||||||
|
|
||||||
@@ -826,6 +830,7 @@ Native shell, background image, and desktop acceptance remain open.
|
|||||||
- Shared implementation: `tokens.css` (`--rs-menu-bg`, `--rs-menu-active-bg`, `--rs-menu-backdrop`, and the `--rs-image-menu-*` tokens), `menu.css`, `appearance.ts` and `backgrounds.ts` (the image switch), and `actionMenu.ts` (popover submenus).
|
- Shared implementation: `tokens.css` (`--rs-menu-bg`, `--rs-menu-active-bg`, `--rs-menu-backdrop`, and the `--rs-image-menu-*` tokens), `menu.css`, `appearance.ts` and `backgrounds.ts` (the image switch), and `actionMenu.ts` (popover submenus).
|
||||||
- Evidence: `tests/smoke/menus/consistency.smoke.mjs` checks an opaque menu without an image, and 92% with a blur over an image. Screenshots are in `output/phase-5a/5a-3/` in the main checkout.
|
- Evidence: `tests/smoke/menus/consistency.smoke.mjs` checks an opaque menu without an image, and 92% with a blur over an image. Screenshots are in `output/phase-5a/5a-3/` in the main checkout.
|
||||||
- Replaces: [UI-013](#ui-013--translucent-menu-surfaces).
|
- Replaces: [UI-013](#ui-013--translucent-menu-surfaces).
|
||||||
|
- Replaced by: [UI-061](#ui-061--translucent-menus-and-hover-fills-over-images) replaces the image rule. Menus without an image stay opaque.
|
||||||
- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open.
|
- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open.
|
||||||
|
|
||||||
### UI-044 — Core palettes and the lightest page
|
### UI-044 — Core palettes and the lightest page
|
||||||
@@ -923,7 +928,7 @@ Native shell, background image, and desktop acceptance remain open.
|
|||||||
|
|
||||||
- Type: Rule change
|
- Type: Rule change
|
||||||
- Date: 2026-10-28
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
||||||
@@ -950,7 +955,7 @@ Native shell, background image, and desktop acceptance remain open.
|
|||||||
- Scope: The main header, the side pane, the left ribbon, the tab bars, the Settings and Browser window title bars, and the window builders of the host.
|
- Scope: The main header, the side pane, the left ribbon, the tab bars, the Settings and Browser window title bars, and the window builders of the host.
|
||||||
- Shared implementation: `WorkbenchHeader.svelte`, `LeftPane.svelte`, `PluginRibbon.svelte`, `TabBar.svelte`, `WindowControls.svelte`, `src-tauri/src/window_frame.rs`, `src-tauri/tauri.macos.conf.json`, and the `--rs-titlebar-inset-start` token.
|
- Shared implementation: `WorkbenchHeader.svelte`, `LeftPane.svelte`, `PluginRibbon.svelte`, `TabBar.svelte`, `WindowControls.svelte`, `src-tauri/src/window_frame.rs`, `src-tauri/tauri.macos.conf.json`, and the `--rs-titlebar-inset-start` token.
|
||||||
- Evidence: `tests/smoke/layout/titleBar.smoke.mjs` and the Rust command list test.
|
- Evidence: `tests/smoke/layout/titleBar.smoke.mjs` and the Rust command list test.
|
||||||
- Replaces / replaced by: The left pane footer, and the ribbon rule "The ribbon has no width when it has no entries."
|
- Replaces / replaced by: The left pane footer, and the ribbon rule "The ribbon has no width when it has no entries." [UI-062](#ui-062--tabs-use-the-free-header-space) replaces the drag area rule.
|
||||||
- Limits: Browser checks use desktop service mocks. Snap Layouts, the native drag area, and the macOS title bar need native acceptance. The macOS code path was not compiled here. On Windows 10, Win+Z does nothing.
|
- Limits: Browser checks use desktop service mocks. Snap Layouts, the native drag area, and the macOS title bar need native acceptance. The macOS code path was not compiled here. On Windows 10, Win+Z does nothing.
|
||||||
|
|
||||||
### UI-051 — Check marks, focus rings, and control states
|
### UI-051 — Check marks, focus rings, and control states
|
||||||
@@ -1012,3 +1017,160 @@ 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.
|
- 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.
|
- 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.
|
- 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.
|
||||||
|
|
||||||
|
### UI-061 — Translucent menus and hover fills over images
|
||||||
|
|
||||||
|
- Type: Rule change
|
||||||
|
- Date: 2026-10-30
|
||||||
|
- Status: Implemented for user review
|
||||||
|
- Decision source: Card 05b9bfa1 reports that menus, the workspace button, and row highlights lost their transparency over a background image.
|
||||||
|
- Previous rule: [UI-043](#ui-043--opaque-menus). With a background image, menus were at least 92% opaque, and a hovered menu row was 92% `--rs-bg-active`. Hovered rows in the work area and the workspace button used the opaque `--rs-bg-active`.
|
||||||
|
- New rule: Without a background image, nothing changes. Menus, hover fills, and the workspace button are opaque. With an image, menus use the surface transparency of Appearance (82% at the default amount of 18%) and keep the blur. Hovered rows and controls in the work area, hovered menu rows, and the workspace button use `--rs-hover-bg`. With an image, it is a 6% veil of `--rs-text-strong`.
|
||||||
|
- Reason: A nearly opaque `--rs-bg-active` hides the image. A translucent `--rs-bg-active` disappears over mid-tone image areas, because its color is close to the tinted pane there. The veil keeps the image as visible as the pane around it. It adds about the same brightness step as the opaque hover over light, mid-tone, and dark image areas. The blur keeps menu labels clear of document text.
|
||||||
|
- Scope: Host menus, plugin menus, submenus, the workspace picker, the workspace button, and the hover fills of the side panes, the tab bar, the view modes, icon buttons, Source control, the Git graph and diff tabs, the PDF toolbar, Find, the editor controls, and the bookmarks bar. Dialogs and Settings keep opaque fills.
|
||||||
|
- Palette change: Silver Serpent `text-dim` is `#c2c6cc` (was `#b3b8be`). It keeps 4.5:1 on a hovered row over a white image.
|
||||||
|
- Shared implementation: `tokens.css` (`--rs-hover-bg`, `--rs-image-hover-bg`, `--rs-image-menu-bg`, and `--rs-image-menu-active-bg`) and `backgrounds.ts` (the image switch).
|
||||||
|
- Evidence: `tests/smoke/menus/consistency.smoke.mjs` and `tests/smoke/features/background.smoke.mjs` check the 82% menu, the blur, and the 6% veil with an image, and opaque fills without one. `tests/unit/theme/characterPalettes.spec.ts` checks the Silver Serpent row colors on a hovered row over a white image.
|
||||||
|
- Replaces: The image rule of [UI-043](#ui-043--opaque-menus). Menus without an image stay opaque.
|
||||||
|
- Limits: Over the brightest image areas, dim text on a hovered row has about 15% less contrast than on the pane around it. Browser checks use desktop service mocks. Native desktop acceptance remains open.
|
||||||
|
|
||||||
|
### UI-062 — Tabs use the free header space
|
||||||
|
|
||||||
|
- Type: Rule change
|
||||||
|
- Date: 2026-11-02
|
||||||
|
- Status: Implemented for user review
|
||||||
|
- Decision source: Card 7f1d29d6 ("wasted free space") reports empty header space beside tabs that scroll.
|
||||||
|
- Previous rule: [UI-050](#ui-050--global-actions-tabs-and-platform-title-bars). A drag area of 120 pixels sat after the tabs. The tabs shrank and scrolled first, so the 120 pixels stayed empty while tabs were out of view.
|
||||||
|
- New rule: The drag area fills the free space after the + button. When the tabs need more room, they use all space up to a drag area of 48 pixels. Then they scroll. Tabs keep their minimum width of 120 pixels. [Interface design](ui-design.md) holds the rule.
|
||||||
|
- Reason: Space that shows a tab is more useful than empty space. 48 pixels keep the window movable when the side pane is closed. While the side pane is open, the empty part of the header above it is also a drag area.
|
||||||
|
- Scope: The header of the main window and of detached tab windows. The header of the browser window keeps its drag area of at least 120 pixels.
|
||||||
|
- Shared implementation: `src/lib/layout/WorkbenchHeader.svelte`.
|
||||||
|
- Exceptions: None.
|
||||||
|
- Evidence: `tests/smoke/layout/titleBar.smoke.mjs` checks a drag area that fills the header with one tab, and a drag area of 48 pixels at the end of the header when 11 tabs scroll.
|
||||||
|
- Replaces / replaced by: The drag area rule of [UI-050](#ui-050--global-actions-tabs-and-platform-title-bars).
|
||||||
|
- Limits: Browser checks use desktop service mocks. The native window drag on the smaller area needs native acceptance.
|
||||||
|
|
||||||
|
### UI-063 — PDF pages in one column
|
||||||
|
|
||||||
|
- Type: Rule change
|
||||||
|
- Date: 2026-11-09
|
||||||
|
- Status: Implemented for user review
|
||||||
|
- Decision source: Cards 9b7b246e, 59ff5dc1, 2e425cbc, 7bd092d2, 2142ca04, and c0900ae8 report a PDF toolbar that a background image hides, no custom zoom, no scroll between pages, lost focus after Ctrl+Tab, and Page Up and Page Down that change pages.
|
||||||
|
- Previous rule: [UI-059](#ui-059--the-pdf-toolbar-on-shared-controls). The tab showed one page at a time. Page Up and Page Down changed the page. The zoom percent was text. The tab had no surface of its own, so a background image showed through the toolbar and the status line.
|
||||||
|
- New rule: The tab shows all pages in one column that scrolls. The wheel, the scroll bar, Page Up, Page Down, Home, End, and the arrow keys scroll. The page field shows the page that fills most of the tab. **Previous page**, **Next page**, and the page field show the top of a page. The zoom percent is a field: a typed percent and Enter set the zoom from 25% to 400%. Ctrl and the wheel also change the zoom. The toolbar, the status line, and the password form are opaque (`--rs-bg-elevated`) with and without a background image. The page area uses the editor surface (`--rs-workarea-editor-bg`). Ctrl+Tab and Ctrl+Shift+Tab give keyboard focus to the new plugin tab.
|
||||||
|
- Reason: A reader scrolls through a document. A page change on Page Down hides the rest of a page that is higher than the tab. A toolbar must stay readable over each image, as headers do.
|
||||||
|
- Scope: The PDF tab. The focus rule applies to each plugin tab: the host focuses the element that the view marks with `data-tab-focus`, or the view.
|
||||||
|
- Shared implementation: `src/lib/features/pdf/PdfViewer.svelte`, `src/lib/features/pdf/model.ts`, `src/lib/plugins/PluginEditor.svelte` (`focus`), and the tab commands in `src/lib/layout/Workbench.svelte`.
|
||||||
|
- Exceptions: A click on a tab or an arrow key in the tab bar keeps the focus in the tab bar.
|
||||||
|
- Evidence: `tests/smoke/features/pdf.smoke.mjs` and `tests/unit/features/pdf.spec.ts`.
|
||||||
|
- Replaces / replaced by: The one-page rule and the zoom text of [UI-059](#ui-059--the-pdf-toolbar-on-shared-controls).
|
||||||
|
- Limits: Only the pages near the visible area have a drawing. Until the viewer reads the size of a page, the page has the size of the first page. Browser checks use desktop service mocks. Native desktop acceptance remains open.
|
||||||
|
|
||||||
|
### UI-064 — Split view shows different tabs
|
||||||
|
|
||||||
|
- Type: Rule change
|
||||||
|
- Date: 2026-11-10
|
||||||
|
- Status: Implemented for user review
|
||||||
|
- Decision source: Card 565874b2 reports that split view shows only the same document side by side. The user expects different documents side by side, also with a web browser.
|
||||||
|
- Previous rule: [UI-021](#ui-021--workspace-links-in-document-panes). Only a file tree item or a workspace link opened a document to the right. Document panes held only documents. A plugin tab, for example a browser tab, covered the whole document area. The **Split** toggle showed Read beside the editor of the same document.
|
||||||
|
- New rule: Each tab menu has **Open to the right**. It shows the tab in a new pane to the right of the active pane. A pane shows a document or a plugin tab. A tab shows in one pane at most, so the item is unavailable for a visible tab. A tab that the user selects, or a file that the user opens, replaces the content of the active pane. The replaced tab stays open. A plugin tab that covers the area moves to the active pane when a tab opens beside it. When one pane is left, its plugin tab covers the area again. A plugin pane has a bar with its title and **Close split**. A document pane beside other panes shows the full path in its bar. The **Split** toggle is now **Read beside**. The file tree menu also has **Open to the right**, also for PDF files and boards. A divider between two panes changes their sizes, with the pointer or the keyboard. A double-click gives the panes equal sizes. A tab that the user drags from the tab bar to a pane replaces the content of that pane. A drop on the left, right, or bottom part of a pane opens a new pane there (left: card 156758f1). A hint shows the place of the drop. The tab that a pane shows can also go to the left, right, or bottom part of its own pane (card e0dc8473). The tab moves to the new pane. The old pane then shows the nearest tab that no pane shows: first the tabs after it, then the tabs before it. Below a plugin tab that covers the area, the old pane shows its document. Without such a tab, the drag shows no hint.
|
||||||
|
- Reason: "Split" named two different things. Users compare a note with a different note, with a web page, or with a PDF file. Equal pane sizes did not fit a web page or a PDF page beside a note.
|
||||||
|
- Scope: Document panes, plugin editor tabs, the tab menu, the tab bar, the file tree menu, and the view control.
|
||||||
|
- Shared implementation: `src/lib/workspace/documentPanes.ts`, `src/lib/workspace/splitLayout.ts` (`stackLayout`, `splitSibling`, `splitDividers`, `setSplitRatio`), `src/lib/layout/DocumentArea.svelte`, `src/lib/layout/TabBar.svelte` (`onDragAt`, `onDropAt`), and `src/lib/layout/Workbench.svelte`. A plugin view stays in the plugin layer above the panes, so a move between panes does not mount it again.
|
||||||
|
- Exceptions: In the menu of a browser tab, **New tab to the right** and **New tab below** open a new browser tab with the home page in a pane beside the tab. These items replace **Split right** and **Split down**, which opened a copy of the page in a split of plugin views only. The separate browser window keeps its own plugin split.
|
||||||
|
- Narrow layout: An area of 640 pixels or less shows the panes one above the other, in the same order and with the same ratios. The area does not scroll. Each pane keeps its own scroll bar. A tab drop opens a new pane only below.
|
||||||
|
- Evidence: `tests/smoke/layout/mixedSplits.smoke.mjs`, `tests/smoke/layout/visibleTabDrag.smoke.mjs` (real mouse input), `tests/smoke/layout/pdfBesideNote.smoke.mjs`, `tests/smoke/layout/splits.smoke.mjs`, and `tests/unit/layout/documentPanes.spec.ts`.
|
||||||
|
- Replaces / replaced by: The document-only panes of [UI-021](#ui-021--workspace-links-in-document-panes), and the name **Split** of [UI-049](#ui-049--one-view-control-and-one-file-name).
|
||||||
|
- Limits: A tab from a different window opens in the tab bar, not in a pane. Browser checks use desktop service mocks. Native desktop acceptance remains open.
|
||||||
|
|
||||||
|
Update 2026-11-16: The user did not find a way to close a split without closing the tab. The **Close split** button showed only a close icon, so it looked like the close button of a tab. Now the button shows a split icon and its name (`src/lib/layout/CloseSplitButton.svelte`). In a pane of 420 pixels or less, it shows only the icon, and a tooltip gives the name. The tab menu also has **Close split** for a tab in a pane beside other panes. The tab stays open. Evidence: `tests/smoke/layout/visibleTabDrag.smoke.mjs`.
|
||||||
|
|||||||
+61
-15
@@ -16,7 +16,7 @@ This guide is for developers who change RuneStone's source code. To use the app,
|
|||||||
|
|
||||||
### First run
|
### First run
|
||||||
|
|
||||||
1. Clone the repository: `https://git.knottywyvern.com/kwyvern/RuneStone`.
|
1. Clone the repository: `https://github.com/KnottyWyvern-GH/RuneStone.git`.
|
||||||
2. In the repository folder, run `pnpm install --frozen-lockfile`.
|
2. In the repository folder, run `pnpm install --frozen-lockfile`.
|
||||||
3. Prepare the browser runtime. See [Built-in browser runtime](#built-in-browser-runtime).
|
3. Prepare the browser runtime. See [Built-in browser runtime](#built-in-browser-runtime).
|
||||||
4. Run `pnpm tauri dev`.
|
4. Run `pnpm tauri dev`.
|
||||||
@@ -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 |
|
| `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 |
|
| `plugins.rs` | Plugin package review, installation, enable state, removal, and recovery |
|
||||||
| `plugin_sources.rs` | Plugin downloads from Gitea releases |
|
| `plugin_sources.rs` | Plugin downloads from Gitea releases |
|
||||||
| `git.rs` | The Git service for the Git plugin. It runs the `git` program. |
|
| `git.rs` | The Git service of the Git feature. It runs the `git` program. |
|
||||||
| `pty.rs`, `terminal_platform.rs` | Pseudo-terminals for the Terminal plugin |
|
| `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 |
|
| `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) |
|
| `spelling.rs` | Spelling suggestions from the operating system (Windows) |
|
||||||
| `settings.rs`, `theme.rs` | The Settings window and theme export |
|
| `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. |
|
| `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`) |
|
| `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 |
|
| `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 |
|
| `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`) |
|
| `theme/` | Appearance settings, palettes, and the theme tokens (`tokens.css`) |
|
||||||
| `ui/` | Shared menus, pickers, and action icons |
|
| `ui/` | Shared menus, pickers, and action icons |
|
||||||
| `i18n/` | Interface text in English, French, Japanese, and Simplified Chinese |
|
| `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 |
|
| Data | Location |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Documents | Ordinary files in the workspace folder |
|
| 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). |
|
| 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). |
|
| 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
|
#### The settings file
|
||||||
|
|
||||||
@@ -131,13 +135,17 @@ On macOS, it is `~/Library/Application Support/<identifier>/`. On Linux, it is `
|
|||||||
"appearance": { "theme": "default", "mode": "dark" },
|
"appearance": { "theme": "default", "mode": "dark" },
|
||||||
"customThemes": [],
|
"customThemes": [],
|
||||||
"customThemesLegacy": [],
|
"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 |
|
| 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. |
|
| 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. |
|
| 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. |
|
| 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.
|
- 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.
|
- The core includes Markdown table editing, rendering, and table formulas.
|
||||||
- Native file access, file watching, search, Git, and terminals belong in Rust.
|
- 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.
|
- For sync, prefer a local Git clone. Do not use a live network share as the sync path.
|
||||||
|
|
||||||
These stay outside the product:
|
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 smoke` | Browser smoke tests. See [Browser smoke tests](#browser-smoke-tests). |
|
||||||
| `pnpm build` | The production frontend build |
|
| `pnpm build` | The production frontend build |
|
||||||
| `pnpm check:menus` | The inventory of menu surfaces. See [Interface design](ui-design.md). |
|
| `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`.
|
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.
|
The `--import` hook compiles `.svelte.ts` modules, so a test can import them.
|
||||||
@@ -199,6 +208,44 @@ 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.
|
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.
|
`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.
|
||||||
|
- Project Management deletes no files. A description draft is `.runestone/pm/drafts/<hex of the card ID>.json`. The data of its unsaved images is in `<hex of the card ID>.images.json` in the same folder. Thus a text change does not write the images again.
|
||||||
|
Only a save of the description or the card writes `.runestone/pm/images/<image ID>.json`. **Save** and **Cancel** of the description replace the draft and its image record with empty records. As a result, a discarded draft leaves no image file.
|
||||||
|
- `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
|
## Plugin SDK
|
||||||
|
|
||||||
The plugin SDK in `packages/plugin-sdk/` is the only source of the public plugin types.
|
The plugin SDK in `packages/plugin-sdk/` is the only source of the public plugin types.
|
||||||
@@ -240,8 +287,7 @@ A test states what it needs near its top. The runner skips the test, with the re
|
|||||||
|
|
||||||
| Line | Requirement |
|
| Line | Requirement |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `// @requires plugin:terminal` | The compiled Terminal plugin |
|
| `// @requires repo:RuneStone_Local_Autocomplete/src` | A file or folder in a sibling plugin checkout |
|
||||||
| `// @requires repo:RuneStone_Git/dist` | A file or folder in a sibling plugin checkout |
|
|
||||||
| `// @requires electron` | The browser engine dependencies. Run `npm ci --prefix browser-runtime`. |
|
| `// @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. |
|
| `// @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 +295,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. |
|
| `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_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. |
|
| `RUNESTONE_CSP` | `1` sends and checks the content security policy. `--csp` sets it. |
|
||||||
| `CHROME_PATH` | A Chromium browser for Playwright |
|
| `CHROME_PATH` | A Chromium browser for Playwright |
|
||||||
| `PLAYWRIGHT_MODULE` | A different Playwright package |
|
| `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.
|
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 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)`.
|
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.
|
A failed test saves `failure.png` in its output folder and prints the page console errors and warnings.
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ This guide explains how to insert and edit images, read diagrams, edit Markdown
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Drag an image from the navigator into a Markdown editor | RuneStone inserts a relative link to the existing file. Press Escape to cancel the drag. |
|
| Drag an image from the navigator into a Markdown editor | RuneStone inserts a relative link to the existing file. Press Escape to cancel the drag. |
|
||||||
| Drop an image from your system file manager, or paste an image | RuneStone copies the image into the workspace `attachments/` folder with a unique name, then inserts a link. |
|
| Drop an image from your system file manager, or paste an image | RuneStone copies the image into the workspace `attachments/` folder with a unique name, then inserts a link. |
|
||||||
|
| Paste an image that you copied with **Copy image** in the RuneStone browser | RuneStone saves the original file that the page loaded. A GIF keeps its animation, also from a website that refuses downloads. |
|
||||||
|
| Paste a GIF, WebP, or AVIF image that you copied in another web browser | That browser copies only the first frame. RuneStone downloads the original file from the image address, so the animation stays. If the website refuses the download, RuneStone saves the first frame and shows a message. |
|
||||||
|
|
||||||
Undo removes the inserted link. It keeps the image file.
|
Undo removes the inserted link. It keeps the image file.
|
||||||
|
|
||||||
@@ -22,11 +24,11 @@ Select an image, then right-click it or press Shift+F10 for these actions:
|
|||||||
- **Copy path** and **Show in Explorer**, for workspace images
|
- **Copy path** and **Show in Explorer**, for workspace images
|
||||||
|
|
||||||
**Remove image**, or the Delete key, removes the image link from the note. It does not delete the file. Undo restores the link.
|
**Remove image**, or the Delete key, removes the image link from the note. It does not delete the file. Undo restores the link.
|
||||||
Zoom works in Write, Read, and Split. It can fit the image or magnify it. Press Escape to close it.
|
Zoom works in Write, Read, and Read beside. It can fit the image or magnify it. Press Escape to close it.
|
||||||
|
|
||||||
## Read diagrams and document properties
|
## Read diagrams and document properties
|
||||||
|
|
||||||
Write, Read, and Split show wiki links, note callouts, and Mermaid diagrams.
|
Write, Read, and Read beside show wiki links, note callouts, and Mermaid diagrams.
|
||||||
RuneStone renders Mermaid diagrams locally. If a diagram is not valid, RuneStone shows an error message and the diagram source.
|
RuneStone renders Mermaid diagrams locally. If a diagram is not valid, RuneStone shows an error message and the diagram source.
|
||||||
Read shows frontmatter in a collapsed **Properties** section.
|
Read shows frontmatter in a collapsed **Properties** section.
|
||||||
|
|
||||||
@@ -95,7 +97,7 @@ Start a cell with `=` to make a formula. Columns use letters A, B, … AA. Row 1
|
|||||||
| Functions | SUM, AVERAGE, MIN, MAX, COUNT, ABS, and ROUND |
|
| Functions | SUM, AVERAGE, MIN, MAX, COUNT, ABS, and ROUND |
|
||||||
|
|
||||||
Functions that take a range ignore text and blank cells. Arithmetic uses zero for a blank cell.
|
Functions that take a range ignore text and blank cells. Arithmetic uses zero for a blank cell.
|
||||||
Results update in Write, Read, and Split. Select a result to edit its formula. Enter saves the formula, and Tab moves to the next cell.
|
Results update in Write, Read, and Read beside. Select a result to edit its formula. Enter saves the formula, and Tab moves to the next cell.
|
||||||
The **Formulas** control below each table explains the syntax. The active cell shows its address.
|
The **Formulas** control below each table explains the syntax. The active cell shows its address.
|
||||||
A formula that is not valid, a missing cell, or a circular reference shows an error label.
|
A formula that is not valid, a missing cell, or a circular reference shows an error label.
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
# 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.
|
||||||
|
An image that you paste or drop into a draft stays with the draft. **Save** adds the image to the card. **Cancel** removes it.
|
||||||
|
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.
|
||||||
|
|
||||||
|
A web browser copies only the first frame of an image. When you paste a GIF or WebP image from a browser, RuneStone downloads the original file.
|
||||||
|
Then the animation stays.
|
||||||
|
|
||||||
|
Some websites refuse that download. Then the card gets the first frame, and RuneStone shows a message.
|
||||||
|
To keep the animation, use **Copy image** in the RuneStone browser. That copy keeps the original file that the page loaded.
|
||||||
|
|
||||||
|
**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
@@ -1,29 +1,30 @@
|
|||||||
# Terminal guide
|
# 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
|
## Open and arrange terminals
|
||||||
|
|
||||||
| Action | How |
|
| 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 |
|
| New terminal | Ctrl+Shift+` or the + button |
|
||||||
| Split the active terminal | Ctrl+Shift+5. The new pane uses the same folder and profile. |
|
| 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+` |
|
| 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 |
|
| 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. |
|
| Change the panel size | **Maximize panel** or **Restore panel**. Shells do not restart. |
|
||||||
| End all sessions in the panel | **Close terminal (end all sessions)** |
|
| End all sessions in the panel | **Close terminal (end all sessions)** |
|
||||||
|
|
||||||
The terminal list shows only when more than one session is open.
|
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
|
## 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 |
|
| 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 |
|
| macOS and Linux | Bash and PowerShell |
|
||||||
|
|
||||||
The menu shows only the shells that RuneStone finds on your computer.
|
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.
|
The same menu has **Split terminal with profile**, **Terminal settings**, **Select the default profile**, and the task commands.
|
||||||
Terminal settings set the font size, scrollback lines, cursor blink, and default profile. RuneStone keeps them on this computer.
|
|
||||||
New terminals get the RuneStone environment, including `PATH`.
|
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
|
## Copy and paste
|
||||||
|
|
||||||
- Drag across terminal text to select it.
|
- Drag across terminal text to select it.
|
||||||
@@ -48,24 +65,25 @@ Open **More terminal actions** for these commands:
|
|||||||
|
|
||||||
| Command | Result |
|
| Command | Result |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| **Run Active File** | Saves and runs the active file in the terminal. |
|
| **Scroll to the previous command** / **Scroll to the next command** (Ctrl+Up / Ctrl+Down) | Moves between command prompts. |
|
||||||
| **Run Selected Text** | Sends the text that is selected in the editor to the terminal. |
|
| **Clear the terminal** | Clears the scrollback. |
|
||||||
| **Clear Terminal** | Clears the scrollback. |
|
| **Run the active file** | Saves and runs the active file in the terminal. |
|
||||||
| **Run Recent Command…** (Ctrl+Alt+R) | Runs a command from this session again. |
|
| **Run selected text** | Sends the text that is selected in the editor to the terminal. |
|
||||||
| **Go to Recent Directory…** (Ctrl+G) | Changes to a recent folder. |
|
| **Start dictation** | Starts Windows voice typing. See [Debug JavaScript and use dictation](#debug-javascript-and-use-dictation). |
|
||||||
| **Scroll to Previous Command** / **Next Command** (Ctrl+Up / Ctrl+Down) | Moves between command prompts. |
|
| **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.
|
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
|
## Configure workspace tasks
|
||||||
|
|
||||||
A task is a named command that you can start from a menu.
|
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`.
|
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`.
|
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`):
|
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.
|
**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.
|
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.
|
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.
|
||||||
|
|||||||
+62
-10
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
[RuneStone](../../README.md) · [User guide](../user-guide.md)
|
[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.
|
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
|
## 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.
|
Without a background image, menus are opaque. With an image, menus use the same transparency as other surfaces and blur the image.
|
||||||
Set **Transparency amount** from 0% to 100%. The default is 18%.
|
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.
|
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.
|
The **Background** section shows a folder of images as a slideshow, or one image, behind the workspace.
|
||||||
2. Set **Image size** to **Fill**, **Fit**, or **Actual size**.
|
Set **Background source** to **Folder**, **Image**, or **None**.
|
||||||
3. Set **Image position**.
|
|
||||||
4. Set **Image overlay** from -100% to 100%. Negative values lighten the image, and positive values darken it.
|
|
||||||
|
|
||||||
The image shows in new tabs. RuneStone keeps it on this computer.
|
### Show a folder as a slideshow
|
||||||
The Project Management plugin can keep a separate image for a board. The Background Slideshow plugin can replace the image for a time.
|
|
||||||
|
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
|
## Edit a theme
|
||||||
|
|
||||||
|
|||||||
+32
-34
@@ -2,23 +2,32 @@
|
|||||||
|
|
||||||
[RuneStone](../README.md) · [User guide](user-guide.md)
|
[RuneStone](../README.md) · [User guide](user-guide.md)
|
||||||
|
|
||||||
This guide installs, updates, or reinstalls RuneStone from a supplied release file.
|
This guide installs, updates, or reinstalls RuneStone from a release file or from a package that you build.
|
||||||
|
|
||||||
| Platform | Release file | Notes |
|
| Platform | Release file | Notes |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Windows 10 or 11, x64 | [RuneStone_0.1.49_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone_Releases/releases/download/v0.1.49/RuneStone_0.1.49_x64-setup.exe) | Installs for the current Windows account |
|
| Windows 10 or 11, x64 | [RuneStone_1.0.0_x64-setup.exe](https://github.com/KnottyWyvern-GH/RuneStone/releases/download/v1.0.0/RuneStone_1.0.0_x64-setup.exe) | Installs for the current Windows account |
|
||||||
| macOS, Apple silicon | [RuneStone_0.1.44_aarch64.dmg](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_aarch64.dmg) | Experimental. Intel Macs are not supported. |
|
| macOS, Apple silicon | None | Build the app from source. See [macOS packages](builds.md#macos-packages). Intel Macs are not supported. |
|
||||||
| Linux, amd64 | [RuneStone_0.1.44_amd64.deb](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.44/RuneStone_0.1.44_amd64.deb) | Experimental. Built on Ubuntu 26.04.1. Needs GLIBC 2.39 or newer. |
|
| Linux, amd64 | None | Build a Debian package from source. See [Build Linux packages](builds.md#build-linux-packages). |
|
||||||
|
|
||||||
You do not need Node.js, Rust, or a source checkout.
|
On Windows, you do not need Node.js, Rust, or a source checkout.
|
||||||
On Windows, the built-in browser needs a separate engine download. See [Use the built-in browser](user-guide.md#use-the-built-in-browser).
|
The built-in browser needs a separate engine download. See [Use the built-in browser](user-guide.md#use-the-built-in-browser).
|
||||||
|
|
||||||
## Install on Windows
|
## Install on Windows
|
||||||
|
|
||||||
1. Save `RuneStone_0.1.49_x64-setup.exe` to Downloads.
|
1. Save `RuneStone_1.0.0_x64-setup.exe` and [windows-SHA256SUMS](https://github.com/KnottyWyvern-GH/RuneStone/raw/master/docs/checksums/1.0.0/windows-SHA256SUMS) to Downloads.
|
||||||
2. Open the file.
|
2. Open PowerShell in Downloads.
|
||||||
3. Complete setup. Keep the default destination unless you need another location.
|
3. Check the download:
|
||||||
4. Open RuneStone from the Start menu.
|
|
||||||
|
```powershell
|
||||||
|
$expected = (Get-Content .\windows-SHA256SUMS).Split(' ')[0]
|
||||||
|
(Get-FileHash .\RuneStone_1.0.0_x64-setup.exe).Hash -eq $expected
|
||||||
|
```
|
||||||
|
|
||||||
|
If the result is not `True`, delete the file and download it again.
|
||||||
|
4. Open the setup file.
|
||||||
|
5. Complete setup. Keep the default destination unless you need another location.
|
||||||
|
6. Open RuneStone from the Start menu.
|
||||||
|
|
||||||
## Update or reinstall on Windows
|
## Update or reinstall on Windows
|
||||||
|
|
||||||
@@ -33,41 +42,30 @@ After an update from 0.1.48 or earlier, a browser tab asks you to download the b
|
|||||||
|
|
||||||
## Install on macOS
|
## Install on macOS
|
||||||
|
|
||||||
1. Save `RuneStone_0.1.44_aarch64.dmg` to Downloads.
|
Build the app on an Apple silicon Mac first. See [macOS packages](builds.md#macos-packages).
|
||||||
2. Open the disk image.
|
|
||||||
3. Drag RuneStone into Applications.
|
|
||||||
4. Eject the disk image.
|
|
||||||
5. Open RuneStone from Applications.
|
|
||||||
|
|
||||||
The app has an ad hoc signature and is not notarized by Apple.
|
1. Copy `RuneStone.app` from `src-tauri/target/release/bundle/macos/` into Applications.
|
||||||
If macOS blocks the first launch, open **System Settings → Privacy & Security** and choose **Open Anyway**.
|
2. Open RuneStone from Applications.
|
||||||
|
|
||||||
## Update or reinstall on macOS
|
## Update or reinstall on macOS
|
||||||
|
|
||||||
1. Save your documents and quit RuneStone.
|
1. Save your documents and quit RuneStone.
|
||||||
2. Open the disk image for the same or a newer version.
|
2. Build the same or a newer version.
|
||||||
3. Drag RuneStone into Applications and confirm the replacement.
|
3. Copy the new `RuneStone.app` into Applications and confirm the replacement.
|
||||||
4. Eject the disk image.
|
4. Open RuneStone from Applications.
|
||||||
5. Open RuneStone from Applications.
|
|
||||||
|
|
||||||
## Install on Linux
|
## Install on Linux
|
||||||
|
|
||||||
1. Save `RuneStone_0.1.44_amd64.deb` and [linux-SHA256SUMS](https://git.knottywyvern.com/kwyvern/RuneStone/raw/branch/master/docs/checksums/0.1.44/linux-SHA256SUMS) to Downloads.
|
Build the Debian package first. See [Build Linux packages](builds.md#build-linux-packages).
|
||||||
2. Open Terminal in Downloads.
|
|
||||||
3. Check the download:
|
1. Open Terminal in the folder that contains the package.
|
||||||
|
2. Install the package. Use the file name of your build:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sha256sum --check linux-SHA256SUMS
|
sudo apt install ./RuneStone_1.0.0_amd64.deb
|
||||||
```
|
```
|
||||||
|
|
||||||
If the result is not `OK`, delete the file and download it again.
|
3. Open RuneStone from your applications menu, or run `runestone` in Terminal.
|
||||||
4. Install the package:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo apt install ./RuneStone_0.1.44_amd64.deb
|
|
||||||
```
|
|
||||||
|
|
||||||
5. Open RuneStone from your applications menu, or run `runestone` in Terminal.
|
|
||||||
|
|
||||||
APT installs the system libraries that the package declares. Run RuneStone as your ordinary desktop user.
|
APT installs the system libraries that the package declares. Run RuneStone as your ordinary desktop user.
|
||||||
|
|
||||||
@@ -77,4 +75,4 @@ APT installs the system libraries that the package declares. Run RuneStone as yo
|
|||||||
2. Open Terminal in the folder that contains the new package.
|
2. Open Terminal in the folder that contains the new package.
|
||||||
3. Install the newer package with the same `sudo apt install ./<file>.deb` command.
|
3. Install the newer package with the same `sudo apt install ./<file>.deb` command.
|
||||||
|
|
||||||
To reinstall the same version, run `sudo apt install --reinstall ./RuneStone_0.1.44_amd64.deb`.
|
To reinstall the same version, run `sudo apt install --reinstall ./<file>.deb`.
|
||||||
|
|||||||
+2
-2
@@ -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. |
|
| 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. |
|
| 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. |
|
| 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. |
|
| 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.
|
Check terminal profiles after a desktop launch too. A desktop launcher can have a different `PATH` from an interactive shell.
|
||||||
|
|
||||||
Known Linux limits:
|
Known Linux limits:
|
||||||
|
|||||||
+117
-139
@@ -1,13 +1,8 @@
|
|||||||
{
|
{
|
||||||
"date": "2026-10-15",
|
"date": "2026-10-29",
|
||||||
"scope": [
|
"scope": [
|
||||||
"RuneStone",
|
"RuneStone",
|
||||||
"RuneStone_Project_Management",
|
|
||||||
"RuneStone_Terminal",
|
|
||||||
"RuneStone_Background_Slideshow",
|
|
||||||
"RuneStone_Local_Autocomplete",
|
"RuneStone_Local_Autocomplete",
|
||||||
"RuneStone_Git",
|
|
||||||
"RuneStone_PDF_Viewer",
|
|
||||||
"RuneStone_CSV_Viewer"
|
"RuneStone_CSV_Viewer"
|
||||||
],
|
],
|
||||||
"limits": [
|
"limits": [
|
||||||
@@ -94,6 +89,13 @@
|
|||||||
"design": "Shared action menu",
|
"design": "Shared action menu",
|
||||||
"check": "tests/smoke/menus/consistency.smoke.mjs"
|
"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": {
|
"RuneStone/src/lib/layout/CommandPalette.svelte": {
|
||||||
"counts": {
|
"counts": {
|
||||||
"picker": 1,
|
"picker": 1,
|
||||||
@@ -153,14 +155,6 @@
|
|||||||
"design": "API type declaration, no renderer",
|
"design": "API type declaration, no renderer",
|
||||||
"check": "pnpm check"
|
"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": {
|
"RuneStone/src/lib/ui/actionMenu.ts": {
|
||||||
"counts": {
|
"counts": {
|
||||||
"action": 1,
|
"action": 1,
|
||||||
@@ -176,120 +170,6 @@
|
|||||||
"design": "Shared action menu",
|
"design": "Shared action menu",
|
||||||
"check": "tests/smoke/menus/consistency.smoke.mjs"
|
"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": {
|
"RuneStone_Local_Autocomplete/src/main.mjs": {
|
||||||
"counts": {
|
"counts": {
|
||||||
"action": 1,
|
"action": 1,
|
||||||
@@ -298,13 +178,6 @@
|
|||||||
"design": "Host radio menu; native server select only on older hosts",
|
"design": "Host radio menu; native server select only on older hosts",
|
||||||
"check": "tests/smoke/plugins/choiceMenus.smoke.mjs"
|
"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": {
|
"RuneStone_CSV_Viewer/src/index.js": {
|
||||||
"counts": {
|
"counts": {
|
||||||
"action": 1,
|
"action": 1,
|
||||||
@@ -322,12 +195,117 @@
|
|||||||
"design": "Shared action menu for interface language; settings retain ordinary controls",
|
"design": "Shared action menu for interface language; settings retain ordinary controls",
|
||||||
"check": "tests/smoke/settings/displayLanguage.smoke.mjs; tests/smoke/menus/consistency.smoke.mjs"
|
"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": {
|
"counts": {
|
||||||
"nativeChoice": 1
|
"action": 1,
|
||||||
|
"localPopup": 4
|
||||||
},
|
},
|
||||||
"design": "Uses the host menu. Keeps a native selector for older hosts.",
|
"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": "RuneStone_Project_Management/tests/october-cards.spec.ts with PM_HOST_URL; both themes, narrow layout, keyboard focus"
|
"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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+26
-145
@@ -11,11 +11,8 @@ This reference gives the package contract, the build procedure, and the API for
|
|||||||
- [Versions and releases](#versions-and-releases)
|
- [Versions and releases](#versions-and-releases)
|
||||||
- [Plugin API](#plugin-api)
|
- [Plugin API](#plugin-api)
|
||||||
- [Use the SDK instead of native calls](#use-the-sdk-instead-of-native-calls)
|
- [Use the SDK instead of native calls](#use-the-sdk-instead-of-native-calls)
|
||||||
- [Terminal API](#terminal-api)
|
|
||||||
- [Folder grants](#folder-grants)
|
- [Folder grants](#folder-grants)
|
||||||
- [Plugin services](#plugin-services)
|
- [Plugin services](#plugin-services)
|
||||||
- [Git API](#git-api)
|
|
||||||
- [Background API](#background-api)
|
|
||||||
|
|
||||||
## Install the SDK
|
## Install the SDK
|
||||||
|
|
||||||
@@ -23,7 +20,7 @@ The plugin SDK `@runestone/plugin-sdk` gives the API types, the feature checks,
|
|||||||
Install it in each plugin project from the URL of its package file on the RuneStone releases page.
|
Install it in each plugin project from the URL of its package file on the RuneStone releases page.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
pnpm add -D "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
pnpm add -D "https://github.com/KnottyWyvern-GH/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
||||||
```
|
```
|
||||||
|
|
||||||
- Always give the full URL. The SDK is not on the npm registry, and another account owns the `@runestone` scope there.
|
- Always give the full URL. The SDK is not on the npm registry, and another account owns the `@runestone` scope there.
|
||||||
@@ -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.
|
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).
|
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: the CSV Viewer repository, a private repository: its `package.json`, `plugin.json`, `scripts/build.mjs`, and `README.md`.
|
||||||
|
|
||||||
| Item | Value |
|
| Item | Value |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Prerequisites | Node.js 24 and pnpm 10. Run `pnpm install --frozen-lockfile` in the Terminal folder. |
|
| 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 Terminal repository root |
|
| Working folder | The CSV Viewer repository root |
|
||||||
| Command | `pnpm build` |
|
| 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 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`.
|
||||||
The build stops when the versions in `package.json` and `plugin.json` are different.
|
Then it runs `scripts/packagePlugin.mjs` of the RuneStone checkout on `dist/`. Set `RUNESTONE_ROOT` to use another RuneStone checkout for this step.
|
||||||
To compile into `dist/` without a ZIP, run `node scripts/build.mjs --no-package`.
|
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.
|
||||||
RuneStone supplies the native terminal sessions. The plugin supplies the interface, shortcuts, and session controls.
|
To compile into `dist/` without a ZIP, run `pnpm compile`.
|
||||||
For use of the terminal, see the [Terminal guide](guides/terminal.md).
|
|
||||||
|
|
||||||
### Example: Workspace overview
|
### Example: Workspace overview
|
||||||
|
|
||||||
@@ -217,8 +213,8 @@ The SDK feature checks do this. Their error names each missing feature and tells
|
|||||||
```ts
|
```ts
|
||||||
import { hasFeature, requireFeature, requireFeatures } from "@runestone/plugin-sdk";
|
import { hasFeature, requireFeature, requireFeatures } from "@runestone/plugin-sdk";
|
||||||
|
|
||||||
requireFeatures(api, ["pty", "workspace.readBytes"]);
|
requireFeatures(api, ["files", "workspace.readBytes"]);
|
||||||
const pty = requireFeature(api, "pty");
|
const files = requireFeature(api, "files");
|
||||||
if (hasFeature(api, "settings.subscribe")) watchSettings();
|
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.
|
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
|
### Activation and cleanup
|
||||||
|
|
||||||
- The host limits activation, each view mount, and each cleanup callback to five seconds. A timeout reports an error.
|
- 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.
|
- Plugins activate in every RuneStone window except browser windows.
|
||||||
- `api.signal` aborts when shutdown starts. Use it to stop pending work.
|
- `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.
|
- 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.
|
- 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.
|
- 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`. |
|
| `assets.read(path)` | | Read a package file as a `Uint8Array`. |
|
||||||
| `ui.showActionMenu(options)` | yes | Open the shared RuneStone action menu. See [Menus](#menus). |
|
| `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). |
|
| `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). |
|
| `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). |
|
| `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
|
### 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)`.
|
A `launch()` handler can select a default target and call `api.openView(id)`.
|
||||||
Explicit `api.openView` calls and restored tabs do not call `launch()`.
|
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
|
### Navigation buttons
|
||||||
|
|
||||||
@@ -387,11 +381,9 @@ Only one enabled plugin can own each key. The host removes contributions before
|
|||||||
|
|
||||||
| Key | Purpose | Owner |
|
| 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 |
|
| `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
|
### 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
|
## 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.
|
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.
|
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. Keep the native call only as a fallback for older hosts.
|
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.
|
The Local Autocomplete and CSV Viewer plugins make no native calls.
|
||||||
|
|
||||||
| 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.
|
|
||||||
Their test scripts replace `window.__TAURI_INTERNALS__` with a test double. That is test code and does not go into the package.
|
Their test scripts replace `window.__TAURI_INTERNALS__` with a test double. That is test code and does not go into the package.
|
||||||
|
|
||||||
## 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
|
## Folder grants
|
||||||
|
|
||||||
`api.files` (`version: 1`) gives access to folders outside the workspace. The user selects each folder. The plugin cannot supply a path.
|
`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()`.
|
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
|
## 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.
|
`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.
|
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.
|
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.
|
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
@@ -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.
|
The built-in browser and the theme editor use the plugin API, but they are not packages. `builtInModules` in `src/lib/plugins/external.ts` lists them. The host starts them in each window, and the plugin menus do not list their tools. A browser window starts only the browser.
|
||||||
`builtInPackages` lists the IDs of old packages for features that RuneStone now includes. The host never loads such a package. Settings → Plug-ins shows it as included with RuneStone, so that the user can remove it.
|
`builtInPackages` lists the IDs of old packages for features that RuneStone now includes. The host never loads such a package. Settings → Plug-ins shows it as included with RuneStone, so that the user can remove it.
|
||||||
|
Native features, such as Git, 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
|
### 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.
|
`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.
|
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
|
## Gitea downloads
|
||||||
|
|
||||||
@@ -157,12 +159,12 @@ The policy stops a script that comes in through rendered content, for example a
|
|||||||
| Directive | Sources | Reason |
|
| Directive | Sources | Reason |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `default-src` | `'self'` | All other types come only from the app. |
|
| `default-src` | `'self'` | All other types come only from the app. |
|
||||||
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: the PDF Viewer decodes JPEG 2000 and JBIG2 images and color profiles with WebAssembly in its worker. It does not permit `eval`. |
|
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: PDF.js in the PDF Viewer feature decodes JPEG 2000 and JBIG2 images and compiles PostScript functions with WebAssembly. Its worker is a file of the app and gets no policy, so this source applies only to PDF.js code on the page. It does not permit `eval`. |
|
||||||
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, the Vite dev server, and plugins (Terminal, CSV Viewer, PDF Viewer, Background Slideshow). |
|
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, xterm in the Terminal feature, the Vite dev server, and plugins (CSV Viewer). |
|
||||||
| `img-src` | `'self' data: blob: https: http:` | `data:`: workspace images, browser frames, tab and site icons, and icons in CSS. `blob:`: background images. `https:` and `http:`: remote images in Markdown previews. |
|
| `img-src` | `'self' data: blob: https: http:` | `data:`: workspace images, browser frames, tab and site icons, and icons in CSS. `blob:`: background images. `https:` and `http:`: remote images in Markdown previews. |
|
||||||
| `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: fonts that the PDF Viewer embeds. |
|
| `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: PDF.js can load the embedded fonts of a PDF from data addresses. |
|
||||||
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the Background Slideshow worker reads its image from a Blob URL. |
|
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the blur worker of the Background feature reads its image from a Blob URL. |
|
||||||
| `worker-src` | `'self' blob:` | `'self'`: workers that the app serves. The app starts no worker now. `blob:`: the PDF Viewer and Background Slideshow workers. |
|
| `worker-src` | `'self' blob:` | `'self'`: workers that the app serves, such as the PDF.js worker of each PDF tab. `blob:`: the blur worker of the Background feature. |
|
||||||
| `object-src` | `'none'` | RuneStone uses no plugins of the web view. |
|
| `object-src` | `'none'` | RuneStone uses no plugins of the web view. |
|
||||||
| `base-uri` | `'self'` | |
|
| `base-uri` | `'self'` | |
|
||||||
| `form-action` | `'none'` | No form sends data to an address. |
|
| `form-action` | `'none'` | No form sends data to an address. |
|
||||||
@@ -184,18 +186,19 @@ Workers that the app loads from its own files get no policy. Workers from Blob U
|
|||||||
| Capability | Windows | Plugins | Commands |
|
| Capability | Windows | Plugins | Commands |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| `default.json` | `main`, `workspace-*`, `terminal-*` | All enabled plugins | All app 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 |
|
| `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, and window controls |
|
| `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:
|
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.
|
- 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_*`, `git_*`, or `pty_*` commands, but plugin settings views run there.
|
- 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.
|
- 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.
|
- `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.
|
||||||
- `backgrounds_*` need a plugin lease of the calling window.
|
- `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.
|
- `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.
|
- 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/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/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/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/sdk.ts` | The public package API types |
|
||||||
| `src/lib/plugins/externalSession.ts` | Activation, API checks, contributions, mounts, and shutdown |
|
| `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 |
|
| `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/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/PluginSettings.svelte` | Plugin configuration pages in Settings |
|
||||||
| `src/lib/plugins/PluginTools.svelte` / `PluginEditor.svelte` | Dialog views and editor views |
|
| `src/lib/plugins/PluginTools.svelte` / `PluginEditor.svelte` | Dialog views and editor views |
|
||||||
| `src/lib/plugins/backgrounds.ts` | Background frames |
|
| `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.pty` and `api.files`. It binds the plugin ID; the plugin never sends it |
|
| `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/plugins/services.ts` | `api.services`: services that one plugin offers to another in the same window |
|
||||||
| `src/lib/completion/` | The [completion API](completion.md) |
|
| `src/lib/completion/` | The [completion API](completion.md) |
|
||||||
| `scripts/packagePlugin.mjs` | The packager for plugin authors |
|
| `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.
|
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).
|
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:
|
Unit tests:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
|
|||||||
+8
-15
@@ -2,15 +2,15 @@
|
|||||||
|
|
||||||
[RuneStone](../README.md) · [User guide](user-guide.md)
|
[RuneStone](../README.md) · [User guide](user-guide.md)
|
||||||
|
|
||||||
This guide explains how to install, enable, update, and remove optional plugins such as Terminal, Git, and PDF Viewer.
|
This guide explains how to install, enable, update, and remove optional plugins.
|
||||||
|
|
||||||
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.
|
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
|
## 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**.
|
1. Open **Settings → Plug-ins**.
|
||||||
2. Choose **Install plugin ZIP**.
|
2. Choose **Install plugin ZIP**.
|
||||||
@@ -71,18 +71,6 @@ To install a prerelease, enter its tag. The release must have exactly one plugin
|
|||||||
Use HTTPS for a remote server. HTTP sends the token and the package without encryption.
|
Use HTTPS for a remote server. HTTP sends the token and the package without encryption.
|
||||||
RuneStone uses the token for this request only and does not save it.
|
RuneStone uses the token for this request only and does not save it.
|
||||||
|
|
||||||
## Plugin guides
|
|
||||||
|
|
||||||
| 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
|
## Plugin help
|
||||||
|
|
||||||
| Problem | Action |
|
| Problem | Action |
|
||||||
@@ -95,6 +83,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. |
|
| 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. |
|
| 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 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). |
|
| An old Table Formulas plugin shows in the list | Uninstall it. RuneStone does not run it. Your formulas stay in your files. See [Calculate with table formulas](guides/document-tools.md#calculate-with-table-formulas). |
|
||||||
|
|
||||||
To see the installed files of a plugin, choose **Show files** beside it. **Open plugins folder** opens the folder for all plugins.
|
To see the installed files of a plugin, choose **Show files** beside it. **Open plugins folder** opens the folder for all plugins.
|
||||||
|
|||||||
+2
-2
@@ -88,7 +88,7 @@ The installer, engine, and SDK scripts stop if the release file exists. The plug
|
|||||||
|
|
||||||
## Publish an installer
|
## Publish an installer
|
||||||
|
|
||||||
Publish RuneStone installers on the [RuneStone releases page](https://git.knottywyvern.com/kwyvern/RuneStone/releases). Browser engine ZIPs and SDK packages use the same page.
|
Publish RuneStone installers on the [RuneStone releases page](https://github.com/KnottyWyvern-GH/RuneStone/releases). Browser engine ZIPs and SDK packages use the same page.
|
||||||
|
|
||||||
1. Build the installer and complete the [installer checks](builds.md#installer-checks).
|
1. Build the installer and complete the [installer checks](builds.md#installer-checks).
|
||||||
2. Create a release with the tag `v<version>` on the commit that sets the version.
|
2. Create a release with the tag `v<version>` on the commit that sets the version.
|
||||||
@@ -181,7 +181,7 @@ Plugin authors install the SDK from the URL of that file. See [Install the SDK](
|
|||||||
|
|
||||||
1. Commit the SDK changes in RuneStone. Run `pnpm check` and `pnpm test`.
|
1. Commit the SDK changes in RuneStone. Run `pnpm check` and `pnpm test`.
|
||||||
2. Run `pnpm release:sdk --release-url <folder URL> --version <version> --dry-run`. Read the plan.
|
2. Run `pnpm release:sdk --release-url <folder URL> --version <version> --dry-run`. Read the plan.
|
||||||
The folder URL is the download folder of the release, for example `https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2`.
|
The folder URL is the download folder of the release, for example `https://github.com/KnottyWyvern-GH/RuneStone/releases/download/plugin-sdk-v0.1.2`.
|
||||||
3. Run the same command without `--dry-run`.
|
3. Run the same command without `--dry-run`.
|
||||||
4. On the RuneStone releases page, create a release with the tag `plugin-sdk-v<version>` on the `source` commit in `sdk.json`.
|
4. On the RuneStone releases page, create a release with the tag `plugin-sdk-v<version>` on the `source` commit in `sdk.json`.
|
||||||
5. Attach only the `.tgz` file. Leave the release description empty.
|
5. Attach only the `.tgz` file. Leave the release description empty.
|
||||||
|
|||||||
+3
-1
@@ -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. |
|
| 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. |
|
| 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. |
|
| 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. |
|
| 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. |
|
| 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. |
|
| 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. |
|
| 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.
|
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.
|
Plugins use the same tokens. [Theme tokens](plugin-development.md#theme-tokens) lists them for plugin authors.
|
||||||
|
|
||||||
|
|||||||
+32
-20
@@ -52,7 +52,8 @@ Do not copy feature-specific colors into a shared control.
|
|||||||
| `--rs-menu-font-size` | 13px | Menu text |
|
| `--rs-menu-font-size` | 13px | Menu text |
|
||||||
| `--rs-menu-icon-size` / `--rs-menu-icon-gap` | 14px / 8px | Menu icon and its gap to the label |
|
| `--rs-menu-icon-size` / `--rs-menu-icon-gap` | 14px / 8px | Menu icon and its gap to the label |
|
||||||
| `--rs-menu-border` | `transparent` | Borderless panel. `--rs-menu-shadow` supplies the edge. |
|
| `--rs-menu-border` | `transparent` | Borderless panel. `--rs-menu-shadow` supplies the edge. |
|
||||||
| `--rs-menu-bg`, `--rs-menu-active-bg` | `--rs-bg-elevated`, `--rs-bg-active` | Opaque menu surface and hover or focus fill. With a background image: at least 92% opaque. |
|
| `--rs-menu-bg`, `--rs-menu-active-bg` | `--rs-bg-elevated`, `--rs-bg-active` | Opaque menu surface and hover or focus fill. With a background image: the surface tint and the `--rs-hover-bg` veil. |
|
||||||
|
| `--rs-hover-bg` | `--rs-bg-active` | Hover fill of rows and controls in the work area, and the fill of the workspace button. With a background image: a 6% veil of `--rs-text-strong`. |
|
||||||
| `--rs-menu-backdrop` | `none` | With a background image: `blur(18px) saturate(1.2)` |
|
| `--rs-menu-backdrop` | `none` | With a background image: `blur(18px) saturate(1.2)` |
|
||||||
| `--rs-surface-opacity` | 82% | Shared surface tint. Appearance settings adjust it. |
|
| `--rs-surface-opacity` | 82% | Shared surface tint. Appearance settings adjust it. |
|
||||||
|
|
||||||
@@ -100,7 +101,7 @@ Use one menu design for context menus, action menus, and their submenus in the h
|
|||||||
- Use the `--rs-menu-*` tokens and `--rs-control-radius`. One menu family shares font, row height, padding, icon size, label alignment, separators, and shadow.
|
- Use the `--rs-menu-*` tokens and `--rs-control-radius`. One menu family shares font, row height, padding, icon size, label alignment, separators, and shadow.
|
||||||
- A menu can grow wider when its content needs more space. All other measurements stay shared.
|
- A menu can grow wider when its content needs more space. All other measurements stay shared.
|
||||||
- Keep the padding inset around every row, so hover and focus fills do not touch the panel edge.
|
- Keep the padding inset around every row, so hover and focus fills do not touch the panel edge.
|
||||||
- The panel is borderless, with a shadow. Its surface is opaque through `--rs-menu-bg` and `--rs-menu-active-bg`. Only with a background image, it is at least 92% opaque and blurs the image. Host menus, plugin menus, submenus, and the workspace picker all use this surface.
|
- The panel is borderless, with a shadow. Its surface is opaque through `--rs-menu-bg` and `--rs-menu-active-bg`. Only with a background image, it uses the surface tint (82% by default) and blurs the image, and a hovered row gets the veil of `--rs-hover-bg`. Host menus, plugin menus, submenus, and the workspace picker all use this surface.
|
||||||
- Submenus show as popovers in the top layer, so the blur of the parent menu cannot clip them.
|
- Submenus show as popovers in the top layer, so the blur of the parent menu cannot clip them.
|
||||||
- Plugins call `api.ui.showActionMenu` for the host menu, when the host API exists. The host handles dismissal, focus return, and plugin cleanup.
|
- Plugins call `api.ui.showActionMenu` for the host menu, when the host API exists. The host handles dismissal, focus return, and plugin cleanup.
|
||||||
|
|
||||||
@@ -142,18 +143,18 @@ Use one menu design for context menus, action menus, and their submenus in the h
|
|||||||
- Native editing menus keep recognized editing, spelling, and emoji commands. The host removes system sharing, writing direction, dictation, and unnamed tools before shared display or native fallback.
|
- Native editing menus keep recognized editing, spelling, and emoji commands. The host removes system sharing, writing direction, dictation, and unnamed tools before shared display or native fallback.
|
||||||
- New note creates a blank note. Its submenu contains templates and Manage templates.
|
- New note creates a blank note. Its submenu contains templates and Manage templates.
|
||||||
|
|
||||||
Decisions: [UI-002](design-decisions.md#ui-002--share-the-requested-dropdown-design), [UI-003](design-decisions.md#ui-003--quiet-menu-choices), [UI-006](design-decisions.md#ui-006--borderless-shared-menus), [UI-007](design-decisions.md#ui-007--repeated-menu-drift), [UI-008](design-decisions.md#ui-008--keep-native-editing-menus-focused), [UI-026](design-decisions.md#ui-026--compact-shared-menu-rows), [UI-027](design-decisions.md#ui-027--direct-spelling-corrections), [UI-043](design-decisions.md#ui-043--opaque-menus).
|
Decisions: [UI-002](design-decisions.md#ui-002--share-the-requested-dropdown-design), [UI-003](design-decisions.md#ui-003--quiet-menu-choices), [UI-006](design-decisions.md#ui-006--borderless-shared-menus), [UI-007](design-decisions.md#ui-007--repeated-menu-drift), [UI-008](design-decisions.md#ui-008--keep-native-editing-menus-focused), [UI-026](design-decisions.md#ui-026--compact-shared-menu-rows), [UI-027](design-decisions.md#ui-027--direct-spelling-corrections), [UI-043](design-decisions.md#ui-043--opaque-menus), [UI-061](design-decisions.md#ui-061--translucent-menus-and-hover-fills-over-images).
|
||||||
|
|
||||||
## Window and navigation
|
## Window and navigation
|
||||||
|
|
||||||
- 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.
|
- 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.
|
- 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.
|
- Tabs keep a minimum width of 120 pixels and scroll. Fades show tabs out of view, and ⌄ lists all tabs. A drag area after the tabs fills the free space of the header. The tabs use all space up to a drag area of 48 pixels before they scroll ([UI-062](design-decisions.md#ui-062--tabs-use-the-free-header-space)).
|
||||||
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- Sidebar widths and visibility persist across window sessions. A different editor does not restore a hidden outline.
|
||||||
@@ -172,17 +173,21 @@ Decisions: [UI-004](design-decisions.md#ui-004--detached-tab-work-area), [UI-039
|
|||||||
- Put related plugin metadata and actions in compact rows.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- **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.
|
- 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
|
## Typography and tables
|
||||||
|
|
||||||
- The interface uses `--rs-font-ui`. Prose uses `--rs-font-prose`. Headings use `--rs-font-heading`.
|
- 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.
|
- 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.
|
- 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.
|
- 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 +197,8 @@ Decisions: [UI-005](design-decisions.md#ui-005--heading-spacing).
|
|||||||
|
|
||||||
## Themes and background images
|
## 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
|
### Palettes
|
||||||
|
|
||||||
- Color choices obey [Functional color](ui-color.md).
|
- Color choices obey [Functional color](ui-color.md).
|
||||||
@@ -215,19 +222,21 @@ Decisions: [UI-009](design-decisions.md#ui-009--character-theme-appearances), [U
|
|||||||
|
|
||||||
- The app image fills the work area below the titlebar, including new tabs and document views. It stays fixed while content scrolls.
|
- The app image fills the work area below the titlebar, including new tabs and document views. It stays fixed while content scrolls.
|
||||||
- Sidebars use `--rs-image-sidebar-bg` (82% tint). Editor surfaces use `--rs-image-editor-bg` (90% tint). Without an image, both are opaque.
|
- Sidebars use `--rs-image-sidebar-bg` (82% tint). Editor surfaces use `--rs-image-editor-bg` (90% tint). Without an image, both are opaque.
|
||||||
- Write, Source, Read, and Split share the editor surface. CodeMirror layers stay transparent above it.
|
- Write, Source, Read, and Read beside share the editor surface. CodeMirror layers stay transparent above it.
|
||||||
- Code blocks in Write and Read use `--rs-code-block-bg`.
|
- Code blocks in Write and Read use `--rs-code-block-bg`.
|
||||||
|
- Hovered rows and controls in the work area, hovered menu rows, and the workspace button use `--rs-hover-bg`. With an image, it is a 6% veil of the strong text color. The image stays visible, and the hover shows over light and dark image areas. Dialogs and Settings keep opaque fills.
|
||||||
- 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.
|
- 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.
|
- 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.
|
- 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.
|
||||||
- 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 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).
|
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), [UI-061](design-decisions.md#ui-061--translucent-menus-and-hover-fills-over-images).
|
||||||
|
|
||||||
### Project Management surfaces
|
### 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.
|
- 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.
|
- 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.
|
- 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.
|
- Card detail buttons have a transparent resting background. Hover, pressed, and focus states stay visible.
|
||||||
@@ -236,13 +245,15 @@ Decisions: [UI-014](design-decisions.md#ui-014--readable-project-management-surf
|
|||||||
|
|
||||||
### Slideshow
|
### 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.
|
- 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.
|
- 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.
|
- The next image loads and decodes before its fade starts. A new frame changes only the custom properties with a new value.
|
||||||
- A new browser tab on `about:blank` shows the host background. A loaded page keeps its own rendering, even when it is empty.
|
- 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
|
## Tooltips and text selection
|
||||||
|
|
||||||
@@ -284,10 +295,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.
|
- 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.
|
- 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.
|
- 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
|
## Review checklist
|
||||||
|
|
||||||
|
|||||||
+77
-8
@@ -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) |
|
| Create, find, or organize files | [Create and find files](#create-and-find-files) |
|
||||||
| Write, read, or follow a link | [Edit documents](#edit-documents) |
|
| Write, read, or follow a link | [Edit documents](#edit-documents) |
|
||||||
| Work with images, diagrams, or tables | [Images, diagrams, and tables](guides/document-tools.md) |
|
| Work with images, diagrams, or tables | [Images, diagrams, and tables](guides/document-tools.md) |
|
||||||
|
| Read a PDF file | [Read PDF files](#read-pdf-files) |
|
||||||
| Start a note from a template | [Use note templates](#use-note-templates) |
|
| Start a note from a template | [Use note templates](#use-note-templates) |
|
||||||
| Arrange tabs and windows | [Manage tabs](#manage-tabs) |
|
| Arrange tabs and windows | [Manage tabs](#manage-tabs) |
|
||||||
| Save, or recover from a changed file | [Save your work](#save-your-work) and [Resolve file conflicts](#resolve-file-conflicts) |
|
| Save, or recover from a changed file | [Save your work](#save-your-work) and [Resolve file conflicts](#resolve-file-conflicts) |
|
||||||
| Change the language or colors | [Change settings](#change-settings) and [Appearance](guides/themes.md) |
|
| 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) |
|
| Browse websites | [Use the built-in browser](#use-the-built-in-browser) |
|
||||||
| Run commands or scripts | [Terminal guide](guides/terminal.md) |
|
| Run commands or scripts | [Terminal guide](guides/terminal.md) |
|
||||||
|
|
||||||
@@ -71,17 +75,17 @@ On macOS and Linux, you can still open, edit, rename, and delete existing files
|
|||||||
|
|
||||||
## Edit documents
|
## Edit documents
|
||||||
|
|
||||||
Each document pane has one view control with three choices, and a **Split** button:
|
Each document pane has one view control with three choices, and a **Read beside** button:
|
||||||
|
|
||||||
| Choice | Shows |
|
| Choice | Shows |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| **Write** | Formatted Markdown. The active line shows its Markdown source. |
|
| **Write** | Formatted Markdown. The active line shows its Markdown source. |
|
||||||
| **Source** | The plain source with line numbers and syntax colors |
|
| **Source** | The plain source with line numbers and syntax colors |
|
||||||
| **Read** | The rendered document, without editing. Markdown files only. |
|
| **Read** | The rendered document, without editing. Markdown files only. |
|
||||||
| **Split** | Read beside Write or Source. Narrow panes stack the two views. Select **Split** again to close it. Markdown files only. |
|
| **Read beside** | Read beside Write or Source. Narrow panes stack the two views. Select **Read beside** 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**.
|
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.
|
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.
|
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.
|
Select a checkbox to complete a task. Copy code blocks without their Markdown fences with the **Copy code** button.
|
||||||
@@ -99,9 +103,9 @@ Read follows CommonMark: a single line break inside a paragraph is a space. To s
|
|||||||
|
|
||||||
- Ctrl+click a link in Write or Source. In Read, a normal click follows the link.
|
- Ctrl+click a link in Write or Source. In Read, a normal click follows the link.
|
||||||
- A workspace file link opens in a new tab and keeps the current document open.
|
- A workspace file link opens in a new tab and keeps the current document open.
|
||||||
- A heading link, such as `guide.md#save-your-work` or `#save-your-work`, scrolls to that heading.
|
- A heading link, such as `guide.md#save-your-work` or `#save-your-work`, puts that heading at the top of the view. A heading near the end of a short document stays lower.
|
||||||
- A wiki link, such as `[[Meeting notes]]`, finds the note by name anywhere in the workspace. If two notes have the same name, use a relative or workspace path.
|
- A wiki link, such as `[[Meeting notes]]`, finds the note by name anywhere in the workspace. If two notes have the same name, use a relative or workspace path.
|
||||||
- The **Backlinks** section below the outline lists notes that link to the current note. Select an entry to open it.
|
- The **Backlinks** section below the outline lists notes that link to the current note. Select an entry to open it. Select the **Backlinks** title to collapse or expand the section. RuneStone keeps that choice for all notes and after a restart.
|
||||||
|
|
||||||
If backlinks look out of date, select **Rebuild note index**. Your Markdown files do not depend on this index.
|
If backlinks look out of date, select **Rebuild note index**. Your Markdown files do not depend on this index.
|
||||||
|
|
||||||
@@ -126,6 +130,28 @@ In Write, these shortcuts format the selected text:
|
|||||||
The menu also has link, search, extraction, and clipboard actions. RuneStone has no formatting toolbar.
|
The menu also has link, search, extraction, and clipboard actions. RuneStone has no formatting toolbar.
|
||||||
Right-click a misspelled word to see spelling suggestions from the operating system.
|
Right-click a misspelled word to see spelling suggestions from the operating system.
|
||||||
|
|
||||||
|
## Read PDF files
|
||||||
|
|
||||||
|
Select a PDF file in the file tree. It opens in its own tab. The file tree marks PDF files with a document icon.
|
||||||
|
|
||||||
|
| Action | How |
|
||||||
|
| --- | --- |
|
||||||
|
| Scroll through the pages | Use the wheel or the scroll bar. With the page area focused, use Page Up, Page Down, Home, End, and the arrow keys. |
|
||||||
|
| Go to a page | Select **Previous page** or **Next page**. Or type a number in the page field and press Enter. |
|
||||||
|
| Zoom | Select **Zoom in** or **Zoom out**. Or type a percent in the zoom field and press Enter. Or hold Ctrl and turn the wheel. The zoom is from 25% to 400%. **Fit width** fits the pages to the tab again. |
|
||||||
|
| Rotate | Select **Rotate clockwise**. Each click turns the pages 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 all pages in one column. The page field shows the page that fills most of the tab. After Ctrl+Tab, the keyboard scrolls the new PDF tab at once.
|
||||||
|
- The tab does not edit PDF files, fill forms, open links, run scripts in a PDF, or print.
|
||||||
|
- Scanned pages show as images, so you cannot select their text.
|
||||||
|
- If a PDF does not open, the tab shows the error. Select **Reload PDF**, or try another copy of the file.
|
||||||
|
|
||||||
|
PDF Viewer is a built-in feature. To turn it off, see [Turn features on or off](#turn-features-on-or-off).
|
||||||
|
|
||||||
## Use note templates
|
## Use note templates
|
||||||
|
|
||||||
A template is a Markdown file in the workspace folder `.runestone/templates/`.
|
A template is a Markdown file in the workspace folder `.runestone/templates/`.
|
||||||
@@ -156,7 +182,26 @@ RuneStone moves the current text of the tab, also unsaved text. It closes the so
|
|||||||
If the move fails, the source tab stays open.
|
If the move fails, the source tab stays open.
|
||||||
|
|
||||||
When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab.
|
When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab.
|
||||||
This includes plugin tabs that show a file, such as a PDF. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening.
|
This includes PDF tabs and plugin tabs that show a file. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening.
|
||||||
|
|
||||||
|
### Show tabs side by side
|
||||||
|
|
||||||
|
Use panes to see two tabs at the same time. For example, browse the web or read a PDF file in one pane, and write a note in the other pane.
|
||||||
|
|
||||||
|
1. Right-click a tab that is not visible, or a file in the file tree.
|
||||||
|
2. Select **Open to the right**.
|
||||||
|
|
||||||
|
The tab opens in a new pane to the right of the active pane. A pane shows a document, a PDF file, or a plugin tab, for example a browser tab. A tab shows in one pane at a time.
|
||||||
|
|
||||||
|
You can also drag a tab from the tab bar to a pane. A drop on the middle of the pane shows the tab in that pane. A drop on the left, right, or bottom part opens a new pane there. A hint shows the place before you release the tab.
|
||||||
|
You can also drag the tab that a pane shows to the left, right, or bottom part of that pane. The tab moves to the new pane, and the old pane shows the next tab that is not visible. This needs a second tab that is not visible.
|
||||||
|
|
||||||
|
- Click a pane to make its tab the active tab. A tab that you select, or a file that you open, replaces the content of the active pane. The replaced tab stays open.
|
||||||
|
- Drag the divider between two panes to change their sizes. Double-click the divider to give the panes equal sizes. With the keyboard, focus the divider and use the arrow keys.
|
||||||
|
- A pane beside other panes names its file in the bar above the document. To close the pane, select **Close split** in that bar. You can also right-click its tab and select **Close split**. The tab stays open.
|
||||||
|
- A browser tab or a PDF tab that fills the area moves to the left pane when a tab opens to the right. When one pane is left, its tab fills the area again.
|
||||||
|
- In the menu of a browser tab, **New tab to the right** and **New tab below** open a new browser tab with the home page in a pane beside it.
|
||||||
|
- The link menu also has **Open to the right**. In a narrow window, the panes show one above the other.
|
||||||
|
|
||||||
## Save your work
|
## Save your work
|
||||||
|
|
||||||
@@ -197,9 +242,29 @@ Settings apply at once to all workspaces on this computer and update all open wi
|
|||||||
| Category | Settings |
|
| Category | Settings |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save |
|
| General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save |
|
||||||
| Appearance | Color theme, transparency, background 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). |
|
| Plug-ins | Install, enable, update, and remove plugins. See [Install and manage plugins](plugins.md). |
|
||||||
| Browser | Homepage, search engine, profiles, ad blocking, and web data |
|
| Browser | Homepage, search engine, profiles, ad blocking, and web data |
|
||||||
|
| Terminal | Default profile, font size, scrollback lines, and cursor blink. The page shows only while Terminal is on. See [Change the terminal settings](guides/terminal.md#change-the-terminal-settings). |
|
||||||
|
| 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 简体中文.
|
**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.
|
It does not translate documents, plugin content, or operating system messages. Some error messages stay in English.
|
||||||
@@ -218,6 +283,10 @@ If a download fails, the tab shows the cause. Select **Retry** to start the down
|
|||||||
Until the engine is installed, web links in your documents open in your system browser.
|
Until the engine is installed, web links in your documents open in your system browser.
|
||||||
After a RuneStone update that needs a new engine, a browser tab offers **Update the engine**.
|
After a RuneStone update that needs a new engine, a browser tab offers **Update the engine**.
|
||||||
|
|
||||||
|
In a page, middle-click a link to open it in a new tab. Middle-click other content to scroll, then move the pointer in the direction to scroll.
|
||||||
|
Right-click an image for **Open image in new tab**, **Save image as…**, **Copy image**, and **Copy image address**.
|
||||||
|
**Copy image** keeps the original file. A GIF that you paste into a document or a card keeps its animation.
|
||||||
|
|
||||||
Use **Settings → Browser** to set the homepage and search engine, manage profiles, block ads, and clear cookies, cache, or history.
|
Use **Settings → Browser** to set the homepage and search engine, manage profiles, block ads, and clear cookies, cache, or history.
|
||||||
**Settings → Browser → Browser engine** shows the installed version. **Remove engine** frees the disk space. Your profiles, bookmarks, and history stay.
|
**Settings → Browser → Browser engine** shows the installed version. **Remove engine** frees the disk space. Your profiles, bookmarks, and history stay.
|
||||||
Each profile keeps its own cookies and bookmarks. Web bookmarks show in the Bookmarks pane.
|
Each profile keeps its own cookies and bookmarks. Web bookmarks show in the Bookmarks pane.
|
||||||
|
|||||||
+8
-3
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "runestone",
|
"name": "runestone",
|
||||||
"version": "0.1.49",
|
"version": "1.0.0a",
|
||||||
"description": "Desktop editor for a local workspace",
|
"description": "Desktop editor for a local workspace",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"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": "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:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
||||||
"check:menus": "node scripts/menuSurfaceAudit.mjs",
|
"check:menus": "node scripts/menuSurfaceAudit.mjs",
|
||||||
|
"check:features": "node scripts/featureChunks.mjs",
|
||||||
"tauri": "tauri",
|
"tauri": "tauri",
|
||||||
"test": "node --experimental-strip-types --import ./tests/unit/_svelte/register.mjs --test \"tests/unit/**/*.spec.ts\"",
|
"test": "node --experimental-strip-types --import ./tests/unit/_svelte/register.mjs --test \"tests/unit/**/*.spec.ts\"",
|
||||||
"smoke": "node scripts/smoke.mjs",
|
"smoke": "node scripts/smoke.mjs",
|
||||||
@@ -24,7 +25,7 @@
|
|||||||
"sdk:build": "node scripts/buildSdk.mjs",
|
"sdk:build": "node scripts/buildSdk.mjs",
|
||||||
"release:sdk": "node scripts/releaseSdk.mjs"
|
"release:sdk": "node scripts/releaseSdk.mjs"
|
||||||
},
|
},
|
||||||
"license": "MIT",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@codemirror/autocomplete": "^6.20.3",
|
"@codemirror/autocomplete": "^6.20.3",
|
||||||
"@codemirror/commands": "^6.11.1",
|
"@codemirror/commands": "^6.11.1",
|
||||||
@@ -53,8 +54,12 @@
|
|||||||
"@tiptap/extension-link": "^3.31.3",
|
"@tiptap/extension-link": "^3.31.3",
|
||||||
"@tiptap/pm": "^3.31.3",
|
"@tiptap/pm": "^3.31.3",
|
||||||
"@tiptap/starter-kit": "^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",
|
"markdown-it": "^15.0.2",
|
||||||
"mermaid": "^12.0.0"
|
"mermaid": "^12.0.0",
|
||||||
|
"pdfjs-dist": "6.4.299",
|
||||||
|
"yaml": "2.9.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@sveltejs/adapter-static": "^3.0.10",
|
"@sveltejs/adapter-static": "^3.0.10",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# RuneStone Plugin SDK
|
# RuneStone Plugin SDK
|
||||||
|
|
||||||
`@runestone/plugin-sdk` gives TypeScript types and small helpers for [RuneStone](https://git.knottywyvern.com/kwyvern/RuneStone) plugins.
|
`@runestone/plugin-sdk` gives TypeScript types and small helpers for [RuneStone](https://github.com/KnottyWyvern-GH/RuneStone) plugins.
|
||||||
RuneStone is a desktop workspace for Markdown notes, code, and project work. Plugins add views, commands, and document editors to it.
|
RuneStone is a desktop workspace for Markdown notes, code, and project work. Plugins add views, commands, and document editors to it.
|
||||||
|
|
||||||
The SDK contains:
|
The SDK contains:
|
||||||
@@ -17,7 +17,7 @@ The SDK does not run plugins and does not call RuneStone. RuneStone gives the `a
|
|||||||
Install the SDK from the URL of its package file on the RuneStone releases page.
|
Install the SDK from the URL of its package file on the RuneStone releases page.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
pnpm add -D "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
pnpm add -D "https://github.com/KnottyWyvern-GH/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
||||||
```
|
```
|
||||||
|
|
||||||
The result in `package.json`:
|
The result in `package.json`:
|
||||||
@@ -25,7 +25,7 @@ The result in `package.json`:
|
|||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@runestone/plugin-sdk": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
"@runestone/plugin-sdk": "https://github.com/KnottyWyvern-GH/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -60,13 +60,13 @@ export function activate(api: PluginApi) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Compile the module with a bundler, so the entry file contains the SDK helpers that it uses. RuneStone loads the entry from a Blob URL, so imports from `node_modules` do not resolve at run time.
|
Compile the module with a bundler, so the entry file contains the SDK helpers that it uses. RuneStone loads the entry from a Blob URL, so imports from `node_modules` do not resolve at run time.
|
||||||
Then make the plugin ZIP. See [Build and package a plugin](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugin-development.md#build-and-package-a-plugin).
|
Then make the plugin ZIP. See [Build and package a plugin](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/plugin-development.md#build-and-package-a-plugin).
|
||||||
|
|
||||||
A type-only import, such as `import type { PluginApi }`, adds no code to the bundle.
|
A type-only import, such as `import type { PluginApi }`, adds no code to the bundle.
|
||||||
|
|
||||||
## Check for features
|
## 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.
|
Make sure that a member exists before you use it.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
@@ -74,8 +74,8 @@ import { hasFeature, requireFeature, requireFeatures, type PluginApi } from "@ru
|
|||||||
|
|
||||||
export function activate(api: PluginApi) {
|
export function activate(api: PluginApi) {
|
||||||
// Stop the activation with one message that names each missing feature.
|
// Stop the activation with one message that names each missing feature.
|
||||||
requireFeatures(api, ["pty", "workspace.readOptional"]);
|
requireFeatures(api, ["files", "workspace.readOptional"]);
|
||||||
const pty = requireFeature(api, "pty");
|
const files = requireFeature(api, "files");
|
||||||
|
|
||||||
// Hide a control when the feature is absent.
|
// Hide a control when the feature is absent.
|
||||||
if (hasFeature(api, "ui.showActionMenu")) showMenuButton();
|
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.
|
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:
|
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.
|
`pluginFeatures` lists all the feature names. The checks examine only whether the member exists.
|
||||||
|
|
||||||
@@ -128,12 +128,12 @@ A new SDK release can add types for new RuneStone features. Use the feature chec
|
|||||||
|
|
||||||
## Documentation and help
|
## Documentation and help
|
||||||
|
|
||||||
- [Plugin development reference](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugin-development.md): the package format, the API, and the build procedure
|
- [Plugin development reference](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/plugin-development.md): the package format, the API, and the build procedure
|
||||||
- [Completion API](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/completion.md)
|
- [Completion API](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/completion.md)
|
||||||
- [Install and manage plugins](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugins.md)
|
- [Install and manage plugins](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/plugins.md)
|
||||||
- [Release policy](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/releases.md#sdk-releases)
|
- [Release policy](https://github.com/KnottyWyvern-GH/RuneStone/blob/master/docs/releases.md#sdk-releases)
|
||||||
|
|
||||||
The SDK source is in the `packages/plugin-sdk` folder of the [RuneStone repository](https://git.knottywyvern.com/kwyvern/RuneStone). Report problems there.
|
The SDK source is in the `packages/plugin-sdk` folder of the [RuneStone repository](https://github.com/KnottyWyvern-GH/RuneStone). Report problems there.
|
||||||
|
|
||||||
Knotty Wyvern maintains RuneStone and the SDK.
|
Knotty Wyvern maintains RuneStone and the SDK.
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
import type { BackgroundApi } from "./backgrounds.ts";
|
|
||||||
import type { CompletionApi } from "./completion.ts";
|
import type { CompletionApi } from "./completion.ts";
|
||||||
import type { Contributions } from "./contributions.ts";
|
import type { Contributions } from "./contributions.ts";
|
||||||
import type { GitApi } from "./git.ts";
|
|
||||||
import type { ActionIcon } from "./icons.ts";
|
import type { ActionIcon } from "./icons.ts";
|
||||||
import type { ActionMenuItem, ActionMenuOptions } from "./menu.ts";
|
import type { ActionMenuItem, ActionMenuOptions } from "./menu.ts";
|
||||||
|
|
||||||
@@ -21,34 +19,6 @@ export interface PluginDocumentType {
|
|||||||
create?: { label: string; defaultName: string; extension: string; contents(): string };
|
create?: { label: string; defaultName: string; extension: string; contents(): string };
|
||||||
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
|
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 FolderGrant { id: string; path: string; name: string }
|
||||||
export interface FolderEntry { name: string; size: number }
|
export interface FolderEntry { name: string; size: number }
|
||||||
/** Folders outside the workspace that the user granted to this plugin. */
|
/** 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. */
|
/** Interface parts that the host draws. */
|
||||||
export interface UiApi { showActionMenu(options: ActionMenuOptions): { close(): void } }
|
export interface UiApi { showActionMenu(options: ActionMenuOptions): { close(): void } }
|
||||||
export interface PluginApi {
|
export interface PluginApi {
|
||||||
pty?: PtyApi;
|
|
||||||
files?: FilesApi;
|
files?: FilesApi;
|
||||||
services?: ServicesApi;
|
services?: ServicesApi;
|
||||||
backgrounds?: BackgroundApi;
|
|
||||||
ui?: UiApi;
|
ui?: UiApi;
|
||||||
git?: GitApi;
|
|
||||||
completion?: CompletionApi;
|
completion?: CompletionApi;
|
||||||
readonly id: string;
|
readonly id: string;
|
||||||
readonly signal: AbortSignal;
|
readonly signal: AbortSignal;
|
||||||
|
|||||||
@@ -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;
|
|
||||||
}
|
|
||||||
@@ -1,20 +1,7 @@
|
|||||||
import type { Dispose } from "./api.ts";
|
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. */
|
/** Host features that `api.contribute(key, value)` registers. Only one enabled plugin can own each key. */
|
||||||
export interface Contributions {
|
export interface Contributions {
|
||||||
git: { blame(path: string, line: number): Promise<GitLineInfo | null> };
|
|
||||||
browser: {
|
browser: {
|
||||||
/** Opens a browser tab, with `url` when it is given. */
|
/** Opens a browser tab, with `url` when it is given. */
|
||||||
newTab?(url?: string): Promise<void>;
|
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. */
|
/** Opens a web link from a document. False means that the system browser opens it. */
|
||||||
open(url: string): Promise<boolean>;
|
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,23 +1,13 @@
|
|||||||
import type { FilesApi, PluginApi, PtyApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts";
|
import type { FilesApi, PluginApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts";
|
||||||
import type { BackgroundApi } from "./backgrounds.ts";
|
|
||||||
import type { CompletionApi } from "./completion.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.
|
* 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.
|
* Older RuneStone hosts can omit these members. Required members, such as `workspace.read`, are not listed.
|
||||||
*/
|
*/
|
||||||
export interface PluginFeatures {
|
export interface PluginFeatures {
|
||||||
pty: PtyApi;
|
|
||||||
files: FilesApi;
|
files: FilesApi;
|
||||||
services: ServicesApi;
|
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: CompletionApi;
|
||||||
"completion.transport": NonNullable<CompletionApi["transport"]>;
|
"completion.transport": NonNullable<CompletionApi["transport"]>;
|
||||||
"ui.showActionMenu": UiApi["showActionMenu"];
|
"ui.showActionMenu": UiApi["showActionMenu"];
|
||||||
@@ -40,16 +30,8 @@ export interface PluginFeatures {
|
|||||||
export type PluginFeature = keyof PluginFeatures;
|
export type PluginFeature = keyof PluginFeatures;
|
||||||
|
|
||||||
const descriptions: { [K in PluginFeature]: string } = {
|
const descriptions: { [K in PluginFeature]: string } = {
|
||||||
pty: "the terminal API",
|
|
||||||
files: "the folder grant API",
|
files: "the folder grant API",
|
||||||
services: "the plugin service 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: "the completion API",
|
||||||
"completion.transport": "the completion model transport",
|
"completion.transport": "the completion model transport",
|
||||||
"ui.showActionMenu": "the shared action menu",
|
"ui.showActionMenu": "the shared action menu",
|
||||||
|
|||||||
@@ -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[];
|
|
||||||
}
|
|
||||||
@@ -22,6 +22,7 @@ export const actionIcons = {
|
|||||||
puzzle: '<path d="M9 3H4v6a3 3 0 1 1 0 6v5h6a3 3 0 1 1 6 0h4v-6a3 3 0 1 0 0-6V3h-5a3 3 0 1 1-6 0Z"/>',
|
puzzle: '<path d="M9 3H4v6a3 3 0 1 1 0 6v5h6a3 3 0 1 1 6 0h4v-6a3 3 0 1 0 0-6V3h-5a3 3 0 1 1-6 0Z"/>',
|
||||||
'split-right': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M12 4v16m3-11 3 3-3 3"/>',
|
'split-right': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M12 4v16m3-11 3 3-3 3"/>',
|
||||||
'split-down': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 12h18m-12 3 3 3 3-3"/>',
|
'split-down': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 12h18m-12 3 3 3 3-3"/>',
|
||||||
|
'split-close': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="m7 9 3 3-3 3m10-6-3 3 3 3"/>',
|
||||||
kanban: '<rect x="3" y="4" width="5" height="16" rx="1"/><rect x="10" y="4" width="5" height="11" rx="1"/><rect x="17" y="4" width="4" height="7" rx="1"/>',
|
kanban: '<rect x="3" y="4" width="5" height="16" rx="1"/><rect x="10" y="4" width="5" height="11" rx="1"/><rect x="17" y="4" width="4" height="7" rx="1"/>',
|
||||||
bookmark: '<path d="M6 4h12v16l-6-3-6 3z"/>',
|
bookmark: '<path d="M6 4h12v16l-6-3-6 3z"/>',
|
||||||
'file-plus': '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M12 18v-6M9 15h6"/>',
|
'file-plus': '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M12 18v-6M9 15h6"/>',
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
// The public types and helpers of the RuneStone plugin API.
|
// 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".
|
// 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 "./api.ts";
|
||||||
export type * from "./backgrounds.ts";
|
|
||||||
export type * from "./completion.ts";
|
export type * from "./completion.ts";
|
||||||
export type * from "./contributions.ts";
|
export type * from "./contributions.ts";
|
||||||
export type * from "./git.ts";
|
|
||||||
export type * from "./menu.ts";
|
export type * from "./menu.ts";
|
||||||
export type { ActionIcon } from "./icons.ts";
|
export type { ActionIcon } from "./icons.ts";
|
||||||
export { API_VERSION, type PluginManifest } from "./manifest.ts";
|
export { API_VERSION, type PluginManifest } from "./manifest.ts";
|
||||||
|
|||||||
Generated
+176
-15
@@ -89,22 +89,34 @@ importers:
|
|||||||
'@tiptap/starter-kit':
|
'@tiptap/starter-kit':
|
||||||
specifier: ^3.31.3
|
specifier: ^3.31.3
|
||||||
version: 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:
|
markdown-it:
|
||||||
specifier: ^15.0.2
|
specifier: ^15.0.2
|
||||||
version: 15.0.2
|
version: 15.0.2
|
||||||
mermaid:
|
mermaid:
|
||||||
specifier: ^12.0.0
|
specifier: ^12.0.0
|
||||||
version: 12.0.0
|
version: 12.0.0
|
||||||
|
pdfjs-dist:
|
||||||
|
specifier: 6.4.299
|
||||||
|
version: 6.4.299
|
||||||
|
yaml:
|
||||||
|
specifier: 2.9.1
|
||||||
|
version: 2.9.1
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@sveltejs/adapter-static':
|
'@sveltejs/adapter-static':
|
||||||
specifier: ^3.0.10
|
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':
|
'@sveltejs/kit':
|
||||||
specifier: ^2.65.1
|
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':
|
'@sveltejs/vite-plugin-svelte':
|
||||||
specifier: ^7.1.2
|
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':
|
'@tauri-apps/cli':
|
||||||
specifier: ^2
|
specifier: ^2
|
||||||
version: 2.11.4
|
version: 2.11.4
|
||||||
@@ -125,7 +137,7 @@ importers:
|
|||||||
version: 6.0.3
|
version: 6.0.3
|
||||||
vite:
|
vite:
|
||||||
specifier: ^8.0.16
|
specifier: ^8.0.16
|
||||||
version: 8.3.0(@types/[email protected])
|
version: 8.3.0(@types/[email protected])([email protected])
|
||||||
|
|
||||||
packages:
|
packages:
|
||||||
|
|
||||||
@@ -272,6 +284,81 @@ packages:
|
|||||||
resolution: {integrity: sha512-K8BeapFUfrfxbRAUQAG5oBOCwo1+bNWzaVnPxTCutkfrTBn6T/j91FIhqxWJ32SUeQ9T3iy1zcmPZ5ROZEvDrg==}
|
resolution: {integrity: sha512-K8BeapFUfrfxbRAUQAG5oBOCwo1+bNWzaVnPxTCutkfrTBn6T/j91FIhqxWJ32SUeQ9T3iy1zcmPZ5ROZEvDrg==}
|
||||||
engines: {node: '>=22.12.0'}
|
engines: {node: '>=22.12.0'}
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-trn7AaDzQ+yeeA0ezhkC7cB1ZDPtp4UYk0EvB5F8qtYL9jEVWtVrU30WOpI52DszoTxaTsCgf5PP4ZVaOlOIHQ==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [android]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-6Y2djEetL8copxfNK6hg7oig/xqTwOchv19hBOm+zBNdKc/02Z3kjZN5wrLzv/l5O04/bAQS6I/AlQpwBlXgPg==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [darwin]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-OZoPwwu4TMMg8GTCFBrg8UFExwQTU/55i3uTC/izDat6PHE+ro9dimyQoOboFf91+NY7Pnn70ScR8f8I8+eZXw==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [darwin]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-dZSYaKROuswU2eUWG5aBKndNVe68elo1YX93xtRax7q658tj8rYE+HwduovWJgs6qwv1r1/CLR60nDeBbyjvyg==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [arm]
|
||||||
|
os: [linux]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-W6FzYE8ADHI93In1vi80KBL6btDtAMuj50Ch5ptkWS8xuntyzbR4h5JDUmXoakxZn2yMInksudTEqVSWoFqFGg==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-+6fQ+rR49hkAa4voh2stLIwQ+4t+gmoseM8Bc53/DlMXb73IKymDPWK9A/NtWeqTW4ijWppYuyuxS2hPI8tzNA==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [linux]
|
||||||
|
libc: [musl]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-17XEMO3t9RW/TtHtSFf2AkaSWuCWdzbPeidz7zrOFawHxoLSJCnpTI1hN5aUvrZNnkNNmt/vZVJCh0ryUaik3A==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [riscv64]
|
||||||
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-lc48IwknVHBsNzXn9Xs5OkUsRX38Ml3Z1aOybQ51mMEzZckm8+4A0qROlyYHEoBPzr1kL3IU8ZUAqDb7wtdX8w==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-bGY1r26S2bs8UNFJcPWcCSNdCFbKep5PATsvtgtC9A5u6SRgr2/jJE/RlhHL5m9ZpixNDhVkLY/5h16Kx5V9YA==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [linux]
|
||||||
|
libc: [musl]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-2vRPBZoaIvJrUkDhZTE2Hn0YrnpJRCWVM3EJACoBKjuWI6WgPxGtUoRMsxRviCsyks8bKTSFdyw14CellnG2qA==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [win32]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-DUlW3lZPz63kYsf8mxgyyZuevhlH0T3/BGP9l+NazhB0F1+gL6D4hqZdnhZpw24DlWmTpATDcyYSZlJOi+DdfQ==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [win32]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-b87ugZpQ5ViwqVBkjervxpwa0GmJPsKHLBNoZN6GpjWeHzTbDUGryriq+2DYW2XbB+xCqSIINQysC0/I87nPbw==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
|
||||||
'@oxc-project/[email protected]':
|
'@oxc-project/[email protected]':
|
||||||
resolution: {integrity: sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==}
|
resolution: {integrity: sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==}
|
||||||
|
|
||||||
@@ -750,6 +837,12 @@ packages:
|
|||||||
'@upsetjs/[email protected]':
|
'@upsetjs/[email protected]':
|
||||||
resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}
|
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]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==}
|
resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==}
|
||||||
engines: {node: '>=0.4.0'}
|
engines: {node: '>=0.4.0'}
|
||||||
@@ -1183,6 +1276,10 @@ packages:
|
|||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==}
|
resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==}
|
||||||
|
|
||||||
|
[email protected]:
|
||||||
|
resolution: {integrity: sha512-AVl138zALtfaAPvADulE0PZThbYzCBS79nL4pOSL/6Sm/4AH5A21BD9VHt97OlCuzJuCpmeZtAtkinisF4Vb1g==}
|
||||||
|
engines: {node: '>=22.13.0 || >=24'}
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
||||||
|
|
||||||
@@ -1395,6 +1492,11 @@ packages:
|
|||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
|
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
|
||||||
|
|
||||||
|
[email protected]:
|
||||||
|
resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==}
|
||||||
|
engines: {node: '>= 14.6'}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==}
|
resolution: {integrity: sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==}
|
||||||
|
|
||||||
@@ -1661,6 +1763,54 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
'@chevrotain/types': 11.1.2
|
'@chevrotain/types': 11.1.2
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optionalDependencies:
|
||||||
|
'@napi-rs/canvas-android-arm64': 1.0.13
|
||||||
|
'@napi-rs/canvas-darwin-arm64': 1.0.13
|
||||||
|
'@napi-rs/canvas-darwin-x64': 1.0.13
|
||||||
|
'@napi-rs/canvas-linux-arm-gnueabihf': 1.0.13
|
||||||
|
'@napi-rs/canvas-linux-arm64-gnu': 1.0.13
|
||||||
|
'@napi-rs/canvas-linux-arm64-musl': 1.0.13
|
||||||
|
'@napi-rs/canvas-linux-riscv64-gnu': 1.0.13
|
||||||
|
'@napi-rs/canvas-linux-x64-gnu': 1.0.13
|
||||||
|
'@napi-rs/canvas-linux-x64-musl': 1.0.13
|
||||||
|
'@napi-rs/canvas-win32-arm64-msvc': 1.0.13
|
||||||
|
'@napi-rs/canvas-win32-x64-msvc': 1.0.13
|
||||||
|
optional: true
|
||||||
|
|
||||||
'@oxc-project/[email protected]': {}
|
'@oxc-project/[email protected]': {}
|
||||||
|
|
||||||
'@polka/[email protected]': {}
|
'@polka/[email protected]': {}
|
||||||
@@ -1718,15 +1868,15 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
acorn: 8.18.0
|
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:
|
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:
|
dependencies:
|
||||||
'@standard-schema/spec': 1.1.0
|
'@standard-schema/spec': 1.1.0
|
||||||
'@sveltejs/acorn-typescript': 1.0.13([email protected])
|
'@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
|
'@types/cookie': 0.6.0
|
||||||
acorn: 8.18.0
|
acorn: 8.18.0
|
||||||
cookie: 0.6.0
|
cookie: 0.6.0
|
||||||
@@ -1738,20 +1888,20 @@ snapshots:
|
|||||||
set-cookie-parser: 3.1.2
|
set-cookie-parser: 3.1.2
|
||||||
sirv: 3.0.2
|
sirv: 3.0.2
|
||||||
svelte: 5.57.1
|
svelte: 5.57.1
|
||||||
vite: 8.3.0(@types/[email protected])
|
vite: 8.3.0(@types/[email protected])([email protected])
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
typescript: 6.0.3
|
typescript: 6.0.3
|
||||||
|
|
||||||
'@sveltejs/[email protected]': {}
|
'@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:
|
dependencies:
|
||||||
deepmerge: 4.3.1
|
deepmerge: 4.3.1
|
||||||
magic-string: 1.4.1
|
magic-string: 1.4.1
|
||||||
obug: 2.2.1
|
obug: 2.2.1
|
||||||
svelte: 5.57.1
|
svelte: 5.57.1
|
||||||
vite: 8.3.0(@types/[email protected])
|
vite: 8.3.0(@types/[email protected])([email protected])
|
||||||
vitefu: 1.1.3([email protected](@types/[email protected]))
|
vitefu: 1.1.3([email protected](@types/[email protected])([email protected]))
|
||||||
|
|
||||||
'@tauri-apps/[email protected]': {}
|
'@tauri-apps/[email protected]': {}
|
||||||
|
|
||||||
@@ -2095,6 +2245,10 @@ snapshots:
|
|||||||
d3-selection: 3.0.0
|
d3-selection: 3.0.0
|
||||||
d3-transition: 3.0.1([email protected])
|
d3-transition: 3.0.1([email protected])
|
||||||
|
|
||||||
|
'@xterm/[email protected]': {}
|
||||||
|
|
||||||
|
'@xterm/[email protected]': {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
@@ -2503,6 +2657,10 @@ snapshots:
|
|||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
|
[email protected]:
|
||||||
|
optionalDependencies:
|
||||||
|
'@napi-rs/canvas': 1.0.13
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
@@ -2710,7 +2868,7 @@ snapshots:
|
|||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected](@types/[email protected]):
|
[email protected](@types/[email protected])([email protected]):
|
||||||
dependencies:
|
dependencies:
|
||||||
lightningcss: 1.33.0
|
lightningcss: 1.33.0
|
||||||
picomatch: 4.0.7
|
picomatch: 4.0.7
|
||||||
@@ -2720,11 +2878,14 @@ snapshots:
|
|||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/node': 24.19.2
|
'@types/node': 24.19.2
|
||||||
fsevents: 2.3.3
|
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:
|
optionalDependencies:
|
||||||
vite: 8.3.0(@types/[email protected])
|
vite: 8.3.0(@types/[email protected])([email protected])
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|||||||
@@ -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();
|
||||||
@@ -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));
|
||||||
@@ -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";
|
||||||
|
}
|
||||||
@@ -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 };
|
||||||
|
}
|
||||||
@@ -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())),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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 };
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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() };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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() };
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -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; });
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
|
|||||||
|
|
||||||
const root = fileURLToPath(new URL('../', import.meta.url));
|
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||||
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..');
|
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..');
|
||||||
export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_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 = {
|
const patterns = {
|
||||||
action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
|
action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
|
||||||
svelteMenu: /<ContextMenu\b/g,
|
svelteMenu: /<ContextMenu\b/g,
|
||||||
|
|||||||
@@ -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
@@ -6,7 +6,7 @@
|
|||||||
// After the parallel run, the runner runs each failed test again, one at a time (--retries, default 1).
|
// 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 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:
|
// 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.
|
// 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:
|
// A test that fails because of a known app defect states it near the top:
|
||||||
// // @known-issue <the defect>
|
// // @known-issue <the defect>
|
||||||
@@ -67,10 +67,6 @@ async function header(file) {
|
|||||||
|
|
||||||
function missing(requirement) {
|
function missing(requirement) {
|
||||||
const [kind, value = ""] = requirement.split(/:(.*)/s);
|
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") {
|
if (kind === "repo") {
|
||||||
const target = path.join(pluginRepos, value);
|
const target = path.join(pluginRepos, value);
|
||||||
return existsSync(target) ? null : `${target} is missing; set RUNESTONE_PLUGIN_REPOS to the folder of the plugin checkouts`;
|
return existsSync(target) ? null : `${target} is missing; set RUNESTONE_PLUGIN_REPOS to the folder of the plugin checkouts`;
|
||||||
|
|||||||
Generated
+1
-1
@@ -3130,7 +3130,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "runestone"
|
name = "runestone"
|
||||||
version = "0.1.49"
|
version = "1.0.0+1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
"dunce",
|
"dunce",
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "runestone"
|
name = "runestone"
|
||||||
version = "0.1.49"
|
version = "1.0.0+1"
|
||||||
description = "Writing workspace plus script editor"
|
description = "Writing workspace plus script editor"
|
||||||
authors = ["Knotty Wyvern"]
|
authors = ["Knotty Wyvern"]
|
||||||
|
license = "Apache-2.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
@@ -46,4 +47,4 @@ opt-level = 3
|
|||||||
strip = true
|
strip = true
|
||||||
|
|
||||||
[package.metadata.runestone]
|
[package.metadata.runestone]
|
||||||
version = "0.1.49"
|
version = "1.0.0a"
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
{
|
{
|
||||||
"version": "0.1.8",
|
"version": "0.1.11",
|
||||||
"protocol": 1,
|
"protocol": 1,
|
||||||
"platforms": {
|
"platforms": {
|
||||||
"windows-x86_64": {
|
"windows-x86_64": {
|
||||||
"url": "https://git.knottywyvern.com/kwyvern/RuneStone_Releases/releases/download/browser-engine-v0.1.8/RuneStone-Browser_0.1.8_win32-x64.zip",
|
"url": "https://github.com/KnottyWyvern-GH/RuneStone/releases/download/browser-engine-v0.1.11/RuneStone-Browser_0.1.11_win32-x64.zip",
|
||||||
"bytes": 163632595,
|
"bytes": 163623801,
|
||||||
"sha256": "d704003bf5fe047b100a3cf0ab84f3321fd272510cf287a229e50d1653d0856b"
|
"sha256": "1e0153b134cebe882b36f74e1f3c2a4ed37acb2caca10548034a8b5d88738d26"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-6
@@ -3,12 +3,14 @@ fn main() {
|
|||||||
tauri_build::Attributes::new().app_manifest(
|
tauri_build::Attributes::new().app_manifest(
|
||||||
tauri_build::AppManifest::new().commands(&[
|
tauri_build::AppManifest::new().commands(&[
|
||||||
"theme_export",
|
"theme_export",
|
||||||
"backgrounds_choose_folder",
|
"background_choose_folder",
|
||||||
"backgrounds_default_folder",
|
"background_folder",
|
||||||
"backgrounds_list",
|
"background_clear_folder",
|
||||||
"backgrounds_read",
|
"background_list",
|
||||||
"backgrounds_read_image_settings",
|
"background_read",
|
||||||
"backgrounds_write_image_settings",
|
"background_read_sidecar",
|
||||||
|
"background_write_sidecar",
|
||||||
|
"background_migrate",
|
||||||
"folders_choose",
|
"folders_choose",
|
||||||
"folders_picture",
|
"folders_picture",
|
||||||
"folders_grants",
|
"folders_grants",
|
||||||
@@ -17,6 +19,7 @@ fn main() {
|
|||||||
"folders_read",
|
"folders_read",
|
||||||
"folders_read_sidecar",
|
"folders_read_sidecar",
|
||||||
"folders_write_sidecar",
|
"folders_write_sidecar",
|
||||||
|
"features_legacy",
|
||||||
"spelling_suggestions",
|
"spelling_suggestions",
|
||||||
"spelling_menu_install",
|
"spelling_menu_install",
|
||||||
"spelling_menu_select",
|
"spelling_menu_select",
|
||||||
@@ -68,6 +71,8 @@ fn main() {
|
|||||||
"workspace_delete",
|
"workspace_delete",
|
||||||
"workspace_read_data_url",
|
"workspace_read_data_url",
|
||||||
"workspace_write_bytes",
|
"workspace_write_bytes",
|
||||||
|
"workspace_save_image_url",
|
||||||
|
"workspace_download_image",
|
||||||
"workspace_copy",
|
"workspace_copy",
|
||||||
"workspace_abs_path",
|
"workspace_abs_path",
|
||||||
"workspace_reveal",
|
"workspace_reveal",
|
||||||
@@ -95,6 +100,7 @@ fn main() {
|
|||||||
"pty_profiles",
|
"pty_profiles",
|
||||||
"pty_new_window",
|
"pty_new_window",
|
||||||
"pty_dictation",
|
"pty_dictation",
|
||||||
|
"pty_running",
|
||||||
]),
|
]),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -13,6 +13,10 @@
|
|||||||
"allow-browser-engine-install",
|
"allow-browser-engine-install",
|
||||||
"allow-browser-engine-cancel",
|
"allow-browser-engine-cancel",
|
||||||
"allow-plugins-snapshot",
|
"allow-plugins-snapshot",
|
||||||
|
"allow-background-folder",
|
||||||
|
"allow-background-list",
|
||||||
|
"allow-background-read",
|
||||||
|
"allow-background-read-sidecar",
|
||||||
"allow-settings-read",
|
"allow-settings-read",
|
||||||
"allow-window-snap-layouts",
|
"allow-window-snap-layouts",
|
||||||
"allow-settings-write",
|
"allow-settings-write",
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
"allow-settings-read",
|
"allow-settings-read",
|
||||||
"allow-settings-write",
|
"allow-settings-write",
|
||||||
"allow-settings-migrate",
|
"allow-settings-migrate",
|
||||||
|
"allow-features-legacy",
|
||||||
"allow-tab-transfer-offer",
|
"allow-tab-transfer-offer",
|
||||||
"allow-tab-transfer-take",
|
"allow-tab-transfer-take",
|
||||||
"allow-tab-transfer-finish",
|
"allow-tab-transfer-finish",
|
||||||
@@ -68,6 +69,8 @@
|
|||||||
"allow-workspace-delete",
|
"allow-workspace-delete",
|
||||||
"allow-workspace-read-data-url",
|
"allow-workspace-read-data-url",
|
||||||
"allow-workspace-write-bytes",
|
"allow-workspace-write-bytes",
|
||||||
|
"allow-workspace-save-image-url",
|
||||||
|
"allow-workspace-download-image",
|
||||||
"allow-workspace-copy",
|
"allow-workspace-copy",
|
||||||
"allow-workspace-abs-path",
|
"allow-workspace-abs-path",
|
||||||
"allow-workspace-reveal",
|
"allow-workspace-reveal",
|
||||||
@@ -95,13 +98,16 @@
|
|||||||
"allow-pty-profiles",
|
"allow-pty-profiles",
|
||||||
"allow-pty-new-window",
|
"allow-pty-new-window",
|
||||||
"allow-pty-dictation",
|
"allow-pty-dictation",
|
||||||
|
"allow-pty-running",
|
||||||
"opener:allow-reveal-item-in-dir",
|
"opener:allow-reveal-item-in-dir",
|
||||||
"allow-backgrounds-choose-folder",
|
"allow-background-choose-folder",
|
||||||
"allow-backgrounds-default-folder",
|
"allow-background-folder",
|
||||||
"allow-backgrounds-list",
|
"allow-background-clear-folder",
|
||||||
"allow-backgrounds-read",
|
"allow-background-list",
|
||||||
"allow-backgrounds-read-image-settings",
|
"allow-background-read",
|
||||||
"allow-backgrounds-write-image-settings",
|
"allow-background-read-sidecar",
|
||||||
|
"allow-background-write-sidecar",
|
||||||
|
"allow-background-migrate",
|
||||||
"allow-folders-choose",
|
"allow-folders-choose",
|
||||||
"allow-folders-picture",
|
"allow-folders-picture",
|
||||||
"allow-folders-grants",
|
"allow-folders-grants",
|
||||||
|
|||||||
@@ -12,6 +12,9 @@
|
|||||||
"allow-window-snap-layouts",
|
"allow-window-snap-layouts",
|
||||||
"allow-settings-write",
|
"allow-settings-write",
|
||||||
"allow-settings-migrate",
|
"allow-settings-migrate",
|
||||||
|
"allow-features-legacy",
|
||||||
|
"allow-pty-running",
|
||||||
|
"allow-pty-profiles",
|
||||||
"core:default",
|
"core:default",
|
||||||
"core:window:allow-close",
|
"core:window:allow-close",
|
||||||
"core:window:allow-minimize",
|
"core:window:allow-minimize",
|
||||||
@@ -42,12 +45,14 @@
|
|||||||
"allow-browser-engine-remove",
|
"allow-browser-engine-remove",
|
||||||
"allow-completion-request",
|
"allow-completion-request",
|
||||||
"allow-completion-cancel",
|
"allow-completion-cancel",
|
||||||
"allow-backgrounds-choose-folder",
|
"allow-background-choose-folder",
|
||||||
"allow-backgrounds-default-folder",
|
"allow-background-folder",
|
||||||
"allow-backgrounds-list",
|
"allow-background-clear-folder",
|
||||||
"allow-backgrounds-read",
|
"allow-background-list",
|
||||||
"allow-backgrounds-read-image-settings",
|
"allow-background-read",
|
||||||
"allow-backgrounds-write-image-settings",
|
"allow-background-read-sidecar",
|
||||||
|
"allow-background-write-sidecar",
|
||||||
|
"allow-background-migrate",
|
||||||
"allow-folders-choose",
|
"allow-folders-choose",
|
||||||
"allow-folders-picture",
|
"allow-folders-picture",
|
||||||
"allow-folders-grants",
|
"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"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-workspace-download-image"
|
||||||
|
description = "Enables the workspace_download_image command without any pre-configured scope."
|
||||||
|
commands.allow = ["workspace_download_image"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-workspace-download-image"
|
||||||
|
description = "Denies the workspace_download_image command without any pre-configured scope."
|
||||||
|
commands.deny = ["workspace_download_image"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-workspace-save-image-url"
|
||||||
|
description = "Enables the workspace_save_image_url command without any pre-configured scope."
|
||||||
|
commands.allow = ["workspace_save_image_url"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-workspace-save-image-url"
|
||||||
|
description = "Denies the workspace_save_image_url command without any pre-configured scope."
|
||||||
|
commands.deny = ["workspace_save_image_url"]
|
||||||
+402
-312
@@ -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::error::{Error, Result};
|
||||||
|
use crate::folders;
|
||||||
use crate::fsutil::{self, is_link};
|
use crate::fsutil::{self, is_link};
|
||||||
use crate::plugins::PluginState;
|
use serde::{Deserialize, Serialize};
|
||||||
use base64::Engine;
|
|
||||||
use serde::Serialize;
|
|
||||||
use std::fs;
|
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::{AppHandle, Manager, Window};
|
||||||
use tauri_plugin_dialog::DialogExt;
|
use tauri_plugin_dialog::DialogExt;
|
||||||
|
|
||||||
const IMAGE_LIMIT: u64 = 50 * 1024 * 1024;
|
const FOLDER_FILE: &str = "background-folder.json";
|
||||||
const SETTINGS_LIMIT: u64 = 1024 * 1024;
|
const SIDECAR: &str = ".runestone-backgrounds.json";
|
||||||
const SETTINGS_FILE: &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)]
|
/// Serializes changes to the folder file.
|
||||||
pub struct BackgroundFile {
|
static LOCK: Mutex<()> = Mutex::new(());
|
||||||
name: String,
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
struct FolderFile {
|
||||||
|
schema: u32,
|
||||||
|
path: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The folder file and the plugin data of one app data folder.
|
||||||
fn require_plugin(app: &AppHandle, label: &str, id: &str) -> Result<()> {
|
struct Host {
|
||||||
app.state::<PluginState>().require_lease(app, label, id)
|
data: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check the lease on a blocking worker, because the plugin lock can wait for package work.
|
fn raster(name: &str) -> bool {
|
||||||
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 {
|
|
||||||
Path::new(name)
|
Path::new(name)
|
||||||
.extension()
|
.extension()
|
||||||
.and_then(|extension| extension.to_str())
|
.and_then(|extension| extension.to_str())
|
||||||
.is_some_and(|extension| {
|
.is_some_and(|extension| matches!(extension.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "gif" | "webp"))
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn raster_signature(bytes: &[u8]) -> bool {
|
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")
|
|| (bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_image(folder: &Path, name: &str) -> Result<Vec<u8>> {
|
/// Read a small JSON file. A missing file gives `None`. A link or a folder is an error.
|
||||||
let root = folder_root(folder)?;
|
fn read_json<T: for<'de> Deserialize<'de>>(path: &Path, limit: u64) -> Result<Option<T>> {
|
||||||
let path = image_path(&root, name)?;
|
let metadata = match fs::symlink_metadata(path) {
|
||||||
// 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());
|
|
||||||
};
|
|
||||||
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())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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,
|
Ok(metadata) => metadata,
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
Err(error) => return Err(Error::from(error)),
|
Err(error) => return Err(error.into()),
|
||||||
};
|
};
|
||||||
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) {
|
if !metadata.is_file() || is_link(&metadata) {
|
||||||
return Err("Image settings must be an ordinary file, not a link.".into());
|
return Err(Error::new(format!("{} must be an ordinary file.", path.display())));
|
||||||
}
|
}
|
||||||
let Some(bytes) = fsutil::read_to_limit(file, SETTINGS_LIMIT)? else {
|
let Some(bytes) = fsutil::read_to_limit(fsutil::open_entry(path)?, limit)? else {
|
||||||
return Err("Image settings exceed 1 MiB.".into());
|
return Err(Error::new(format!("{} is too large.", path.display())));
|
||||||
};
|
};
|
||||||
String::from_utf8(bytes).map(Some).map_err(Error::from)
|
Ok(Some(serde_json::from_slice(&bytes)?))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_image_settings(folder: &Path, contents: &str, expected: Option<&str>) -> Result<()> {
|
impl Host {
|
||||||
static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
fn file(&self) -> PathBuf {
|
||||||
let _lock = WRITE_LOCK.lock()?;
|
self.data.join(FOLDER_FILE)
|
||||||
if contents.len() as u64 > SETTINGS_LIMIT {
|
|
||||||
return Err("Image settings exceed 1 MiB.".into());
|
|
||||||
}
|
}
|
||||||
let value: serde_json::Value = serde_json::from_str(contents)?;
|
|
||||||
if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1)
|
fn stored(&self) -> Result<Option<PathBuf>> {
|
||||||
|| !value.get("images").is_some_and(serde_json::Value::is_object)
|
let Some(file) = read_json::<FolderFile>(&self.file(), FOLDER_FILE_LIMIT)? else { return Ok(None) };
|
||||||
{
|
if file.schema != 1 {
|
||||||
return Err("Use image settings with schema 1 and an images object.".into());
|
return Err("Unknown background folder file schema.".into());
|
||||||
|
}
|
||||||
|
Ok(Some(file.path))
|
||||||
}
|
}
|
||||||
let root = folder_root(folder)?;
|
|
||||||
if read_image_settings(&root)?.as_deref() != expected {
|
fn save(&self, path: &Path) -> Result<()> {
|
||||||
return Err("Image settings changed. Reload them before saving.".into());
|
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)?)
|
||||||
}
|
}
|
||||||
let path = root.join(SETTINGS_FILE);
|
|
||||||
if expected.is_some() {
|
/// Keep `folder` as the background folder. It must be an existing folder, not a whole drive.
|
||||||
fsutil::write_text(&path, contents, expected)
|
fn choose(&self, folder: &Path) -> Result<String> {
|
||||||
} else {
|
let root = folders::granted_root(folder)?;
|
||||||
// Publish a complete new file without replacing a file created by another process.
|
let _lock = LOCK.lock()?;
|
||||||
let temp = root.join(format!(".runestone-backgrounds-{}.tmp", uuid::Uuid::new_v4()));
|
self.save(&root)?;
|
||||||
Ok(fsutil::create_file(&path, &temp, contents.as_bytes())?)
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_sidecar(&self) -> Result<Option<String>> {
|
||||||
|
folders::read_sidecar(&self.root()?, SIDECAR)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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) {
|
||||||
|
return Err("Use image settings with schema 1 and an images object.".into());
|
||||||
|
}
|
||||||
|
folders::write_sidecar(&self.root()?, SIDECAR, contents, expected)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 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]
|
#[tauri::command]
|
||||||
pub async fn backgrounds_read_image_settings(app: AppHandle, window: Window, id: String, folder: String) -> Result<Option<String>> {
|
pub async fn background_folder(app: AppHandle) -> Result<Option<String>> {
|
||||||
check_plugin(&app, &window, &id).await?;
|
run(&app, |host| host.folder()).await
|
||||||
let result = tauri::async_runtime::spawn_blocking(move || read_image_settings(Path::new(&folder))).await??;
|
|
||||||
check_plugin(&app, &window, &id).await?;
|
|
||||||
Ok(result)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn backgrounds_write_image_settings(app: AppHandle, window: Window, id: String, folder: String, contents: String, expected: Option<String>) -> Result<()> {
|
pub async fn background_clear_folder(app: AppHandle) -> Result<()> {
|
||||||
check_plugin(&app, &window, &id).await?;
|
run(&app, |host| host.clear()).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)?;
|
#[tauri::command]
|
||||||
write_image_settings(Path::new(&folder), &contents, expected.as_deref())
|
pub async fn background_list(app: AppHandle) -> Result<Vec<String>> {
|
||||||
}).await?
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::folders::LIST_LIMIT;
|
||||||
|
|
||||||
|
const PNG: &[u8] = b"\x89PNG\r\n\x1a\n";
|
||||||
|
|
||||||
struct Fixture(PathBuf);
|
struct Fixture(PathBuf);
|
||||||
impl Fixture {
|
impl Fixture {
|
||||||
fn new() -> Self {
|
fn new() -> Self {
|
||||||
let root = std::env::temp_dir()
|
let root = std::env::temp_dir().join(format!("runestone-background-{}", uuid::Uuid::new_v4()));
|
||||||
.join(format!("runestone-backgrounds-{}", uuid::Uuid::new_v4()));
|
|
||||||
fs::create_dir(&root).unwrap();
|
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 {
|
impl Drop for Fixture {
|
||||||
@@ -282,103 +258,217 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
/// Make a link, or return `false` when Windows does not allow links for this user.
|
||||||
fn image_settings_preserve_external_changes_and_validate_file_limits() {
|
fn link(original: &Path, link: &Path, folder: bool) -> bool {
|
||||||
let fixture = Fixture::new();
|
#[cfg(unix)]
|
||||||
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
|
{
|
||||||
let next = r#"{"schema":1,"images":{}}"#;
|
let _ = folder;
|
||||||
assert_eq!(read_image_settings(&fixture.0).unwrap(), None);
|
std::os::unix::fs::symlink(original, link).unwrap();
|
||||||
write_image_settings(&fixture.0, first, None).unwrap();
|
true
|
||||||
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
|
}
|
||||||
assert!(write_image_settings(&fixture.0, next, None).is_err());
|
#[cfg(windows)]
|
||||||
assert!(write_image_settings(&fixture.0, next, Some("stale")).is_err());
|
{
|
||||||
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
|
let result = if folder { std::os::windows::fs::symlink_dir(original, link) } else { std::os::windows::fs::symlink_file(original, link) };
|
||||||
write_image_settings(&fixture.0, next, Some(first)).unwrap();
|
match result {
|
||||||
assert!(write_image_settings(&fixture.0, r#"{"schema":2,"images":{}}"#, Some(next)).is_err());
|
Ok(()) => true,
|
||||||
assert!(write_image_settings(&fixture.0, &"x".repeat(SETTINGS_LIMIT as usize + 1), Some(next)).is_err());
|
Err(error) if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => {
|
||||||
fs::File::create(fixture.0.join(SETTINGS_FILE)).unwrap().set_len(SETTINGS_LIMIT + 1).unwrap();
|
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
|
||||||
assert!(read_image_settings(&fixture.0).is_err());
|
false
|
||||||
}
|
}
|
||||||
|
Err(error) => panic!("{error}"),
|
||||||
#[test]
|
}
|
||||||
fn listing_is_nonrecursive_and_filters_extensions() {
|
|
||||||
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"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn reads_reject_traversal_invalid_images_and_oversized_files() {
|
|
||||||
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"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn raster_types_are_recognized() {
|
fn the_host_keeps_one_folder_until_it_is_cleared() {
|
||||||
for bytes in [
|
let fixture = Fixture::new();
|
||||||
b"\x89PNG\r\n\x1a\n".as_slice(),
|
let images = fixture.folder("images");
|
||||||
b"\xff\xd8\xff",
|
let other = fixture.folder("other");
|
||||||
b"GIF87a",
|
let host = fixture.host();
|
||||||
b"GIF89a",
|
assert_eq!(host.folder().unwrap(), None);
|
||||||
b"RIFF0000WEBP",
|
assert!(host.list().unwrap_err().to_string().contains("Choose a background folder"));
|
||||||
] {
|
assert_eq!(host.choose(&images).unwrap(), images.to_string_lossy());
|
||||||
assert!(raster_signature(bytes));
|
// 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 the_chosen_folder_must_be_an_existing_folder() {
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
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 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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}");
|
||||||
}
|
}
|
||||||
assert!(!raster_signature(b"RIFF0000WAVE"));
|
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]
|
#[test]
|
||||||
fn links_cannot_escape_the_folder() {
|
fn links_cannot_escape_the_folder() {
|
||||||
let fixture = Fixture::new();
|
let fixture = Fixture::new();
|
||||||
let outside = Fixture::new();
|
let images = fixture.folder("images");
|
||||||
let original = outside.0.join("outside.png");
|
let outside = fixture.folder("outside");
|
||||||
fs::write(&original, b"\x89PNG\r\n\x1a\n").unwrap();
|
fs::write(outside.join("secret.png"), PNG).unwrap();
|
||||||
let link = fixture.0.join("link.png");
|
let host = fixture.host();
|
||||||
#[cfg(unix)]
|
host.choose(&images).unwrap();
|
||||||
std::os::unix::fs::symlink(&original, &link).unwrap();
|
if !link(&outside.join("secret.png"), &images.join("link.png"), false) {
|
||||||
#[cfg(windows)]
|
return;
|
||||||
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.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
panic!("{error}");
|
|
||||||
}
|
}
|
||||||
assert!(list_images(&fixture.0).unwrap().is_empty());
|
assert!(host.list().unwrap().is_empty());
|
||||||
assert!(read_image(&fixture.0, "link.png").is_err());
|
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"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,8 @@ const COMMANDS: &[&str] = &[
|
|||||||
"insertText",
|
"insertText",
|
||||||
"edit",
|
"edit",
|
||||||
"contextAction",
|
"contextAction",
|
||||||
|
"copiedImage",
|
||||||
|
"linkAt",
|
||||||
"frameAck",
|
"frameAck",
|
||||||
"createProfile",
|
"createProfile",
|
||||||
"renameProfile",
|
"renameProfile",
|
||||||
@@ -480,7 +482,7 @@ impl BrowserState {
|
|||||||
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
|
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
|
||||||
return Ok(worker.routing.lock()?.snapshot(result, owner));
|
return Ok(worker.routing.lock()?.snapshot(result, owner));
|
||||||
}
|
}
|
||||||
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
|
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "copiedImage", "linkAt", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
|
||||||
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
|
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
|
||||||
match worker.routing.lock()?.owners.get(id) {
|
match worker.routing.lock()?.owners.get(id) {
|
||||||
Some(window) if window == owner => {},
|
Some(window) if window == owner => {},
|
||||||
|
|||||||
@@ -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
@@ -18,9 +18,9 @@ use tauri_plugin_dialog::DialogExt;
|
|||||||
|
|
||||||
const GRANTS_FILE: &str = "folder-grants.json";
|
const GRANTS_FILE: &str = "folder-grants.json";
|
||||||
const GRANT_LIMIT: usize = 64;
|
const GRANT_LIMIT: usize = 64;
|
||||||
const READ_LIMIT: u64 = 64 * 1024 * 1024;
|
pub(crate) const READ_LIMIT: u64 = 64 * 1024 * 1024;
|
||||||
const SIDECAR_LIMIT: u64 = 1024 * 1024;
|
pub(crate) const SIDECAR_LIMIT: u64 = 1024 * 1024;
|
||||||
const LIST_LIMIT: usize = 10_000;
|
pub(crate) const LIST_LIMIT: usize = 10_000;
|
||||||
|
|
||||||
/// Serializes changes to grant files and sidecar files.
|
/// Serializes changes to grant files and sidecar files.
|
||||||
static LOCK: Mutex<()> = Mutex::new(());
|
static LOCK: Mutex<()> = Mutex::new(());
|
||||||
@@ -47,7 +47,7 @@ pub struct FolderGrant {
|
|||||||
|
|
||||||
#[derive(Debug, Serialize, PartialEq)]
|
#[derive(Debug, Serialize, PartialEq)]
|
||||||
pub struct FolderEntry {
|
pub struct FolderEntry {
|
||||||
name: String,
|
pub(crate) name: String,
|
||||||
size: u64,
|
size: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,7 +172,7 @@ impl Grants {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Resolve a chosen folder. Reject relative paths, parent segments, files, and whole drives.
|
/// 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)) {
|
if !folder.is_absolute() || folder.components().any(|part| matches!(part, Component::ParentDir)) {
|
||||||
return Err("Supply an absolute folder path without parent segments.".into());
|
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.
|
/// 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)?;
|
let metadata = fs::symlink_metadata(path)?;
|
||||||
if !metadata.is_file() || is_link(&metadata) {
|
if !metadata.is_file() || is_link(&metadata) {
|
||||||
return Err("Granted folder access is limited to ordinary files, not links or folders.".into());
|
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()))
|
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();
|
let mut entries = Vec::new();
|
||||||
for entry in fs::read_dir(root)? {
|
for entry in fs::read_dir(root)? {
|
||||||
let entry = entry?;
|
let entry = entry?;
|
||||||
@@ -232,7 +232,7 @@ fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
|
|||||||
Ok(entries)
|
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 path = file_path(root, name)?;
|
||||||
let (file, size) = open_plain(root, &path)?;
|
let (file, size) = open_plain(root, &path)?;
|
||||||
if size > READ_LIMIT {
|
if size > READ_LIMIT {
|
||||||
@@ -251,7 +251,7 @@ fn sidecar_path(root: &Path, name: &str) -> Result<PathBuf> {
|
|||||||
file_path(root, name)
|
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)?;
|
let path = sidecar_path(root, name)?;
|
||||||
match fs::symlink_metadata(&path) {
|
match fs::symlink_metadata(&path) {
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
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).
|
/// 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)?;
|
let path = sidecar_path(root, name)?;
|
||||||
if contents.len() as u64 > SIDECAR_LIMIT {
|
if contents.len() as u64 > SIDECAR_LIMIT {
|
||||||
return Err("The sidecar file exceeds 1 MiB.".into());
|
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> {
|
fn grants(app: &AppHandle) -> Result<Grants> {
|
||||||
Ok(Grants { data: app.path().app_data_dir()?.join("plugin-data") })
|
Ok(Grants { data: app.path().app_data_dir()?.join("plugin-data") })
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-6
@@ -16,6 +16,7 @@ mod spelling;
|
|||||||
mod theme;
|
mod theme;
|
||||||
mod backgrounds;
|
mod backgrounds;
|
||||||
mod folders;
|
mod folders;
|
||||||
|
mod features;
|
||||||
mod window_frame;
|
mod window_frame;
|
||||||
|
|
||||||
use pty::PtyState;
|
use pty::PtyState;
|
||||||
@@ -37,12 +38,14 @@ pub fn run() {
|
|||||||
.manage(preferences::PreferencesState::default())
|
.manage(preferences::PreferencesState::default())
|
||||||
.manage(tab_transfer::TabTransferState::default())
|
.manage(tab_transfer::TabTransferState::default())
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
backgrounds::backgrounds_choose_folder,
|
backgrounds::background_choose_folder,
|
||||||
backgrounds::backgrounds_default_folder,
|
backgrounds::background_folder,
|
||||||
backgrounds::backgrounds_list,
|
backgrounds::background_clear_folder,
|
||||||
backgrounds::backgrounds_read,
|
backgrounds::background_list,
|
||||||
backgrounds::backgrounds_read_image_settings,
|
backgrounds::background_read,
|
||||||
backgrounds::backgrounds_write_image_settings,
|
backgrounds::background_read_sidecar,
|
||||||
|
backgrounds::background_write_sidecar,
|
||||||
|
backgrounds::background_migrate,
|
||||||
folders::folders_choose,
|
folders::folders_choose,
|
||||||
folders::folders_picture,
|
folders::folders_picture,
|
||||||
folders::folders_grants,
|
folders::folders_grants,
|
||||||
@@ -51,6 +54,7 @@ pub fn run() {
|
|||||||
folders::folders_read,
|
folders::folders_read,
|
||||||
folders::folders_read_sidecar,
|
folders::folders_read_sidecar,
|
||||||
folders::folders_write_sidecar,
|
folders::folders_write_sidecar,
|
||||||
|
features::features_legacy,
|
||||||
theme::theme_export,
|
theme::theme_export,
|
||||||
spelling::spelling_menu_install,
|
spelling::spelling_menu_install,
|
||||||
spelling::spelling_suggestions,
|
spelling::spelling_suggestions,
|
||||||
@@ -103,6 +107,8 @@ pub fn run() {
|
|||||||
workspace::workspace_delete,
|
workspace::workspace_delete,
|
||||||
workspace::workspace_read_data_url,
|
workspace::workspace_read_data_url,
|
||||||
workspace::workspace_write_bytes,
|
workspace::workspace_write_bytes,
|
||||||
|
workspace::workspace_save_image_url,
|
||||||
|
workspace::workspace_download_image,
|
||||||
workspace::workspace_copy,
|
workspace::workspace_copy,
|
||||||
workspace::workspace_abs_path,
|
workspace::workspace_abs_path,
|
||||||
workspace::workspace_reveal,
|
workspace::workspace_reveal,
|
||||||
@@ -130,6 +136,7 @@ pub fn run() {
|
|||||||
pty::pty_profiles,
|
pty::pty_profiles,
|
||||||
pty::pty_new_window,
|
pty::pty_new_window,
|
||||||
pty::pty_dictation,
|
pty::pty_dictation,
|
||||||
|
pty::pty_running,
|
||||||
])
|
])
|
||||||
.build(tauri::generate_context!())
|
.build(tauri::generate_context!())
|
||||||
.expect("error while building tauri application")
|
.expect("error while building tauri application")
|
||||||
|
|||||||
@@ -1466,6 +1466,39 @@ pub async fn plugins_reveal(
|
|||||||
app.opener().reveal_item_in_dir(path).map_err(Error::from)
|
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]
|
#[tauri::command]
|
||||||
pub async fn plugins_data(
|
pub async fn plugins_data(
|
||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
@@ -1863,6 +1896,31 @@ mod tests {
|
|||||||
assert!(f.service.inspect("main", f.source.clone()).error.is_none());
|
assert!(f.service.inspect("main", f.source.clone()).error.is_none());
|
||||||
}
|
}
|
||||||
#[test]
|
#[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() {
|
fn feature_packages_use_the_standard_install_and_remove_lifecycle() {
|
||||||
for id in ["runestone.terminal", "runestone.table-formulas"] {
|
for id in ["runestone.terminal", "runestone.table-formulas"] {
|
||||||
let mut f = Fixture::new();
|
let mut f = Fixture::new();
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
//!
|
//!
|
||||||
//! The file holds a `schema` number, a `revision` number, and one value for each section.
|
//! The file holds a `schema` number, a `revision` number, and one value for each section.
|
||||||
//! The host does not interpret the section values. The frontend normalizes them.
|
//! The host does not interpret the section values. The frontend normalizes them.
|
||||||
//! Every write replaces the complete file atomically and sends `settings-changed` to all windows.
|
//! A write that changes a section replaces the complete file atomically and sends `settings-changed` to all windows.
|
||||||
|
//! A write of the value that a section already holds changes nothing and sends no event.
|
||||||
//! Plugin settings stay in the app data folder (see `plugins.rs`).
|
//! Plugin settings stay in the app data folder (see `plugins.rs`).
|
||||||
|
|
||||||
use std::io;
|
use std::io;
|
||||||
@@ -20,7 +21,8 @@ use crate::fsutil;
|
|||||||
pub const FILE_NAME: &str = "settings.json";
|
pub const FILE_NAME: &str = "settings.json";
|
||||||
pub const SCHEMA: u64 = 1;
|
pub const SCHEMA: u64 = 1;
|
||||||
/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion.
|
/// 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.
|
/// 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 MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
|
||||||
pub const CHANGED_EVENT: &str = "settings-changed";
|
pub const CHANGED_EVENT: &str = "settings-changed";
|
||||||
@@ -177,6 +179,19 @@ impl Store {
|
|||||||
Ok(Change { section: section.into(), revision: next, value })
|
Ok(Change { section: section.into(), revision: next, value })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Like `write`, but when the file already holds `value` in this section, the file stays as it is.
|
||||||
|
/// The change then has the current revision, and `false` tells the caller to send no event.
|
||||||
|
/// The compare ignores the key order of objects. Without this check, windows that save the same value
|
||||||
|
/// can start each other again without end, and each write replaces the file.
|
||||||
|
pub fn write_if_changed(&mut self, section: &str, value: Value) -> Result<(Change, bool)> {
|
||||||
|
check_section(section)?;
|
||||||
|
let loaded = self.load()?;
|
||||||
|
if loaded.exists && *loaded.document.get(section).unwrap_or(&Value::Null) == value {
|
||||||
|
return Ok((Change { section: section.into(), revision: revision(&loaded.document), value }, false));
|
||||||
|
}
|
||||||
|
Ok((self.write(section, value)?, true))
|
||||||
|
}
|
||||||
|
|
||||||
/// Write the first file from the migrated values. When a file exists, keep it and return it unchanged.
|
/// Write the first file from the migrated values. When a file exists, keep it and return it unchanged.
|
||||||
pub fn migrate(&mut self, sections: Map<String, Value>) -> Result<Snapshot> {
|
pub fn migrate(&mut self, sections: Map<String, Value>) -> Result<Snapshot> {
|
||||||
for name in sections.keys() { check_section(name)?; }
|
for name in sections.keys() { check_section(name)?; }
|
||||||
@@ -228,9 +243,9 @@ pub async fn settings_read(app: AppHandle) -> Result<Snapshot> {
|
|||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn settings_write(app: AppHandle, section: String, value: Value) -> Result<Change> {
|
pub async fn settings_write(app: AppHandle, section: String, value: Value) -> Result<Change> {
|
||||||
let change = with_store(&app, move |store| store.write(§ion, value)).await?;
|
let (change, saved) = with_store(&app, move |store| store.write_if_changed(§ion, value)).await?;
|
||||||
// Every window shows the same preferences, so the change goes to all of them.
|
// Every window shows the same preferences, so the change goes to all of them.
|
||||||
let _ = app.emit(CHANGED_EVENT, &change);
|
if saved { let _ = app.emit(CHANGED_EVENT, &change); }
|
||||||
Ok(change)
|
Ok(change)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -291,6 +306,35 @@ mod tests {
|
|||||||
fs::remove_dir_all(dir).unwrap();
|
fs::remove_dir_all(dir).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_write_of_the_stored_value_keeps_the_file_and_the_revision() {
|
||||||
|
let (dir, path) = fixture("unchanged");
|
||||||
|
let mut store = Store::new(path.clone());
|
||||||
|
// A missing file gets created, also for a value that matches the empty default.
|
||||||
|
let (created, saved) = store.write_if_changed("language", Value::Null).unwrap();
|
||||||
|
assert!(saved);
|
||||||
|
assert_eq!(created.revision, 1);
|
||||||
|
let (first, saved) = store.write_if_changed("appearance", json!({ "theme": "harvest-moon", "mode": "dark", "transparency": { "enabled": true, "amount": 18 } })).unwrap();
|
||||||
|
assert!(saved);
|
||||||
|
assert_eq!(first.revision, 2);
|
||||||
|
let before = fs::read(&path).unwrap();
|
||||||
|
// The same value in a different key order changes nothing.
|
||||||
|
let (again, saved) = store.write_if_changed("appearance", json!({ "transparency": { "amount": 18, "enabled": true }, "mode": "dark", "theme": "harvest-moon" })).unwrap();
|
||||||
|
assert!(!saved, "No save and no event");
|
||||||
|
assert_eq!(again.revision, 2);
|
||||||
|
assert_eq!(fs::read(&path).unwrap(), before, "The file stays as it is");
|
||||||
|
// A missing section and `null` are the same.
|
||||||
|
assert!(!store.write_if_changed("terminal", Value::Null).unwrap().1);
|
||||||
|
// A different value saves as usual.
|
||||||
|
let (changed, saved) = store.write_if_changed("appearance", json!({ "theme": "harvest-moon", "mode": "light" })).unwrap();
|
||||||
|
assert!(saved);
|
||||||
|
assert_eq!(changed.revision, 3);
|
||||||
|
assert_eq!(on_disk(&path)["appearance"], json!({ "mode": "light", "theme": "harvest-moon" }));
|
||||||
|
assert!(store.write_if_changed("plugins", json!({})).is_err(), "Unknown sections stay refused");
|
||||||
|
assert_eq!(files(&dir), vec![FILE_NAME.to_owned()], "No temporary files remain");
|
||||||
|
fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn writes_reject_unknown_sections_and_values_above_the_limit() {
|
fn writes_reject_unknown_sections_and_values_above_the_limit() {
|
||||||
let (dir, path) = fixture("limits");
|
let (dir, path) = fixture("limits");
|
||||||
|
|||||||
+411
-104
@@ -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::io::{Read, Write};
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::mpsc::{Receiver, RecvTimeoutError};
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use std::thread;
|
use std::thread;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
|
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId};
|
use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId};
|
||||||
use tauri::{AppHandle, Emitter, Manager, State};
|
use tauri::{AppHandle, Manager, State};
|
||||||
|
|
||||||
use crate::error::{Error, Result};
|
use crate::error::{Error, Result};
|
||||||
use crate::workspace::{current_root, WorkspaceState};
|
use crate::workspace::{current_root, WorkspaceState};
|
||||||
use crate::terminal_platform::find_executable;
|
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 {
|
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 {
|
struct OpenPty {
|
||||||
owner: String,
|
owner: String,
|
||||||
|
/// A unique number for this session. A session ID can come back after a reload.
|
||||||
|
serial: u64,
|
||||||
integration_file: Option<PathBuf>,
|
integration_file: Option<PathBuf>,
|
||||||
master: Box<dyn MasterPty + Send>,
|
master: Box<dyn MasterPty + Send>,
|
||||||
writer: std::sync::Arc<Mutex<Box<dyn Write + Send>>>,
|
writer: std::sync::Arc<Mutex<Box<dyn Write + Send>>>,
|
||||||
@@ -33,12 +63,13 @@ impl Drop for OpenPty {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PtyState {
|
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) {
|
pub fn close_window(&self, label: &str) {
|
||||||
let closed: Vec<OpenPty> = match self.inner.lock() {
|
let closed: Vec<OpenPty> = match self.inner.lock() {
|
||||||
Ok(mut sessions) => {
|
Ok(mut sessions) => {
|
||||||
let ids: Vec<String> = sessions.iter().filter(|(_, session)| session.owner == label).map(|(id, _)| id.clone()).collect();
|
sessions.pages.remove(label);
|
||||||
ids.iter().filter_map(|id| sessions.remove(id)).collect()
|
take_window(&mut sessions.open, label)
|
||||||
}
|
}
|
||||||
Err(_) => return,
|
Err(_) => return,
|
||||||
};
|
};
|
||||||
@@ -55,22 +86,51 @@ impl PtyState {
|
|||||||
|
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
inner: Mutex::new(HashMap::new()),
|
inner: Mutex::new(Sessions::default()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Serialize)]
|
/// Remove the sessions of one window from the map. The caller stops them outside the lock.
|
||||||
pub struct PtyData {
|
fn take_window(open: &mut HashMap<String, OpenPty>, owner: &str) -> Vec<OpenPty> {
|
||||||
pub id: String,
|
let ids: Vec<String> = open.iter().filter(|(_, session)| session.owner == owner).map(|(id, _)| id.clone()).collect();
|
||||||
// xterm owns UTF-8 decoding so multibyte characters split across reads survive.
|
ids.iter().filter_map(|id| open.remove(id)).collect()
|
||||||
pub data: Vec<u8>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Serialize)]
|
/// The number of open sessions of all windows.
|
||||||
pub struct PtyExit {
|
fn running(pty: &PtyState) -> Result<usize> {
|
||||||
pub id: String,
|
Ok(pty.inner.lock().map_err(|_| Error::new("pty lock"))?.open.len())
|
||||||
pub code: Option<u32>,
|
}
|
||||||
|
|
||||||
|
/// 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.
|
/// 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>);
|
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
|
/// 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 }`.
|
/// `ArrayBuffer` in JavaScript). The exit status goes as `{ "exit": code }`.
|
||||||
struct ChannelOutput(Channel<InvokeResponseBody>);
|
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.
|
/// Read the PTY until EOF and send each read to `chunks`.
|
||||||
fn output(channel: Option<Channel<InvokeResponseBody>>, events: impl FnOnce() -> Box<dyn PtyOutput>) -> Box<dyn PtyOutput> {
|
fn read_chunks(mut reader: impl Read, chunks: std::sync::mpsc::Sender<Vec<u8>>) {
|
||||||
match channel {
|
let mut buf = vec![0u8; 16 * 1024];
|
||||||
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];
|
|
||||||
loop {
|
loop {
|
||||||
match reader.read(&mut buf) {
|
match reader.read(&mut buf) {
|
||||||
Ok(0) | Err(_) => break,
|
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());
|
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);
|
integration_file = Some(rc);
|
||||||
}
|
}
|
||||||
// The cmd prompt cannot encode base64, so it reports the folder as plain text with `Cwd`.
|
// 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.
|
// 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\\"]); }
|
"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"]); }
|
"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)
|
.spawn_command(cmd)
|
||||||
.map_err(Error::from_display)?;
|
.map_err(Error::from_display)?;
|
||||||
drop(pair.slave);
|
drop(pair.slave);
|
||||||
|
static NEXT_SERIAL: AtomicU64 = AtomicU64::new(0);
|
||||||
let session = OpenPty {
|
let session = OpenPty {
|
||||||
owner: owner.into(),
|
owner: owner.into(),
|
||||||
|
serial: NEXT_SERIAL.fetch_add(1, Ordering::Relaxed),
|
||||||
integration_file,
|
integration_file,
|
||||||
master: pair.master,
|
master: pair.master,
|
||||||
writer: std::sync::Arc::new(Mutex::new(writer)),
|
writer: std::sync::Arc::new(Mutex::new(writer)),
|
||||||
@@ -284,77 +363,103 @@ pub async fn pty_open(
|
|||||||
webview: tauri::Webview,
|
webview: tauri::Webview,
|
||||||
workspace: State<'_, WorkspaceState>,
|
workspace: State<'_, WorkspaceState>,
|
||||||
id: String,
|
id: String,
|
||||||
|
page: String,
|
||||||
cols: u16,
|
cols: u16,
|
||||||
rows: u16,
|
rows: u16,
|
||||||
cwd: String,
|
cwd: String,
|
||||||
profile: Option<String>,
|
profile: Option<String>,
|
||||||
directory: Option<String>,
|
directory: Option<String>,
|
||||||
channel: Option<JavaScriptChannelId>,
|
channel: JavaScriptChannelId,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
check_page(&page)?;
|
||||||
let root = current_root(&workspace, window.label())?;
|
let root = current_root(&workspace, window.label())?;
|
||||||
if root.to_string_lossy() != cwd {
|
if root.to_string_lossy() != cwd {
|
||||||
return Err(Error::new("workspace changed before the terminal started"));
|
return Err(Error::new("workspace changed before the terminal started"));
|
||||||
}
|
}
|
||||||
let owner = window.label().to_owned();
|
let owner = window.label().to_owned();
|
||||||
// A session with a channel sends no `pty-data` or `pty-exit` events.
|
let output = ChannelOutput(channel.channel_on(webview));
|
||||||
let channel = channel.map(|channel| 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, owner, root, id, cols, rows, profile, directory, channel)).await?
|
tauri::async_runtime::spawn_blocking(move || open(app, request, output)).await?
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
struct OpenRequest {
|
||||||
fn open(
|
|
||||||
app: AppHandle,
|
|
||||||
owner: String,
|
owner: String,
|
||||||
root: PathBuf,
|
page: String,
|
||||||
id: String,
|
id: String,
|
||||||
cols: u16,
|
cols: u16,
|
||||||
rows: u16,
|
rows: u16,
|
||||||
profile: Option<String>,
|
profile: Option<String>,
|
||||||
directory: Option<String>,
|
directory: PathBuf,
|
||||||
channel: Option<Channel<InvokeResponseBody>>,
|
}
|
||||||
) -> Result<()> {
|
|
||||||
|
/// 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 pty = app.state::<PtyState>();
|
||||||
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
let (left, started) = {
|
||||||
if guard.contains_key(&id) {
|
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
||||||
return Err(Error::new("terminal already exists"));
|
let left = enter_page(&mut guard, &request.owner, &request.page)?;
|
||||||
}
|
(left, start(&mut guard, &request))
|
||||||
let directory = directory.map(PathBuf::from).unwrap_or(root);
|
};
|
||||||
if !directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
|
// A reload left these sessions. Stop their shells outside the lock.
|
||||||
let (session, reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?;
|
drop(left);
|
||||||
guard.insert(id.clone(), session);
|
let (serial, reader, mut child) = started?;
|
||||||
drop(guard);
|
|
||||||
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
||||||
let wait_app = app.clone();
|
let wait_app = app.clone();
|
||||||
let wait_id = id.clone();
|
let wait_id = request.id;
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
let code = child.wait().ok().map(|status| status.exit_code());
|
let code = child.wait().ok().map(|status| status.exit_code());
|
||||||
// Close ConPTY after the shell exits so the output reader reaches EOF.
|
// 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
|
let session = wait_app
|
||||||
.state::<PtyState>()
|
.state::<PtyState>()
|
||||||
.inner
|
.inner
|
||||||
.lock()
|
.lock()
|
||||||
.ok()
|
.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);
|
drop(session);
|
||||||
let _ = exit_tx.send(code);
|
let _ = exit_tx.send(code);
|
||||||
});
|
});
|
||||||
let output = output(channel, || Box::new(EventOutput { app: app.clone(), owner, id }));
|
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
|
||||||
thread::spawn(move || pump(reader, exit_rx, output.as_ref()));
|
thread::spawn(move || read_chunks(reader, chunk_tx));
|
||||||
|
thread::spawn(move || pump(chunk_rx, exit_rx, &output, BATCH_BYTES, BATCH_WAIT));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Write input on a blocking worker. A shell that does not read its input can fill the pipe,
|
type StartedShell = (u64, Box<dyn Read + Send>, Box<dyn portable_pty::Child + Send + Sync>);
|
||||||
/// and the write then waits. The Terminal plugin waits for each write before the next one.
|
|
||||||
#[tauri::command]
|
/// Start the shell and insert its session. The caller holds the lock.
|
||||||
pub async fn pty_write(app: AppHandle, id: String, data: String) -> Result<()> {
|
fn start(sessions: &mut Sessions, request: &OpenRequest) -> Result<StartedShell> {
|
||||||
tauri::async_runtime::spawn_blocking(move || write(&app.state::<PtyState>(), &id, &data)).await?
|
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 writer = {
|
||||||
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
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"))?;
|
owned(&guard, owner, id)?.writer.clone()
|
||||||
session.writer.clone()
|
|
||||||
};
|
};
|
||||||
// Other terminals stay usable while this write waits.
|
// Other terminals stay usable while this write waits.
|
||||||
let mut writer = writer.lock().map_err(|_| Error::new("pty writer lock"))?;
|
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]
|
#[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 guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
||||||
let session = guard.get(&id).ok_or_else(|| Error::new("terminal is not open"))?;
|
owned(&guard, owner, id)?
|
||||||
session
|
|
||||||
.master
|
.master
|
||||||
.resize(PtySize {
|
.resize(PtySize {
|
||||||
rows: rows.max(2),
|
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.
|
/// 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]
|
#[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 || {
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
let pty = app.state::<PtyState>();
|
let session = close(&app.state::<PtyState>(), &owner, &id)?;
|
||||||
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
|
||||||
let session = guard.remove(&id);
|
|
||||||
drop(guard);
|
|
||||||
drop(session);
|
drop(session);
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
.await?
|
.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]
|
#[tauri::command]
|
||||||
pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> Result<()> {
|
pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> Result<()> {
|
||||||
let root = current_root(&workspace, window.label())?;
|
let root = current_root(&workspace, window.label())?;
|
||||||
@@ -436,28 +559,111 @@ mod tests {
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
/// Records the window events that a session would send.
|
#[derive(Debug, PartialEq)]
|
||||||
struct FakeEvents(Arc<Mutex<Vec<String>>>);
|
enum Sent {
|
||||||
impl PtyOutput for FakeEvents {
|
Data(Vec<u8>),
|
||||||
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(format!("pty-data {}", String::from_utf8_lossy(bytes))); }
|
Exit(Option<u32>),
|
||||||
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(format!("pty-exit {code:?}")); }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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();
|
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
||||||
exit_tx.send(Some(3)).unwrap();
|
let recorder = Recorder::default();
|
||||||
let output = output(channel, move || Box::new(FakeEvents(events)));
|
let output = recorder.clone();
|
||||||
pump(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), exit_rx, output.as_ref());
|
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]
|
#[test]
|
||||||
fn a_channel_session_sends_raw_bytes_and_no_window_events() {
|
fn small_chunks_within_the_wait_become_one_message() {
|
||||||
let events = Arc::new(Mutex::new(Vec::new()));
|
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 received = Arc::new(Mutex::new(Vec::new()));
|
||||||
let sink = received.clone();
|
let sink = received.clone();
|
||||||
let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) });
|
let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) });
|
||||||
run_pump(Some(channel), events.clone());
|
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
|
||||||
assert!(events.lock().unwrap().is_empty(), "a channel session must not send pty-data or pty-exit events");
|
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();
|
let received = received.lock().unwrap();
|
||||||
assert_eq!(received.len(), 2);
|
assert_eq!(received.len(), 2);
|
||||||
match &received[0] {
|
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]
|
#[test]
|
||||||
fn a_session_without_a_channel_keeps_the_window_events() {
|
fn only_the_owner_window_can_use_a_session() {
|
||||||
let events = Arc::new(Mutex::new(Vec::new()));
|
let pty = PtyState::new();
|
||||||
run_pump(None, events.clone());
|
pty.inner.lock().unwrap().open.insert("t1".into(), shell("a"));
|
||||||
assert_eq!(*events.lock().unwrap(), vec!["pty-data hello λ".to_owned(), "pty-exit Some(3)".to_owned()]);
|
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]
|
#[test]
|
||||||
|
|||||||
+152
-2
@@ -967,10 +967,14 @@ fn read_data_url(root: &Path, rel: &str) -> Result<String> {
|
|||||||
}
|
}
|
||||||
let bytes = fsutil::read_to_limit(file, MAX_IMAGE_BYTES as u64)?
|
let bytes = fsutil::read_to_limit(file, MAX_IMAGE_BYTES as u64)?
|
||||||
.ok_or_else(|| Error::new("image is too large"))?;
|
.ok_or_else(|| Error::new("image is too large"))?;
|
||||||
Ok(format!(
|
Ok(data_url(mime, &bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn data_url(mime: &str, bytes: &[u8]) -> String {
|
||||||
|
format!(
|
||||||
"data:{mime};base64,{}",
|
"data:{mime};base64,{}",
|
||||||
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes)
|
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes)
|
||||||
))
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn copy_destination(path: &Path, number: u32) -> PathBuf {
|
fn copy_destination(path: &Path, number: u32) -> PathBuf {
|
||||||
@@ -1244,6 +1248,108 @@ fn write_image(root: &Path, rel: &str, base64: &str) -> Result<()> {
|
|||||||
fsutil::write_bytes(&path, &bytes)
|
fsutil::write_bytes(&path, &bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Save the original of an image that a web page copied. The clipboard has only a still copy,
|
||||||
|
/// so an animated GIF needs its source file. `rel` has no extension. The format of the
|
||||||
|
/// downloaded file sets it. Returns the path of the new file.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn workspace_save_image_url(
|
||||||
|
window: tauri::Window,
|
||||||
|
state: State<'_, WorkspaceState>,
|
||||||
|
url: String,
|
||||||
|
rel: String,
|
||||||
|
) -> Result<String> {
|
||||||
|
let root = current_root(&state, window.label())?;
|
||||||
|
blocking(move || {
|
||||||
|
let bytes = download_image(&url)?;
|
||||||
|
save_image(&root, &rel, &bytes)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Download a web image and return it as a data URL. Project Management keeps card images
|
||||||
|
/// as data URLs, so this gives a card the original of a copied image.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn workspace_download_image(url: String) -> Result<String> {
|
||||||
|
blocking(move || image_data_url(&download_image(&url)?)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn image_data_url(bytes: &[u8]) -> Result<String> {
|
||||||
|
let extension = image_extension(bytes).ok_or_else(|| Error::new("file is not an image"))?;
|
||||||
|
let mime = mime_from_path(Path::new(&format!("image.{extension}")))
|
||||||
|
.ok_or_else(|| Error::new("file is not an image"))?;
|
||||||
|
Ok(data_url(mime, bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn download_image(url: &str) -> Result<Vec<u8>> {
|
||||||
|
use std::io::Read;
|
||||||
|
let web = |url: &reqwest::Url| matches!(url.scheme(), "http" | "https");
|
||||||
|
let url = reqwest::Url::parse(url).map_err(|_| Error::new("invalid image address"))?;
|
||||||
|
if !web(&url) {
|
||||||
|
return Err(Error::new("image address is not http or https"));
|
||||||
|
}
|
||||||
|
let client = reqwest::blocking::Client::builder()
|
||||||
|
.user_agent(concat!("RuneStone/", env!("CARGO_PKG_VERSION")))
|
||||||
|
.connect_timeout(Duration::from_secs(10))
|
||||||
|
.timeout(Duration::from_secs(30))
|
||||||
|
.redirect(reqwest::redirect::Policy::custom(move |attempt| {
|
||||||
|
if attempt.previous().len() >= 5 || !web(attempt.url()) {
|
||||||
|
attempt.stop()
|
||||||
|
} else {
|
||||||
|
attempt.follow()
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.build()
|
||||||
|
.map_err(Error::from_display)?;
|
||||||
|
let response = client.get(url).send().map_err(Error::from_display)?;
|
||||||
|
if !response.status().is_success() {
|
||||||
|
return Err(Error::new(format!("image server answered {}", response.status())));
|
||||||
|
}
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
response.take(MAX_IMAGE_BYTES as u64 + 1).read_to_end(&mut bytes)?;
|
||||||
|
if bytes.len() > MAX_IMAGE_BYTES {
|
||||||
|
return Err(Error::new("image is too large"));
|
||||||
|
}
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_image(root: &Path, rel: &str, bytes: &[u8]) -> Result<String> {
|
||||||
|
let extension = image_extension(bytes).ok_or_else(|| Error::new("file is not an image"))?;
|
||||||
|
let rel = format!("{rel}.{extension}");
|
||||||
|
let path = resolve_for_write(root, &rel)?;
|
||||||
|
check_new_components(root, &rel)?;
|
||||||
|
if path.exists() {
|
||||||
|
return Err(Error::new("a file with that name already exists"));
|
||||||
|
}
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
fs::create_dir_all(parent)?;
|
||||||
|
}
|
||||||
|
fsutil::write_bytes(&path, bytes)?;
|
||||||
|
Ok(rel)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The extension of a raster image format from its first bytes. A web server can send a
|
||||||
|
/// wrong type, and an SVG file can contain scripts, so the type header and SVG do not count.
|
||||||
|
fn image_extension(bytes: &[u8]) -> Option<&'static str> {
|
||||||
|
let at = |start: usize, value: &[u8]| bytes.get(start..start + value.len()) == Some(value);
|
||||||
|
if at(0, b"GIF87a") || at(0, b"GIF89a") {
|
||||||
|
Some("gif")
|
||||||
|
} else if at(0, b"\x89PNG\r\n\x1a\n") {
|
||||||
|
Some("png")
|
||||||
|
} else if at(0, b"\xff\xd8\xff") {
|
||||||
|
Some("jpg")
|
||||||
|
} else if at(0, b"RIFF") && at(8, b"WEBP") {
|
||||||
|
Some("webp")
|
||||||
|
} else if at(4, b"ftypavif") || at(4, b"ftypavis") {
|
||||||
|
Some("avif")
|
||||||
|
} else if at(0, b"BM") {
|
||||||
|
Some("bmp")
|
||||||
|
} else if at(0, b"\0\0\x01\0") {
|
||||||
|
Some("ico")
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -1598,6 +1704,50 @@ mod tests {
|
|||||||
fs::remove_dir_all(root).unwrap();
|
fs::remove_dir_all(root).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn image_formats_come_from_the_file_contents() {
|
||||||
|
assert_eq!(image_extension(b"GIF89a\x01\0"), Some("gif"));
|
||||||
|
assert_eq!(image_extension(b"GIF87a"), Some("gif"));
|
||||||
|
assert_eq!(image_extension(b"\x89PNG\r\n\x1a\n\0"), Some("png"));
|
||||||
|
assert_eq!(image_extension(b"\xff\xd8\xff\xe0"), Some("jpg"));
|
||||||
|
assert_eq!(image_extension(b"RIFF\0\0\0\0WEBPVP8 "), Some("webp"));
|
||||||
|
assert_eq!(image_extension(b"\0\0\0\x1cftypavif"), Some("avif"));
|
||||||
|
assert_eq!(image_extension(b"BM\0\0"), Some("bmp"));
|
||||||
|
assert_eq!(image_extension(b"\0\0\x01\0\x01\0"), Some("ico"));
|
||||||
|
assert_eq!(image_extension(b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"), None);
|
||||||
|
assert_eq!(image_extension(b"<!doctype html>"), None);
|
||||||
|
assert_eq!(image_extension(b"RIFF"), None);
|
||||||
|
assert_eq!(image_extension(b""), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn web_images_keep_their_original_format() {
|
||||||
|
let root = workspace_fixture("image-url");
|
||||||
|
let gif = b"GIF89a\x01\0\x01\0\0\0\0;".to_vec();
|
||||||
|
let (base, server) = crate::plugin_sources::tests::server(vec![
|
||||||
|
("302 Found\r\nLocation: /cat.gif".into(), Vec::new()),
|
||||||
|
("200 OK\r\nContent-Type: image/png".into(), gif.clone()),
|
||||||
|
("200 OK\r\nContent-Type: image/gif".into(), b"<!doctype html>".to_vec()),
|
||||||
|
("404 Not Found".into(), Vec::new()),
|
||||||
|
]);
|
||||||
|
let bytes = download_image(&format!("{base}/image")).unwrap();
|
||||||
|
assert_eq!(save_image(&root, "attachments/pasted", &bytes).unwrap(), "attachments/pasted.gif");
|
||||||
|
assert_eq!(fs::read(root.join("attachments/pasted.gif")).unwrap(), gif);
|
||||||
|
assert_eq!(image_data_url(&bytes).unwrap(), "data:image/gif;base64,R0lGODlhAQABAAAAADs=");
|
||||||
|
let page = download_image(&format!("{base}/page")).unwrap();
|
||||||
|
assert_eq!(save_image(&root, "attachments/page", &page).unwrap_err().to_string(), "file is not an image");
|
||||||
|
assert_eq!(image_data_url(&page).unwrap_err().to_string(), "file is not an image");
|
||||||
|
assert_eq!(image_data_url(b"\xff\xd8\xff\xe0").unwrap(), "data:image/jpeg;base64,/9j/4A==");
|
||||||
|
assert!(download_image(&format!("{base}/missing")).unwrap_err().to_string().contains("404"));
|
||||||
|
let requests = server.join().unwrap();
|
||||||
|
assert!(requests[1].starts_with("GET /cat.gif "));
|
||||||
|
assert!(download_image("file:///C:/cat.gif").is_err());
|
||||||
|
assert!(save_image(&root, "attachments/pasted", &gif).is_err(), "an existing file stays");
|
||||||
|
assert!(save_image(&root, "../outside", &gif).is_err());
|
||||||
|
assert_eq!(names(&root.join("attachments")), ["pasted.gif"]);
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn permanent_delete_removes_files_and_folders_but_never_the_root() {
|
fn permanent_delete_removes_files_and_folders_but_never_the_root() {
|
||||||
let root = workspace_fixture("delete");
|
let root = workspace_fixture("delete");
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "RuneStone",
|
"productName": "RuneStone",
|
||||||
"version": "0.1.49",
|
"version": "1.0.0+1",
|
||||||
"identifier": "com.runestone.app",
|
"identifier": "com.runestone.app",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "pnpm dev",
|
"beforeDevCommand": "pnpm dev",
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
@import "./lib/ui/menu.css";
|
@import "./lib/ui/menu.css";
|
||||||
@import "./lib/ui/switch.css";
|
@import "./lib/ui/switch.css";
|
||||||
@import "./lib/theme/base.css";
|
@import "./lib/theme/base.css";
|
||||||
|
@import "./lib/theme/background.css";
|
||||||
@import "./lib/ui/tooltip.css";
|
@import "./lib/ui/tooltip.css";
|
||||||
@import "./lib/layout/reading.css";
|
@import "./lib/layout/reading.css";
|
||||||
@import "./lib/editor/noteTitle.css";
|
@import "./lib/editor/noteTitle.css";
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
<style>
|
<style>
|
||||||
.bookmarks{color:var(--rs-text);font-family:var(--rs-font-ui)}.row{display:flex;align-items:center;padding:0 5px;border-radius:var(--rs-control-radius)}.row:hover{background:var(--rs-bg-active)}
|
.bookmarks{color:var(--rs-text);font-family:var(--rs-font-ui)}.row{display:flex;align-items:center;padding:0 5px;border-radius:var(--rs-control-radius)}.row:hover{background:var(--rs-hover-bg)}
|
||||||
.link{display:flex;align-items:center;gap:8px;flex:1;min-width:0;padding:7px 5px;border:0;border-radius:var(--rs-control-radius);color:inherit;background:transparent;text-align:left;cursor:pointer}
|
.link{display:flex;align-items:center;gap:8px;flex:1;min-width:0;padding:7px 5px;border:0;border-radius:var(--rs-control-radius);color:inherit;background:transparent;text-align:left;cursor:pointer}
|
||||||
span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.link:focus-visible{outline:2px solid var(--rs-focus)}p{padding:8px;font-size:12px}.error{color:var(--rs-error)}.note{margin:0;color:var(--rs-text-dim)}
|
span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.link:focus-visible{outline:2px solid var(--rs-focus)}p{padding:8px;font-size:12px}.error{color:var(--rs-error)}.note{margin:0;color:var(--rs-text-dim)}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
import { TabSession, type TabStatus } from './tabSession';
|
import { TabSession, type TabStatus } from './tabSession';
|
||||||
import { engine } from './engine';
|
import { engine } from './engine';
|
||||||
import { AutoScroll } from './autoScroll';
|
import { AutoScroll } from './autoScroll';
|
||||||
|
import { keepCopiedImage } from '$lib/workspace/copiedImage';
|
||||||
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props();
|
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props();
|
||||||
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: $t('Opening browser…') });
|
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: $t('Opening browser…') });
|
||||||
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); });
|
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); });
|
||||||
@@ -43,7 +44,7 @@
|
|||||||
let scrollAnchor = $state<{ x: number; y: number } | null>(null);
|
let scrollAnchor = $state<{ x: number; y: number } | null>(null);
|
||||||
let scrollFrame = 0, moveFrame = 0, movePending = false;
|
let scrollFrame = 0, moveFrame = 0, movePending = false;
|
||||||
let pendingMove: Record<string, unknown> | undefined;
|
let pendingMove: Record<string, unknown> | undefined;
|
||||||
let suppressedRelease = -1;
|
let suppressedRelease = -1, middlePressed = false;
|
||||||
const result = $derived(current?.find?.text === findText ? current.find : null);
|
const result = $derived(current?.find?.text === findText ? current.find : null);
|
||||||
const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`);
|
const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`);
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
@@ -116,8 +117,9 @@
|
|||||||
{ label: $t('Copy link address'), icon: 'copy', run: action('copyLink') },
|
{ label: $t('Copy link address'), icon: 'copy', run: action('copyLink') },
|
||||||
{ label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true });
|
{ label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true });
|
||||||
if (context.hasImageContents) items.push(
|
if (context.hasImageContents) items.push(
|
||||||
|
{ label: $t('Open image in new tab'), icon: 'file-plus', disabled: !context.srcURL, run: () => void newTab(current?.profileId || 'user', context.srcURL) },
|
||||||
{ label: $t('Save image as…'), icon: 'save', disabled: !context.srcURL, run: action('saveImage') },
|
{ label: $t('Save image as…'), icon: 'save', disabled: !context.srcURL, run: action('saveImage') },
|
||||||
{ label: $t('Copy image'), icon: 'copy', run: action('copyImage') },
|
{ label: $t('Copy image'), icon: 'copy', run: () => copyImage(context) },
|
||||||
{ label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
|
{ label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
|
||||||
if (context.isEditable) items.push(
|
if (context.isEditable) items.push(
|
||||||
{ label: $t('Undo'), icon: 'undo', shortcut: keys('Mod+Z'), disabled: !context.editFlags.canUndo, run: edit('undo') },
|
{ label: $t('Undo'), icon: 'undo', shortcut: keys('Mod+Z'), disabled: !context.editFlags.canUndo, run: edit('undo') },
|
||||||
@@ -142,6 +144,23 @@
|
|||||||
if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
|
if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
|
||||||
await connection.send(command, args);
|
await connection.send(command, args);
|
||||||
}
|
}
|
||||||
|
// A paste of a copied image uses the bytes that the page loaded. The engine gives them in parts.
|
||||||
|
// A paste can come before the reply, so the copy is known at once by its address.
|
||||||
|
function copyImage(context: PageMenu) {
|
||||||
|
const owner = tabId;
|
||||||
|
const data = (async () => {
|
||||||
|
const reply = await connection.send('contextAction', { token: context.token, action: 'copyImage' }) as { copied?: { token: string; mime: string } } | null | undefined;
|
||||||
|
const copied = reply?.copied;
|
||||||
|
if (!copied) return undefined;
|
||||||
|
let data = '';
|
||||||
|
for (let offset: number | null = 0; offset !== null;) {
|
||||||
|
const part: { data: string; next: number | null } = await request('copiedImage', { tabId: owner, token: copied.token, offset });
|
||||||
|
data += part.data; offset = part.next;
|
||||||
|
}
|
||||||
|
return `data:${copied.mime};base64,${data}`;
|
||||||
|
})().catch(() => undefined);
|
||||||
|
if (context.srcURL) keepCopiedImage(context.srcURL, data);
|
||||||
|
}
|
||||||
async function openTab(profileId = current?.profileId || $browserState?.profiles[0]?.id || 'user') {
|
async function openTab(profileId = current?.profileId || $browserState?.profiles[0]?.id || 'user') {
|
||||||
if (opening) return;
|
if (opening) return;
|
||||||
opening = true;
|
opening = true;
|
||||||
@@ -194,23 +213,37 @@
|
|||||||
if (mounted && pendingMove) moveFrame = requestAnimationFrame(flushMove);
|
if (mounted && pendingMove) moveFrame = requestAnimationFrame(flushMove);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// The frame has the CSS size of the page viewport. A surface point less the frame offset is the same page point.
|
||||||
|
function pagePoint(point: { x: number; y: number }) {
|
||||||
|
return { x: Math.max(0, Math.min(width - 1, Math.round(point.x - imageBox.x))), y: Math.max(0, Math.min(height - 1, Math.round(point.y - imageBox.y))) };
|
||||||
|
}
|
||||||
|
// A middle-click starts scrolling at once. On a link, it stops the scroll and opens the link in a new tab.
|
||||||
|
async function openLinkAt(input: { x: number; y: number }) {
|
||||||
|
const owner = tabId;
|
||||||
|
const found = await request<{ url: string | null }>('linkAt', { tabId: owner, ...input }).catch(() => null);
|
||||||
|
if (!found?.url || owner !== tabId || !autoScroll.anchor) return;
|
||||||
|
stopScroll();
|
||||||
|
if (middlePressed) suppressedRelease = 1;
|
||||||
|
void newTab(current?.profileId || 'user', found.url);
|
||||||
|
}
|
||||||
function pointer(event: MouseEvent | WheelEvent, type: string) {
|
function pointer(event: MouseEvent | WheelEvent, type: string) {
|
||||||
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true });
|
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true });
|
||||||
const rect = surface.getBoundingClientRect();
|
const rect = surface.getBoundingClientRect();
|
||||||
const point = { x: event.clientX - rect.left, y: event.clientY - rect.top };
|
const point = { x: event.clientX - rect.left, y: event.clientY - rect.top };
|
||||||
|
if (event.button === 1) middlePressed = type === 'mouseDown';
|
||||||
if (type === 'mouseUp' && event.button === suppressedRelease) { suppressedRelease = -1; return; }
|
if (type === 'mouseUp' && event.button === suppressedRelease) { suppressedRelease = -1; return; }
|
||||||
if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; }
|
if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; }
|
||||||
if (type === 'mouseDown' && event.button === 1 && ready) {
|
if (type === 'mouseDown' && event.button === 1 && ready) {
|
||||||
pendingMove = undefined; cancelAnimationFrame(moveFrame); moveFrame = 0;
|
pendingMove = undefined; cancelAnimationFrame(moveFrame); moveFrame = 0;
|
||||||
autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep); return;
|
autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep);
|
||||||
|
void openLinkAt(pagePoint(point)); return;
|
||||||
}
|
}
|
||||||
if (autoScroll.anchor) {
|
if (autoScroll.anchor) {
|
||||||
if (type === 'mouseMove') autoScroll.move(point);
|
if (type === 'mouseMove') autoScroll.move(point);
|
||||||
if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); }
|
if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); }
|
||||||
if (type === 'mouseWheel') stopScroll(); else return;
|
if (type === 'mouseWheel') stopScroll(); else return;
|
||||||
}
|
}
|
||||||
// The frame has the CSS size of the page viewport. A surface point less the frame offset is the same page point.
|
const input = { type, ...pagePoint(point),
|
||||||
const input = { type, x: Math.max(0, Math.min(width - 1, Math.round(point.x - imageBox.x))), y: Math.max(0, Math.min(height - 1, Math.round(point.y - imageBox.y))),
|
|
||||||
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event),
|
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event),
|
||||||
...('deltaY' in event ? { deltaY: -event.deltaY * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? height : 1), deltaX: -event.deltaX * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? width : 1) } : {}) };
|
...('deltaY' in event ? { deltaY: -event.deltaY * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? height : 1), deltaX: -event.deltaX * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? width : 1) } : {}) };
|
||||||
if (type === 'mouseWheel') { wheels.push(input as Parameters<WheelQueue['push']>[0]); return; }
|
if (type === 'mouseWheel') { wheels.push(input as Parameters<WheelQueue['push']>[0]); return; }
|
||||||
@@ -286,7 +319,7 @@
|
|||||||
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
|
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
|
||||||
onblur={stopScroll}></textarea>
|
onblur={stopScroll}></textarea>
|
||||||
{#if image && ready && !blank}<img src={image} class:exact={imageBox.exact} style:width={`${imageBox.width}px`} style:height={`${imageBox.height}px`} style:transform={`translate(${imageBox.x}px, ${imageBox.y}px)`} alt={$t("Web page rendered by the browser")} draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
|
{#if image && ready && !blank}<img src={image} class:exact={imageBox.exact} style:width={`${imageBox.width}px`} style:height={`${imageBox.height}px`} style:transform={`translate(${imageBox.x}px, ${imageBox.y}px)`} alt={$t("Web page rendered by the browser")} draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
|
||||||
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
|
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true"><Icon icon="scroll" /></span>{/if}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<style>
|
<style>
|
||||||
@@ -298,7 +331,7 @@
|
|||||||
input{flex:1}.profile-choice{max-width:160px;display:flex;align-items:center;gap:var(--rs-menu-icon-gap);cursor:pointer}input:focus-visible,.profile-choice:focus-visible{outline:2px solid var(--rs-focus)}
|
input{flex:1}.profile-choice{max-width:160px;display:flex;align-items:center;gap:var(--rs-menu-icon-gap);cursor:pointer}input:focus-visible,.profile-choice:focus-visible{outline:2px solid var(--rs-focus)}
|
||||||
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
|
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
|
||||||
.browser.blank,.blank .surface{background:transparent}
|
.browser.blank,.blank .surface{background:transparent}
|
||||||
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);font-size:20px;pointer-events:none;box-shadow:0 1px 4px #0006}
|
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:26px;height:26px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);pointer-events:none;box-shadow:0 1px 4px #0006}.scroll-anchor :global(svg){width:20px;height:20px;flex-basis:20px}
|
||||||
img{display:block;pointer-events:none;user-select:none;will-change:transform}img.exact{image-rendering:pixelated}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px}
|
img{display:block;pointer-events:none;user-select:none;will-change:transform}img.exact{image-rendering:pixelated}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px}
|
||||||
.error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)}
|
.error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)}
|
||||||
.reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer}
|
.reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer}
|
||||||
|
|||||||
@@ -47,9 +47,10 @@ export async function activate(api: PluginApi) {
|
|||||||
const id = `tab-${crypto.randomUUID()}`;
|
const id = `tab-${crypto.randomUUID()}`;
|
||||||
const saved: SavedView = { view: id, profileId, url, runtimeId: '' };
|
const saved: SavedView = { view: id, profileId, url, runtimeId: '' };
|
||||||
const run = (command: string, args?: Record<string, unknown>) => { void saved.control?.action(command, args); };
|
const run = (command: string, args?: Record<string, unknown>) => { void saved.control?.action(command, args); };
|
||||||
|
// A new tab with the home page of the profile opens in a pane beside this tab.
|
||||||
const split = (direction: 'right' | 'down') => {
|
const split = (direction: 'right' | 'down') => {
|
||||||
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
|
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
|
||||||
void open(current?.profileId || saved.profileId, current?.url || saved.url || 'about:blank', { split: direction, relativeTo: id });
|
void open(current?.profileId || saved.profileId, undefined, { split: direction, relativeTo: id });
|
||||||
};
|
};
|
||||||
api.registerView({ id, title: 'Browser', placement: 'editor', icon: 'globe', pinned, launcher: false,
|
api.registerView({ id, title: 'Browser', placement: 'editor', icon: 'globe', pinned, launcher: false,
|
||||||
tabDragData: ({ pinned }) => {
|
tabDragData: ({ pinned }) => {
|
||||||
@@ -65,8 +66,8 @@ export async function activate(api: PluginApi) {
|
|||||||
return [
|
return [
|
||||||
{ separator: true },
|
{ separator: true },
|
||||||
{ label: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
|
{ label: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
|
||||||
{ label: tr("Split right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
|
{ label: tr("New tab to the right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
|
||||||
{ label: tr("Split down"), icon: 'split-down', disabled: !ready, run: () => split('down') },
|
{ label: tr("New tab below"), icon: 'split-down', disabled: !ready, run: () => split('down') },
|
||||||
{ separator: true },
|
{ separator: true },
|
||||||
{ label: tr("Find…"), icon: 'search', shortcut: keys('Mod+F'), disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
|
{ label: tr("Find…"), icon: 'search', shortcut: keys('Mod+F'), disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
|
||||||
{ label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') },
|
{ label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') },
|
||||||
|
|||||||
@@ -75,12 +75,14 @@ export class TabSession {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async send(command: string, args: Record<string, unknown> = {}) {
|
/** Returns the reply of the engine, or undefined when the request did not complete. */
|
||||||
|
async send(command: string, args: Record<string, unknown> = {}): Promise<unknown> {
|
||||||
if (this.closed || this.value.phase !== 'ready') return;
|
if (this.closed || this.value.phase !== 'ready') return;
|
||||||
const tabId = this.value.tabId;
|
const tabId = this.value.tabId;
|
||||||
try {
|
try {
|
||||||
await this.transport(command, { ...args, tabId });
|
const reply = await this.transport(command, { ...args, tabId });
|
||||||
if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' });
|
if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' });
|
||||||
|
return reply;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Replies from the previous connection cannot replace the current error.
|
// Replies from the previous connection cannot replace the current error.
|
||||||
if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return;
|
if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return;
|
||||||
|
|||||||
@@ -13,9 +13,11 @@
|
|||||||
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
|
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
|
||||||
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
|
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
|
||||||
import { linkCandidates } from "$lib/workspace/markdownLinks";
|
import { linkCandidates } from "$lib/workspace/markdownLinks";
|
||||||
|
import { documentHeadings } from "$lib/workspace/headingLinks";
|
||||||
import { editImageSource, imageSource } from "./imageSource";
|
import { editImageSource, imageSource } from "./imageSource";
|
||||||
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
|
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
|
||||||
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle } from "$lib/workspace/media";
|
import { loadImageSize } from "$lib/workspace/imageSizes";
|
||||||
|
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle, pastedImageSource } from "$lib/workspace/media";
|
||||||
import { registerImageDropTarget } from "./workspaceImageDrop";
|
import { registerImageDropTarget } from "./workspaceImageDrop";
|
||||||
import { workspaceFileLink } from "./workspaceFileLink";
|
import { workspaceFileLink } from "./workspaceFileLink";
|
||||||
import { savedEditor, saveEditor } from "./editorStates";
|
import { savedEditor, saveEditor } from "./editorStates";
|
||||||
@@ -48,7 +50,7 @@
|
|||||||
onChange: (value: string, id: string) => void;
|
onChange: (value: string, id: string) => void;
|
||||||
onRenameTitle?: (id: string, title: string) => Promise<void>;
|
onRenameTitle?: (id: string, title: string) => Promise<void>;
|
||||||
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
|
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
|
||||||
onInsertImage?: (file: File) => Promise<string | null>;
|
onInsertImage?: (file: File, source?: string) => Promise<string | null>;
|
||||||
focusLine?: number | null;
|
focusLine?: number | null;
|
||||||
/** The line and the column of the cursor, from 1. */
|
/** The line and the column of the cursor, from 1. */
|
||||||
onSelectionLine?: (line: number, column: number) => void;
|
onSelectionLine?: (line: number, column: number) => void;
|
||||||
@@ -99,7 +101,12 @@
|
|||||||
let decoded = source;
|
let decoded = source;
|
||||||
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
|
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
|
||||||
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
|
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
|
||||||
try { urls.set(source, await workspaceReadDataUrl(candidate)); return; } catch { /* Try attachment location. */ }
|
try {
|
||||||
|
const url = await workspaceReadDataUrl(candidate);
|
||||||
|
await loadImageSize(url);
|
||||||
|
urls.set(source, url);
|
||||||
|
return;
|
||||||
|
} catch { /* Try attachment location. */ }
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
loading.set(source, task);
|
loading.set(source, task);
|
||||||
@@ -126,10 +133,12 @@
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null;
|
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null;
|
||||||
await importImages(view, files, position);
|
// Read the HTML now. The clipboard data is empty after the paste event.
|
||||||
|
const source = event instanceof ClipboardEvent && files.length === 1 ? pastedImageSource(data?.getData("text/html") ?? "") : undefined;
|
||||||
|
await importImages(view, files, position, undefined, source);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string) {
|
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string, source?: string) {
|
||||||
const range = position === null ? view.state.selection.main : { from: position, to: position };
|
const range = position === null ? view.state.selection.main : { from: position, to: position };
|
||||||
const id = Symbol(), path = buffer.relPath;
|
const id = Symbol(), path = buffer.relPath;
|
||||||
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
|
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
|
||||||
@@ -137,7 +146,7 @@
|
|||||||
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
|
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
if (editor !== view) return;
|
if (editor !== view) return;
|
||||||
const snippet = await onInsertImage?.(file);
|
const snippet = await onInsertImage?.(file, source);
|
||||||
if (snippet) snippets.push(snippet);
|
if (snippet) snippets.push(snippet);
|
||||||
}
|
}
|
||||||
if (editor !== view || !snippets.length) return;
|
if (editor !== view || !snippets.length) return;
|
||||||
@@ -432,8 +441,11 @@
|
|||||||
const view = editor;
|
const view = editor;
|
||||||
if (!view || line == null) return;
|
if (!view || line == null) return;
|
||||||
untrack(() => {
|
untrack(() => {
|
||||||
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from;
|
const number = Math.min(view.state.doc.lines, Math.max(1, line));
|
||||||
const effects = [EditorView.scrollIntoView(anchor, { y: "center" })];
|
const anchor = view.state.doc.line(number).from;
|
||||||
|
// A heading starts the text to read, so it goes to the top, as in Read. Other lines, such as a search match, stay in the center.
|
||||||
|
const heading = markdownDocument && documentHeadings(view.state.doc.toString()).some(entry => entry.line === number);
|
||||||
|
const effects = [EditorView.scrollIntoView(anchor, heading ? { y: "start", yMargin: 24 } : { y: "center" })];
|
||||||
foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
|
foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
|
||||||
view.dispatch({ selection: { anchor }, effects });
|
view.dispatch({ selection: { anchor }, effects });
|
||||||
view.focus();
|
view.focus();
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
.reading .rs-heading-toggle { inset-inline-start: -24px; }
|
.reading .rs-heading-toggle { inset-inline-start: -24px; }
|
||||||
.live-writer .rs-heading-toggle { top: .7em; }
|
.live-writer .rs-heading-toggle { top: .7em; }
|
||||||
.rs-heading-toggle { position: absolute; inset-inline-start: -30px; top: 0; width: 28px; height: 28px; padding: 6px; border: 0; border-radius: var(--rs-control-radius); color: var(--rs-text-dim); background: transparent; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; vertical-align: middle; }
|
.rs-heading-toggle { position: absolute; inset-inline-start: -30px; top: 0; width: 28px; height: 28px; padding: 6px; border: 0; border-radius: var(--rs-control-radius); color: var(--rs-text-dim); background: transparent; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; vertical-align: middle; }
|
||||||
.rs-heading-toggle:hover, .rs-heading-toggle:focus-visible { color: var(--rs-text); background: var(--rs-bg-active); }
|
.rs-heading-toggle:hover, .rs-heading-toggle:focus-visible { color: var(--rs-text); background: var(--rs-hover-bg); }
|
||||||
.rs-heading-toggle:focus-visible { outline: 1px solid var(--rs-focus); outline-offset: 1px; }
|
.rs-heading-toggle:focus-visible { outline: 1px solid var(--rs-focus); outline-offset: 1px; }
|
||||||
.rs-heading-toggle svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
|
.rs-heading-toggle svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
|
||||||
.rs-heading-toggle[aria-expanded="true"] svg { transform: rotate(90deg); }
|
.rs-heading-toggle[aria-expanded="true"] svg { transform: rotate(90deg); }
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user