Compare commits
98
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e5c3cb165 | ||
|
|
d3218b2501 | ||
|
|
58f77b2e9f | ||
|
|
f019d5d8d4 | ||
|
|
135e6d6d92 | ||
|
|
a950edfb13 | ||
|
|
54ccea199e | ||
|
|
2928bc220b | ||
|
|
0bf7d47496 | ||
|
|
516671a235 | ||
|
|
4f8d91e70b | ||
|
|
0cc83b7b93 | ||
|
|
5958c9c252 | ||
|
|
d10615d903 | ||
|
|
aebe700366 | ||
|
|
c06d48f250 | ||
|
|
6004e126f7 | ||
|
|
48b8249ba6 | ||
|
|
5dc53e4a5e | ||
|
|
8bc11c801f | ||
|
|
c271e2bae1 | ||
|
|
eeddd880e1 | ||
|
|
0fdc991b2e | ||
|
|
b7a9784f55 | ||
|
|
c8cf56b224 | ||
|
|
9cf82503d0 | ||
|
|
ebacdb8164 | ||
|
|
b2348d0fe8 | ||
|
|
5483881bc2 | ||
|
|
d160568249 | ||
|
|
35f39e93f3 | ||
|
|
a34c1a5dce | ||
|
|
445d0200b2 | ||
|
|
5bd616d7fd | ||
|
|
af68d92969 | ||
|
|
1c19da25ba | ||
|
|
e9c59f28de | ||
|
|
3e6bc5f088 | ||
|
|
f32f60b540 | ||
|
|
6cd9195370 | ||
|
|
724402729e | ||
|
|
80f5d908e0 | ||
|
|
36a06a9c6b | ||
|
|
4d09da30d9 | ||
|
|
d62ee5d0b7 | ||
|
|
c1ad9fa60c | ||
|
|
bb0b8f88b6 | ||
|
|
9591c251e9 | ||
|
|
374d4db933 | ||
|
|
e83bf46268 | ||
|
|
a6d6e96d6d | ||
|
|
eb2adf6a11 | ||
|
|
5e1533c371 | ||
|
|
72671e5d01 | ||
|
|
777cab2cc1 | ||
|
|
5d5ba9e1f7 | ||
|
|
a0eef01ed0 | ||
|
|
2448c68abf | ||
|
|
70510a114f | ||
|
|
7914942698 | ||
|
|
e217eb31d2 | ||
|
|
bd46f3a189 | ||
|
|
69f90df571 | ||
|
|
c66ea1ce83 | ||
|
|
e433bed28e | ||
|
|
90d1940c73 | ||
|
|
2d2a146e34 | ||
|
|
4240d7dad1 | ||
|
|
d7a87795f5 | ||
|
|
44a0ef7ba7 | ||
|
|
3fa514f19a | ||
|
|
46e3daae6c | ||
|
|
562ef87d24 | ||
|
|
f741389418 | ||
|
|
b742d274f1 | ||
|
|
0dd43335fe | ||
|
|
4e14be33bd | ||
|
|
ae388885bb | ||
|
|
3daf5270a7 | ||
|
|
622c2dffaa | ||
|
|
146dbf0305 | ||
|
|
7c497ba569 | ||
|
|
7e7660d9bb | ||
|
|
da28f6eaf6 | ||
|
|
42dd0fa711 | ||
|
|
68e86ab6eb | ||
|
|
b066359b66 | ||
|
|
30cbfeedd6 | ||
|
|
edef2520af | ||
|
|
f6eaa52949 | ||
|
|
909894b9c8 | ||
|
|
a8b1defb9d | ||
|
|
dd9fc64676 | ||
|
|
5d0a4a24f9 | ||
|
|
6b7af0d527 | ||
|
|
0268c5c9f0 | ||
|
|
43106ed9c7 | ||
|
|
bdc15e952d |
@@ -1,2 +0,0 @@
|
|||||||
# Tauri writes these files with LF line endings on each build.
|
|
||||||
src-tauri/permissions/autogenerated/*.toml text eol=lf
|
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Agent instructions
|
||||||
|
|
||||||
|
The instructions for AI agents in this repository are in [CLAUDE.md](CLAUDE.md). Read and obey that file.
|
||||||
@@ -2,10 +2,9 @@
|
|||||||
|
|
||||||
RuneStone is a desktop workspace for Markdown notes, code, and project work in ordinary local files.
|
RuneStone is a desktop workspace for Markdown notes, code, and project work in ordinary local files.
|
||||||
A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface (`src/`).
|
A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface (`src/`).
|
||||||
Git, Background, 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.
|
Git is a native feature with an off switch in Settings → Features (`src/lib/features/`). It does not use the plugin API.
|
||||||
Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_CSV_Viewer`.
|
Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_Terminal`.
|
||||||
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/kwyvern-gh/RuneStone`. Its releases page holds the installers, the browser engine ZIPs, and the SDK packages.
|
|
||||||
|
|
||||||
## Skills
|
## Skills
|
||||||
|
|
||||||
@@ -120,5 +119,5 @@ Rules from the owner:
|
|||||||
|
|
||||||
## Subagents
|
## Subagents
|
||||||
|
|
||||||
Use only Haiku 5.5 (`model: "haiku"`) or Opus 5.5 (`model: "opus"`, effort `high` to `xhigh`). Never use Sonnet or Fable.
|
Use only Haiku 5.5 (`model: "haiku"`) or Opus 5.5 (`model: "opus"`, effort `medium` 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.
|
||||||
|
|||||||
@@ -1,202 +0,0 @@
|
|||||||
|
|
||||||
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.
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
RuneStone
|
|
||||||
Copyright 2026 Knotty Wyvern
|
|
||||||
|
|
||||||
This product includes third-party software. See THIRD_PARTY_NOTICES.md for its licenses.
|
|
||||||
@@ -4,25 +4,29 @@ RuneStone is a desktop workspace for Markdown notes, code, and project work that
|
|||||||
|
|
||||||
## Install and start
|
## Install and start
|
||||||
|
|
||||||
On Windows 10 or 11 (x64):
|
Download the installer for your computer.
|
||||||
|
|
||||||
1. Download [RuneStone_1.0.0_x64-setup.exe](https://github.com/kwyvern-gh/RuneStone/releases/download/v1.0.0/RuneStone_1.0.0_x64-setup.exe).
|
| Platform | Installer | Status |
|
||||||
2. Open the installer and complete setup.
|
| --- | --- | --- |
|
||||||
3. Open RuneStone from the Start menu.
|
| Windows 10 or 11, x64 | [RuneStone_0.1.49_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.49/RuneStone_0.1.49_x64-setup.exe) | Primary platform |
|
||||||
|
| 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 |
|
||||||
|
|
||||||
The built-in browser needs a separate engine download of about 160 MB. A browser tab offers it on first use.
|
- **Windows:** Open the installer and complete setup. Then open RuneStone from the Start menu.
|
||||||
|
- **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.
|
||||||
- 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, such as Terminal, Git, Project Management, PDF Viewer, and CSV Viewer.
|
||||||
- Add optional plugins from plugin ZIP files.
|
|
||||||
|
|
||||||
## Find help
|
## Find help
|
||||||
|
|
||||||
@@ -43,10 +47,6 @@ 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)
|
[kwyvern-gh](https://github.com/kwyvern-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.11",
|
"version": "0.1.8",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "runestone-browser",
|
"name": "runestone-browser",
|
||||||
"version": "0.1.11",
|
"version": "0.1.8",
|
||||||
"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.11",
|
"version": "0.1.8",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Isolated browser runtime included with RuneStone",
|
"description": "Isolated browser runtime included with RuneStone",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
@@ -5,27 +5,7 @@ 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,31 +31,6 @@ 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;
|
||||||
@@ -166,9 +141,7 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
|
|||||||
changed();
|
changed();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// Each new document gets a renderer widget without device emulation. A page that replaces itself before it finishes
|
wc.on('did-navigate', (_event, url) => { store.visit(profileId, url, item.title); changed(); });
|
||||||
// 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) => {
|
||||||
@@ -275,13 +248,7 @@ 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': {
|
case 'copyImage': if (context.hasImageContents) wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale)); break;
|
||||||
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;
|
||||||
@@ -292,22 +259,6 @@ 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,64 +124,6 @@ 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,8 +6,7 @@ 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;
|
||||||
// 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, canEmitFrame: () => !framePending, emit: value => {
|
||||||
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; });
|
||||||
} });
|
} });
|
||||||
|
|||||||
+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 1.0.0 download link in the README: version `1.0.0` gives `releases/1.0.0/RuneStone_1.0.0_x64-setup.exe`.
|
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`.
|
||||||
|
|
||||||
### 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 `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`.
|
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`.
|
||||||
|
|
||||||
`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.
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
313f15e68c3b3a6eec9fb223548c9843e6e87af5566885088ddbf7434742e100 RuneStone_0.1.44_amd64.deb
|
||||||
@@ -1 +0,0 @@
|
|||||||
66d20b7321e1cdfb001e606d2cff2e174589e70eaf736edb6fbbf655e5591876 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 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).
|
||||||
|
|||||||
+2
-147
@@ -352,7 +352,6 @@ 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
|
||||||
|
|
||||||
@@ -443,7 +442,6 @@ 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
|
||||||
|
|
||||||
@@ -591,7 +589,6 @@ 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
|
||||||
|
|
||||||
@@ -814,7 +811,6 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
|
|||||||
- 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
|
||||||
|
|
||||||
@@ -830,7 +826,6 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
|
|||||||
- 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
|
||||||
@@ -928,7 +923,7 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
|
|||||||
|
|
||||||
- Type: Rule change
|
- Type: Rule change
|
||||||
- Date: 2026-10-28
|
- Date: 2026-10-28
|
||||||
- Status: Implemented for user review. The names beside the icons are superseded by [UI-056](#ui-056--icon-only-view-control).
|
- Status: Implemented for user review
|
||||||
- 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.
|
||||||
@@ -955,7 +950,7 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
|
|||||||
- 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." [UI-062](#ui-062--tabs-use-the-free-header-space) replaces the drag area rule.
|
- Replaces / replaced by: The left pane footer, and the ribbon rule "The ribbon has no width when it has no entries."
|
||||||
- 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
|
||||||
@@ -1032,143 +1027,3 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
|
|||||||
- 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/`.
|
- 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).
|
- 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.
|
- 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 right or bottom part of a pane opens a new pane there. A hint shows the place of the drop.
|
|
||||||
- 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/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.
|
|
||||||
|
|||||||
+18
-40
@@ -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://github.com/kwyvern-gh/RuneStone.git`.
|
1. Clone the repository: `https://git.knottywyvern.com/kwyvern/RuneStone`.
|
||||||
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`.
|
||||||
@@ -63,10 +63,10 @@ Windows is the primary platform. macOS and Linux builds are experimental.
|
|||||||
| `plugins.rs` | Plugin package review, installation, enable state, removal, and recovery |
|
| `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 of the Git feature. It runs the `git` program. |
|
| `git.rs` | The Git service of the Git feature. It runs the `git` program. |
|
||||||
| `features.rs` | Reads the old plugin packages of the native features one time, for the first-start migration. It changes no plugin file. |
|
| `features.rs` | Reads the old plugin packages of the native features one time, for the switch 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. |
|
| `pty.rs`, `terminal_platform.rs` | Pseudo-terminals for the Terminal plugin |
|
||||||
| `browser.rs` | The process of the built-in browser engine |
|
| `browser.rs` | The process of the built-in browser engine |
|
||||||
| `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 |
|
| `backgrounds.rs` | Background image folders for themes and plugins |
|
||||||
| `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. |
|
||||||
@@ -88,7 +88,7 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command
|
|||||||
| `settings/` | The settings store (`store.ts`), and the code that moves the old browser values to the settings file (`migration.ts`) |
|
| `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 |
|
||||||
| `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). |
|
| `features/` | The native features with an off switch: the catalog (`catalog.ts`), the switches (`state.ts`), the first-start migration, the loader, and one folder for each feature (`git/`). See [Native features](#native-features). |
|
||||||
| `completion/` | Contracts and services that plugins use |
|
| `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 |
|
| `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`) |
|
||||||
@@ -114,12 +114,11 @@ 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, and the boards, cards, labels, and images of Project Management (`.runestone/pm/`) | `.runestone/` in the workspace |
|
| Workspace state: tab order, pins, bookmarks, templates, Project Management boards | `.runestone/` in the workspace |
|
||||||
| Installed plugins and their settings | The app data folder. See [plugin storage](plugin-host.md#storage-and-recovery). |
|
| 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, feature switches, Background, Terminal, Project Management | `settings.json` in the app config folder |
|
| Preferences: general settings, appearance, custom themes, display language | `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, 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. |
|
| Window layout and the open tabs of each workspace | The WebView storage (`localStorage`) of the app. RuneStone can lose these values without harm. |
|
||||||
|
|
||||||
#### The settings file
|
#### The settings file
|
||||||
|
|
||||||
@@ -136,16 +135,13 @@ On macOS, it is `~/Library/Application Support/<identifier>/`. On Linux, it is `
|
|||||||
"customThemes": [],
|
"customThemes": [],
|
||||||
"customThemesLegacy": [],
|
"customThemesLegacy": [],
|
||||||
"language": "en",
|
"language": "en",
|
||||||
"features": { "git": true, "background": true, "terminal": true, "pdf": true, "pm": true },
|
"features": { "git": 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), `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. |
|
| Sections | `general`, `appearance`, `customThemes`, `customThemesLegacy` (the original version 1 themes), `language`, and `features` (the switches of the native features). The host does not interpret their values. The frontend normalizes each section. |
|
||||||
| 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. |
|
||||||
@@ -210,41 +206,22 @@ Errors of the plugin API stay in English, because they are for plugin developers
|
|||||||
|
|
||||||
## Native features
|
## 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.
|
Git is a native feature: host code with an off switch in **Settings → Features**. It does not use the plugin API.
|
||||||
|
|
||||||
| Part | File |
|
| Part | File |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| The catalog: ID, old plugin ID, name, views, commands, and document types | `src/lib/features/catalog.ts` |
|
| The catalog: ID, old plugin ID, name, views, and commands | `src/lib/features/catalog.ts` |
|
||||||
| The switches: the `features` settings section | `src/lib/features/state.ts` |
|
| The switches: the `features` settings section | `src/lib/features/state.ts` |
|
||||||
| The first start: each switch takes the state of the old plugin package, or the default of the feature when `followsPackage` is false | `src/lib/features/migration.ts` and `src-tauri/src/features.rs` |
|
| The first start: each switch takes the state of the old plugin package | `src/lib/features/migration.ts` and `src-tauri/src/features.rs` |
|
||||||
| One import at first need in each window | `src/lib/features/loader.ts` |
|
| One import at first need in each window | `src/lib/features/loader.ts` |
|
||||||
| A start without a view: the launch rules, also the rule for browser windows | `src/lib/features/launch.ts` |
|
| Views and commands in the workbench | `src/lib/features/session.ts` and `src/lib/plugins/external.ts` |
|
||||||
| Views, commands, and document tabs in the workbench | `src/lib/features/session.ts` and `src/lib/plugins/external.ts` |
|
|
||||||
| The feature code | `src/lib/features/<feature>/index.ts` and its components |
|
| The feature code | `src/lib/features/<feature>/index.ts` and its components |
|
||||||
|
|
||||||
- The catalog holds only static data, so the main bundle stays small. The feature code loads when the user first opens a view, a tab, or a command of the feature. An off feature loads nothing.
|
- The catalog holds only static data, so the main bundle stays small. The feature code loads when the user first opens a view, a tab, or a command of the feature. An off feature loads nothing.
|
||||||
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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`.
|
||||||
|
|
||||||
## Plugin SDK
|
## Plugin SDK
|
||||||
|
|
||||||
@@ -287,6 +264,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_Local_Autocomplete/src` | 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. |
|
||||||
@@ -295,14 +273,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, for tab transfers, and for the `pty_*` shells of Terminal. All pages of one browser context share them.
|
The harness also has default handlers for the settings file and for tab transfers. 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,8 +10,6 @@ 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.
|
||||||
|
|
||||||
@@ -24,11 +22,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 Read beside. It can fit the image or magnify it. Press Escape to close it.
|
Zoom works in Write, Read, and Split. 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 Read beside show wiki links, note callouts, and Mermaid diagrams.
|
Write, Read, and Split 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.
|
||||||
|
|
||||||
@@ -97,7 +95,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 Read beside. Select a result to edit its formula. Enter saves the formula, and Tab moves to the next 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.
|
||||||
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.
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -13,7 +13,7 @@ Git is part of RuneStone and is on by default. It needs the `git` program on the
|
|||||||
3. Select a file to open its diff in an editor tab. **Open file** in that tab opens the file in the editor.
|
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.
|
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.
|
Source control shows the current branch and two groups. **Staged changes** go into the next commit. **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.
|
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.
|
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.
|
||||||
|
|||||||
@@ -1,175 +0,0 @@
|
|||||||
# 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.
|
|
||||||
+20
-47
@@ -1,30 +1,29 @@
|
|||||||
# Terminal guide
|
# Terminal guide
|
||||||
|
|
||||||
[RuneStone](../../README.md) · [User guide](../user-guide.md)
|
[RuneStone](../../README.md) · [User guide](../user-guide.md) · [Install a plugin](../plugins.md#install-a-plugin)
|
||||||
|
|
||||||
This guide explains how to use shells, scripts, and workspace tasks in the terminal of RuneStone.
|
This guide explains how to use shells, scripts, and workspace tasks with the optional Terminal plugin.
|
||||||
|
|
||||||
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).
|
Install and enable the Terminal plugin first. The shells and script runtimes that you use must be installed on your computer.
|
||||||
|
|
||||||
## Open and arrange terminals
|
## Open and arrange terminals
|
||||||
|
|
||||||
| Action | How |
|
| Action | How |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Show or hide the terminal panel | **Terminal** in the left ribbon, Ctrl+`, or Ctrl+J. Sessions and scrollback stay. |
|
| Show or hide the terminal panel | 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 or **Split terminal**. The new pane uses the same folder and profile. |
|
| Split the active terminal | Ctrl+Shift+5. The new pane uses the same folder and profile. |
|
||||||
| New terminal window | Ctrl+Shift+Alt+`, or **New terminal window** in the profile menu |
|
| New terminal window | Ctrl+Shift+Alt+` |
|
||||||
| 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 terminal window ends its sessions. When you close a workspace window with running sessions, RuneStone asks first.
|
Closing a separate terminal window ends its sessions.
|
||||||
You can type before a shell starts. RuneStone sends the text when the shell is ready.
|
|
||||||
|
|
||||||
## Choose a shell
|
## Choose a shell
|
||||||
|
|
||||||
Open **Terminal profiles and tasks** (the arrow beside the + button) to start a terminal with a specific profile.
|
Open the menu beside the + button to start a terminal with a specific profile.
|
||||||
|
|
||||||
| System | Profiles |
|
| System | Profiles |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -32,26 +31,10 @@ Open **Terminal profiles and tasks** (the arrow beside the + button) to start a
|
|||||||
| 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**, **Terminal settings**, **Select the default profile**, and the task commands.
|
The same menu has **Split Terminal with Profile**, **Select Default Profile**, **Configure Terminal Settings**, and the task commands.
|
||||||
|
Terminal settings set the font size, scrollback lines, cursor blink, and default profile. RuneStone keeps them on this computer.
|
||||||
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.
|
||||||
@@ -65,25 +48,24 @@ Open **More terminal actions** for these commands:
|
|||||||
|
|
||||||
| Command | Result |
|
| Command | Result |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| **Scroll to the previous command** / **Scroll to the next command** (Ctrl+Up / Ctrl+Down) | Moves between command prompts. |
|
| **Run Active File** | Saves and runs the active file in the terminal. |
|
||||||
| **Clear the terminal** | Clears the scrollback. |
|
| **Run Selected Text** | Sends the text that is selected in the editor to the terminal. |
|
||||||
| **Run the active file** | Saves and runs the active file in the terminal. |
|
| **Clear Terminal** | Clears the scrollback. |
|
||||||
| **Run selected text** | Sends the text that is selected in the editor to the terminal. |
|
| **Run Recent Command…** (Ctrl+Alt+R) | Runs a command from this session again. |
|
||||||
| **Start dictation** | Starts Windows voice typing. See [Debug JavaScript and use dictation](#debug-javascript-and-use-dictation). |
|
| **Go to Recent Directory…** (Ctrl+G) | Changes to a recent folder. |
|
||||||
| **Go to a recent folder…** (Ctrl+G) | Changes to a recent folder. |
|
| **Scroll to Previous Command** / **Next Command** (Ctrl+Up / Ctrl+Down) | Moves between command prompts. |
|
||||||
| **Run a recent command…** (Ctrl+Alt+R) | Runs a command from this session again. |
|
|
||||||
|
|
||||||
**Run the active file** supports Python, JavaScript, PowerShell, Bash, Ruby, Windows batch files, and executables.
|
**Run 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 a task…** and select the task.
|
4. Choose **Run Task…** and select the task.
|
||||||
|
|
||||||
Example (`.runestone/tasks.json`):
|
Example (`.runestone/tasks.json`):
|
||||||
|
|
||||||
@@ -102,14 +84,5 @@ 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.
|
|
||||||
|
|||||||
+10
-62
@@ -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, show a background, and edit, create, or share a custom theme.
|
This guide explains how to choose colors, set a background image, 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,72 +21,20 @@ 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](#show-a-background) and compatible plugin surfaces.
|
**Transparent surfaces** tints work areas with a background image and compatible plugin surfaces.
|
||||||
Without a background image, menus are opaque. With an image, menus use the same transparency as other surfaces and blur the image.
|
Menus stay opaque. With a background image, menus are at least 92% opaque and blur the image.
|
||||||
Set **Transparency amount** from 0% to 100%. The default is 18%.
|
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.
|
||||||
|
|
||||||
## Show a background
|
## Set a background image
|
||||||
|
|
||||||
The **Background** section shows a folder of images as a slideshow, or one image, behind the workspace.
|
1. Choose **Choose image…** and select a PNG, JPEG, WebP, or GIF file up to 50 MiB.
|
||||||
Set **Background source** to **Folder**, **Image**, or **None**.
|
2. Set **Image size** to **Fill**, **Fit**, or **Actual size**.
|
||||||
|
3. Set **Image position**.
|
||||||
|
4. Set **Image overlay** from -100% to 100%. Negative values lighten the image, and positive values darken it.
|
||||||
|
|
||||||
### Show a folder as a slideshow
|
The image shows in new tabs. RuneStone keeps it on this computer.
|
||||||
|
The Project Management plugin can keep a separate image for a board. The Background Slideshow plugin can replace the image for a time.
|
||||||
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
|
||||||
|
|
||||||
|
|||||||
+34
-32
@@ -2,32 +2,23 @@
|
|||||||
|
|
||||||
[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 release file or from a package that you build.
|
This guide installs, updates, or reinstalls RuneStone from a supplied release file.
|
||||||
|
|
||||||
| Platform | Release file | Notes |
|
| Platform | Release file | Notes |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Windows 10 or 11, x64 | [RuneStone_1.0.0_x64-setup.exe](https://github.com/kwyvern-gh/RuneStone/releases/download/v1.0.0/RuneStone_1.0.0_x64-setup.exe) | Installs for the current Windows account |
|
| Windows 10 or 11, x64 | [RuneStone_0.1.49_x64-setup.exe](https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/v0.1.49/RuneStone_0.1.49_x64-setup.exe) | Installs for the current Windows account |
|
||||||
| macOS, Apple silicon | None | Build the app from source. See [macOS packages](builds.md#macos-packages). Intel Macs are not supported. |
|
| 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. |
|
||||||
| Linux, amd64 | None | Build a Debian package from source. See [Build Linux packages](builds.md#build-linux-packages). |
|
| 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. |
|
||||||
|
|
||||||
On Windows, you do not need Node.js, Rust, or a source checkout.
|
You do not need Node.js, Rust, or a source checkout.
|
||||||
The built-in browser needs a separate engine download. See [Use the built-in browser](user-guide.md#use-the-built-in-browser).
|
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).
|
||||||
|
|
||||||
## Install on Windows
|
## Install on Windows
|
||||||
|
|
||||||
1. Save `RuneStone_1.0.0_x64-setup.exe` and [windows-SHA256SUMS](https://github.com/kwyvern-gh/RuneStone/raw/master/docs/checksums/1.0.0/windows-SHA256SUMS) to Downloads.
|
1. Save `RuneStone_0.1.49_x64-setup.exe` to Downloads.
|
||||||
2. Open PowerShell in Downloads.
|
2. Open the file.
|
||||||
3. Check the download:
|
3. Complete setup. Keep the default destination unless you need another location.
|
||||||
|
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
|
||||||
|
|
||||||
@@ -42,30 +33,41 @@ After an update from 0.1.48 or earlier, a browser tab asks you to download the b
|
|||||||
|
|
||||||
## Install on macOS
|
## Install on macOS
|
||||||
|
|
||||||
Build the app on an Apple silicon Mac first. See [macOS packages](builds.md#macos-packages).
|
1. Save `RuneStone_0.1.44_aarch64.dmg` to Downloads.
|
||||||
|
2. Open the disk image.
|
||||||
|
3. Drag RuneStone into Applications.
|
||||||
|
4. Eject the disk image.
|
||||||
|
5. Open RuneStone from Applications.
|
||||||
|
|
||||||
1. Copy `RuneStone.app` from `src-tauri/target/release/bundle/macos/` into Applications.
|
The app has an ad hoc signature and is not notarized by Apple.
|
||||||
2. Open RuneStone from Applications.
|
If macOS blocks the first launch, open **System Settings → Privacy & Security** and choose **Open Anyway**.
|
||||||
|
|
||||||
## 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. Build the same or a newer version.
|
2. Open the disk image for the same or a newer version.
|
||||||
3. Copy the new `RuneStone.app` into Applications and confirm the replacement.
|
3. Drag RuneStone into Applications and confirm the replacement.
|
||||||
4. Open RuneStone from Applications.
|
4. Eject the disk image.
|
||||||
|
5. Open RuneStone from Applications.
|
||||||
|
|
||||||
## Install on Linux
|
## Install on Linux
|
||||||
|
|
||||||
Build the Debian package first. See [Build Linux packages](builds.md#build-linux-packages).
|
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.
|
||||||
|
2. Open Terminal in Downloads.
|
||||||
1. Open Terminal in the folder that contains the package.
|
3. Check the download:
|
||||||
2. Install the package. Use the file name of your build:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo apt install ./RuneStone_1.0.0_amd64.deb
|
sha256sum --check linux-SHA256SUMS
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Open RuneStone from your applications menu, or run `runestone` in Terminal.
|
If the result is not `OK`, delete the file and download it again.
|
||||||
|
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.
|
||||||
|
|
||||||
@@ -75,4 +77,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 ./<file>.deb`.
|
To reinstall the same version, run `sudo apt install --reinstall ./RuneStone_0.1.44_amd64.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 | Open the terminal panel. Bash starts in the workspace, accepts Unicode, resizes, and exits when its session closes. |
|
| Terminal plugin | Install the Terminal ZIP. 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 use of Terminal, see the [Terminal guide](guides/terminal.md).
|
For the Terminal ZIP, see [Build examples](plugin-development.md#build-examples) and the [plugin installation guide](plugins.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:
|
||||||
|
|||||||
+131
-110
@@ -1,8 +1,12 @@
|
|||||||
{
|
{
|
||||||
"date": "2026-10-29",
|
"date": "2026-10-15",
|
||||||
"scope": [
|
"scope": [
|
||||||
"RuneStone",
|
"RuneStone",
|
||||||
|
"RuneStone_Project_Management",
|
||||||
|
"RuneStone_Terminal",
|
||||||
|
"RuneStone_Background_Slideshow",
|
||||||
"RuneStone_Local_Autocomplete",
|
"RuneStone_Local_Autocomplete",
|
||||||
|
"RuneStone_PDF_Viewer",
|
||||||
"RuneStone_CSV_Viewer"
|
"RuneStone_CSV_Viewer"
|
||||||
],
|
],
|
||||||
"limits": [
|
"limits": [
|
||||||
@@ -155,6 +159,14 @@
|
|||||||
"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,
|
||||||
@@ -170,6 +182,120 @@
|
|||||||
"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,
|
||||||
@@ -195,117 +321,12 @@
|
|||||||
"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/src/lib/features/background/BackgroundSettings.svelte": {
|
"RuneStone_Project_Management/src/workspace-default.ts": {
|
||||||
"counts": {
|
"counts": {
|
||||||
"action": 1,
|
"nativeChoice": 1
|
||||||
"localPopup": 4
|
|
||||||
},
|
},
|
||||||
"design": "Shared action menu for the source, the order, the image position, and the image size. Theme choice stays on preview cards (UI-047).",
|
"design": "Uses the host menu. Keeps a native selector for older hosts.",
|
||||||
"check": "tests/smoke/features/background.smoke.mjs"
|
"check": "RuneStone_Project_Management/tests/october-cards.spec.ts with PM_HOST_URL; both themes, narrow layout, keyboard focus"
|
||||||
},
|
|
||||||
"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"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+120
-26
@@ -11,8 +11,10 @@ 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)
|
||||||
|
- [Background API](#background-api)
|
||||||
|
|
||||||
## Install the SDK
|
## Install the SDK
|
||||||
|
|
||||||
@@ -20,7 +22,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://github.com/kwyvern-gh/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
pnpm add -D "https://git.knottywyvern.com/kwyvern/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.
|
||||||
@@ -144,21 +146,22 @@ 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: CSV Viewer
|
### Example: Terminal
|
||||||
|
|
||||||
Source: the CSV Viewer repository, a private repository: its `package.json`, `plugin.json`, `scripts/build.mjs`, and `README.md`.
|
Source: [Terminal repository](https://git.knottywyvern.com/kwyvern/RuneStone_Terminal), its `package.json`, and its `scripts/build.mjs`.
|
||||||
|
|
||||||
| Item | Value |
|
| Item | Value |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 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/`. |
|
| Prerequisites | Node.js 24 and pnpm 10. Run `pnpm install --frozen-lockfile` in the Terminal folder. |
|
||||||
| Working folder | The CSV Viewer repository root |
|
| Working folder | The Terminal repository root |
|
||||||
| Command | `pnpm build` |
|
| Command | `pnpm build` |
|
||||||
| Output | `releases/runestone.csv-viewer-<version>.zip` in the CSV Viewer folder. `<version>` is the `version` of `plugin.json`, for example `0.1.3`. |
|
| Output | `releases/runestone.terminal-<version>.zip` in the Terminal folder |
|
||||||
|
|
||||||
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 compiles the Svelte interface and its dependencies into `dist/` (`main.js`, `style.css`, `plugin.json`, and `README.md`). Then it makes the ZIP.
|
||||||
Then it runs `scripts/packagePlugin.mjs` of the RuneStone checkout on `dist/`. Set `RUNESTONE_ROOT` to use another RuneStone checkout for this step.
|
The build stops when the versions in `package.json` and `plugin.json` are different.
|
||||||
The build stops when the versions in `package.json` and `plugin.json` are different. It also stops when the release ZIP of the version exists. Set the next version in both files first.
|
To compile into `dist/` without a ZIP, run `node scripts/build.mjs --no-package`.
|
||||||
To compile into `dist/` without a ZIP, run `pnpm compile`.
|
RuneStone supplies the native terminal sessions. The plugin supplies the interface, shortcuts, and session controls.
|
||||||
|
For use of the terminal, see the [Terminal guide](guides/terminal.md).
|
||||||
|
|
||||||
### Example: Workspace overview
|
### Example: Workspace overview
|
||||||
|
|
||||||
@@ -213,8 +216,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, ["files", "workspace.readBytes"]);
|
requireFeatures(api, ["pty", "workspace.readBytes"]);
|
||||||
const files = requireFeature(api, "files");
|
const pty = requireFeature(api, "pty");
|
||||||
if (hasFeature(api, "settings.subscribe")) watchSettings();
|
if (hasFeature(api, "settings.subscribe")) watchSettings();
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -222,8 +225,6 @@ 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.
|
||||||
@@ -231,7 +232,7 @@ The host has no `api.backgrounds`. Only the native Background feature shows imag
|
|||||||
- 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, and views first. Then it runs view cleanups and `onDispose` callbacks in reverse order.
|
- On disable, the host removes contributions, commands, views, and background frames 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.
|
||||||
|
|
||||||
@@ -263,8 +264,10 @@ The host has no `api.backgrounds`. Only the native Background feature shows imag
|
|||||||
| `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). |
|
||||||
|
| `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
|
||||||
|
|
||||||
@@ -306,6 +309,7 @@ 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
|
||||||
|
|
||||||
@@ -381,9 +385,10 @@ 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 |
|
||||||
| `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 |
|
||||||
|
|
||||||
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.
|
A terminal contribution must stop its controls and native sessions before its cleanup finishes.
|
||||||
|
|
||||||
### Theme tokens
|
### Theme tokens
|
||||||
|
|
||||||
@@ -418,12 +423,49 @@ 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 of the [API reference](#api-reference). They check plugin shutdown, and they will stay available when a later host runs each plugin in its own isolated context.
|
Use the `api` members below. They check plugin shutdown, and they will stay available when a later host runs each plugin in its own isolated context.
|
||||||
Make sure that an optional member exists before you use it.
|
Make sure that an optional member exists before you use it. Keep the native call only as a fallback for older hosts.
|
||||||
|
|
||||||
The Local Autocomplete and CSV Viewer plugins make no native calls.
|
The host still accepts the native calls of released plugins. A later host can remove them.
|
||||||
|
|
||||||
|
| Plugin | Current call | Purpose | Use instead |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Terminal | `invoke("pty_open")`, `listen("pty-data")`, `listen("pty-exit")` | Start a shell and receive its output and exit code | `api.pty.open({ ..., onData, onExit })` |
|
||||||
|
| Terminal | `invoke("pty_write")`, `invoke("pty_resize")`, `invoke("pty_close")` | Send input, change the size, stop the shell | `write`, `resize`, and `close` of the session from `api.pty.open` |
|
||||||
|
| Terminal | `invoke("pty_profiles")` | List the installed shells | `api.pty.profiles()` |
|
||||||
|
| Terminal | `invoke("pty_new_window")` | Open a terminal window | `api.pty.openWindow()` |
|
||||||
|
| Terminal | `invoke("pty_dictation")` | Start Windows voice typing | `api.pty.dictation()` |
|
||||||
|
| Terminal | `invoke("workspace_read", { rel: ".runestone/tasks.json" })` | Read the task list of the workspace | `api.workspace.read(path)` |
|
||||||
|
| Background Slideshow | `api.backgrounds.chooseFolder`, `list`, `read`, `defaultFolder`, `readImageSettings`, `writeImageSettings` | Read images and per-image settings from a folder outside the workspace | `api.files` with a folder grant |
|
||||||
|
| Background Slideshow | `api.workspace.readOptional(".runestone/pm/workspace.json")` | Read the board names of Project Management | A service of Project Management through `api.services` |
|
||||||
|
|
||||||
|
The 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.
|
||||||
@@ -449,13 +491,6 @@ 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.
|
||||||
@@ -470,3 +505,62 @@ 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.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|||||||
+21
-19
@@ -33,7 +33,7 @@ The browser preview (`pnpm dev`) has no installed plugins unless a smoke test su
|
|||||||
|
|
||||||
The built-in browser and the theme editor use the plugin API, but they are not packages. `builtInModules` in `src/lib/plugins/external.ts` lists them. The host starts them in each window, and the plugin menus do not list their tools. A browser window starts only the browser.
|
The built-in browser and the theme editor use the plugin API, but they are not packages. `builtInModules` in `src/lib/plugins/external.ts` lists them. The host starts them in each window, and the plugin menus do not list their tools. A browser window starts only the browser.
|
||||||
`builtInPackages` lists the IDs of old packages for features that RuneStone now includes. The host never loads such a package. Settings → Plug-ins shows it as included with RuneStone, so that the user can remove it.
|
`builtInPackages` lists the IDs of old packages for features that RuneStone now includes. The host never loads such a package. Settings → Plug-ins shows it as included with RuneStone, so that the user can remove it.
|
||||||
Native features, such as Git, 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).
|
Native features, such as Git, do not use the plugin API. `syncFeatures` in `external.ts` gives each feature that is on a feature session (`src/lib/features/session.ts`) under the ID of its old package, so that its views share the tab model of plugin views. Browser windows start no native feature. See [Native features](development.md#native-features).
|
||||||
`features_legacy` (`src-tauri/src/features.rs`) reads the catalog row and the kept `plugin-data/<id>/settings.json` of an old package. It accepts only the IDs of native features and changes no file.
|
`features_legacy` (`src-tauri/src/features.rs`) reads the catalog row and the kept `plugin-data/<id>/settings.json` of an old package. It accepts only the IDs of native features and changes no file.
|
||||||
|
|
||||||
### Scans
|
### Scans
|
||||||
@@ -108,7 +108,7 @@ The uninstall dialog puts focus on **Cancel**. Escape cancels.
|
|||||||
|
|
||||||
`plugins_load` returns the entry module and records a lease for the window. `plugins_release` ends the lease and records any cleanup error.
|
`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 folder grant commands (`folders_*`), need a lease for the calling window.
|
Native services for plugins, such as the background file commands, need a lease for the calling window.
|
||||||
|
|
||||||
## Gitea downloads
|
## Gitea downloads
|
||||||
|
|
||||||
@@ -159,12 +159,12 @@ The policy stops a script that comes in through rendered content, for example a
|
|||||||
| Directive | Sources | Reason |
|
| Directive | Sources | Reason |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `default-src` | `'self'` | All other types come only from the app. |
|
| `default-src` | `'self'` | All other types come only from the app. |
|
||||||
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: 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`. |
|
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: the PDF Viewer decodes JPEG 2000 and JBIG2 images and color profiles with WebAssembly in its worker. It does not permit `eval`. |
|
||||||
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, xterm in the Terminal feature, the Vite dev server, and plugins (CSV Viewer). |
|
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, the Vite dev server, and plugins (Terminal, CSV Viewer, PDF Viewer, Background Slideshow). |
|
||||||
| `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:`: PDF.js can load the embedded fonts of a PDF from data addresses. |
|
| `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: fonts that the PDF Viewer embeds. |
|
||||||
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the blur worker of the Background feature reads its image from a Blob URL. |
|
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the Background Slideshow worker reads its image from a Blob URL. |
|
||||||
| `worker-src` | `'self' blob:` | `'self'`: workers that the app serves, such as the PDF.js worker of each PDF tab. `blob:`: the blur worker of the Background feature. |
|
| `worker-src` | `'self' blob:` | `'self'`: workers that the app serves. The app starts no worker now. `blob:`: the PDF Viewer and Background Slideshow workers. |
|
||||||
| `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. |
|
||||||
@@ -186,19 +186,18 @@ 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, the Background folder, folder grants, completion, browser, `pty_profiles`, and `pty_running` |
|
| `settings.json` | `settings-main`, `settings-workspace-*` | All enabled plugins | Settings, plugins, backgrounds, completion, browser |
|
||||||
| `browser.json` | `browser-*` | Only the built-in browser (`builtInModules` in `src/lib/plugins/external.ts`) | Browser, `plugins_snapshot`, settings, spelling, window controls, and the read commands of the Background folder (`background_folder`, `background_list`, `background_read`, `background_read_sidecar`) |
|
| `browser.json` | `browser-*` | Only the built-in browser (`builtInModules` in `src/lib/plugins/external.ts`) | Browser, `plugins_snapshot`, settings, spelling, and window controls |
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
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 `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.
|
- Terminal windows use the plugin host commands, `pty_*` through the Terminal plugin, and `core:window:allow-destroy`. Other plugins in the same window expect the full host API.
|
||||||
- Settings windows use no `workspace_*` 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.
|
- Settings windows use no `workspace_*`, `git_*`, or `pty_*` commands, but plugin settings views run there.
|
||||||
- Commands that need a workspace (`workspace_*`, `git_*`, `pty_open`, `pty_new_window`) fail in a window without a bound workspace.
|
- 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` act only on the sessions of the calling window. A session of another window counts as a missing session.
|
- `pty_write`, `pty_resize`, and `pty_close` do not check the window that opened the terminal.
|
||||||
- `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.
|
- `backgrounds_*` need a plugin lease of the calling window.
|
||||||
- `folders_*` need a plugin lease of the calling window. The `background_*` commands of the Background feature need no lease. They take no path: the host keeps the folder that the folder dialog gave.
|
|
||||||
- `browser_request` needs the session token that `browser_connect` gives the window. A plugin lease does not replace it.
|
- `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.
|
||||||
|
|
||||||
@@ -208,9 +207,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` | The image folder of the native Background feature. Plugins use folder grants |
|
| `src-tauri/src/backgrounds.rs` | Background folder and image commands. Deprecated for 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` | 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-tauri/src/pty.rs` | Terminal sessions for `api.pty`. A session with an IPC channel gets raw output bytes; a session without one gets the older window events |
|
||||||
| `src/lib/plugins/sdk.ts` | The public package API types |
|
| `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 |
|
||||||
@@ -219,8 +218,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` | 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/backgrounds.ts` | Background frames |
|
||||||
| `src/lib/plugins/nativeServices.ts` | The host side of `api.files`. It binds the plugin ID. The plugin never sends it |
|
| `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/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 |
|
||||||
@@ -230,6 +229,9 @@ 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
|
||||||
|
|||||||
+14
-7
@@ -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.
|
This guide explains how to install, enable, update, and remove optional plugins such as Terminal, PDF Viewer, and CSV Viewer.
|
||||||
|
|
||||||
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).
|
Manage all plugins in **Settings → Plug-ins**. The built-in browser, table formulas, and Git are part of RuneStone and are not plugins. To turn Git 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.csv-viewer-<version>.zip`. Do not extract it.
|
Get the release ZIP of the plugin, such as `runestone.terminal-<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,6 +71,17 @@ 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) |
|
||||||
|
| 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 |
|
||||||
@@ -84,10 +95,6 @@ RuneStone uses the token for this request only and does not save it.
|
|||||||
| A Gitea release has no usable package | Check the release tag. Ask the publisher for a release with one attached plugin ZIP. |
|
| 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 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://github.com/kwyvern-gh/RuneStone/releases). Browser engine ZIPs and SDK packages use the same page.
|
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.
|
||||||
|
|
||||||
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://github.com/kwyvern-gh/RuneStone/releases/download/plugin-sdk-v0.1.2`.
|
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`.
|
||||||
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.
|
||||||
|
|||||||
+1
-3
@@ -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 `src/lib/features/pm/ui/style.css` | Full saturation and value, with opaque symbols and readable text. |
|
| Priority (Project Management) | `--pm-priority-color` in the plugin `src/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,8 +38,6 @@ 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.
|
||||||
|
|
||||||
|
|||||||
+20
-30
@@ -52,8 +52,7 @@ 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: the surface tint and the `--rs-hover-bg` veil. |
|
| `--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-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. |
|
||||||
|
|
||||||
@@ -101,7 +100,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 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.
|
- 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.
|
||||||
- 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.
|
||||||
|
|
||||||
@@ -143,18 +142,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), [UI-061](design-decisions.md#ui-061--translucent-menus-and-hover-fills-over-images).
|
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).
|
||||||
|
|
||||||
## 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, 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.
|
- 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.
|
||||||
- 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)).
|
- Tabs keep a minimum width of 120 pixels and scroll. Fades show tabs out of view, and ⌄ lists all tabs. A drag area of 120 pixels sits after the tabs. In a narrow header, the tabs shrink first, and the drag area keeps at least 48 pixels.
|
||||||
- Windows and Linux title bars use square caption buttons, 46 pixels wide and full height. Rest the pointer on maximize for Snap Layouts on Windows 11. macOS keeps its native traffic lights, and title bars leave `--rs-titlebar-inset-start` free for them.
|
- 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, 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.
|
- 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 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.
|
- 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.
|
||||||
- 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.
|
||||||
@@ -174,20 +173,18 @@ Decisions: [UI-004](design-decisions.md#ui-004--detached-tab-work-area), [UI-039
|
|||||||
- Controls wrap at narrow widths, and the content area scrolls. Long navigation must leave room for the selected page.
|
- 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.
|
- **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.
|
- A feature that is off shows no controls: no navigation button, ribbon button, command, or tab.
|
||||||
- **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), [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).
|
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).
|
||||||
|
|
||||||
## 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 in Settings → Terminal.
|
- 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.
|
||||||
- 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.
|
||||||
@@ -197,8 +194,6 @@ 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).
|
||||||
@@ -222,21 +217,19 @@ 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 Read beside share the editor surface. CodeMirror layers stay transparent above it.
|
- Write, Source, Read, and Split 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. The one image of Background can be up to 50 MiB. Its bytes stay in IndexedDB, and the appearance settings keep a small reference.
|
- The 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 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.
|
- 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.
|
||||||
- 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), [UI-061](design-decisions.md#ui-061--translucent-menus-and-hover-fills-over-images).
|
Decisions: [UI-010](design-decisions.md#ui-010--background-surface-visibility), [UI-011](design-decisions.md#ui-011--backgrounds-across-the-work-area), [UI-016](design-decisions.md#ui-016--translucent-code-blocks).
|
||||||
|
|
||||||
### Project Management surfaces
|
### 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 board images and slideshow frames.
|
- The host gives `--rs-workarea-plugin-bg` and `--rs-workarea-surface-opacity` for saved 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.
|
||||||
@@ -245,15 +238,13 @@ Decisions: [UI-014](design-decisions.md#ui-014--readable-project-management-surf
|
|||||||
|
|
||||||
### Slideshow
|
### Slideshow
|
||||||
|
|
||||||
- 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.
|
- 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.
|
||||||
- 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.
|
||||||
- The next image loads and decodes before its fade starts. A new frame changes only the custom properties with a new value.
|
- Portrait images show in full over a blurred cover layer by default. The image editor previews a per-image fit, position, and overlay, and saves or resets the override. Global settings apply to other images. The [plugin API](plugin-development.md#plugin-api) defines the storage.
|
||||||
- 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.
|
- A new browser tab on `about:blank` shows the host background. A loaded page keeps its own rendering, even when it is empty.
|
||||||
- **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), [UI-057](design-decisions.md#ui-057--background-replaces-background-image-and-background-slideshow).
|
Decisions: [UI-015](design-decisions.md#ui-015--slower-slideshow-fades), [UI-020](design-decisions.md#ui-020--per-image-slideshow-layout).
|
||||||
|
|
||||||
## Tooltips and text selection
|
## Tooltips and text selection
|
||||||
|
|
||||||
@@ -295,11 +286,10 @@ 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 **Create your first board**.
|
- 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.
|
||||||
- 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), [UI-060](design-decisions.md#ui-060--native-project-management).
|
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).
|
||||||
|
|
||||||
## Review checklist
|
## Review checklist
|
||||||
|
|
||||||
|
|||||||
+13
-65
@@ -10,15 +10,13 @@ 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) |
|
||||||
| Review changes and commit with Git | [Git guide](guides/git.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) |
|
| 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) |
|
| Add Terminal or other 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) |
|
||||||
|
|
||||||
@@ -75,17 +73,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 **Read beside** button:
|
Each document pane has one view control with three choices, and a **Split** 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. |
|
||||||
| **Read beside** | Read beside Write or Source. Narrow panes stack the two views. Select **Read beside** again to close it. Markdown files only. |
|
| **Split** | Read beside Write or Source. Narrow panes stack the two views. Select **Split** again to close it. Markdown files only. |
|
||||||
|
|
||||||
Press Ctrl+E to switch between Write and Source. Press Ctrl+Shift+E to switch between Read and the editor. The tab menu has the same choices under **View**.
|
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**.
|
||||||
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.
|
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 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.
|
||||||
@@ -103,9 +101,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`, puts that heading at the top of the view. A heading near the end of a short document stays lower.
|
- A heading link, such as `guide.md#save-your-work` or `#save-your-work`, scrolls to that heading.
|
||||||
- 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. Select the **Backlinks** title to collapse or expand the section. RuneStone keeps that choice for all notes and after a restart.
|
- The **Backlinks** section below the outline lists notes that link to the current note. Select an entry to open it.
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
@@ -130,28 +128,6 @@ 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/`.
|
||||||
@@ -182,25 +158,7 @@ RuneStone moves the current text of the tab, also unsaved text. It closes the so
|
|||||||
If the move fails, the source tab stays open.
|
If the move fails, the source tab stays open.
|
||||||
|
|
||||||
When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab.
|
When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab.
|
||||||
This includes 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.
|
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.
|
||||||
|
|
||||||
### 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 right or bottom part opens a new pane there. A hint shows the place before you release the tab.
|
|
||||||
|
|
||||||
- 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. Select **Close split** in that bar to close the pane. 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
|
||||||
|
|
||||||
@@ -241,27 +199,21 @@ 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 (a folder slideshow or one image), and custom themes. See [Appearance and custom themes](guides/themes.md). |
|
| Appearance | Color theme, transparency, background 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). |
|
| Features | Turn Git 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
|
### 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.
|
Git is a built-in feature 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 on uses no extra memory until you first use it, for example when you open Source control.
|
||||||
- A feature that is off does not load. Its buttons, commands, and tabs do not show.
|
- A feature that is off does not load. Its buttons, commands, and tabs do not show.
|
||||||
- Terminal off ends the terminal sessions of every window. When a window runs a shell, RuneStone asks first.
|
|
||||||
- A change applies at once in all windows. The code that a window loaded stays in memory until you restart RuneStone.
|
- A change applies at once in all windows. The code that a window loaded stays in memory until you restart RuneStone.
|
||||||
|
|
||||||
After an update, Git takes the state of its old plugin package: on when the package was enabled, off when it was disabled. Without an old package, Git starts on.
|
After an update, each new built-in feature takes the state of its old plugin package: on when the package was enabled, off when it was disabled.
|
||||||
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.
|
Without an old package, the feature starts on. Settings → Plug-ins shows an old package as **Included with RuneStone**. You can uninstall it.
|
||||||
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
|
||||||
|
|
||||||
@@ -282,10 +234,6 @@ 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.
|
||||||
|
|||||||
+3
-7
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "runestone",
|
"name": "runestone",
|
||||||
"version": "1.0.1c",
|
"version": "0.1.49",
|
||||||
"description": "Desktop editor for a local workspace",
|
"description": "Desktop editor for a local workspace",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -25,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": "Apache-2.0",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@codemirror/autocomplete": "^6.20.3",
|
"@codemirror/autocomplete": "^6.20.3",
|
||||||
"@codemirror/commands": "^6.11.1",
|
"@codemirror/commands": "^6.11.1",
|
||||||
@@ -54,12 +54,8 @@
|
|||||||
"@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://github.com/kwyvern-gh/RuneStone) plugins.
|
`@runestone/plugin-sdk` gives TypeScript types and small helpers for [RuneStone](https://git.knottywyvern.com/kwyvern/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://github.com/kwyvern-gh/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
pnpm add -D "https://git.knottywyvern.com/kwyvern/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://github.com/kwyvern-gh/RuneStone/releases/download/plugin-sdk-v0.1.2/runestone-plugin-sdk-0.1.2.tgz"
|
"@runestone/plugin-sdk": "https://git.knottywyvern.com/kwyvern/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://github.com/kwyvern-gh/RuneStone/blob/master/docs/plugin-development.md#build-and-package-a-plugin).
|
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).
|
||||||
|
|
||||||
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.files`, `api.services`, and `api.workspace.readBytes`.
|
Members marked optional in `PluginApi` can be absent on older RuneStone versions. Examples are `api.pty`, `api.files`, 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, ["files", "workspace.readOptional"]);
|
requireFeatures(api, ["pty", "workspace.readOptional"]);
|
||||||
const files = requireFeature(api, "files");
|
const pty = requireFeature(api, "pty");
|
||||||
|
|
||||||
// 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 folder grant API (api.files). Update RuneStone to a version that has this feature.`
|
`This plugin needs the terminal API (api.pty). 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://github.com/kwyvern-gh/RuneStone/blob/master/docs/plugin-development.md): the package format, the API, and the build procedure
|
- [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
|
||||||
- [Completion API](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/completion.md)
|
- [Completion API](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/completion.md)
|
||||||
- [Install and manage plugins](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/plugins.md)
|
- [Install and manage plugins](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugins.md)
|
||||||
- [Release policy](https://github.com/kwyvern-gh/RuneStone/blob/master/docs/releases.md#sdk-releases)
|
- [Release policy](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/releases.md#sdk-releases)
|
||||||
|
|
||||||
The SDK source is in the `packages/plugin-sdk` folder of the [RuneStone repository](https://github.com/kwyvern-gh/RuneStone). Report problems there.
|
The SDK source is in the `packages/plugin-sdk` folder of the [RuneStone repository](https://git.knottywyvern.com/kwyvern/RuneStone). Report problems there.
|
||||||
|
|
||||||
Knotty Wyvern maintains RuneStone and the SDK.
|
Knotty Wyvern maintains RuneStone and the SDK.
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
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 { ActionIcon } from "./icons.ts";
|
import type { ActionIcon } from "./icons.ts";
|
||||||
@@ -19,6 +20,34 @@ 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. */
|
||||||
@@ -60,8 +89,10 @@ 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;
|
||||||
completion?: CompletionApi;
|
completion?: CompletionApi;
|
||||||
readonly id: string;
|
readonly id: string;
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/** 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,5 +1,16 @@
|
|||||||
import type { Dispose } from "./api.ts";
|
import type { Dispose } from "./api.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 {
|
||||||
browser: {
|
browser: {
|
||||||
@@ -10,4 +21,8 @@ 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,4 +1,5 @@
|
|||||||
import type { FilesApi, PluginApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts";
|
import type { FilesApi, PluginApi, PtyApi, 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";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -6,8 +7,10 @@ import type { CompletionApi } from "./completion.ts";
|
|||||||
* 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;
|
||||||
completion: CompletionApi;
|
completion: CompletionApi;
|
||||||
"completion.transport": NonNullable<CompletionApi["transport"]>;
|
"completion.transport": NonNullable<CompletionApi["transport"]>;
|
||||||
"ui.showActionMenu": UiApi["showActionMenu"];
|
"ui.showActionMenu": UiApi["showActionMenu"];
|
||||||
@@ -30,8 +33,10 @@ 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",
|
||||||
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,6 +1,7 @@
|
|||||||
// 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 "./menu.ts";
|
export type * from "./menu.ts";
|
||||||
|
|||||||
Generated
+15
-176
@@ -89,34 +89,22 @@ 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])([email protected](@types/[email protected])([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](@types/[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])([email protected](@types/[email protected])([email protected]))
|
version: 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[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])([email protected]))
|
version: 7.3.0([email protected])([email protected](@types/[email protected]))
|
||||||
'@tauri-apps/cli':
|
'@tauri-apps/cli':
|
||||||
specifier: ^2
|
specifier: ^2
|
||||||
version: 2.11.4
|
version: 2.11.4
|
||||||
@@ -137,7 +125,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])([email protected])
|
version: 8.3.0(@types/[email protected])
|
||||||
|
|
||||||
packages:
|
packages:
|
||||||
|
|
||||||
@@ -284,81 +272,6 @@ 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==}
|
||||||
|
|
||||||
@@ -837,12 +750,6 @@ 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'}
|
||||||
@@ -1276,10 +1183,6 @@ 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==}
|
||||||
|
|
||||||
@@ -1492,11 +1395,6 @@ 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==}
|
||||||
|
|
||||||
@@ -1763,54 +1661,6 @@ 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]': {}
|
||||||
@@ -1868,15 +1718,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])([email protected](@types/[email protected])([email protected])))':
|
'@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])))':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@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/kit': 2.70.3(@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]))':
|
'@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[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])([email protected]))
|
'@sveltejs/vite-plugin-svelte': 7.3.0([email protected])([email protected](@types/[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
|
||||||
@@ -1888,20 +1738,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])([email protected])
|
vite: 8.3.0(@types/[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])([email protected]))':
|
'@sveltejs/[email protected]([email protected])([email protected](@types/[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])([email protected])
|
vite: 8.3.0(@types/[email protected])
|
||||||
vitefu: 1.1.3([email protected](@types/[email protected])([email protected]))
|
vitefu: 1.1.3([email protected](@types/[email protected]))
|
||||||
|
|
||||||
'@tauri-apps/[email protected]': {}
|
'@tauri-apps/[email protected]': {}
|
||||||
|
|
||||||
@@ -2245,10 +2095,6 @@ 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]: {}
|
||||||
@@ -2657,10 +2503,6 @@ snapshots:
|
|||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]:
|
|
||||||
optionalDependencies:
|
|
||||||
'@napi-rs/canvas': 1.0.13
|
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
@@ -2868,7 +2710,7 @@ snapshots:
|
|||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected](@types/[email protected])([email protected]):
|
[email protected](@types/[email protected]):
|
||||||
dependencies:
|
dependencies:
|
||||||
lightningcss: 1.33.0
|
lightningcss: 1.33.0
|
||||||
picomatch: 4.0.7
|
picomatch: 4.0.7
|
||||||
@@ -2878,14 +2720,11 @@ 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]([email protected](@types/[email protected])):
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
vite: 8.3.0(@types/[email protected])([email protected])
|
vite: 8.3.0(@types/[email protected])
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]: {}
|
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import path from "node:path";
|
|||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
/** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */
|
/** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */
|
||||||
export const FEATURE_FOLDERS = ["git", "background", "terminal", "pdf", "pm"];
|
export const FEATURE_FOLDERS = ["git"];
|
||||||
/** Libraries that only features need. */
|
/** Libraries that only features need. */
|
||||||
export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"];
|
export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"];
|
||||||
|
|
||||||
|
|||||||
@@ -31,10 +31,7 @@ export const TABLE = {
|
|||||||
background: {
|
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` },
|
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",
|
nativeKey: "background",
|
||||||
/**
|
/** The style property of the body that holds the current background image. The action counts its changes. */
|
||||||
* The style property of the body that holds the current background image. The action counts its changes.
|
|
||||||
* Native: `backgroundHub.applyApp` (src/lib/plugins/backgrounds.ts) sets it for each new image of Background.
|
|
||||||
*/
|
|
||||||
imageProperty: { plugin: "--rs-background-image", native: "--rs-background-image" },
|
imageProperty: { plugin: "--rs-background-image", native: "--rs-background-image" },
|
||||||
changes: 3,
|
changes: 3,
|
||||||
seconds: 10,
|
seconds: 10,
|
||||||
@@ -42,10 +39,6 @@ export const TABLE = {
|
|||||||
terminal: {
|
terminal: {
|
||||||
plugin: { id: "runestone.terminal", repo: "runestone-terminal", tag: "v0.1.11", zip: `${PLUGIN_RELEASES}/RuneStone_Terminal/releases/runestone.terminal-0.1.11.zip` },
|
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",
|
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",
|
ribbon: ".plugin-ribbon",
|
||||||
button: "Terminal",
|
button: "Terminal",
|
||||||
surface: ".xterm",
|
surface: ".xterm",
|
||||||
@@ -57,11 +50,6 @@ export const TABLE = {
|
|||||||
pdf: {
|
pdf: {
|
||||||
plugin: { id: "runestone.pdf-viewer", repo: "runestone-pdf-viewer", tag: "v0.0.5", zip: `${PLUGIN_RELEASES}/RuneStone_PDF_Viewer/releases/runestone.pdf-viewer-0.0.5.zip` },
|
plugin: { id: "runestone.pdf-viewer", repo: "runestone-pdf-viewer", tag: "v0.0.5", zip: `${PLUGIN_RELEASES}/RuneStone_PDF_Viewer/releases/runestone.pdf-viewer-0.0.5.zip` },
|
||||||
nativeKey: "pdf",
|
nativeKey: "pdf",
|
||||||
/**
|
|
||||||
* Both modes use the same names. Native: the tree row opens a PDF tab, and the first tab loads the PDF Viewer feature
|
|
||||||
* and PDF.js (src/lib/features/pdf/), so the action includes that load. Each page canvas is an image named "PDF page N",
|
|
||||||
* and the page field is a spin button named "Page number". Enter in the field goes to the page.
|
|
||||||
*/
|
|
||||||
row: '[data-tree-rel="sample.pdf"]',
|
row: '[data-tree-rel="sample.pdf"]',
|
||||||
firstPage: "PDF page 1",
|
firstPage: "PDF page 1",
|
||||||
pageInput: "Page number",
|
pageInput: "Page number",
|
||||||
@@ -71,11 +59,8 @@ export const TABLE = {
|
|||||||
pm: {
|
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` },
|
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",
|
nativeKey: "pm",
|
||||||
/**
|
/** Where the view opens: `palette`, or `menu:<ribbon menu name>`. */
|
||||||
* Where the view opens: `palette`, `menu:<ribbon menu name>`, or `ribbon:<ribbon button name>`. Native: the static
|
openIn: { plugin: "menu:Plug-in views", native: "menu:Plug-in views" },
|
||||||
* 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",
|
title: "Project Management",
|
||||||
card: { plugin: ".pm-card", native: ".pm-card" },
|
card: { plugin: ".pm-card", native: ".pm-card" },
|
||||||
minCards: 50,
|
minCards: 50,
|
||||||
@@ -104,14 +89,9 @@ export async function runPaletteCommand(page, title) {
|
|||||||
await input.press("Enter");
|
await input.press("Enter");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Run a command from the palette or from a ribbon menu. `where` is `palette` or `menu:<menu name>`. */
|
||||||
* 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) {
|
export async function runCommand(page, where, title) {
|
||||||
if (where === "palette") return runPaletteCommand(page, 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];
|
const menu = /^menu:(.+)$/.exec(where)?.[1];
|
||||||
if (!menu) throw new Error(`Unknown command place ${where}.`);
|
if (!menu) throw new Error(`Unknown command place ${where}.`);
|
||||||
await page.locator(".plugin-ribbon").getByRole("button", { name: menu, exact: true }).click();
|
await page.locator(".plugin-ribbon").getByRole("button", { name: menu, exact: true }).click();
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
// The tool starts a test build with an isolated identifier, drives it through CDP, and stops only the process tree that it started.
|
// 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>/.
|
// Run `node scripts/measureFeatures.mjs --help` for the arguments. The results go to output/phase-7/<stage>/.
|
||||||
import { existsSync } from "node:fs";
|
import { existsSync } from "node:fs";
|
||||||
import { realpathSync } from "node:fs";
|
|
||||||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
@@ -48,19 +47,6 @@ async function seedBackgroundPlugin(folders, backgrounds) {
|
|||||||
await writeFile(path.join(folder, "settings.json"), JSON.stringify({ grant, folder: backgrounds, seconds: TABLE.features.background.seconds, order: "name", enabled: true, targets: ["app"], overlay: 0, position: "center", size: "cover" }));
|
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. */
|
/** The features that are on in the running app. */
|
||||||
async function readState(app, mode, invoke) {
|
async function readState(app, mode, invoke) {
|
||||||
if (mode === "plugin") {
|
if (mode === "plugin") {
|
||||||
@@ -156,7 +142,6 @@ export async function main(argv = process.argv.slice(2)) {
|
|||||||
log(`Resetting ${folders.roaming} and ${folders.local}.`);
|
log(`Resetting ${folders.roaming} and ${folders.local}.`);
|
||||||
await resetData(folders, options.identifier);
|
await resetData(folders, options.identifier);
|
||||||
if (options.mode === "plugin" && options.features.includes("background")) await seedBackgroundPlugin(folders, fixture.backgrounds);
|
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.
|
// The setup start opens the workspace. It also proves the test identity.
|
||||||
let session = await app.launch({ exe, port: options.port });
|
let session = await app.launch({ exe, port: options.port });
|
||||||
|
|||||||
@@ -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_Local_Autocomplete', 'RuneStone_CSV_Viewer'];
|
export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Terminal', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_PDF_Viewer', '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,
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
// RuneStone_Terminal imports this path for its smoke test. The helper lives in the shared smoke harness.
|
||||||
|
export * from "../tests/smoke/_harness/pluginMocks.mjs";
|
||||||
+5
-1
@@ -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 repo:RuneStone_Local_Autocomplete/src electron
|
// // @requires plugin:terminal repo:RuneStone_Git/dist 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,6 +67,10 @@ 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 = "1.0.1+3"
|
version = "0.1.49"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
"dunce",
|
"dunce",
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "runestone"
|
name = "runestone"
|
||||||
version = "1.0.1+3"
|
version = "0.1.49"
|
||||||
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]
|
||||||
@@ -47,4 +46,4 @@ opt-level = 3
|
|||||||
strip = true
|
strip = true
|
||||||
|
|
||||||
[package.metadata.runestone]
|
[package.metadata.runestone]
|
||||||
version = "1.0.1c"
|
version = "0.1.49"
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
{
|
{
|
||||||
"version": "0.1.11",
|
"version": "0.1.8",
|
||||||
"protocol": 1,
|
"protocol": 1,
|
||||||
"platforms": {
|
"platforms": {
|
||||||
"windows-x86_64": {
|
"windows-x86_64": {
|
||||||
"url": "https://github.com/kwyvern-gh/RuneStone/releases/download/browser-engine-v0.1.11/RuneStone-Browser_0.1.11_win32-x64.zip",
|
"url": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/browser-engine-v0.1.8/RuneStone-Browser_0.1.8_win32-x64.zip",
|
||||||
"bytes": 163623801,
|
"bytes": 163632595,
|
||||||
"sha256": "1e0153b134cebe882b36f74e1f3c2a4ed37acb2caca10548034a8b5d88738d26"
|
"sha256": "d704003bf5fe047b100a3cf0ab84f3321fd272510cf287a229e50d1653d0856b"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-11
@@ -3,14 +3,12 @@ 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",
|
||||||
"background_choose_folder",
|
"backgrounds_choose_folder",
|
||||||
"background_folder",
|
"backgrounds_default_folder",
|
||||||
"background_clear_folder",
|
"backgrounds_list",
|
||||||
"background_list",
|
"backgrounds_read",
|
||||||
"background_read",
|
"backgrounds_read_image_settings",
|
||||||
"background_read_sidecar",
|
"backgrounds_write_image_settings",
|
||||||
"background_write_sidecar",
|
|
||||||
"background_migrate",
|
|
||||||
"folders_choose",
|
"folders_choose",
|
||||||
"folders_picture",
|
"folders_picture",
|
||||||
"folders_grants",
|
"folders_grants",
|
||||||
@@ -71,8 +69,6 @@ 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",
|
||||||
@@ -100,7 +96,6 @@ fn main() {
|
|||||||
"pty_profiles",
|
"pty_profiles",
|
||||||
"pty_new_window",
|
"pty_new_window",
|
||||||
"pty_dictation",
|
"pty_dictation",
|
||||||
"pty_running",
|
|
||||||
]),
|
]),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -13,10 +13,6 @@
|
|||||||
"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",
|
||||||
|
|||||||
@@ -69,8 +69,6 @@
|
|||||||
"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",
|
||||||
@@ -98,16 +96,13 @@
|
|||||||
"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-background-choose-folder",
|
"allow-backgrounds-choose-folder",
|
||||||
"allow-background-folder",
|
"allow-backgrounds-default-folder",
|
||||||
"allow-background-clear-folder",
|
"allow-backgrounds-list",
|
||||||
"allow-background-list",
|
"allow-backgrounds-read",
|
||||||
"allow-background-read",
|
"allow-backgrounds-read-image-settings",
|
||||||
"allow-background-read-sidecar",
|
"allow-backgrounds-write-image-settings",
|
||||||
"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",
|
||||||
|
|||||||
@@ -13,8 +13,6 @@
|
|||||||
"allow-settings-write",
|
"allow-settings-write",
|
||||||
"allow-settings-migrate",
|
"allow-settings-migrate",
|
||||||
"allow-features-legacy",
|
"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",
|
||||||
@@ -45,14 +43,12 @@
|
|||||||
"allow-browser-engine-remove",
|
"allow-browser-engine-remove",
|
||||||
"allow-completion-request",
|
"allow-completion-request",
|
||||||
"allow-completion-cancel",
|
"allow-completion-cancel",
|
||||||
"allow-background-choose-folder",
|
"allow-backgrounds-choose-folder",
|
||||||
"allow-background-folder",
|
"allow-backgrounds-default-folder",
|
||||||
"allow-background-clear-folder",
|
"allow-backgrounds-list",
|
||||||
"allow-background-list",
|
"allow-backgrounds-read",
|
||||||
"allow-background-read",
|
"allow-backgrounds-read-image-settings",
|
||||||
"allow-background-read-sidecar",
|
"allow-backgrounds-write-image-settings",
|
||||||
"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",
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
# 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"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# 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"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# 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"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# 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"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# 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"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# 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"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# 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"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# 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"]
|
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# 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"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# 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"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# 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"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# 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"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# 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"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# 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"]
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# 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"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# 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"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# 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"]
|
|
||||||
+296
-386
@@ -1,46 +1,99 @@
|
|||||||
//! 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 serde::{Deserialize, Serialize};
|
use crate::plugins::PluginState;
|
||||||
|
use base64::Engine;
|
||||||
|
use serde::Serialize;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Component, 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 FOLDER_FILE: &str = "background-folder.json";
|
const IMAGE_LIMIT: u64 = 50 * 1024 * 1024;
|
||||||
const SIDECAR: &str = ".runestone-backgrounds.json";
|
const SETTINGS_LIMIT: u64 = 1024 * 1024;
|
||||||
/// The old plugin whose folder grant the migration takes.
|
const SETTINGS_FILE: &str = ".runestone-backgrounds.json";
|
||||||
const LEGACY_PLUGIN: &str = "runestone.bg-slideshow";
|
|
||||||
const FOLDER_FILE_LIMIT: u64 = 64 * 1024;
|
|
||||||
|
|
||||||
/// Serializes changes to the folder file.
|
#[derive(Debug, Serialize)]
|
||||||
static LOCK: Mutex<()> = Mutex::new(());
|
pub struct BackgroundFile {
|
||||||
|
name: String,
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
|
||||||
struct FolderFile {
|
|
||||||
schema: u32,
|
|
||||||
path: PathBuf,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The folder file and the plugin data of one app data folder.
|
|
||||||
struct Host {
|
fn require_plugin(app: &AppHandle, label: &str, id: &str) -> Result<()> {
|
||||||
data: PathBuf,
|
app.state::<PluginState>().require_lease(app, label, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn raster(name: &str) -> bool {
|
/// Check the lease on a blocking worker, because the plugin lock can wait for package work.
|
||||||
|
async fn check_plugin(app: &AppHandle, window: &Window, id: &str) -> Result<()> {
|
||||||
|
let (app, label, id) = (app.clone(), window.label().to_owned(), id.to_owned());
|
||||||
|
tauri::async_runtime::spawn_blocking(move || require_plugin(&app, &label, &id)).await?
|
||||||
|
}
|
||||||
|
|
||||||
|
fn folder_root(folder: &Path) -> Result<PathBuf> {
|
||||||
|
if !folder.is_absolute()
|
||||||
|
|| folder
|
||||||
|
.components()
|
||||||
|
.any(|part| matches!(part, Component::ParentDir))
|
||||||
|
{
|
||||||
|
return Err("Supply an absolute background folder path without parent segments.".into());
|
||||||
|
}
|
||||||
|
let root = dunce::canonicalize(folder)?;
|
||||||
|
if !root.is_dir() {
|
||||||
|
return Err("The background folder does not exist.".into());
|
||||||
|
}
|
||||||
|
Ok(root)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported(name: &str) -> bool {
|
||||||
Path::new(name)
|
Path::new(name)
|
||||||
.extension()
|
.extension()
|
||||||
.and_then(|extension| extension.to_str())
|
.and_then(|extension| extension.to_str())
|
||||||
.is_some_and(|extension| matches!(extension.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "gif" | "webp"))
|
.is_some_and(|extension| {
|
||||||
|
matches!(
|
||||||
|
extension.to_ascii_lowercase().as_str(),
|
||||||
|
"png" | "jpg" | "jpeg" | "gif" | "webp"
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn image_path(root: &Path, name: &str) -> Result<PathBuf> {
|
||||||
|
if name.is_empty()
|
||||||
|
|| name.contains(['/', '\\', ':'])
|
||||||
|
|| name.ends_with(['.', ' '])
|
||||||
|
|| !supported(name)
|
||||||
|
|| Path::new(name).components().count() != 1
|
||||||
|
|| !matches!(
|
||||||
|
Path::new(name).components().next(),
|
||||||
|
Some(Component::Normal(_))
|
||||||
|
)
|
||||||
|
{
|
||||||
|
return Err("Supply one PNG, JPEG, GIF, or WebP filename.".into());
|
||||||
|
}
|
||||||
|
let path = root.join(name);
|
||||||
|
let metadata = fs::symlink_metadata(&path)?;
|
||||||
|
if !metadata.is_file() || is_link(&metadata) {
|
||||||
|
return Err("Background images must be ordinary files, not links.".into());
|
||||||
|
}
|
||||||
|
let resolved = dunce::canonicalize(&path)?;
|
||||||
|
if resolved.parent() != Some(root) {
|
||||||
|
return Err("The background image is outside its folder.".into());
|
||||||
|
}
|
||||||
|
Ok(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_images(folder: &Path) -> Result<Vec<BackgroundFile>> {
|
||||||
|
let root = folder_root(folder)?;
|
||||||
|
let mut images = Vec::new();
|
||||||
|
for entry in fs::read_dir(&root)? {
|
||||||
|
let entry = entry?;
|
||||||
|
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if supported(&name) && image_path(&root, &name).is_ok() {
|
||||||
|
images.push(BackgroundFile { name });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
images.sort_by(|a, b| a.name.cmp(&b.name));
|
||||||
|
Ok(images)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn raster_signature(bytes: &[u8]) -> bool {
|
fn raster_signature(bytes: &[u8]) -> bool {
|
||||||
@@ -51,205 +104,176 @@ 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")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read a small JSON file. A missing file gives `None`. A link or a folder is an error.
|
fn read_image(folder: &Path, name: &str) -> Result<Vec<u8>> {
|
||||||
fn read_json<T: for<'de> Deserialize<'de>>(path: &Path, limit: u64) -> Result<Option<T>> {
|
let root = folder_root(folder)?;
|
||||||
let metadata = match fs::symlink_metadata(path) {
|
let path = image_path(&root, name)?;
|
||||||
Ok(metadata) => metadata,
|
// Open the entry itself so a replaced link cannot redirect the read.
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
let file = fsutil::open_entry(&path)?;
|
||||||
Err(error) => return Err(error.into()),
|
let metadata = file.metadata()?;
|
||||||
};
|
|
||||||
if !metadata.is_file() || is_link(&metadata) {
|
if !metadata.is_file() || is_link(&metadata) {
|
||||||
return Err(Error::new(format!("{} must be an ordinary file.", path.display())));
|
return Err("Background images must be ordinary files, not links.".into());
|
||||||
}
|
}
|
||||||
let Some(bytes) = fsutil::read_to_limit(fsutil::open_entry(path)?, limit)? else {
|
if metadata.len() > IMAGE_LIMIT {
|
||||||
return Err(Error::new(format!("{} is too large.", path.display())));
|
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());
|
||||||
};
|
};
|
||||||
Ok(Some(serde_json::from_slice(&bytes)?))
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Host {
|
|
||||||
fn file(&self) -> PathBuf {
|
|
||||||
self.data.join(FOLDER_FILE)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stored(&self) -> Result<Option<PathBuf>> {
|
|
||||||
let Some(file) = read_json::<FolderFile>(&self.file(), FOLDER_FILE_LIMIT)? else { return Ok(None) };
|
|
||||||
if file.schema != 1 {
|
|
||||||
return Err("Unknown background folder file schema.".into());
|
|
||||||
}
|
|
||||||
Ok(Some(file.path))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn save(&self, path: &Path) -> Result<()> {
|
|
||||||
fs::create_dir_all(&self.data)?;
|
|
||||||
let bytes = serde_json::to_vec_pretty(&FolderFile { schema: 1, path: path.to_path_buf() })?;
|
|
||||||
let temp = self.data.join(format!("{FOLDER_FILE}.{}.tmp", uuid::Uuid::new_v4()));
|
|
||||||
Ok(fsutil::replace_file(&self.file(), &temp, &bytes)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Keep `folder` as the background folder. It must be an existing folder, not a whole drive.
|
|
||||||
fn choose(&self, folder: &Path) -> Result<String> {
|
|
||||||
let root = folders::granted_root(folder)?;
|
|
||||||
let _lock = LOCK.lock()?;
|
|
||||||
self.save(&root)?;
|
|
||||||
Ok(root.to_string_lossy().into_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The kept folder for display, or `None`.
|
|
||||||
fn folder(&self) -> Result<Option<String>> {
|
|
||||||
Ok(self.stored()?.map(|path| path.to_string_lossy().into_owned()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn clear(&self) -> Result<()> {
|
|
||||||
let _lock = LOCK.lock()?;
|
|
||||||
match fs::remove_file(self.file()) {
|
|
||||||
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()),
|
|
||||||
_ => Ok(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The kept folder, still an ordinary folder at the same resolved path.
|
|
||||||
/// A folder that became a link or a file does not redirect the access.
|
|
||||||
fn root(&self) -> Result<PathBuf> {
|
|
||||||
let path = self.stored()?.ok_or_else(|| Error::new("Choose a background folder first."))?;
|
|
||||||
let metadata = fs::symlink_metadata(&path).map_err(|_| Error::new("The background folder is missing. Choose the folder again."))?;
|
|
||||||
if !metadata.is_dir() || is_link(&metadata) || dunce::canonicalize(&path)? != path {
|
|
||||||
return Err("The background folder changed into a link or a file. Choose the folder again.".into());
|
|
||||||
}
|
|
||||||
Ok(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The names of the raster images directly in the folder.
|
|
||||||
fn list(&self) -> Result<Vec<String>> {
|
|
||||||
Ok(folders::list_files(&self.root()?)?
|
|
||||||
.into_iter()
|
|
||||||
.map(|entry| entry.name)
|
|
||||||
.filter(|name| raster(name))
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read(&self, name: &str) -> Result<Vec<u8>> {
|
|
||||||
if !raster(name) {
|
|
||||||
return Err("Supply one PNG, JPEG, GIF, or WebP file name.".into());
|
|
||||||
}
|
|
||||||
let bytes = folders::read_file(&self.root()?, name)?;
|
|
||||||
if !raster_signature(&bytes) {
|
if !raster_signature(&bytes) {
|
||||||
return Err("The file is not a supported raster image.".into());
|
return Err("The file is not a supported raster image.".into());
|
||||||
}
|
}
|
||||||
Ok(bytes)
|
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]
|
#[tauri::command]
|
||||||
pub async fn background_choose_folder(app: AppHandle, window: Window, title: Option<String>) -> Result<Option<String>> {
|
pub async fn backgrounds_default_folder(
|
||||||
let (picker_app, picker_window) = (app.clone(), window.clone());
|
app: AppHandle,
|
||||||
let title = title.filter(|title| !title.trim().is_empty() && title.len() <= 200).unwrap_or_else(|| "Choose the background folder".into());
|
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 || {
|
let selected = tauri::async_runtime::spawn_blocking(move || {
|
||||||
picker_app.dialog().file().set_parent(&picker_window).set_title(title).blocking_pick_folder()
|
picker_app
|
||||||
|
.dialog()
|
||||||
|
.file()
|
||||||
|
.set_parent(&picker_window)
|
||||||
|
.set_title("Choose background image folder")
|
||||||
|
.blocking_pick_folder()
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
let Some(selected) = selected else { return Ok(None) };
|
check_plugin(&app, &window, &id).await?;
|
||||||
let folder = selected.into_path().map_err(Error::from_display)?;
|
selected
|
||||||
run(&app, move |host| host.choose(&folder)).await.map(Some)
|
.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]
|
#[tauri::command]
|
||||||
pub async fn background_folder(app: AppHandle) -> Result<Option<String>> {
|
pub async fn backgrounds_list(
|
||||||
run(&app, |host| host.folder()).await
|
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]
|
#[tauri::command]
|
||||||
pub async fn background_clear_folder(app: AppHandle) -> Result<()> {
|
pub async fn backgrounds_read(
|
||||||
run(&app, |host| host.clear()).await
|
app: AppHandle,
|
||||||
|
window: Window,
|
||||||
|
id: String,
|
||||||
|
folder: String,
|
||||||
|
name: String,
|
||||||
|
) -> Result<String> {
|
||||||
|
check_plugin(&app, &window, &id).await?;
|
||||||
|
let result =
|
||||||
|
tauri::async_runtime::spawn_blocking(move || read_image(Path::new(&folder), &name))
|
||||||
|
.await??;
|
||||||
|
check_plugin(&app, &window, &id).await?;
|
||||||
|
Ok(base64::engine::general_purpose::STANDARD.encode(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_image_settings(folder: &Path) -> Result<Option<String>> {
|
||||||
|
let root = folder_root(folder)?;
|
||||||
|
let path = root.join(SETTINGS_FILE);
|
||||||
|
let metadata = match fs::symlink_metadata(&path) {
|
||||||
|
Ok(metadata) => metadata,
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
|
Err(error) => return Err(Error::from(error)),
|
||||||
|
};
|
||||||
|
if !metadata.is_file() || is_link(&metadata) || metadata.len() > SETTINGS_LIMIT {
|
||||||
|
return Err("Image settings must be an ordinary file within 1 MiB.".into());
|
||||||
|
}
|
||||||
|
let file = fsutil::open_entry(&path)?;
|
||||||
|
let metadata = file.metadata()?;
|
||||||
|
if !metadata.is_file() || is_link(&metadata) {
|
||||||
|
return Err("Image settings must be an ordinary file, not a link.".into());
|
||||||
|
}
|
||||||
|
let Some(bytes) = fsutil::read_to_limit(file, SETTINGS_LIMIT)? else {
|
||||||
|
return Err("Image settings exceed 1 MiB.".into());
|
||||||
|
};
|
||||||
|
String::from_utf8(bytes).map(Some).map_err(Error::from)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_image_settings(folder: &Path, contents: &str, expected: Option<&str>) -> Result<()> {
|
||||||
|
static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||||
|
let _lock = WRITE_LOCK.lock()?;
|
||||||
|
if contents.len() as u64 > SETTINGS_LIMIT {
|
||||||
|
return Err("Image settings exceed 1 MiB.".into());
|
||||||
|
}
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
let root = folder_root(folder)?;
|
||||||
|
if read_image_settings(&root)?.as_deref() != expected {
|
||||||
|
return Err("Image settings changed. Reload them before saving.".into());
|
||||||
|
}
|
||||||
|
let path = root.join(SETTINGS_FILE);
|
||||||
|
if expected.is_some() {
|
||||||
|
fsutil::write_text(&path, contents, expected)
|
||||||
|
} else {
|
||||||
|
// Publish a complete new file without replacing a file created by another process.
|
||||||
|
let temp = root.join(format!(".runestone-backgrounds-{}.tmp", uuid::Uuid::new_v4()));
|
||||||
|
Ok(fsutil::create_file(&path, &temp, contents.as_bytes())?)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn background_list(app: AppHandle) -> Result<Vec<String>> {
|
pub async fn backgrounds_read_image_settings(app: AppHandle, window: Window, id: String, folder: String) -> Result<Option<String>> {
|
||||||
run(&app, |host| host.list()).await
|
check_plugin(&app, &window, &id).await?;
|
||||||
}
|
let result = tauri::async_runtime::spawn_blocking(move || read_image_settings(Path::new(&folder))).await??;
|
||||||
|
check_plugin(&app, &window, &id).await?;
|
||||||
/// Return the bytes as an `ArrayBuffer`, not as JSON or base64 text.
|
Ok(result)
|
||||||
#[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]
|
#[tauri::command]
|
||||||
pub async fn background_read_sidecar(app: AppHandle) -> Result<Option<String>> {
|
pub async fn backgrounds_write_image_settings(app: AppHandle, window: Window, id: String, folder: String, contents: String, expected: Option<String>) -> Result<()> {
|
||||||
run(&app, |host| host.read_sidecar()).await
|
check_plugin(&app, &window, &id).await?;
|
||||||
}
|
// Check the lease again immediately before the write on the blocking worker.
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
#[tauri::command]
|
require_plugin(&app, window.label(), &id)?;
|
||||||
pub async fn background_write_sidecar(app: AppHandle, contents: String, expected: Option<String>) -> Result<()> {
|
write_image_settings(Path::new(&folder), &contents, expected.as_deref())
|
||||||
run(&app, move |host| host.write_sidecar(&contents, expected.as_deref())).await
|
}).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().join(format!("runestone-background-{}", uuid::Uuid::new_v4()));
|
let root = std::env::temp_dir()
|
||||||
|
.join(format!("runestone-backgrounds-{}", uuid::Uuid::new_v4()));
|
||||||
fs::create_dir(&root).unwrap();
|
fs::create_dir(&root).unwrap();
|
||||||
Self(dunce::canonicalize(root).unwrap())
|
Self(root)
|
||||||
}
|
|
||||||
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 {
|
||||||
@@ -258,217 +282,103 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Make a link, or return `false` when Windows does not allow links for this user.
|
#[test]
|
||||||
fn link(original: &Path, link: &Path, folder: bool) -> bool {
|
fn image_settings_preserve_external_changes_and_validate_file_limits() {
|
||||||
#[cfg(unix)]
|
let fixture = Fixture::new();
|
||||||
{
|
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
|
||||||
let _ = folder;
|
let next = r#"{"schema":1,"images":{}}"#;
|
||||||
std::os::unix::fs::symlink(original, link).unwrap();
|
assert_eq!(read_image_settings(&fixture.0).unwrap(), None);
|
||||||
true
|
write_image_settings(&fixture.0, first, None).unwrap();
|
||||||
}
|
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
|
||||||
#[cfg(windows)]
|
assert!(write_image_settings(&fixture.0, next, None).is_err());
|
||||||
{
|
assert!(write_image_settings(&fixture.0, next, Some("stale")).is_err());
|
||||||
let result = if folder { std::os::windows::fs::symlink_dir(original, link) } else { std::os::windows::fs::symlink_file(original, link) };
|
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
|
||||||
match result {
|
write_image_settings(&fixture.0, next, Some(first)).unwrap();
|
||||||
Ok(()) => true,
|
assert!(write_image_settings(&fixture.0, r#"{"schema":2,"images":{}}"#, Some(next)).is_err());
|
||||||
Err(error) if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => {
|
assert!(write_image_settings(&fixture.0, &"x".repeat(SETTINGS_LIMIT as usize + 1), Some(next)).is_err());
|
||||||
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
|
fs::File::create(fixture.0.join(SETTINGS_FILE)).unwrap().set_len(SETTINGS_LIMIT + 1).unwrap();
|
||||||
false
|
assert!(read_image_settings(&fixture.0).is_err());
|
||||||
}
|
|
||||||
Err(error) => panic!("{error}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_host_keeps_one_folder_until_it_is_cleared() {
|
fn listing_is_nonrecursive_and_filters_extensions() {
|
||||||
let fixture = Fixture::new();
|
let fixture = Fixture::new();
|
||||||
let images = fixture.folder("images");
|
fs::write(fixture.0.join("a.PNG"), b"\x89PNG\r\n\x1a\n").unwrap();
|
||||||
let other = fixture.folder("other");
|
fs::write(fixture.0.join("b.jpg"), b"\xff\xd8\xff").unwrap();
|
||||||
let host = fixture.host();
|
fs::write(fixture.0.join("text.svg"), b"<svg />").unwrap();
|
||||||
assert_eq!(host.folder().unwrap(), None);
|
fs::create_dir(fixture.0.join("nested.gif")).unwrap();
|
||||||
assert!(host.list().unwrap_err().to_string().contains("Choose a background folder"));
|
fs::write(fixture.0.join("nested.gif/hidden.png"), b"png").unwrap();
|
||||||
assert_eq!(host.choose(&images).unwrap(), images.to_string_lossy());
|
let names: Vec<_> = list_images(&fixture.0)
|
||||||
// A new host reads the kept folder, as after a restart.
|
.unwrap()
|
||||||
assert_eq!(fixture.host().folder().unwrap(), Some(images.to_string_lossy().into_owned()));
|
.into_iter()
|
||||||
host.choose(&other).unwrap();
|
.map(|image| image.name)
|
||||||
assert_eq!(host.folder().unwrap(), Some(other.to_string_lossy().into_owned()));
|
.collect();
|
||||||
host.clear().unwrap();
|
assert_eq!(names, vec!["a.PNG", "b.jpg"]);
|
||||||
host.clear().unwrap();
|
assert_eq!(
|
||||||
assert_eq!(host.folder().unwrap(), None);
|
read_image(&fixture.0, "a.PNG").unwrap(),
|
||||||
|
b"\x89PNG\r\n\x1a\n"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_chosen_folder_must_be_an_existing_folder() {
|
fn reads_reject_traversal_invalid_images_and_oversized_files() {
|
||||||
let fixture = Fixture::new();
|
let fixture = Fixture::new();
|
||||||
let host = fixture.host();
|
for name in [
|
||||||
let images = fixture.folder("images");
|
"../escape.png",
|
||||||
assert!(host.choose(Path::new("relative")).is_err());
|
"nested/image.png",
|
||||||
assert!(host.choose(&images.join("..").join("images")).is_err());
|
"nested\\image.png",
|
||||||
assert!(host.choose(&fixture.0.join("missing")).is_err());
|
"C:\\image.png",
|
||||||
fs::write(fixture.0.join("file.txt"), "x").unwrap();
|
"image.png:stream",
|
||||||
assert!(host.choose(&fixture.0.join("file.txt")).is_err());
|
"image.svg",
|
||||||
let drive = images.ancestors().last().unwrap().to_path_buf();
|
] {
|
||||||
assert!(host.choose(&drive).is_err());
|
assert!(read_image(&fixture.0, name).is_err(), "{name}");
|
||||||
assert_eq!(host.folder().unwrap(), None);
|
}
|
||||||
// A damaged folder file is an error, not a silent reset.
|
assert!(list_images(Path::new("relative")).is_err());
|
||||||
fs::write(host.file(), "{damaged").unwrap();
|
fs::write(fixture.0.join("invalid.png"), b"<svg />").unwrap();
|
||||||
assert!(host.folder().is_err());
|
assert!(read_image(&fixture.0, "invalid.png")
|
||||||
fs::write(host.file(), r#"{"schema":2,"path":"C:\\"}"#).unwrap();
|
.unwrap_err()
|
||||||
assert!(host.folder().is_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 the_listing_has_only_the_raster_files_directly_in_the_folder() {
|
fn raster_types_are_recognized() {
|
||||||
let fixture = Fixture::new();
|
for bytes in [
|
||||||
let images = fixture.folder("images");
|
b"\x89PNG\r\n\x1a\n".as_slice(),
|
||||||
let host = fixture.host();
|
b"\xff\xd8\xff",
|
||||||
host.choose(&images).unwrap();
|
b"GIF87a",
|
||||||
fs::write(images.join("b.PNG"), PNG).unwrap();
|
b"GIF89a",
|
||||||
fs::write(images.join("a.jpg"), b"\xff\xd8\xff").unwrap();
|
b"RIFF0000WEBP",
|
||||||
fs::write(images.join("c.webp"), b"RIFF0000WEBP").unwrap();
|
] {
|
||||||
fs::write(images.join("text.svg"), b"<svg />").unwrap();
|
assert!(raster_signature(bytes));
|
||||||
fs::write(images.join("notes.md"), b"# notes").unwrap();
|
|
||||||
fs::write(images.join(SIDECAR), b"{}").unwrap();
|
|
||||||
fixture.folder("images/nested.gif");
|
|
||||||
fs::write(images.join("nested.gif/hidden.png"), PNG).unwrap();
|
|
||||||
assert_eq!(host.list().unwrap(), vec!["a.jpg", "b.PNG", "c.webp"]);
|
|
||||||
assert_eq!(host.read("b.PNG").unwrap(), PNG);
|
|
||||||
}
|
}
|
||||||
|
assert!(!raster_signature(b"RIFF0000WAVE"));
|
||||||
#[test]
|
|
||||||
fn reads_reject_other_names_other_types_and_large_files() {
|
|
||||||
let fixture = Fixture::new();
|
|
||||||
let images = fixture.folder("images");
|
|
||||||
fs::write(fixture.0.join("outside.png"), PNG).unwrap();
|
|
||||||
let host = fixture.host();
|
|
||||||
host.choose(&images).unwrap();
|
|
||||||
for name in ["../outside.png", "nested/image.png", "nested\\image.png", "C:\\image.png", "image.png:stream", "image.svg", "notes.md", "", "nul.png"] {
|
|
||||||
assert!(host.read(name).is_err(), "{name}");
|
|
||||||
}
|
|
||||||
fs::write(images.join("fake.png"), b"<svg />").unwrap();
|
|
||||||
assert!(host.read("fake.png").unwrap_err().to_string().contains("raster"));
|
|
||||||
fs::File::create(images.join("large.png")).unwrap().set_len(folders::READ_LIMIT + 1).unwrap();
|
|
||||||
assert!(host.read("large.png").unwrap_err().to_string().contains("64 MiB"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_listing_has_a_size_limit() {
|
|
||||||
let fixture = Fixture::new();
|
|
||||||
let images = fixture.folder("images");
|
|
||||||
let host = fixture.host();
|
|
||||||
host.choose(&images).unwrap();
|
|
||||||
for index in 0..=LIST_LIMIT {
|
|
||||||
fs::write(images.join(format!("{index}.png")), b"").unwrap();
|
|
||||||
}
|
|
||||||
assert!(host.list().unwrap_err().to_string().contains("10000"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn links_cannot_escape_the_folder() {
|
fn links_cannot_escape_the_folder() {
|
||||||
let fixture = Fixture::new();
|
let fixture = Fixture::new();
|
||||||
let images = fixture.folder("images");
|
let outside = Fixture::new();
|
||||||
let outside = fixture.folder("outside");
|
let original = outside.0.join("outside.png");
|
||||||
fs::write(outside.join("secret.png"), PNG).unwrap();
|
fs::write(&original, b"\x89PNG\r\n\x1a\n").unwrap();
|
||||||
let host = fixture.host();
|
let link = fixture.0.join("link.png");
|
||||||
host.choose(&images).unwrap();
|
#[cfg(unix)]
|
||||||
if !link(&outside.join("secret.png"), &images.join("link.png"), false) {
|
std::os::unix::fs::symlink(&original, &link).unwrap();
|
||||||
|
#[cfg(windows)]
|
||||||
|
if let Err(error) = std::os::windows::fs::symlink_file(&original, &link) {
|
||||||
|
if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) {
|
||||||
|
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
assert!(host.list().unwrap().is_empty());
|
panic!("{error}");
|
||||||
assert!(host.read("link.png").is_err());
|
|
||||||
// A kept folder that is replaced by a link loses its access.
|
|
||||||
let moved = fixture.folder("moved");
|
|
||||||
host.choose(&moved).unwrap();
|
|
||||||
fs::remove_dir(&moved).unwrap();
|
|
||||||
assert!(link(&outside, &moved, true));
|
|
||||||
assert!(host.list().unwrap_err().to_string().contains("Choose the folder again"));
|
|
||||||
}
|
}
|
||||||
|
assert!(list_images(&fixture.0).unwrap().is_empty());
|
||||||
#[test]
|
assert!(read_image(&fixture.0, "link.png").is_err());
|
||||||
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,8 +34,6 @@ const COMMANDS: &[&str] = &[
|
|||||||
"insertText",
|
"insertText",
|
||||||
"edit",
|
"edit",
|
||||||
"contextAction",
|
"contextAction",
|
||||||
"copiedImage",
|
|
||||||
"linkAt",
|
|
||||||
"frameAck",
|
"frameAck",
|
||||||
"createProfile",
|
"createProfile",
|
||||||
"renameProfile",
|
"renameProfile",
|
||||||
@@ -482,7 +480,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", "copiedImage", "linkAt", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
|
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "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 => {},
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use crate::error::{Error, Result};
|
|||||||
use crate::plugins::{legacy_packages, LegacyPackage};
|
use crate::plugins::{legacy_packages, LegacyPackage};
|
||||||
|
|
||||||
/// The packages that native features replace. A request for another ID fails.
|
/// The packages that native features replace. A request for another ID fails.
|
||||||
pub const LEGACY_PACKAGES: [&str; 5] = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm"];
|
pub const LEGACY_PACKAGES: [&str; 1] = ["runestone.git"];
|
||||||
|
|
||||||
fn check(ids: &[String]) -> Result<()> {
|
fn check(ids: &[String]) -> Result<()> {
|
||||||
if ids.len() > LEGACY_PACKAGES.len() {
|
if ids.len() > LEGACY_PACKAGES.len() {
|
||||||
@@ -33,17 +33,10 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn only_the_packages_of_native_features_are_read() {
|
fn only_the_packages_of_native_features_are_read() {
|
||||||
assert!(check(&["runestone.git".into()]).is_ok());
|
assert!(check(&["runestone.git".into()]).is_ok());
|
||||||
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into()]).is_ok());
|
|
||||||
assert!(check(&["runestone.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());
|
assert!(check(&[]).is_ok());
|
||||||
for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] {
|
for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] {
|
||||||
assert!(check(&[id.into()]).is_err(), "{id}");
|
assert!(check(&[id.into()]).is_err(), "{id}");
|
||||||
}
|
}
|
||||||
let too_many = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm", "runestone.git"].map(String::from);
|
assert!(check(&["runestone.git".into(), "runestone.git".into()]).is_err());
|
||||||
assert!(too_many.len() > LEGACY_PACKAGES.len());
|
|
||||||
assert!(check(&too_many).is_err());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-16
@@ -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;
|
||||||
pub(crate) const READ_LIMIT: u64 = 64 * 1024 * 1024;
|
const READ_LIMIT: u64 = 64 * 1024 * 1024;
|
||||||
pub(crate) const SIDECAR_LIMIT: u64 = 1024 * 1024;
|
const SIDECAR_LIMIT: u64 = 1024 * 1024;
|
||||||
pub(crate) const LIST_LIMIT: usize = 10_000;
|
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 {
|
||||||
pub(crate) name: String,
|
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.
|
||||||
pub(crate) fn granted_root(folder: &Path) -> Result<PathBuf> {
|
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.
|
||||||
pub(crate) fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
|
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 @@ pub(crate) fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
|
|||||||
Ok((file, opened.len()))
|
Ok((file, opened.len()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
|
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 @@ pub(crate) fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
|
|||||||
Ok(entries)
|
Ok(entries)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn read_file(root: &Path, name: &str) -> Result<Vec<u8>> {
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
|
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 @@ pub(crate) 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).
|
||||||
pub(crate) fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>) -> Result<()> {
|
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,12 +285,6 @@ pub(crate) fn write_sidecar(root: &Path, name: &str, contents: &str, expected: O
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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") })
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-11
@@ -38,14 +38,12 @@ 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::background_choose_folder,
|
backgrounds::backgrounds_choose_folder,
|
||||||
backgrounds::background_folder,
|
backgrounds::backgrounds_default_folder,
|
||||||
backgrounds::background_clear_folder,
|
backgrounds::backgrounds_list,
|
||||||
backgrounds::background_list,
|
backgrounds::backgrounds_read,
|
||||||
backgrounds::background_read,
|
backgrounds::backgrounds_read_image_settings,
|
||||||
backgrounds::background_read_sidecar,
|
backgrounds::backgrounds_write_image_settings,
|
||||||
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,
|
||||||
@@ -107,8 +105,6 @@ 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,
|
||||||
@@ -136,7 +132,6 @@ 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")
|
||||||
|
|||||||
@@ -20,8 +20,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.
|
||||||
/// `features` holds the switches of the native features. `background` and `terminal` hold the settings of the Background and Terminal features.
|
/// `features` holds the switches of the native features.
|
||||||
pub const SECTIONS: [&str; 9] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background", "terminal", "projectManagement"];
|
pub const SECTIONS: [&str; 6] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features"];
|
||||||
/// 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";
|
||||||
|
|||||||
+100
-407
@@ -1,54 +1,24 @@
|
|||||||
//! Shell sessions for the native Terminal feature of RuneStone (`src/lib/features/terminal/`).
|
use std::collections::HashMap;
|
||||||
|
|
||||||
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, Manager, State};
|
use tauri::{AppHandle, Emitter, 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<Sessions>,
|
inner: Mutex<HashMap<String, OpenPty>>,
|
||||||
}
|
|
||||||
|
|
||||||
#[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>>>,
|
||||||
@@ -63,13 +33,12 @@ impl Drop for OpenPty {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PtyState {
|
impl PtyState {
|
||||||
/// Close the window's terminals and forget its pages. Remove the terminals under the lock,
|
/// Close the window's terminals. Remove them under the lock, then stop the shells outside it.
|
||||||
/// 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) => {
|
||||||
sessions.pages.remove(label);
|
let ids: Vec<String> = sessions.iter().filter(|(_, session)| session.owner == label).map(|(id, _)| id.clone()).collect();
|
||||||
take_window(&mut sessions.open, label)
|
ids.iter().filter_map(|id| sessions.remove(id)).collect()
|
||||||
}
|
}
|
||||||
Err(_) => return,
|
Err(_) => return,
|
||||||
};
|
};
|
||||||
@@ -86,51 +55,22 @@ impl PtyState {
|
|||||||
|
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
inner: Mutex::new(Sessions::default()),
|
inner: Mutex::new(HashMap::new()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove the sessions of one window from the map. The caller stops them outside the lock.
|
#[derive(Clone, Serialize)]
|
||||||
fn take_window(open: &mut HashMap<String, OpenPty>, owner: &str) -> Vec<OpenPty> {
|
pub struct PtyData {
|
||||||
let ids: Vec<String> = open.iter().filter(|(_, session)| session.owner == owner).map(|(id, _)| id.clone()).collect();
|
pub id: String,
|
||||||
ids.iter().filter_map(|id| open.remove(id)).collect()
|
// xterm owns UTF-8 decoding so multibyte characters split across reads survive.
|
||||||
|
pub data: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The number of open sessions of all windows.
|
#[derive(Clone, Serialize)]
|
||||||
fn running(pty: &PtyState) -> Result<usize> {
|
pub struct PtyExit {
|
||||||
Ok(pty.inner.lock().map_err(|_| Error::new("pty lock"))?.open.len())
|
pub id: String,
|
||||||
}
|
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.
|
||||||
@@ -139,6 +79,24 @@ 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>);
|
||||||
@@ -152,57 +110,22 @@ impl PtyOutput for ChannelOutput {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read the PTY until EOF and send each read to `chunks`.
|
/// Use the channel when the caller supplies one. Without a channel, use window events.
|
||||||
fn read_chunks(mut reader: impl Read, chunks: std::sync::mpsc::Sender<Vec<u8>>) {
|
fn output(channel: Option<Channel<InvokeResponseBody>>, events: impl FnOnce() -> Box<dyn PtyOutput>) -> Box<dyn PtyOutput> {
|
||||||
let mut buf = vec![0u8; 16 * 1024];
|
match channel {
|
||||||
loop {
|
Some(channel) => Box::new(ChannelOutput(channel)),
|
||||||
match reader.read(&mut buf) {
|
None => events(),
|
||||||
Ok(0) | Err(_) => break,
|
|
||||||
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
|
/// Send the output until the reader reaches EOF. Then send the exit status.
|
||||||
/// the first chunk that arrives. It collects more chunks until `wait` after that chunk or
|
fn pump(mut reader: impl Read, exit: std::sync::mpsc::Receiver<Option<u32>>, output: &dyn PtyOutput) {
|
||||||
/// until `max_bytes`. A chunk that does not fit starts the next message. A chunk larger than
|
let mut buf = [0u8; 4096];
|
||||||
/// `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 {
|
loop {
|
||||||
let mut message = match next.take() {
|
match reader.read(&mut buf) {
|
||||||
Some(chunk) => chunk,
|
Ok(0) | Err(_) => break,
|
||||||
None => match chunks.recv() {
|
Ok(n) => output.data(&buf[..n]),
|
||||||
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());
|
||||||
}
|
}
|
||||||
@@ -323,7 +246,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 feature reads both `Cwd` (plain) and `RSCwd` (base64). A Windows path
|
// The Terminal plugin 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"]); }
|
||||||
@@ -342,10 +265,8 @@ 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)),
|
||||||
@@ -363,103 +284,77 @@ 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: JavaScriptChannelId,
|
channel: Option<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();
|
||||||
let output = ChannelOutput(channel.channel_on(webview));
|
// A session with a channel sends no `pty-data` or `pty-exit` events.
|
||||||
let request = OpenRequest { owner, page, id, cols, rows, profile, directory: directory.map(PathBuf::from).unwrap_or(root) };
|
let channel = channel.map(|channel| channel.channel_on(webview));
|
||||||
tauri::async_runtime::spawn_blocking(move || open(app, request, output)).await?
|
tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory, channel)).await?
|
||||||
}
|
}
|
||||||
|
|
||||||
struct OpenRequest {
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn open(
|
||||||
|
app: AppHandle,
|
||||||
owner: String,
|
owner: String,
|
||||||
page: String,
|
root: PathBuf,
|
||||||
id: String,
|
id: String,
|
||||||
cols: u16,
|
cols: u16,
|
||||||
rows: u16,
|
rows: u16,
|
||||||
profile: Option<String>,
|
profile: Option<String>,
|
||||||
directory: PathBuf,
|
directory: Option<String>,
|
||||||
}
|
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 (left, started) = {
|
|
||||||
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
||||||
let left = enter_page(&mut guard, &request.owner, &request.page)?;
|
if guard.contains_key(&id) {
|
||||||
(left, start(&mut guard, &request))
|
return Err(Error::new("terminal already exists"));
|
||||||
};
|
}
|
||||||
// A reload left these sessions. Stop their shells outside the lock.
|
let directory = directory.map(PathBuf::from).unwrap_or(root);
|
||||||
drop(left);
|
if !directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
|
||||||
let (serial, reader, mut child) = started?;
|
let (session, reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?;
|
||||||
|
guard.insert(id.clone(), session);
|
||||||
|
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 = request.id;
|
let wait_id = id.clone();
|
||||||
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| match sessions.open.get(&wait_id) {
|
.and_then(|mut sessions| sessions.remove(&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 (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
|
let output = output(channel, || Box::new(EventOutput { app: app.clone(), owner, id }));
|
||||||
thread::spawn(move || read_chunks(reader, chunk_tx));
|
thread::spawn(move || pump(reader, exit_rx, output.as_ref()));
|
||||||
thread::spawn(move || pump(chunk_rx, exit_rx, &output, BATCH_BYTES, BATCH_WAIT));
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
type StartedShell = (u64, Box<dyn Read + Send>, Box<dyn portable_pty::Child + Send + Sync>);
|
|
||||||
|
|
||||||
/// Start the shell and insert its session. The caller holds the lock.
|
|
||||||
fn start(sessions: &mut Sessions, request: &OpenRequest) -> Result<StartedShell> {
|
|
||||||
if sessions.open.contains_key(&request.id) {
|
|
||||||
return Err(Error::new("terminal already exists"));
|
|
||||||
}
|
|
||||||
if !request.directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
|
|
||||||
let (session, reader, child) = spawn_shell(&request.directory, request.cols, request.rows, request.profile.as_deref(), &request.owner)?;
|
|
||||||
let serial = session.serial;
|
|
||||||
sessions.open.insert(request.id.clone(), session);
|
|
||||||
Ok((serial, reader, child))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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,
|
/// 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.
|
/// and the write then waits. The Terminal plugin waits for each write before the next one.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn pty_write(app: AppHandle, window: tauri::Window, id: String, data: String) -> Result<()> {
|
pub async fn pty_write(app: AppHandle, id: String, data: String) -> Result<()> {
|
||||||
let owner = window.label().to_owned();
|
tauri::async_runtime::spawn_blocking(move || write(&app.state::<PtyState>(), &id, &data)).await?
|
||||||
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<()> {
|
fn write(pty: &PtyState, 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"))?;
|
||||||
owned(&guard, owner, id)?.writer.clone()
|
let session = guard.get(id).ok_or_else(|| Error::new("terminal is not open"))?;
|
||||||
|
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"))?;
|
||||||
@@ -471,13 +366,10 @@ fn write(pty: &PtyState, owner: &str, id: &str, data: &str) -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn pty_resize(pty: State<PtyState>, window: tauri::Window, id: String, cols: u16, rows: u16) -> Result<()> {
|
pub fn pty_resize(pty: State<PtyState>, 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"))?;
|
||||||
owned(&guard, owner, id)?
|
let session = guard.get(&id).ok_or_else(|| Error::new("terminal is not open"))?;
|
||||||
|
session
|
||||||
.master
|
.master
|
||||||
.resize(PtySize {
|
.resize(PtySize {
|
||||||
rows: rows.max(2),
|
rows: rows.max(2),
|
||||||
@@ -490,34 +382,19 @@ fn resize(pty: &PtyState, owner: &str, id: &str, cols: u16, rows: u16) -> Result
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 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, window: tauri::Window, id: String) -> Result<()> {
|
pub async fn pty_close(app: AppHandle, id: String) -> Result<()> {
|
||||||
let owner = window.label().to_owned();
|
|
||||||
tauri::async_runtime::spawn_blocking(move || {
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
let session = close(&app.state::<PtyState>(), &owner, &id)?;
|
let pty = app.state::<PtyState>();
|
||||||
|
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())?;
|
||||||
@@ -559,111 +436,28 @@ mod tests {
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
/// Records the window events that a session would send.
|
||||||
enum Sent {
|
struct FakeEvents(Arc<Mutex<Vec<String>>>);
|
||||||
Data(Vec<u8>),
|
impl PtyOutput for FakeEvents {
|
||||||
Exit(Option<u32>),
|
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(format!("pty-data {}", String::from_utf8_lossy(bytes))); }
|
||||||
|
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(format!("pty-exit {code:?}")); }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Records the messages that a session sends.
|
fn run_pump(channel: Option<Channel<InvokeResponseBody>>, events: Arc<Mutex<Vec<String>>>) {
|
||||||
#[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();
|
||||||
let recorder = Recorder::default();
|
exit_tx.send(Some(3)).unwrap();
|
||||||
let output = recorder.clone();
|
let output = output(channel, move || Box::new(FakeEvents(events)));
|
||||||
let handle = thread::spawn(move || pump(chunk_rx, exit_rx, &output, max_bytes, wait));
|
pump(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), exit_rx, output.as_ref());
|
||||||
(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 small_chunks_within_the_wait_become_one_message() {
|
fn a_channel_session_sends_raw_bytes_and_no_window_events() {
|
||||||
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5));
|
let events = Arc::new(Mutex::new(Vec::new()));
|
||||||
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(()) });
|
||||||
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
|
run_pump(Some(channel), events.clone());
|
||||||
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
assert!(events.lock().unwrap().is_empty(), "a channel session must not send pty-data or pty-exit events");
|
||||||
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] {
|
||||||
@@ -676,112 +470,11 @@ 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 only_the_owner_window_can_use_a_session() {
|
fn a_session_without_a_channel_keeps_the_window_events() {
|
||||||
let pty = PtyState::new();
|
let events = Arc::new(Mutex::new(Vec::new()));
|
||||||
pty.inner.lock().unwrap().open.insert("t1".into(), shell("a"));
|
run_pump(None, events.clone());
|
||||||
assert_eq!(write(&pty, "b", "t1", "\r").unwrap_err().to_string(), NOT_OPEN);
|
assert_eq!(*events.lock().unwrap(), vec!["pty-data hello λ".to_owned(), "pty-exit Some(3)".to_owned()]);
|
||||||
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]
|
||||||
|
|||||||
+2
-152
@@ -967,14 +967,10 @@ 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(data_url(mime, &bytes))
|
Ok(format!(
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
||||||
@@ -1248,108 +1244,6 @@ 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::*;
|
||||||
@@ -1704,50 +1598,6 @@ 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": "1.0.1+3",
|
"version": "0.1.49",
|
||||||
"identifier": "com.runestone.app",
|
"identifier": "com.runestone.app",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "pnpm dev",
|
"beforeDevCommand": "pnpm dev",
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
@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-hover-bg)}
|
.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)}
|
||||||
.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,7 +11,6 @@
|
|||||||
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); });
|
||||||
@@ -44,7 +43,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, middlePressed = false;
|
let suppressedRelease = -1;
|
||||||
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(() => {
|
||||||
@@ -117,9 +116,8 @@
|
|||||||
{ 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: () => copyImage(context) },
|
{ label: $t('Copy image'), icon: 'copy', run: action('copyImage') },
|
||||||
{ 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') },
|
||||||
@@ -144,23 +142,6 @@
|
|||||||
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;
|
||||||
@@ -213,37 +194,23 @@
|
|||||||
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);
|
autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep); return;
|
||||||
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;
|
||||||
}
|
}
|
||||||
const input = { type, ...pagePoint(point),
|
// 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, 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; }
|
||||||
@@ -319,7 +286,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"><Icon icon="scroll" /></span>{/if}
|
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<style>
|
<style>
|
||||||
@@ -331,7 +298,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: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}
|
.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}
|
||||||
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,10 +47,9 @@ 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, undefined, { split: direction, relativeTo: id });
|
void open(current?.profileId || saved.profileId, current?.url || saved.url || 'about:blank', { 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 }) => {
|
||||||
@@ -66,8 +65,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("New tab to the right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
|
{ label: tr("Split right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
|
||||||
{ label: tr("New tab below"), icon: 'split-down', disabled: !ready, run: () => split('down') },
|
{ label: tr("Split down"), 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,14 +75,12 @@ export class TabSession {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/** Returns the reply of the engine, or undefined when the request did not complete. */
|
async send(command: string, args: Record<string, unknown> = {}) {
|
||||||
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 {
|
||||||
const reply = await this.transport(command, { ...args, tabId });
|
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,11 +13,9 @@
|
|||||||
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 { loadImageSize } from "$lib/workspace/imageSizes";
|
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle } from "$lib/workspace/media";
|
||||||
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";
|
||||||
@@ -50,7 +48,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, source?: string) => Promise<string | null>;
|
onInsertImage?: (file: File) => 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;
|
||||||
@@ -101,12 +99,7 @@
|
|||||||
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 {
|
try { urls.set(source, await workspaceReadDataUrl(candidate)); return; } catch { /* Try attachment location. */ }
|
||||||
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);
|
||||||
@@ -133,12 +126,10 @@
|
|||||||
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;
|
||||||
// Read the HTML now. The clipboard data is empty after the paste event.
|
await importImages(view, files, position);
|
||||||
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, source?: string) {
|
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: 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 }) });
|
||||||
@@ -146,7 +137,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, source);
|
const snippet = await onInsertImage?.(file);
|
||||||
if (snippet) snippets.push(snippet);
|
if (snippet) snippets.push(snippet);
|
||||||
}
|
}
|
||||||
if (editor !== view || !snippets.length) return;
|
if (editor !== view || !snippets.length) return;
|
||||||
@@ -441,11 +432,8 @@
|
|||||||
const view = editor;
|
const view = editor;
|
||||||
if (!view || line == null) return;
|
if (!view || line == null) return;
|
||||||
untrack(() => {
|
untrack(() => {
|
||||||
const number = Math.min(view.state.doc.lines, Math.max(1, line));
|
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from;
|
||||||
const anchor = view.state.doc.line(number).from;
|
const effects = [EditorView.scrollIntoView(anchor, { y: "center" })];
|
||||||
// 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-hover-bg); }
|
.rs-heading-toggle:hover, .rs-heading-toggle:focus-visible { color: var(--rs-text); background: var(--rs-bg-active); }
|
||||||
.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); }
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
.md-image-actions { position: absolute; top: 8px; right: 8px; display: flex; gap: 2px; padding: 3px; border-radius: 6px; background: var(--rs-bg-elevated); box-shadow: 0 2px 8px #0005; opacity: 0; transition: opacity 100ms; }
|
.md-image-actions { position: absolute; top: 8px; right: 8px; display: flex; gap: 2px; padding: 3px; border-radius: 6px; background: var(--rs-bg-elevated); box-shadow: 0 2px 8px #0005; opacity: 0; transition: opacity 100ms; }
|
||||||
.md-image-frame:hover .md-image-actions, .md-image-frame:focus-within .md-image-actions { opacity: 1; }
|
.md-image-frame:hover .md-image-actions, .md-image-frame:focus-within .md-image-actions { opacity: 1; }
|
||||||
.image-action { position: relative; display: inline-grid; place-items: center; flex: 0 0 34px; width: 34px; height: 34px; padding: 6px; color: var(--rs-text); border: 0; border-radius: 4px; background: transparent; cursor: pointer; }
|
.image-action { position: relative; display: inline-grid; place-items: center; flex: 0 0 34px; width: 34px; height: 34px; padding: 6px; color: var(--rs-text); border: 0; border-radius: 4px; background: transparent; cursor: pointer; }
|
||||||
.image-action:hover, .image-action:focus-visible { background: var(--rs-hover-bg); color: var(--rs-text-strong); }
|
.image-action:hover, .image-action:focus-visible { background: var(--rs-bg-active); color: var(--rs-text-strong); }
|
||||||
.image-action:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; }
|
.image-action:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; }
|
||||||
.image-action:disabled { color: var(--rs-text-dim); cursor: default; }
|
.image-action:disabled { color: var(--rs-text-dim); cursor: default; }
|
||||||
.image-lightbox { position: fixed; inset: 0; width: 100vw; height: 100vh; max-width: none; max-height: none; margin: 0; padding: 0; border: 0; background: var(--rs-image-viewer-bg); color: var(--rs-text); }
|
.image-lightbox { position: fixed; inset: 0; width: 100vw; height: 100vh; max-width: none; max-height: none; margin: 0; padding: 0; border: 0; background: var(--rs-image-viewer-bg); color: var(--rs-text); }
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { attachTooltip } from "../ui/tooltip";
|
|||||||
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
|
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
|
||||||
import type { ActionMenuItem } from "../ui/actionMenu";
|
import type { ActionMenuItem } from "../ui/actionMenu";
|
||||||
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
|
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
|
||||||
import { imageSize, rememberImageSize } from "../workspace/imageSizes";
|
|
||||||
|
|
||||||
export type ImageActions = {
|
export type ImageActions = {
|
||||||
edit?: () => void;
|
edit?: () => void;
|
||||||
@@ -57,8 +56,6 @@ function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
|
|||||||
viewport.className = "image-lightbox-viewport";
|
viewport.className = "image-lightbox-viewport";
|
||||||
const image = original.cloneNode() as HTMLImageElement;
|
const image = original.cloneNode() as HTMLImageElement;
|
||||||
image.removeAttribute("loading");
|
image.removeAttribute("loading");
|
||||||
image.removeAttribute("width");
|
|
||||||
image.removeAttribute("height");
|
|
||||||
image.draggable = false;
|
image.draggable = false;
|
||||||
let scale = 0;
|
let scale = 0;
|
||||||
const status = document.createElement("span");
|
const status = document.createElement("span");
|
||||||
@@ -94,12 +91,6 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
|
|||||||
const cleanup: (() => void)[] = [];
|
const cleanup: (() => void)[] = [];
|
||||||
for (const image of root.querySelectorAll<HTMLImageElement>("img[data-md-src]")) {
|
for (const image of root.querySelectorAll<HTMLImageElement>("img[data-md-src]")) {
|
||||||
if (image.closest(".md-image-frame")) continue;
|
if (image.closest(".md-image-frame")) continue;
|
||||||
// A remote image gives its size when it loads. The next view of this image keeps its space from the start.
|
|
||||||
const remember = () => rememberImageSize(image.src, image.naturalWidth, image.naturalHeight);
|
|
||||||
image.addEventListener("load", remember);
|
|
||||||
cleanup.push(() => image.removeEventListener("load", remember));
|
|
||||||
const known = !image.getAttribute("width") && imageSize(image.src);
|
|
||||||
if (known) { image.width = known.width; image.height = known.height; }
|
|
||||||
const frame = document.createElement("span");
|
const frame = document.createElement("span");
|
||||||
frame.className = "md-image-frame";
|
frame.className = "md-image-frame";
|
||||||
frame.contentEditable = "false";
|
frame.contentEditable = "false";
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { imageControls, type ImageActions } from "./imageControls";
|
|||||||
import { editImageSource } from "./imageSource";
|
import { editImageSource } from "./imageSource";
|
||||||
import { requestText } from "../workspace/dialogs.svelte";
|
import { requestText } from "../workspace/dialogs.svelte";
|
||||||
import { isRemoteImage } from "../workspace/media";
|
import { isRemoteImage } from "../workspace/media";
|
||||||
import { estimatedImageHeight } from "../workspace/imageSizes";
|
|
||||||
import { actionIcon } from "../ui/actionIcons";
|
import { actionIcon } from "../ui/actionIcons";
|
||||||
|
|
||||||
export type ImageContext = {
|
export type ImageContext = {
|
||||||
@@ -19,7 +18,6 @@ const cleanups = new WeakMap<HTMLElement, () => void>();
|
|||||||
export class ImagePreview extends WidgetType {
|
export class ImagePreview extends WidgetType {
|
||||||
constructor(readonly html: string, readonly source: string, readonly context: ImageContext, readonly editing = false, readonly block = true) { super(); }
|
constructor(readonly html: string, readonly source: string, readonly context: ImageContext, readonly editing = false, readonly block = true) { super(); }
|
||||||
eq(other: ImagePreview) { return this.html === other.html && this.source === other.source && this.editing === other.editing && this.block === other.block; }
|
eq(other: ImagePreview) { return this.html === other.html && this.source === other.source && this.editing === other.editing && this.block === other.block; }
|
||||||
get estimatedHeight() { return estimatedImageHeight(this.html); }
|
|
||||||
toDOM(view: EditorView) {
|
toDOM(view: EditorView) {
|
||||||
const dom = document.createElement(this.block ? "div" : "span");
|
const dom = document.createElement(this.block ? "div" : "span");
|
||||||
dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`;
|
dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`;
|
||||||
|
|||||||
+13
-124
@@ -4,7 +4,7 @@ import { isMac } from "../ui/shortcuts";
|
|||||||
/** The tooltip of a link in Write. A click with Ctrl, or Cmd on macOS, opens the link. */
|
/** The tooltip of a link in Write. A click with Ctrl, or Cmd on macOS, opens the link. */
|
||||||
const linkTooltip = () => tr("{modifier}+click to open link", { modifier: isMac() ? "⌘" : "Ctrl" });
|
const linkTooltip = () => tr("{modifier}+click to open link", { modifier: isMac() ? "⌘" : "Ctrl" });
|
||||||
import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
|
import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
|
||||||
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
|
||||||
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
|
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
|
||||||
import { renderMarkdownSections } from "../workspace/noteHtml";
|
import { renderMarkdownSections } from "../workspace/noteHtml";
|
||||||
import { renderDiagrams } from "../workspace/diagrams";
|
import { renderDiagrams } from "../workspace/diagrams";
|
||||||
@@ -22,34 +22,9 @@ import { listLabels } from "./markdownLists";
|
|||||||
import { activeTableFormulas } from "../formulas/index.ts";
|
import { activeTableFormulas } from "../formulas/index.ts";
|
||||||
|
|
||||||
const previewFormulas = new WeakMap<HTMLElement, unknown>();
|
const previewFormulas = new WeakMap<HTMLElement, unknown>();
|
||||||
const previewHtml = new WeakMap<HTMLElement, string>();
|
|
||||||
export const refreshImages = StateEffect.define<void>();
|
export const refreshImages = StateEffect.define<void>();
|
||||||
const imageCleanups = new WeakMap<HTMLElement, () => void>();
|
const imageCleanups = new WeakMap<HTMLElement, () => void>();
|
||||||
|
|
||||||
/**
|
|
||||||
* CodeMirror reads the line height of the document from the first short line that holds only plain text.
|
|
||||||
* A different height makes it estimate all heights again, and the view then jumps to other text.
|
|
||||||
* A mark span keeps a line with a different height out of that reading.
|
|
||||||
*/
|
|
||||||
const otherLineHeight = Decoration.mark({ class: "writer-line-text" });
|
|
||||||
|
|
||||||
// A resize observer records the height of a preview without a CodeMirror measure request.
|
|
||||||
// A request from toDOM restarts the layout loop of CodeMirror, and a loop that restarts too often does not restore the scroll position.
|
|
||||||
const previewHeights = new WeakMap<Element, { value: number }>();
|
|
||||||
let previewSizes: ResizeObserver | undefined;
|
|
||||||
function watchPreviewHeight(dom: HTMLElement, height: { value: number }) {
|
|
||||||
previewSizes ??= new ResizeObserver(entries => {
|
|
||||||
for (const { target } of entries) {
|
|
||||||
const holder = previewHeights.get(target);
|
|
||||||
if (holder && target.isConnected) holder.value = (target as HTMLElement).offsetHeight;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
const known = previewHeights.get(dom);
|
|
||||||
if (known && known !== height) height.value = known.value;
|
|
||||||
previewHeights.set(dom, height);
|
|
||||||
previewSizes.observe(dom);
|
|
||||||
}
|
|
||||||
|
|
||||||
const linkTooltips = ViewPlugin.define(view => {
|
const linkTooltips = ViewPlugin.define(view => {
|
||||||
const attached = new Map<HTMLElement, () => void>();
|
const attached = new Map<HTMLElement, () => void>();
|
||||||
const refresh = () => {
|
const refresh = () => {
|
||||||
@@ -144,35 +119,23 @@ class ListLabel extends WidgetType {
|
|||||||
ignoreEvent() { return false; }
|
ignoreEvent() { return false; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The heights of previews, by their HTML, from a layout outside the editor. CodeMirror draws only the lines near the view.
|
|
||||||
* Without a height, a large table counts as one line until its first draw. The document then grows by thousands of pixels
|
|
||||||
* at one time, the scrollbar moves, and the layout loop of CodeMirror can stop before it restores the scroll position.
|
|
||||||
*/
|
|
||||||
const measuredHeights = new Map<string, { width: number; height: number }>();
|
|
||||||
const maxMeasuredHeights = 1000;
|
|
||||||
|
|
||||||
class Preview extends WidgetType {
|
class Preview extends WidgetType {
|
||||||
readonly formulas = activeTableFormulas();
|
readonly formulas = activeTableFormulas();
|
||||||
readonly estimate: number;
|
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { super(); }
|
||||||
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) {
|
get estimatedHeight() { return this.height.value; }
|
||||||
super();
|
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
|
||||||
this.estimate = measuredHeights.get(html)?.height ?? -1;
|
measure(dom: HTMLElement, view: EditorView) {
|
||||||
|
view.requestMeasure({ key: this.height, read: () => dom.offsetHeight, write: height => { this.height.value = height; } });
|
||||||
}
|
}
|
||||||
get estimatedHeight() { return this.height.value >= 0 ? this.height.value : this.estimate; }
|
updateDOM(dom: HTMLElement, view: EditorView) {
|
||||||
// A new estimate must reach the height map of CodeMirror. updateDOM keeps the drawn table.
|
if (previewFormulas.get(dom) !== this.formulas || tableEditors.get(dom)?.source !== this.source) return false;
|
||||||
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible && other.estimate === this.estimate; }
|
this.measure(dom, view);
|
||||||
updateDOM(dom: HTMLElement) {
|
|
||||||
const table = tableEditors.get(dom);
|
|
||||||
if (previewFormulas.get(dom) !== this.formulas || (table ? table.source !== this.source : previewHtml.get(dom) !== this.html)) return false;
|
|
||||||
watchPreviewHeight(dom, this.height);
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
destroy(dom: HTMLElement) { previewSizes?.unobserve(dom); tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
|
destroy(dom: HTMLElement) { tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
|
||||||
toDOM(view: EditorView) {
|
toDOM(view: EditorView) {
|
||||||
const dom = document.createElement("div");
|
const dom = document.createElement("div");
|
||||||
previewFormulas.set(dom, this.formulas);
|
previewFormulas.set(dom, this.formulas);
|
||||||
previewHtml.set(dom, this.html);
|
|
||||||
dom.className = "reading writer-preview";
|
dom.className = "reading writer-preview";
|
||||||
dom.innerHTML = this.html;
|
dom.innerHTML = this.html;
|
||||||
// Widgets handle their own events, so CodeMirror's link handler cannot run.
|
// Widgets handle their own events, so CodeMirror's link handler cannot run.
|
||||||
@@ -190,7 +153,7 @@ class Preview extends WidgetType {
|
|||||||
}, { capture: true });
|
}, { capture: true });
|
||||||
tableControls(dom, view, this.source, this.actions);
|
tableControls(dom, view, this.source, this.actions);
|
||||||
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
|
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
|
||||||
watchPreviewHeight(dom, this.height);
|
this.measure(dom, view);
|
||||||
dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove());
|
dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove());
|
||||||
dom.addEventListener("mousedown", event => {
|
dom.addEventListener("mousedown", event => {
|
||||||
if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return;
|
if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return;
|
||||||
@@ -211,45 +174,6 @@ class Preview extends WidgetType {
|
|||||||
ignoreEvent() { return true; }
|
ignoreEvent() { return true; }
|
||||||
}
|
}
|
||||||
|
|
||||||
function textColumnWidth(view: EditorView) {
|
|
||||||
const style = getComputedStyle(view.contentDOM);
|
|
||||||
return view.contentDOM.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Measure previews in one layout pass, in a hidden copy of the text column. A copy has the table frame and footer, but not the table controls. */
|
|
||||||
function measurePreviews(view: EditorView, widgets: Preview[], width: number) {
|
|
||||||
const host = document.createElement("div");
|
|
||||||
host.className = view.contentDOM.className;
|
|
||||||
host.setAttribute("aria-hidden", "true");
|
|
||||||
host.style.cssText = "position:absolute;inset:0 0 auto 0;height:0;min-height:0;padding-block:0;overflow:hidden;visibility:hidden;pointer-events:none";
|
|
||||||
const footer = document.createElement("div");
|
|
||||||
footer.className = "table-footer";
|
|
||||||
const tools = activeTableFormulas()?.createFormulaTools(() => {}, () => {});
|
|
||||||
if (tools) footer.append(tools.formulaTools);
|
|
||||||
const copies = widgets.map(widget => {
|
|
||||||
const copy = document.createElement("div");
|
|
||||||
copy.className = "reading writer-preview";
|
|
||||||
copy.innerHTML = widget.html;
|
|
||||||
const scroll = copy.querySelector(".md-table-scroll");
|
|
||||||
if (scroll && parseMarkdownTable(widget.source)) {
|
|
||||||
const frame = document.createElement("div");
|
|
||||||
frame.className = "writer-table";
|
|
||||||
scroll.before(frame);
|
|
||||||
frame.append(scroll);
|
|
||||||
frame.after(footer.cloneNode(true));
|
|
||||||
}
|
|
||||||
host.append(copy);
|
|
||||||
return copy;
|
|
||||||
});
|
|
||||||
view.scrollDOM.append(host);
|
|
||||||
if (measuredHeights.size + widgets.length > maxMeasuredHeights) measuredHeights.clear();
|
|
||||||
copies.forEach((copy, index) => {
|
|
||||||
measuredHeights.set(widgets[index].html, { width, height: copy.offsetHeight });
|
|
||||||
widgets[index].height.value = -1;
|
|
||||||
});
|
|
||||||
host.remove();
|
|
||||||
}
|
|
||||||
|
|
||||||
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
|
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
|
||||||
const selecting = StateEffect.define<boolean>();
|
const selecting = StateEffect.define<boolean>();
|
||||||
const mouseSelecting = StateField.define({
|
const mouseSelecting = StateField.define({
|
||||||
@@ -332,10 +256,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
|||||||
const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
|
const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
|
||||||
for (let number = 1; number <= state.doc.lines; number++) {
|
for (let number = 1; number <= state.doc.lines; number++) {
|
||||||
const line = state.doc.line(number);
|
const line = state.doc.line(number);
|
||||||
if (!line.text.trim() && !hidden(line.from, line.to)) {
|
if (!line.text.trim() && !hidden(line.from, line.to)) ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
|
||||||
ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
|
|
||||||
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({ atomic: true }).range(from, to)); };
|
const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({ atomic: true }).range(from, to)); };
|
||||||
const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); };
|
const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); };
|
||||||
@@ -353,7 +274,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
|||||||
for (let number = first.number; number <= last.number; number++) {
|
for (let number = first.number; number <= last.number; number++) {
|
||||||
const line = state.doc.line(number);
|
const line = state.doc.line(number);
|
||||||
ranges.push(Decoration.line({ class: editingCode ? "writer-code-source" : `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
|
ranges.push(Decoration.line({ class: editingCode ? "writer-code-source" : `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
|
||||||
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
|
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -363,7 +283,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
|||||||
const pendingList = node.name === "SetextHeading2" && state.doc.lineAt(node.to).text.trim() === "-";
|
const pendingList = node.name === "SetextHeading2" && state.doc.lineAt(node.to).text.trim() === "-";
|
||||||
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name) && !pendingList) {
|
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name) && !pendingList) {
|
||||||
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
|
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
|
||||||
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
|
|
||||||
}
|
}
|
||||||
if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to });
|
if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to });
|
||||||
if (node.name === "TaskMarker") {
|
if (node.name === "TaskMarker") {
|
||||||
@@ -447,36 +366,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
|||||||
filter: (_from, _to, decoration) => decoration.spec.atomic === true,
|
filter: (_from, _to, decoration) => decoration.spec.atomic === true,
|
||||||
}))],
|
}))],
|
||||||
});
|
});
|
||||||
// Give each preview that is not drawn a height, after the document opens, changes, or gets another width.
|
|
||||||
const previewMeasuring = ViewPlugin.fromClass(class {
|
|
||||||
frame = 0;
|
|
||||||
width = -1;
|
|
||||||
constructor(readonly view: EditorView) { this.schedule(); }
|
|
||||||
update(update: ViewUpdate) {
|
|
||||||
if (update.geometryChanged || update.startState.field(decorations) !== update.state.field(decorations)) this.schedule();
|
|
||||||
}
|
|
||||||
schedule() {
|
|
||||||
this.frame ||= requestAnimationFrame(() => { this.frame = 0; this.measure(); });
|
|
||||||
}
|
|
||||||
measure() {
|
|
||||||
const { view } = this, width = textColumnWidth(view);
|
|
||||||
// The editor has no width while another view or tab covers it.
|
|
||||||
if (width < 50) return;
|
|
||||||
const resized = Math.abs(width - this.width) > 1;
|
|
||||||
this.width = width;
|
|
||||||
const { from: drawnFrom, to: drawnTo } = view.viewport;
|
|
||||||
const widgets: Preview[] = [];
|
|
||||||
view.state.field(decorations).between(0, view.state.doc.length, (from, to, decoration) => {
|
|
||||||
const widget = decoration.spec.widget;
|
|
||||||
if (!(widget instanceof Preview) || (from < drawnTo && to > drawnFrom)) return;
|
|
||||||
if ((resized || widget.height.value < 0) && measuredHeights.get(widget.html)?.width !== width) widgets.push(widget);
|
|
||||||
});
|
|
||||||
if (!widgets.length) return;
|
|
||||||
measurePreviews(view, widgets, width);
|
|
||||||
view.dispatch({ effects: refreshImages.of() });
|
|
||||||
}
|
|
||||||
destroy() { cancelAnimationFrame(this.frame); }
|
|
||||||
});
|
|
||||||
const mousePreview = ViewPlugin.define(view => {
|
const mousePreview = ViewPlugin.define(view => {
|
||||||
const finish = () => {
|
const finish = () => {
|
||||||
if (!view.state.field(mouseSelecting)) return;
|
if (!view.state.field(mouseSelecting)) return;
|
||||||
@@ -511,6 +400,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
|||||||
window.removeEventListener("blur", finish);
|
window.removeEventListener("blur", finish);
|
||||||
} };
|
} };
|
||||||
});
|
});
|
||||||
return [imageSource, linkTooltips, bodyFocused, mouseSelecting, decorations, previewMeasuring, mousePreview, syncBodyFocus,
|
return [imageSource, linkTooltips, bodyFocused, mouseSelecting, decorations, mousePreview, syncBodyFocus,
|
||||||
EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing))];
|
EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing))];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,10 @@
|
|||||||
import { SearchQuery } from "@codemirror/search";
|
import { SearchQuery } from "@codemirror/search";
|
||||||
import { documentMatches, type FindTarget } from "./findTarget";
|
import { documentMatches, type FindTarget } from "./findTarget";
|
||||||
|
|
||||||
/** Keys that do not change the text of the find field. These keys keep the selected match. */
|
|
||||||
const keepsMatch = /^(?:Enter|Escape|Tab|Shift|Control|Alt|Meta|CapsLock|ContextMenu|F\d+)$/;
|
|
||||||
|
|
||||||
/** Search the visible reading text without changing its Markdown or rendered nodes. */
|
/** Search the visible reading text without changing its Markdown or rendered nodes. */
|
||||||
export function readingSearch(root: HTMLElement, close: () => void, options: { includeButtons?: boolean; focusOnClose?: () => void } = {}): FindTarget {
|
export function readingSearch(root: HTMLElement, close: () => void, options: { includeButtons?: boolean; focusOnClose?: () => void } = {}): FindTarget {
|
||||||
let query = new SearchQuery({ search: "" });
|
let query = new SearchQuery({ search: "" });
|
||||||
let current = -1;
|
let current = -1;
|
||||||
// The window selection also holds the caret of a focused find field. There it reads as collapsed and outside the text.
|
|
||||||
function matchSelected() {
|
|
||||||
const selection = window.getSelection();
|
|
||||||
return !!selection && !selection.isCollapsed && root.contains(selection.anchorNode);
|
|
||||||
}
|
|
||||||
function ranges() {
|
function ranges() {
|
||||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
||||||
const nodes: { node: Text; from: number; to: number }[] = [];
|
const nodes: { node: Text; from: number; to: number }[] = [];
|
||||||
@@ -48,15 +40,7 @@ export function readingSearch(root: HTMLElement, close: () => void, options: { i
|
|||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
get query() { return query; }, readOnly: true, canSelectAll: false,
|
get query() { return query; }, readOnly: true, canSelectAll: false,
|
||||||
setQuery(value) { if (query.eq(value)) return; query = value; current = -1; if (matchSelected()) window.getSelection()?.removeAllRanges(); },
|
setQuery(value) { if (query.eq(value)) return; query = value; current = -1; window.getSelection()?.removeAllRanges(); },
|
||||||
// A selected match takes the caret from the find field, and the browser then drops typed keys. Put the caret back first.
|
|
||||||
// The field cannot report its old caret at this time, so the caret goes to the end of the text.
|
|
||||||
keydown(event) {
|
|
||||||
const field = event.target;
|
|
||||||
const copy = (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c";
|
|
||||||
if (field instanceof HTMLInputElement && field.type === "text" && !copy && !keepsMatch.test(event.key) && matchSelected()) field.setSelectionRange(field.value.length, field.value.length);
|
|
||||||
return false;
|
|
||||||
},
|
|
||||||
next, selectAll() {}, replace() {},
|
next, selectAll() {}, replace() {},
|
||||||
close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); },
|
close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); },
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -35,7 +35,7 @@
|
|||||||
.table-drag-handle[hidden], .table-drop-indicator[hidden] { display: none; }
|
.table-drag-handle[hidden], .table-drop-indicator[hidden] { display: none; }
|
||||||
.table-drag-handle .action-icon { width: 18px; height: 18px; pointer-events: none; }
|
.table-drag-handle .action-icon { width: 18px; height: 18px; pointer-events: none; }
|
||||||
.table-drag-column .action-icon { transform: rotate(90deg); }
|
.table-drag-column .action-icon { transform: rotate(90deg); }
|
||||||
.table-drag-handle:hover, .table-drag-handle:focus-visible:not([data-pointer-focus]) { opacity: 1; color: var(--rs-text); background: var(--rs-hover-bg); outline: 2px solid var(--rs-accent); outline-offset: -2px; z-index: 2; }
|
.table-drag-handle:hover, .table-drag-handle:focus-visible:not([data-pointer-focus]) { opacity: 1; color: var(--rs-text); background: var(--rs-bg-active); outline: 2px solid var(--rs-accent); outline-offset: -2px; z-index: 2; }
|
||||||
.writer-table.is-table-dragging, .writer-table.is-table-dragging * { cursor: grabbing !important; user-select: none; }
|
.writer-table.is-table-dragging, .writer-table.is-table-dragging * { cursor: grabbing !important; user-select: none; }
|
||||||
.writer-table.is-table-dragging .table-drag-handle::after { display: none; }
|
.writer-table.is-table-dragging .table-drag-handle::after { display: none; }
|
||||||
.table-drop-indicator { position: absolute; z-index: 3; border-radius: 2px; background: var(--rs-accent); pointer-events: none; }
|
.table-drop-indicator { position: absolute; z-index: 3; border-radius: 2px; background: var(--rs-accent); pointer-events: none; }
|
||||||
|
|||||||
@@ -451,13 +451,6 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
|||||||
event.preventDefault(); activate(cell);
|
event.preventDefault(); activate(cell);
|
||||||
const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY });
|
const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY });
|
||||||
if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); }
|
if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); }
|
||||||
} else if (event.detail === 1 && editor && !editor.view.composing && editor.view.dom.contains(event.target)) {
|
|
||||||
// ProseMirror reads a native click on the next selectionchange. Its
|
|
||||||
// delayed focus check can run first and restore the old selection, so
|
|
||||||
// the click is lost under load. Set the clicked position here. The
|
|
||||||
// browser then places the same caret, and a drag starts from it.
|
|
||||||
const hit = editor.view.posAtCoords({ left: event.clientX, top: event.clientY });
|
|
||||||
if (hit) editor.commands.setTextSelection(hit.pos);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
refreshFormulas();
|
refreshFormulas();
|
||||||
|
|||||||
@@ -1,123 +0,0 @@
|
|||||||
<!--
|
|
||||||
Settings → Project Management, and the Project Management settings of the board menu. It is in the main bundle and
|
|
||||||
loads no feature code: the priority levels are in the `projectManagement` settings section (`pmSettings.ts`), and
|
|
||||||
the default board is in `.runestone/pm/workspace.json` of the workspace (`pmBoards.ts`). It shows only while
|
|
||||||
Project Management is on. Each change saves at once.
|
|
||||||
-->
|
|
||||||
<script lang="ts">
|
|
||||||
import { onDestroy, onMount } from "svelte";
|
|
||||||
import { message, t } from "$lib/i18n";
|
|
||||||
import Icon from "$lib/ui/Icon.svelte";
|
|
||||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
|
||||||
import { PRIORITY_LEVELS, onProjectManagementChange, readProjectManagement, writeProjectManagement, type PriorityLevels, type ProjectManagementSettings } from "./pmSettings";
|
|
||||||
import { readBoardCatalog, writeDefaultBoard, type BoardSummary } from "./pmBoards";
|
|
||||||
|
|
||||||
let { compact = false }: { compact?: boolean } = $props();
|
|
||||||
// The errors here are catalog keys without values (pmBoards.ts) or host text. The full `errorText()` of the feature
|
|
||||||
// (pm/ui/text.ts) is not necessary, and this component must load no feature module.
|
|
||||||
const errorText = (reason: unknown) => $t(reason instanceof Error ? reason.message : String(reason));
|
|
||||||
|
|
||||||
const levelNames: Record<PriorityLevels, string> = { 2: message("2 — High and Low"), 3: message("3 — High, Medium, and Low"), 5: message("5 — Highest through Lowest") };
|
|
||||||
let settings = $state<ProjectManagementSettings>(readProjectManagement());
|
|
||||||
let boards = $state<BoardSummary[]>([]);
|
|
||||||
let defaultBoard = $state("");
|
|
||||||
let boardsReady = $state(false);
|
|
||||||
let boardNote = $state("");
|
|
||||||
let saving = $state(false);
|
|
||||||
let notice = $state("");
|
|
||||||
let error = $state("");
|
|
||||||
let closeMenu = () => {};
|
|
||||||
let disposed = false;
|
|
||||||
const active = $derived(boards.filter(board => !board.archived));
|
|
||||||
const boardName = $derived(defaultBoard ? active.find(board => board.id === defaultBoard)?.name ?? $t("Unavailable board (opens All tasks)") : $t("All tasks"));
|
|
||||||
|
|
||||||
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
|
|
||||||
closeMenu();
|
|
||||||
const anchor = event.currentTarget as HTMLButtonElement;
|
|
||||||
const bounds = anchor.getBoundingClientRect();
|
|
||||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
|
|
||||||
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveLevels(priorityLevels: PriorityLevels) {
|
|
||||||
error = "";
|
|
||||||
settings = { ...settings, priorityLevels };
|
|
||||||
writeProjectManagement(settings).then(() => { notice = $t("Changes saved."); })
|
|
||||||
.catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); notice = ""; settings = readProjectManagement(); });
|
|
||||||
}
|
|
||||||
|
|
||||||
async function saveDefault(id: string) {
|
|
||||||
const previous = defaultBoard;
|
|
||||||
error = ""; saving = true; defaultBoard = id;
|
|
||||||
try { await writeDefaultBoard(id || null); if (!disposed) notice = $t("Changes saved."); }
|
|
||||||
catch (reason) { if (!disposed) { defaultBoard = previous; notice = ""; error = errorText(reason); } }
|
|
||||||
finally { saving = false; }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function readBoards() {
|
|
||||||
try {
|
|
||||||
const catalog = await readBoardCatalog();
|
|
||||||
if (disposed) return;
|
|
||||||
boards = catalog.boards;
|
|
||||||
defaultBoard = catalog.defaultBoardId ?? "";
|
|
||||||
boardsReady = true;
|
|
||||||
boardNote = "";
|
|
||||||
} catch (reason) {
|
|
||||||
if (!disposed) boardNote = /no workspace/i.test(String(reason)) ? $t("Open a workspace to choose its default board.") : errorText(reason);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onMount(() => {
|
|
||||||
void readBoards();
|
|
||||||
return onProjectManagementChange(() => { settings = readProjectManagement(); });
|
|
||||||
});
|
|
||||||
onDestroy(() => { disposed = true; closeMenu(); });
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="pm-settings">
|
|
||||||
{#if !compact}
|
|
||||||
<h2>{$t("Project Management")}</h2>
|
|
||||||
<p class="intro">{$t("The boards of each workspace stay in {folder} in the workspace.", { folder: ".runestone/pm" })}</p>
|
|
||||||
{/if}
|
|
||||||
<div class="card">
|
|
||||||
<div class="setting-row">
|
|
||||||
<div><span class="name" id="pm-priority-label">{$t("Priority levels")}</span><p id="pm-priority-description">{$t("Existing card priorities stay unchanged when you change this setting.")}</p></div>
|
|
||||||
<button class="picker" type="button" aria-label={$t("Priority levels")} aria-describedby="pm-priority-description" aria-haspopup="menu"
|
|
||||||
onclick={event => picker(event, $t("Priority levels"), PRIORITY_LEVELS.map(levels => ({ label: $t(levelNames[levels]), checked: settings.priorityLevels === levels, run: () => saveLevels(levels) })))}>
|
|
||||||
{$t(levelNames[settings.priorityLevels])}<Icon icon="chevron-down" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div class="setting-row">
|
|
||||||
<div><span class="name" id="pm-default-label">{$t("Default board")}</span><p id="pm-default-description">{boardNote || $t("Choose the board that opens in this workspace. Restored tabs keep their board.")}</p></div>
|
|
||||||
<button class="picker" type="button" aria-label={$t("Default board")} aria-describedby="pm-default-description" aria-haspopup="menu" disabled={!boardsReady || saving}
|
|
||||||
onclick={event => picker(event, $t("Default board"), [
|
|
||||||
{ label: $t("All tasks"), checked: !defaultBoard, run: () => void saveDefault("") },
|
|
||||||
...active.map(board => ({ label: board.name, checked: defaultBoard === board.id, run: () => void saveDefault(board.id) })),
|
|
||||||
])}>
|
|
||||||
{boardName}<Icon icon="chevron-down" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
|
||||||
<p class="saved" role="status">{notice}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.pm-settings { min-width: 0; }
|
|
||||||
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
|
|
||||||
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
|
|
||||||
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
|
|
||||||
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
|
||||||
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
|
|
||||||
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
|
|
||||||
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
|
||||||
.name { font-weight: 500; color: var(--rs-text); }
|
|
||||||
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
|
|
||||||
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); box-sizing: border-box; max-width: 100%; min-width: 160px; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: left; cursor: pointer; }
|
|
||||||
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
|
|
||||||
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
|
|
||||||
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
|
||||||
.picker:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
|
||||||
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
|
|
||||||
.error { color: var(--rs-error); margin-top: 10px; }
|
|
||||||
</style>
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
// The place of the terminal panel in the workbench and in the terminal window. It is in the main bundle.
|
|
||||||
// The first mount loads the Terminal feature (xterm included). An unmount closes the sessions of this panel.
|
|
||||||
import { onMount } from "svelte";
|
|
||||||
import { t } from "$lib/i18n";
|
|
||||||
import { terminalInstance, type TerminalAction, type TerminalMount, type TerminalProps } from "./terminalHost";
|
|
||||||
let props: TerminalProps = $props();
|
|
||||||
let container: HTMLDivElement;
|
|
||||||
let mounted = $state.raw<TerminalMount>();
|
|
||||||
let loading = $state(true);
|
|
||||||
let error = $state("");
|
|
||||||
let ready: Promise<TerminalMount | undefined> = Promise.resolve(undefined);
|
|
||||||
onMount(() => {
|
|
||||||
let disposed = false;
|
|
||||||
ready = terminalInstance().then(instance => {
|
|
||||||
if (disposed) return undefined;
|
|
||||||
mounted = instance.mountDock(container, { ...props });
|
|
||||||
return mounted;
|
|
||||||
}).catch(reason => { if (!disposed) error = String(reason); return undefined; }).finally(() => { loading = false; });
|
|
||||||
return () => {
|
|
||||||
disposed = true;
|
|
||||||
const current = mounted;
|
|
||||||
mounted = undefined;
|
|
||||||
void current?.dispose().catch(reason => console.error("The terminal panel did not close cleanly.", reason));
|
|
||||||
};
|
|
||||||
});
|
|
||||||
$effect(() => { mounted?.update({ ...props }); });
|
|
||||||
/** Run a terminal action. It waits for the first load. */
|
|
||||||
export async function command(action: Exclude<TerminalAction, "toggle">) { await (await ready)?.command(action); }
|
|
||||||
</script>
|
|
||||||
{#if error}<p class="error" role="alert">{$t("The terminal could not start: {error}", { error })}</p>{/if}
|
|
||||||
{#if loading}<p class="loading">{$t("Loading the terminal…")}</p>{/if}
|
|
||||||
<div class="terminal-host" bind:this={container}></div>
|
|
||||||
<style>
|
|
||||||
.terminal-host { display: flex; flex-direction: column; flex: 1; height: 100%; min-height: 0; min-width: 0; }
|
|
||||||
.error, .loading { margin: 0; padding: 7px 12px; font-size: 12px; }
|
|
||||||
.error { color: var(--rs-error); }
|
|
||||||
.loading { color: var(--rs-text-dim); }
|
|
||||||
</style>
|
|
||||||
@@ -1,113 +0,0 @@
|
|||||||
<!--
|
|
||||||
Settings → Terminal. It is in the main bundle and loads no feature code, so it does not load xterm.
|
|
||||||
It shows only while Terminal is on. Each change saves at once to the `terminal` section, and open terminals take it.
|
|
||||||
-->
|
|
||||||
<script lang="ts">
|
|
||||||
import { onDestroy, onMount } from "svelte";
|
|
||||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
|
||||||
import { t, tr } from "$lib/i18n";
|
|
||||||
import Icon from "$lib/ui/Icon.svelte";
|
|
||||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
|
||||||
import { FONT_SIZE, SCROLLBACK, onTerminalChange, readTerminal, writeTerminal, type TerminalSettings } from "./terminalSettings";
|
|
||||||
|
|
||||||
type Profile = { id: string; title: string; kind: string };
|
|
||||||
const initial = readTerminal();
|
|
||||||
let settings = $state<TerminalSettings>(initial);
|
|
||||||
let fontSize = $state<number | undefined>(initial.fontSize);
|
|
||||||
let scrollback = $state<number | undefined>(initial.scrollback);
|
|
||||||
let profiles = $state<Profile[]>([]);
|
|
||||||
let profileNote = $state("");
|
|
||||||
let message = $state("");
|
|
||||||
let error = $state("");
|
|
||||||
let closeMenu = () => {};
|
|
||||||
/** The shells that a new terminal can use. The Node.js debug terminal is not a default. */
|
|
||||||
const shells = $derived(profiles.filter(profile => profile.kind !== "node"));
|
|
||||||
const current = $derived(shells.find(profile => profile.id === settings.defaultProfile) ?? shells[0]);
|
|
||||||
|
|
||||||
function read() {
|
|
||||||
settings = readTerminal();
|
|
||||||
fontSize = settings.fontSize;
|
|
||||||
scrollback = settings.scrollback;
|
|
||||||
}
|
|
||||||
function save(next: TerminalSettings) {
|
|
||||||
error = "";
|
|
||||||
settings = next;
|
|
||||||
writeTerminal(next).then(() => { message = tr("Changes saved."); })
|
|
||||||
.catch(() => { error = tr("Could not save these settings. Your previous settings still apply. Try again."); message = ""; });
|
|
||||||
}
|
|
||||||
function changeNumber(value: number | undefined, range: { min: number; max: number }, key: "fontSize" | "scrollback") {
|
|
||||||
if (typeof value !== "number" || !Number.isInteger(value) || value < range.min || value > range.max) {
|
|
||||||
error = tr("Choose a whole number from {min} to {max}.", { min: range.min.toLocaleString(), max: range.max.toLocaleString() });
|
|
||||||
message = "";
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
save({ ...settings, [key]: value });
|
|
||||||
}
|
|
||||||
function profileMenu(event: MouseEvent) {
|
|
||||||
closeMenu();
|
|
||||||
const anchor = event.currentTarget as HTMLButtonElement;
|
|
||||||
const bounds = anchor.getBoundingClientRect();
|
|
||||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: tr("Default terminal profile"), parent: anchor.closest("dialog") ?? undefined,
|
|
||||||
items: shells.map(profile => ({ label: profile.title, icon: "code", radio: true, checked: current?.id === profile.id,
|
|
||||||
run: () => save({ ...settings, defaultProfile: profile.id }) })) }).close;
|
|
||||||
}
|
|
||||||
onMount(() => {
|
|
||||||
const stop = onTerminalChange(read);
|
|
||||||
if (!isTauri()) profileNote = tr("The desktop app lists the installed shells.");
|
|
||||||
else invoke<Profile[]>("pty_profiles").then(found => {
|
|
||||||
profiles = found;
|
|
||||||
if (!found.some(profile => profile.kind !== "node")) profileNote = tr("RuneStone found no supported shells on PATH.");
|
|
||||||
}).catch(reason => { profileNote = tr("RuneStone could not list the shells: {error}", { error: String(reason) }); });
|
|
||||||
return stop;
|
|
||||||
});
|
|
||||||
onDestroy(() => closeMenu());
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="terminal-settings">
|
|
||||||
<h2>{$t("Terminal")}</h2>
|
|
||||||
<p class="intro">{$t("Font, scrollback, and cursor apply to open terminals. The default profile applies to new terminals.")}</p>
|
|
||||||
<div class="card">
|
|
||||||
<div class="setting-row">
|
|
||||||
<div><span class="name" id="terminal-profile-label">{$t("Default profile")}</span><p id="terminal-profile-description">{profileNote || $t("The shell of a new terminal.")}</p></div>
|
|
||||||
<button class="picker" type="button" aria-label={$t("Default profile")} aria-describedby="terminal-profile-description" aria-haspopup="menu" disabled={!shells.length} onclick={profileMenu}>
|
|
||||||
{current?.title ?? $t("No shell")}<Icon icon="chevron-down" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div class="setting-row">
|
|
||||||
<div><label for="terminal-font-size">{$t("Font size")}</label><p id="terminal-font-description">{$t("From {min} to {max} pixels.", { min: FONT_SIZE.min, max: FONT_SIZE.max })}</p></div>
|
|
||||||
<input id="terminal-font-size" type="number" min={FONT_SIZE.min} max={FONT_SIZE.max} step="1" required aria-describedby="terminal-font-description" bind:value={fontSize} onchange={() => changeNumber(fontSize, FONT_SIZE, "fontSize")} />
|
|
||||||
</div>
|
|
||||||
<div class="setting-row">
|
|
||||||
<div><label for="terminal-scrollback">{$t("Scrollback lines")}</label><p id="terminal-scrollback-description">{$t("The lines that a terminal keeps above the screen, from {min} to {max}.", { min: SCROLLBACK.min.toLocaleString(), max: SCROLLBACK.max.toLocaleString() })}</p></div>
|
|
||||||
<input id="terminal-scrollback" type="number" min={SCROLLBACK.min} max={SCROLLBACK.max} step="100" required aria-describedby="terminal-scrollback-description" bind:value={scrollback} onchange={() => changeNumber(scrollback, SCROLLBACK, "scrollback")} />
|
|
||||||
</div>
|
|
||||||
<div class="setting-row">
|
|
||||||
<div><label for="terminal-cursor-blink">{$t("Blink cursor")}</label><p id="terminal-blink-description">{$t("The cursor blinks in the focused terminal.")}</p></div>
|
|
||||||
<input id="terminal-cursor-blink" class="rs-switch" type="checkbox" role="switch" aria-describedby="terminal-blink-description" checked={settings.cursorBlink} onchange={event => save({ ...settings, cursorBlink: event.currentTarget.checked })} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
|
||||||
<p class="saved" role="status">{message}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.terminal-settings { min-width: 0; }
|
|
||||||
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
|
|
||||||
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
|
|
||||||
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
|
|
||||||
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
|
||||||
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
|
|
||||||
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
|
|
||||||
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
|
||||||
.setting-row label, .name { font-weight: 500; color: var(--rs-text); }
|
|
||||||
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
|
|
||||||
input[type=number], .picker { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
|
||||||
input[type=number] { width: 96px; }
|
|
||||||
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); max-width: 100%; min-width: 160px; text-align: left; cursor: pointer; }
|
|
||||||
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
|
|
||||||
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
|
|
||||||
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
|
||||||
:is(.picker, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
|
||||||
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
|
|
||||||
.error { color: var(--rs-error); margin-top: 10px; }
|
|
||||||
</style>
|
|
||||||
@@ -1,295 +0,0 @@
|
|||||||
<!--
|
|
||||||
Appearance → Background. The source is a folder (a slideshow), one image, or none. The folder layout and the order
|
|
||||||
are in the `background` settings section. The image and its layout stay in `appearance.newTabBackground`.
|
|
||||||
This component also works in the settings window, where the slideshow does not run. It sends Next to every window.
|
|
||||||
-->
|
|
||||||
<script lang="ts">
|
|
||||||
import { onDestroy, onMount } from "svelte";
|
|
||||||
import { t, tr } from "$lib/i18n";
|
|
||||||
import Icon from "$lib/ui/Icon.svelte";
|
|
||||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
|
||||||
import { onSettingsChange } from "$lib/settings/store";
|
|
||||||
import { featureSwitches } from "$lib/features/state";
|
|
||||||
import { readBoardCatalog } from "../pmBoards";
|
|
||||||
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, saveAppearance, type Appearance } from "$lib/theme/appearance";
|
|
||||||
import { removeBackgroundImage, saveBackgroundImage } from "$lib/theme/backgroundImages";
|
|
||||||
import { hasImage, normalizeLayout, readBackground, writeBackground, type BackgroundLayout, type BackgroundSettings, type BackgroundSource } from "../backgroundSettings";
|
|
||||||
import { folderHost, readSavedImage, sendBackgroundCommand } from "./sources";
|
|
||||||
import { imageNames } from "./imageSettings";
|
|
||||||
import ImageEditor from "./ImageEditor.svelte";
|
|
||||||
|
|
||||||
/** The background targets of single boards need a UUID board ID. */
|
|
||||||
const boardId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
||||||
|
|
||||||
let settings = $state<BackgroundSettings>(readBackground());
|
|
||||||
let appearance = $state<Appearance>(readAppearance());
|
|
||||||
let folder = $state<string | null>(null);
|
|
||||||
let folderNote = $state("");
|
|
||||||
let boards = $state<{ id: string; name: string }[]>([]);
|
|
||||||
let boardsNote = $state("");
|
|
||||||
let previewUrl = $state("");
|
|
||||||
let error = $state("");
|
|
||||||
let imageInput: HTMLInputElement;
|
|
||||||
let imageRevision = 0;
|
|
||||||
let boardRevision = 0;
|
|
||||||
let previewKey = "";
|
|
||||||
let closeMenu = () => {};
|
|
||||||
let disposed = false;
|
|
||||||
|
|
||||||
const image = $derived(appearance.newTabBackground);
|
|
||||||
const layout = $derived<BackgroundLayout | null>(settings.source === "folder" ? normalizeLayout(settings) : settings.source === "image" && hasImage(appearance) ? normalizeLayout(image) : null);
|
|
||||||
const sourceLabels = $derived<Record<BackgroundSource, string>>({ folder: $t("Folder"), image: $t("Image"), none: $t("None") });
|
|
||||||
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
|
|
||||||
const sizeLabels = $derived([$t("Fill"), $t("Fit"), $t("Actual size")]);
|
|
||||||
const orderLabels = $derived({ name: $t("File name"), random: $t("Random") });
|
|
||||||
const targets = $derived([
|
|
||||||
{ id: "app", name: $t("The workspace and new tabs") },
|
|
||||||
{ id: "pm-all", name: $t("All Project Management boards") },
|
|
||||||
...boards.map(board => ({ id: `pm-board:${board.id}`, name: $t("Board: {name}", { name: board.name }) })),
|
|
||||||
// Keep saved targets without a current board, so that the user can remove them.
|
|
||||||
...settings.targets.filter(id => id.startsWith("pm-board:") && !boards.some(board => `pm-board:${board.id}` === id))
|
|
||||||
.map(id => ({ id, name: $t("Unavailable board: {id}", { id: id.slice(9) }) })),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const report = (reason: unknown) => { if (!disposed) error = reason instanceof Error ? reason.message : String(reason); };
|
|
||||||
|
|
||||||
function save(next: BackgroundSettings) {
|
|
||||||
settings = next; error = "";
|
|
||||||
writeBackground(next).catch(() => report(tr("Could not save the background settings.")));
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveImageAppearance(next: Appearance) {
|
|
||||||
try {
|
|
||||||
saveAppearance(next).catch(() => report(tr("Could not save appearance settings.")));
|
|
||||||
appearance = readAppearance(); error = ""; return true;
|
|
||||||
} catch { report(tr("Could not save appearance settings.")); return false; }
|
|
||||||
}
|
|
||||||
|
|
||||||
function changeLayout(patch: Partial<BackgroundLayout>) {
|
|
||||||
if (settings.source === "folder") save({ ...settings, ...patch });
|
|
||||||
else if (image) saveImageAppearance({ ...appearance, newTabBackground: { ...image, ...patch } });
|
|
||||||
}
|
|
||||||
|
|
||||||
function changeOverlay(input: HTMLInputElement) {
|
|
||||||
const percent = input.valueAsNumber;
|
|
||||||
if (!Number.isFinite(percent)) return;
|
|
||||||
changeLayout({ overlay: Math.round(Math.max(-100, Math.min(100, percent))) / 100 });
|
|
||||||
}
|
|
||||||
|
|
||||||
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
|
|
||||||
closeMenu();
|
|
||||||
const anchor = event.currentTarget as HTMLButtonElement;
|
|
||||||
const bounds = anchor.getBoundingClientRect();
|
|
||||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
|
|
||||||
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function chooseSource(source: BackgroundSource) {
|
|
||||||
error = "";
|
|
||||||
if (source === "folder" && !folder) { await chooseFolder(); return; }
|
|
||||||
if (source === "image" && !hasImage(appearance)) { imageInput.click(); return; }
|
|
||||||
save({ ...settings, source });
|
|
||||||
}
|
|
||||||
|
|
||||||
async function chooseFolder() {
|
|
||||||
try {
|
|
||||||
const chosen = await folderHost.choose(tr("Choose the background folder"));
|
|
||||||
if (!chosen || disposed) return;
|
|
||||||
folder = chosen;
|
|
||||||
save({ ...settings, source: "folder" });
|
|
||||||
await sendBackgroundCommand("reload");
|
|
||||||
void inspectFolder();
|
|
||||||
} catch (reason) { report(reason); }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function removeFolder() {
|
|
||||||
try {
|
|
||||||
await folderHost.clear();
|
|
||||||
folder = null; folderNote = "";
|
|
||||||
if (settings.source === "folder") save({ ...settings, source: "none" });
|
|
||||||
await sendBackgroundCommand("reload");
|
|
||||||
} catch (reason) { report(reason); }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Count the images of the folder, so that the user sees a problem at once. */
|
|
||||||
async function inspectFolder() {
|
|
||||||
if (!folder) { folderNote = ""; return; }
|
|
||||||
try {
|
|
||||||
const count = imageNames(await folderHost.list()).length;
|
|
||||||
if (!disposed) folderNote = count ? tr(count === 1 ? "{count} image." : "{count} images.", { count }) : tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files.");
|
|
||||||
} catch (reason) { if (!disposed) folderNote = reason instanceof Error ? reason.message : String(reason); }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function importImage(file?: File) {
|
|
||||||
if (!file) return;
|
|
||||||
const revision = ++imageRevision;
|
|
||||||
try {
|
|
||||||
if (!["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)) throw new Error(tr("Choose a PNG, JPEG, WebP, or GIF image."));
|
|
||||||
const imageId = await saveBackgroundImage(file);
|
|
||||||
if (revision !== imageRevision) { await removeBackgroundImage(imageId); return; }
|
|
||||||
const old = appearance.newTabBackground?.imageId;
|
|
||||||
if (saveImageAppearance({ ...appearance, newTabBackground: { ...appearance.newTabBackground, image: undefined, imageId, overlay: appearance.newTabBackground?.overlay ?? 0 } })) {
|
|
||||||
if (settings.source !== "image") save({ ...settings, source: "image" });
|
|
||||||
if (old) await removeBackgroundImage(old);
|
|
||||||
} else await removeBackgroundImage(imageId);
|
|
||||||
} catch (reason) { if (revision === imageRevision) report(reason); }
|
|
||||||
finally { if (revision === imageRevision) imageInput.value = ""; }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function removeImage() {
|
|
||||||
imageRevision++;
|
|
||||||
const old = appearance.newTabBackground?.imageId;
|
|
||||||
if (saveImageAppearance({ ...appearance, newTabBackground: undefined }) && old) {
|
|
||||||
try { await removeBackgroundImage(old); } catch { report(tr("Could not remove the saved image from storage.")); }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleTarget(id: string, on: boolean) {
|
|
||||||
save({ ...settings, targets: on ? [...new Set([...settings.targets, id])] : settings.targets.filter(target => target !== id) });
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The active boards of `.runestone/pm/workspace.json`. It needs no Project Management code. */
|
|
||||||
async function discoverBoards(on: boolean) {
|
|
||||||
const revision = ++boardRevision;
|
|
||||||
if (!on) {
|
|
||||||
boards = []; boardsNote = tr("Turn on Project Management to show the background on one board.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const catalog = await readBoardCatalog();
|
|
||||||
if (disposed || revision !== boardRevision) return;
|
|
||||||
boards = catalog.boards.filter(board => !board.archived && boardId.test(board.id)).map(board => ({ id: board.id, name: board.name }));
|
|
||||||
boardsNote = boards.length ? "" : tr("The workspace has no boards.");
|
|
||||||
} catch (reason) {
|
|
||||||
if (!disposed && revision === boardRevision) boardsNote = tr("Could not read the workspace boards: {error}", { error: reason instanceof Error ? reason.message : String(reason) });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The preview of the saved image. It uses its own blob URL, so it works in every window. */
|
|
||||||
async function updatePreview() {
|
|
||||||
const saved = settings.source === "image" ? appearance.newTabBackground : undefined;
|
|
||||||
const key = saved && hasImage(appearance) ? saved.imageId ?? `${saved.image?.length}:${saved.image?.slice(-48)}` : "";
|
|
||||||
if (key === previewKey) return;
|
|
||||||
previewKey = key;
|
|
||||||
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
|
||||||
previewUrl = "";
|
|
||||||
if (!key || !saved) return;
|
|
||||||
try {
|
|
||||||
const url = URL.createObjectURL(await readSavedImage(saved));
|
|
||||||
if (disposed || previewKey !== key) { URL.revokeObjectURL(url); return; }
|
|
||||||
previewUrl = url;
|
|
||||||
} catch (reason) { report(reason); }
|
|
||||||
}
|
|
||||||
|
|
||||||
const overlayShade = $derived(layout ? `linear-gradient(rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}),rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}))` : "none");
|
|
||||||
|
|
||||||
$effect(() => { void settings.source; void appearance.newTabBackground; void updatePreview(); });
|
|
||||||
|
|
||||||
onMount(() => {
|
|
||||||
const read = () => { settings = readBackground(); appearance = readAppearance(); };
|
|
||||||
const stops = [onSettingsChange("background", read), onSettingsChange("appearance", read), featureSwitches.subscribe(switches => { void discoverBoards(switches.pm); })];
|
|
||||||
void folderHost.current().then(value => { if (!disposed) { folder = value; void inspectFolder(); } }, () => { folder = null; });
|
|
||||||
return () => stops.forEach(stop => stop());
|
|
||||||
});
|
|
||||||
onDestroy(() => { disposed = true; closeMenu(); if (previewUrl) URL.revokeObjectURL(previewUrl); });
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="background-settings">
|
|
||||||
<div class="card">
|
|
||||||
<div class="setting-row"><span>{$t("Background source")}</span><button class="picker" aria-label={$t("Background source")} aria-haspopup="menu"
|
|
||||||
onclick={event => picker(event, $t("Background source"), (["folder", "image", "none"] as const).map(source => ({ label: sourceLabels[source], checked: settings.source === source, run: () => void chooseSource(source) })))}>{sourceLabels[settings.source]}<Icon icon="chevron-down" /></button></div>
|
|
||||||
{#if settings.source === "folder"}
|
|
||||||
<div class="setting-row folder-row"><label for="background-folder">{$t("Image folder")}</label><div class="controls folder-controls">
|
|
||||||
<input id="background-folder" readonly value={folder ?? ""} title={folder ?? ""} placeholder={$t("No folder selected")} />
|
|
||||||
<button onclick={() => void chooseFolder()}><Icon icon="folder-open" />{$t("Choose folder…")}</button>
|
|
||||||
{#if folder}<button onclick={() => void removeFolder()}>{$t("Remove folder")}</button>{/if}
|
|
||||||
</div></div>
|
|
||||||
<div class="setting-row"><label for="background-seconds">{$t("Seconds per image")}</label><input id="background-seconds" type="number" min="1" max="86400" step="1" value={settings.seconds}
|
|
||||||
onchange={event => { if (event.currentTarget.reportValidity()) save({ ...settings, seconds: event.currentTarget.valueAsNumber }); }} /></div>
|
|
||||||
<div class="setting-row"><span>{$t("Image order")}</span><button class="picker" aria-label={$t("Image order")} aria-haspopup="menu"
|
|
||||||
onclick={event => picker(event, $t("Image order"), (["name", "random"] as const).map(order => ({ label: orderLabels[order], checked: settings.order === order, run: () => save({ ...settings, order }) })))}>{orderLabels[settings.order]}<Icon icon="chevron-down" /></button></div>
|
|
||||||
<div class="setting-row"><span>{$t("Slideshow")}</span><div class="controls">
|
|
||||||
<button onclick={() => void sendBackgroundCommand("next").catch(report)}><Icon icon="arrow-right" />{$t("Next image")}</button>
|
|
||||||
<button aria-pressed={settings.paused} onclick={() => save({ ...settings, paused: !settings.paused })}>{settings.paused ? $t("Resume slideshow") : $t("Pause slideshow")}</button>
|
|
||||||
</div></div>
|
|
||||||
{:else if settings.source === "image"}
|
|
||||||
<div class="background-preview" role="img" aria-label={$t("Background image preview")}
|
|
||||||
style:background-image={previewUrl ? `${overlayShade}, url("${previewUrl}")` : "none"}
|
|
||||||
style:background-size={layout ? `100% 100%, ${layout.size}` : undefined}
|
|
||||||
style:background-position={layout ? `center, ${layout.position}` : undefined}><span>{$t("Background")}</span></div>
|
|
||||||
<div class="actions">
|
|
||||||
<button onclick={() => imageInput.click()}>{$t("Choose image…")}</button>
|
|
||||||
{#if image}<button onclick={() => void removeImage()}>{$t("Remove image")}</button>{/if}
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
{#if layout}
|
|
||||||
<div class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("Image position")} aria-haspopup="menu"
|
|
||||||
onclick={event => picker(event, $t("Image position"), BACKGROUND_POSITIONS.map((value, index) => ({ label: positionLabels[index], checked: layout?.position === value, run: () => changeLayout({ position: value }) })))}>{positionLabels[BACKGROUND_POSITIONS.indexOf(layout.position)]}<Icon icon="chevron-down" /></button></div>
|
|
||||||
<div class="setting-row"><span>{$t("Image size")}</span><button class="picker" aria-label={$t("Image size")} aria-haspopup="menu"
|
|
||||||
onclick={event => picker(event, $t("Image size"), BACKGROUND_SIZES.map((value, index) => ({ label: sizeLabels[index], checked: layout?.size === value, run: () => changeLayout({ size: value }) })))}>{sizeLabels[BACKGROUND_SIZES.indexOf(layout.size)]}<Icon icon="chevron-down" /></button></div>
|
|
||||||
<div class="setting-row"><span>{$t("Image overlay")}</span><div class="controls overlay-controls">
|
|
||||||
<input type="range" aria-label={$t("Image overlay")} min="-100" max="100" value={Math.round(layout.overlay * 100)} oninput={event => changeOverlay(event.currentTarget)} />
|
|
||||||
<label class="overlay-value"><input type="number" aria-label={$t("Image overlay percentage")} min="-100" max="100" step="1" value={Math.round(layout.overlay * 100)}
|
|
||||||
oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((layout?.overlay ?? 0) * 100)); }} /><span>%</span></label>
|
|
||||||
</div></div>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
<input bind:this={imageInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importImage(event.currentTarget.files?.[0])} />
|
|
||||||
{#if settings.source === "folder"}
|
|
||||||
<p>{$t("Add PNG, JPEG, GIF, or WebP images to the folder. Portrait images show in full over a blurred fill.")}</p>
|
|
||||||
{#if folderNote}<p role="status">{folderNote}</p>{/if}
|
|
||||||
{:else if settings.source === "image"}
|
|
||||||
<p>{$t("PNG, JPEG, WebP, or GIF, up to 50 MiB. The image stays on this device.")}</p>
|
|
||||||
{:else}
|
|
||||||
<p>{$t("Choose a folder for a slideshow, or one image.")}</p>
|
|
||||||
{/if}
|
|
||||||
{#if layout}<p>{$t("Move the overlay left to lighten the image or right to darken it.")}</p>{/if}
|
|
||||||
{#if settings.source === "folder" && folder}
|
|
||||||
<ImageEditor {settings} />
|
|
||||||
{/if}
|
|
||||||
{#if settings.source !== "none"}
|
|
||||||
<fieldset class="targets">
|
|
||||||
<legend>{$t("Show the background in")}</legend>
|
|
||||||
{#each targets as target (target.id)}
|
|
||||||
<label class="check"><input type="checkbox" checked={settings.targets.includes(target.id)} onchange={event => toggleTarget(target.id, event.currentTarget.checked)} /><span>{target.name}</span></label>
|
|
||||||
{/each}
|
|
||||||
{#if boardsNote}<p>{boardsNote}</p>{/if}
|
|
||||||
</fieldset>
|
|
||||||
{/if}
|
|
||||||
{#if error}<p role="alert">{error}</p>{/if}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.background-settings { display: grid; gap: var(--rs-settings-gap); min-width: 0; }
|
|
||||||
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
|
|
||||||
.card { padding: 0 var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); min-width: 0; }
|
|
||||||
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; min-width: 0; }
|
|
||||||
.card > * + * { border-top: 1px solid var(--rs-border); }
|
|
||||||
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; max-width: 100%; }
|
|
||||||
.folder-controls { flex: 1 1 320px; justify-content: flex-end; }
|
|
||||||
.folder-controls input { flex: 1 1 160px; min-width: 120px; width: 0; }
|
|
||||||
input:not([type=checkbox]):not([type=range]), button { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
|
||||||
button { display: inline-flex; align-items: center; gap: 6px; background: var(--rs-bg-elevated); cursor: pointer; }
|
|
||||||
button:hover { background: var(--rs-bg-active); }
|
|
||||||
button[aria-pressed="true"] { border-color: var(--rs-accent); }
|
|
||||||
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
|
||||||
.picker { max-width: 100%; background: var(--rs-bg); }
|
|
||||||
input[type=number] { width: 88px; }
|
|
||||||
:is(button, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
|
||||||
.actions { display: flex; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; }
|
|
||||||
.background-preview { height: 120px; margin-top: var(--rs-settings-row-padding); background-color: var(--rs-bg); background-repeat: no-repeat; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); display: grid; place-items: center; }
|
|
||||||
.background-preview span { padding: 8px 14px; background: var(--rs-bg-elevated); border-radius: var(--rs-control-radius); }
|
|
||||||
.overlay-controls input[type=range] { width: 160px; max-width: 100%; min-width: 0; appearance: none; background: transparent; height: var(--rs-settings-control-height); margin: 0; cursor: pointer; }
|
|
||||||
.overlay-controls input[type=range]::-webkit-slider-runnable-track { height: 6px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
|
|
||||||
.overlay-controls input[type=range]::-webkit-slider-thumb { appearance: none; width: 18px; height: 18px; margin-top: -7px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
|
|
||||||
.overlay-controls input[type=range]::-moz-range-track { height: 4px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
|
|
||||||
.overlay-controls input[type=range]::-moz-range-thumb { width: 14px; height: 14px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
|
|
||||||
.overlay-controls input[type=range]:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; border-radius: var(--rs-control-radius); }
|
|
||||||
.overlay-value { display: flex; align-items: center; gap: 4px; }
|
|
||||||
.overlay-value input { width: 64px; }
|
|
||||||
.targets { display: grid; gap: 2px; min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
|
|
||||||
.targets legend { padding: 0 4px; color: var(--rs-text); }
|
|
||||||
.check { display: flex; align-items: center; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); overflow-wrap: anywhere; }
|
|
||||||
.check input { flex-shrink: 0; accent-color: var(--rs-accent); }
|
|
||||||
[role=alert] { color: var(--rs-error); }
|
|
||||||
</style>
|
|
||||||
@@ -1,227 +0,0 @@
|
|||||||
<!--
|
|
||||||
The appearance of one image of the folder: fit, position, and overlay. It saves the sidecar file of the folder
|
|
||||||
(`.runestone-backgrounds.json`) only when the file did not change since the read. Then every window reads it again.
|
|
||||||
-->
|
|
||||||
<script lang="ts">
|
|
||||||
import { onDestroy, untrack } from "svelte";
|
|
||||||
import { t, tr } from "$lib/i18n";
|
|
||||||
import Icon from "$lib/ui/Icon.svelte";
|
|
||||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
|
||||||
import { BACKGROUND_POSITIONS } from "$lib/theme/appearance";
|
|
||||||
import { normalizeLayout, type BackgroundSettings } from "../backgroundSettings";
|
|
||||||
import { folderHost, sendBackgroundCommand } from "./sources";
|
|
||||||
import { imageAppearance, imageFits, imageNames, parseImageSettings, sidecarName, type ImageAppearance, type ImageSettings } from "./imageSettings";
|
|
||||||
|
|
||||||
let { settings }: { settings: BackgroundSettings } = $props();
|
|
||||||
|
|
||||||
let names = $state<string[]>([]);
|
|
||||||
let selected = $state("");
|
|
||||||
let query = $state("");
|
|
||||||
let pickerOpen = $state(false);
|
|
||||||
let draft = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
|
|
||||||
let baseline = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
|
|
||||||
let saved = $state<ImageSettings>({ schema: 1, images: {} });
|
|
||||||
let source: string | null = null;
|
|
||||||
let url = $state("");
|
|
||||||
let portrait = false;
|
|
||||||
let loaded = $state(false);
|
|
||||||
let busy = $state(false);
|
|
||||||
let status = $state({ text: "", error: false });
|
|
||||||
let generation = 0;
|
|
||||||
let closed = false;
|
|
||||||
let closeMenu = () => {};
|
|
||||||
let trigger: HTMLButtonElement | undefined = $state();
|
|
||||||
let search: HTMLInputElement | undefined = $state();
|
|
||||||
const pickerId = $props.id();
|
|
||||||
|
|
||||||
const filtered = $derived(names.filter(name => name.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())));
|
|
||||||
const fitLabels = $derived<Record<string, string>>({ cover: $t("Fill"), contain: $t("Fit"), auto: $t("Actual size"), blurred: $t("Full image with blurred fill") });
|
|
||||||
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
|
|
||||||
const changed = $derived(draft.fit !== baseline.fit || draft.position !== baseline.position || draft.overlay !== baseline.overlay);
|
|
||||||
|
|
||||||
const report = (reason: unknown) => { if (!closed) status = { text: reason instanceof Error ? reason.message : String(reason), error: true }; };
|
|
||||||
|
|
||||||
/** The values that differ from the inherited appearance. Only these go to the file. */
|
|
||||||
function changes(): Partial<ImageAppearance> {
|
|
||||||
return {
|
|
||||||
...(draft.fit !== baseline.fit ? { fit: draft.fit } : {}),
|
|
||||||
...(draft.position !== baseline.position ? { position: draft.position } : {}),
|
|
||||||
...(draft.overlay !== baseline.overlay ? { overlay: draft.overlay } : {}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function load() {
|
|
||||||
const revision = ++generation;
|
|
||||||
loaded = false; pickerOpen = false; names = [];
|
|
||||||
if (url) URL.revokeObjectURL(url);
|
|
||||||
url = "";
|
|
||||||
try {
|
|
||||||
const [text, list] = await Promise.all([folderHost.readSidecar(), folderHost.list()]);
|
|
||||||
if (closed || revision !== generation) return;
|
|
||||||
saved = parseImageSettings(text); source = text;
|
|
||||||
names = imageNames(list);
|
|
||||||
if (!names.includes(selected)) selected = names[0] ?? "";
|
|
||||||
if (selected) await choose(selected);
|
|
||||||
else status = { text: tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."), error: false };
|
|
||||||
} catch (reason) { report(reason); }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function choose(name: string) {
|
|
||||||
const revision = ++generation;
|
|
||||||
selected = name; loaded = false;
|
|
||||||
if (url) URL.revokeObjectURL(url);
|
|
||||||
url = "";
|
|
||||||
try {
|
|
||||||
const next = URL.createObjectURL(await folderHost.read(name));
|
|
||||||
try {
|
|
||||||
const image = new Image(); image.src = next; await image.decode();
|
|
||||||
if (closed || revision !== generation) { URL.revokeObjectURL(next); return; }
|
|
||||||
portrait = image.naturalHeight > image.naturalWidth;
|
|
||||||
} catch (error) { URL.revokeObjectURL(next); throw error; }
|
|
||||||
url = next;
|
|
||||||
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
|
|
||||||
baseline = { ...draft };
|
|
||||||
loaded = true;
|
|
||||||
status = { text: saved.images[name] ? tr("Saved appearance.") : tr("Default appearance."), error: false };
|
|
||||||
} catch (reason) { report(reason); }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A change of the folder layout changes the inherited values. Keep the edits of the user. */
|
|
||||||
function inherit() {
|
|
||||||
if (!loaded) return;
|
|
||||||
const next = imageAppearance(normalizeLayout(settings), saved.images[selected], portrait);
|
|
||||||
if (next.fit === baseline.fit && next.position === baseline.position && next.overlay === baseline.overlay) return;
|
|
||||||
const edited = changes();
|
|
||||||
baseline = next;
|
|
||||||
draft = { ...next, ...edited };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function write(reset: boolean) {
|
|
||||||
if (!loaded || busy) return;
|
|
||||||
const edited = changes();
|
|
||||||
if (!reset && !Object.keys(edited).length) return;
|
|
||||||
busy = true;
|
|
||||||
const revision = generation, name = selected;
|
|
||||||
try {
|
|
||||||
const next = structuredClone($state.snapshot(saved)) as ImageSettings;
|
|
||||||
if (reset) delete next.images[name]; else next.images[name] = { ...next.images[name], ...edited };
|
|
||||||
const contents = JSON.stringify(next, null, 2) + "\n";
|
|
||||||
await folderHost.writeSidecar(contents, source);
|
|
||||||
if (closed || revision !== generation) return;
|
|
||||||
source = contents; saved = next;
|
|
||||||
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
|
|
||||||
baseline = { ...draft };
|
|
||||||
status = { text: reset ? tr("Default appearance restored.") : tr("Image appearance saved."), error: false };
|
|
||||||
await sendBackgroundCommand("reload");
|
|
||||||
} catch (reason) { report(reason); }
|
|
||||||
finally { busy = false; }
|
|
||||||
}
|
|
||||||
|
|
||||||
function menu(event: MouseEvent, field: "fit" | "position") {
|
|
||||||
closeMenu();
|
|
||||||
const anchor = event.currentTarget as HTMLButtonElement;
|
|
||||||
const bounds = anchor.getBoundingClientRect();
|
|
||||||
const values: readonly string[] = field === "fit" ? imageFits : BACKGROUND_POSITIONS;
|
|
||||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === "fit" ? $t("Image fit") : $t("Position of this image"), parent: anchor.closest("dialog") ?? undefined,
|
|
||||||
items: values.map((value, index) => ({ label: field === "fit" ? fitLabels[value] : positionLabels[index], radio: true, checked: draft[field] === value,
|
|
||||||
run: () => { draft = { ...draft, [field]: value }; } })) }).close;
|
|
||||||
}
|
|
||||||
|
|
||||||
function overlay(input: HTMLInputElement) {
|
|
||||||
if (input.validity.valid && Number.isFinite(input.valueAsNumber)) draft = { ...draft, overlay: Math.round(Math.max(-100, Math.min(100, input.valueAsNumber))) / 100 };
|
|
||||||
}
|
|
||||||
|
|
||||||
function openPicker() {
|
|
||||||
if (pickerOpen) { pickerOpen = false; return; }
|
|
||||||
query = ""; pickerOpen = true;
|
|
||||||
queueMicrotask(() => search?.focus());
|
|
||||||
}
|
|
||||||
|
|
||||||
function pick(name: string) {
|
|
||||||
pickerOpen = false;
|
|
||||||
void choose(name).then(() => trigger?.focus());
|
|
||||||
}
|
|
||||||
|
|
||||||
function moveFocus(event: KeyboardEvent, list: HTMLElement) {
|
|
||||||
const rows = [...list.querySelectorAll<HTMLButtonElement>("button")];
|
|
||||||
if (!rows.length) return;
|
|
||||||
const index = rows.indexOf(document.activeElement as HTMLButtonElement);
|
|
||||||
const next = event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : index < 0 ? (event.key === "ArrowDown" ? 0 : rows.length - 1) : Math.max(0, Math.min(rows.length - 1, index + (event.key === "ArrowDown" ? 1 : -1)));
|
|
||||||
event.preventDefault();
|
|
||||||
rows[next].focus();
|
|
||||||
}
|
|
||||||
|
|
||||||
$effect(() => { void settings.size; void settings.position; void settings.overlay; untrack(inherit); });
|
|
||||||
void load();
|
|
||||||
onDestroy(() => { closed = true; generation++; closeMenu(); if (url) URL.revokeObjectURL(url); });
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<details class="image-editor">
|
|
||||||
<summary>{$t("Per-image appearance")}</summary>
|
|
||||||
<p>{$t("Choose an image to change its fit, position, and overlay. Portrait images show in full over a blurred fill by default.")}</p>
|
|
||||||
<fieldset disabled={busy}>
|
|
||||||
<div class="row"><span>{$t("Image")}</span>
|
|
||||||
<button bind:this={trigger} class="choice" aria-label={$t("Image to change")} aria-expanded={pickerOpen} aria-controls={pickerId} disabled={!names.length} onclick={openPicker}>
|
|
||||||
<span class="name">{selected || $t("Choose an image")}</span><Icon icon="chevron-down" /></button></div>
|
|
||||||
{#if pickerOpen}
|
|
||||||
<!-- svelte-ignore a11y_no_static_element_interactions (Escape closes the picker.) -->
|
|
||||||
<div id={pickerId} class="rs-picker image-picker" onkeydown={event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); pickerOpen = false; trigger?.focus(); } }}>
|
|
||||||
<input bind:this={search} type="search" aria-label={$t("Find an image")} placeholder={$t("Find an image")} bind:value={query}
|
|
||||||
onkeydown={event => { if (event.key === "ArrowDown" || event.key === "ArrowUp") moveFocus(event, event.currentTarget.nextElementSibling as HTMLElement); else if (event.key === "Enter" && filtered[0]) { event.preventDefault(); pick(filtered[0]); } }} />
|
|
||||||
<div class="options" role="listbox" aria-label={$t("Image files")} tabindex="-1"
|
|
||||||
onkeydown={event => { if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) moveFocus(event, event.currentTarget); }}>
|
|
||||||
{#each filtered.slice(0, 100) as name (name)}
|
|
||||||
<button class="rs-picker-row" role="option" tabindex="-1" aria-selected={name === selected} onclick={() => pick(name)}>{name}</button>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
<p role="status">{!filtered.length ? $t("No matching images.") : filtered.length > 100 ? $t("{count} matches. Type more of the name to see other images.", { count: filtered.length }) : $t(filtered.length === 1 ? "{count} image." : "{count} images.", { count: filtered.length })}</p>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
<div class="preview" role="img" aria-label={selected ? $t("Selected image preview: {name}", { name: selected }) : $t("Selected image preview")}>
|
|
||||||
{#if url}
|
|
||||||
{#if draft.fit === "blurred"}<span class="fill" style:background-image={`url("${url}")`}></span>{/if}
|
|
||||||
<span class="foreground" style:background-image={`url("${url}")`} style:background-size={draft.fit === "blurred" ? "contain" : draft.fit} style:background-position={draft.position}></span>
|
|
||||||
{/if}
|
|
||||||
<span class="shade" style:background={draft.overlay < 0 ? "white" : "black"} style:opacity={String(Math.abs(draft.overlay))}></span>
|
|
||||||
</div>
|
|
||||||
<div class="row"><span>{$t("Fit")}</span><button class="choice" aria-label={$t("Image fit")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "fit")}>{fitLabels[draft.fit]}<Icon icon="chevron-down" /></button></div>
|
|
||||||
<div class="row"><span>{$t("Position")}</span><button class="choice" aria-label={$t("Position of this image")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "position")}>{positionLabels[BACKGROUND_POSITIONS.indexOf(draft.position)]}<Icon icon="chevron-down" /></button></div>
|
|
||||||
<div class="row"><span>{$t("Overlay")}</span><div class="controls">
|
|
||||||
<input type="range" min="-100" max="100" aria-label={$t("Overlay of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} />
|
|
||||||
<input type="number" min="-100" max="100" step="1" required aria-label={$t("Overlay percentage of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} /><span>%</span>
|
|
||||||
</div></div>
|
|
||||||
<div class="controls">
|
|
||||||
<button disabled={!loaded || !changed} onclick={() => void write(false)}><Icon icon="save" />{$t("Save image appearance")}</button>
|
|
||||||
<button disabled={!loaded || !saved.images[selected]} onclick={() => void write(true)}><Icon icon="undo" />{$t("Reset image appearance")}</button>
|
|
||||||
<button onclick={() => void load()}><Icon icon="refresh" />{$t("Reload image settings")}</button>
|
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
{#if status.text}<p role={status.error ? "alert" : "status"} class:error={status.error}>{status.text}</p>{/if}
|
|
||||||
</details>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.image-editor { display: grid; gap: var(--rs-settings-gap); min-width: 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
|
|
||||||
summary { cursor: pointer; min-height: var(--rs-settings-control-height); line-height: var(--rs-settings-control-height); border-radius: var(--rs-control-radius); }
|
|
||||||
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
|
|
||||||
.error { color: var(--rs-error); }
|
|
||||||
fieldset { display: grid; gap: var(--rs-settings-gap); min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: 0; border: 0; }
|
|
||||||
.row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
|
|
||||||
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
|
|
||||||
button:not(.rs-picker-row), input:not([type=range]) { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
|
||||||
button:not(.rs-picker-row) { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
|
|
||||||
button:not(.rs-picker-row):hover:not(:disabled) { background: var(--rs-bg-active); }
|
|
||||||
button:disabled, input:disabled { opacity: .55; cursor: default; }
|
|
||||||
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
|
||||||
:is(button, input, summary):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
|
||||||
.choice { max-width: 100%; min-width: 0; }
|
|
||||||
.choice .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
||||||
input[type=number] { width: 72px; }
|
|
||||||
input[type=range] { width: 160px; max-width: 100%; accent-color: var(--rs-accent); }
|
|
||||||
.image-picker { display: grid; gap: var(--rs-settings-gap); width: 100%; min-width: 0; position: static; }
|
|
||||||
.image-picker input { width: 100%; min-width: 0; }
|
|
||||||
.options { display: grid; gap: 2px; max-height: 220px; overflow: auto; min-width: 0; }
|
|
||||||
.options button { justify-content: flex-start; text-align: left; overflow-wrap: anywhere; }
|
|
||||||
.preview { position: relative; width: 100%; height: 170px; overflow: hidden; border-radius: var(--rs-control-radius); background-color: var(--rs-bg-active); }
|
|
||||||
.fill, .foreground, .shade { position: absolute; inset: 0; background-repeat: no-repeat; pointer-events: none; }
|
|
||||||
.fill { inset: -24px; filter: blur(18px); background-size: cover; background-position: center; }
|
|
||||||
</style>
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user