Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d1fb40434 | ||
|
|
47510c88b5 | ||
|
|
046860ad1c | ||
|
|
42ba0ce882 | ||
|
|
85b6602b31 | ||
|
|
c483c012b3 | ||
|
|
1bb2874753 | ||
|
|
dbdec05752 | ||
|
|
73b41fa86b | ||
|
|
e546ab6969 | ||
|
|
b9d97d0724 | ||
|
|
7213c119da | ||
|
|
c452fab735 | ||
|
|
64b172649b | ||
|
|
f8fd8e30dc | ||
|
|
f85f9b49d3 | ||
|
|
7463cf3905 | ||
|
|
531238039d | ||
|
|
5377d88ca6 | ||
|
|
9e4349fe42 | ||
|
|
86fc7cea2f | ||
|
|
f3e44a2132 | ||
|
|
5cbf284841 | ||
|
|
5bf262b82b | ||
|
|
80fef698ce | ||
|
|
a85f91e07d | ||
|
|
918e653a0a | ||
|
|
9ce2b75568 | ||
|
|
146256714b | ||
|
|
e7c9c5b672 | ||
|
|
83ca4071d4 | ||
|
|
3f82f87a81 | ||
|
|
fac1ec00da | ||
|
|
b173d75e98 | ||
|
|
6ca825990d | ||
|
|
b1cde7e783 | ||
|
|
1d7f87f71d | ||
|
|
9f6a047867 | ||
|
|
70e896b3cb | ||
|
|
6a604fe4d8 | ||
|
|
18a952d4c1 | ||
|
|
94cbdcf0b1 | ||
|
|
297118cfc1 | ||
|
|
20303d5ddc | ||
|
|
72a6da0ca3 | ||
|
|
61862ef792 | ||
|
|
74b35b0120 | ||
|
|
0c7e80d896 | ||
|
|
409be9d31a | ||
|
|
5ab3161bf5 | ||
|
|
673cddfff6 | ||
|
|
eabc3780c9 | ||
|
|
4f2ee4256a | ||
|
|
4aac0ac70b | ||
|
|
f6ccbf59bc | ||
|
|
ac9faba229 | ||
|
|
1e7e9dfc41 | ||
|
|
543b489b11 | ||
|
|
2e463dab3a | ||
|
|
6584b2f92f | ||
|
|
4efc2f3968 | ||
|
|
365e4ad732 | ||
|
|
9f5f1f669d | ||
|
|
2953ab1ee3 | ||
|
|
976fcdc354 | ||
|
|
c7fee5beeb | ||
|
|
3dfef1961d | ||
|
|
b82225ce08 | ||
|
|
227aecb8f6 | ||
|
|
3d0cad3312 | ||
|
|
560f08cfb9 | ||
|
|
17c73925bf | ||
|
|
e7a36c3129 | ||
|
|
01a92f1edf | ||
|
|
744aa20496 | ||
|
|
e351ee588a | ||
|
|
b06ec4be7b | ||
|
|
8883e93d2b | ||
|
|
0377141e4f | ||
|
|
d712c4ea85 | ||
|
|
ffe3523f26 | ||
|
|
2e98159083 | ||
|
|
4f9f84446d | ||
|
|
7468bdf5de | ||
|
|
cfb49218f7 | ||
|
|
953a920a23 | ||
|
|
146d7a5fb9 | ||
|
|
45aac067f8 | ||
|
|
ba4ed63f4c | ||
|
|
384ccda515 | ||
|
|
1c1b9c4d1a | ||
|
|
642ad3e13a | ||
|
|
3592b86a94 | ||
|
|
b49ed22665 | ||
|
|
abb35b8fac | ||
|
|
598c5a2391 | ||
|
|
7f54e959b8 |
No files matched your search
@@ -13,10 +13,10 @@ env:
|
||||
RUST_BACKTRACE: 1
|
||||
|
||||
jobs:
|
||||
# Make sure that the program correctly builds,
|
||||
# passes format and lints, as well as tests
|
||||
build-test:
|
||||
name: Build, check and test
|
||||
# Type-checks the daemon on Linux: formatting, and clippy over every target, which compiles
|
||||
# the cfg(target_os = "linux") paths without linking them. Linking is the Windows job's.
|
||||
check:
|
||||
name: Check and lint (Linux)
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
@@ -34,21 +34,56 @@ jobs:
|
||||
run: cargo fmt --check
|
||||
|
||||
- name: Install system build dependencies
|
||||
# pkg-config finds libobs for its build script; nothing is linked here, so the distro's
|
||||
# version is enough even though the Windows build links a newer obs.lib.
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y pkg-config libglib2.0-dev libobs-dev libc6-dev clang libwayland-client0 libwayland-dev
|
||||
|
||||
- name: Build
|
||||
run: cargo build
|
||||
env:
|
||||
RUSTFLAGS: -Dwarnings
|
||||
sudo apt-get install -y pkg-config libglib2.0-dev libobs-dev libc6-dev clang libwayland-dev
|
||||
|
||||
- name: Lint
|
||||
run: cargo clippy --all-targets --all-features
|
||||
|
||||
- name: Run tests with verbose logging (timeout 30min)
|
||||
run: timeout 30m cargo test -- --nocapture
|
||||
env:
|
||||
RUST_LOG: debug
|
||||
# The daemon ships on Windows and links Windows' obs.lib, so that is the build worth checking.
|
||||
# It cross-compiles from the Linux runner: obs.lib rides with the libobs crate, and cargo-xwin
|
||||
# brings the MSVC runtime and the Windows SDK. Tests need a machine that can run the exe, so
|
||||
# they stay local: `cargo test` in record-daemon on Windows.
|
||||
build:
|
||||
name: Build (Windows x64)
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: record-daemon
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# TODO: Add windows native builds
|
||||
- name: Install Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: x86_64-pc-windows-msvc
|
||||
|
||||
- name: Install the cross linker
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y clang lld llvm
|
||||
|
||||
- name: Install cargo-xwin
|
||||
run: cargo install cargo-xwin --locked
|
||||
|
||||
- name: Build
|
||||
# libobs-wrapper's build script asks for X11 and Wayland through #[cfg], which it
|
||||
# resolves against the machine running the script rather than the target: a Linux
|
||||
# host cross-building for Windows asks the linker for two libraries that cannot
|
||||
# exist there. Empty archives on the search path answer it without adding anything
|
||||
# to the exe.
|
||||
env:
|
||||
RUSTFLAGS: -Dwarnings -L native=/tmp/xwin-stubs
|
||||
run: |
|
||||
mkdir -p /tmp/xwin-stubs
|
||||
printf 'void stub(void) {}\n' > /tmp/xwin-stub.c
|
||||
clang --target=x86_64-pc-windows-msvc -c /tmp/xwin-stub.c -o /tmp/xwin-stub.obj
|
||||
libtool=$(command -v llvm-lib || ls /usr/lib/llvm-*/bin/llvm-lib | head -1)
|
||||
for lib in X11 wayland-client; do
|
||||
"$libtool" /out:/tmp/xwin-stubs/$lib.lib /tmp/xwin-stub.obj
|
||||
done
|
||||
cargo xwin build --target x86_64-pc-windows-msvc
|
||||
@@ -0,0 +1,2 @@
|
||||
/.rhema/
|
||||
/app/vendor/rune/target
|
||||
@@ -0,0 +1,37 @@
|
||||
# Working in this repository
|
||||
|
||||
The repository holds two Rust programs: `record-daemon/` (the recorder) and `app/` (the rune
|
||||
front end).
|
||||
|
||||
## Before every commit
|
||||
|
||||
In `app/` and in `record-daemon/`, all of these must pass:
|
||||
|
||||
```sh
|
||||
cargo fmt
|
||||
cargo clippy --all-targets -- -D warnings
|
||||
cargo test
|
||||
```
|
||||
|
||||
`cargo build` must print no warning for these crates. The vendored crates under `app/vendor/`
|
||||
and the rune checkout can print their own; they are silenced at their crate root, so do not add
|
||||
allows in our own code to hide a warning that is ours to fix.
|
||||
|
||||
For UI work, check the screen without a window and look at the PNG:
|
||||
|
||||
```sh
|
||||
cd app
|
||||
cargo run -- --snap /tmp/screen.png --scene history
|
||||
cargo run -- --snap /tmp/live.png --live --at 40 # real daemon and recordings
|
||||
```
|
||||
|
||||
## Commit messages
|
||||
|
||||
History uses `<area>: <imperative summary>`, for example `app: open the review screen from a
|
||||
card` or `record-daemon: stop writing a log per game`. Lowercase after the colon, no trailing
|
||||
period, subject at most 72 characters. The body says why, wrapped at 80 columns.
|
||||
|
||||
## Rune gaps
|
||||
|
||||
`docs/rune-upstream.md` lists the faults we work around in rune, with the file to change and how
|
||||
to check a fix.
|
||||
@@ -0,0 +1,3 @@
|
||||
/target
|
||||
/dist
|
||||
/.rhema
|
||||
Generated
+5120
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,52 @@
|
||||
[package]
|
||||
name = "leaguerecorder"
|
||||
version = "0.3.3"
|
||||
edition = "2024"
|
||||
description = "Native League Recorder desktop app (rune)"
|
||||
license = "MIT"
|
||||
|
||||
[[bin]]
|
||||
name = "leaguerecorder"
|
||||
path = "src/main.rs"
|
||||
|
||||
[build-dependencies]
|
||||
# Bakes icons/icon.ico into the exe's resources (build.rs), for Explorer and shortcuts.
|
||||
winresource = "0.1"
|
||||
|
||||
[dependencies]
|
||||
rune = { path = "vendor/rune/crates/rune", features = ["native-file-dialog"] }
|
||||
rune-kit = { path = "vendor/rune/crates/rune-kit" }
|
||||
rune-notify = { path = "vendor/rune/crates/rune-notify" }
|
||||
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
directories = "6"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std", "serde"] }
|
||||
tokio = { version = "1", features = ["rt", "net", "io-util", "time", "sync"] }
|
||||
uuid = { version = "1", features = ["v4", "serde"] }
|
||||
ffmpeg-sidecar = "2.7"
|
||||
ureq = "3.5"
|
||||
# PNG decode of the bundled tray icon; the same crate and features rune itself uses.
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = "0.56"
|
||||
windows = { version = "0.62", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Console",
|
||||
"Win32_System_Diagnostics_ToolHelp",
|
||||
"Win32_System_Threading",
|
||||
] }
|
||||
|
||||
# Rune comes from a local checkout of the pinned rev, carrying two cherry-picked patches
|
||||
# (anomalyco/rune issues 1320 and 1325) on branch `ported`.
|
||||
# Rune's other crates are patched in the workspace that builds it. A dependency's `[patch]` doesn't apply
|
||||
# the app that depends on it, so these three copies (from rune's own vendor/) are repeated here.
|
||||
[patch.crates-io]
|
||||
wgpu-hal = { path = "vendor/wgpu-hal" }
|
||||
winit = { path = "vendor/winit" }
|
||||
parley_engine = { path = "vendor/parley_engine" }
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
strip = true
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
# League Recorder (rune app)
|
||||
|
||||
The native front end for `record-daemon`. It talks to the daemon over its existing
|
||||
named-pipe protocol and draws with [rune](https://github.com/anomalyco/rune).
|
||||
|
||||
## Run it
|
||||
|
||||
```sh
|
||||
cargo run
|
||||
```
|
||||
|
||||
The binary is a windowed app on Windows (`windows_subsystem = "windows"` in `main.rs`), so
|
||||
launching it from Explorer, the Run key or the login item never opens a console. The printing
|
||||
modes still work from a shell: `attach_console` borrows the console of whatever started the app,
|
||||
and nothing happens when nothing did.
|
||||
|
||||
The app starts the daemon if it isn't running, then reads its settings and status. `cargo run --
|
||||
--probe` does the same without a window and prints the daemon's answers; `cargo run -- --games`
|
||||
prints how many timelines load from disk.
|
||||
|
||||
Headless renders, for looking at a screen without a window:
|
||||
|
||||
```sh
|
||||
cargo run -- --snap history.png --scene history
|
||||
cargo run -- --snap settings.png --scene settings
|
||||
cargo run -- --snap recording.png --scene recording # the settings tab
|
||||
cargo run -- --snap recording-live.png --scene recording-live # a game being recorded
|
||||
cargo run -- --snap recording-live-delete.png --scene recording-live-delete
|
||||
cargo run -- --snap recording-idle.png --scene recording-idle
|
||||
cargo run -- --snap audio.png --scene audio
|
||||
cargo run -- --snap review.png --scene review
|
||||
cargo run -- --snap review-full.png --scene review-full # the picture alone, at rest
|
||||
cargo run -- --snap clips.png --scene clips
|
||||
cargo run -- --snap clip.png --scene clip
|
||||
cargo run -- --snap clips-many.png --scene clips-many --at 1 # 36 demo clips, to see the scrollbar
|
||||
cargo run -- --snap many.png --scene many --at 1 # 60 sample games, to see the scrollbar
|
||||
```
|
||||
|
||||
Pass `--at 1` when the screenshot depends on a laid-out size (the scrollbar does): layout callbacks
|
||||
run after the first frame.
|
||||
|
||||
`--live` renders without sample data: the app talks to the daemon and reads the real timelines
|
||||
from disk. Loading them takes a few seconds with a large history, so give it time before `--at`.
|
||||
|
||||
```sh
|
||||
cargo run -- --snap live.png --live --at 40
|
||||
```
|
||||
|
||||
Without `--live`, a headless run never starts the daemon and reads no recording: `App::new` loads
|
||||
the sample recordings from `history::sample` when it sees rune's tooling flags. Portraits still
|
||||
come from the Data Dragon cache (or download into it) so the PNGs show real champion faces.
|
||||
|
||||
## Test
|
||||
|
||||
```sh
|
||||
cargo test
|
||||
```
|
||||
|
||||
The tests pin the wire format the daemon parses (`ipc::tests`, `settings::tests`), timeline
|
||||
reading (`history::tests`), highlight clipping (`highlight::tests`) and formatting.
|
||||
|
||||
## Layout
|
||||
|
||||
| File | What it holds |
|
||||
| --- | --- |
|
||||
| `src/main.rs` | Entry point, single instance, notifications, app spec, `--probe` |
|
||||
| `src/app.rs` | App state, `poll` (daemon answers, tray events, status), screen dispatch |
|
||||
| `src/ipc.rs` | Protocol types and the named-pipe client, on a worker thread |
|
||||
| `src/daemon.rs` | Finding, starting and logging the daemon |
|
||||
| `src/settings.rs` | The daemon's settings model, field for field |
|
||||
| `src/history.rs` | Timelines from disk and the values the cards show |
|
||||
| `src/portraits.rs` | Champion portraits: the Data Dragon cache and its downloads |
|
||||
| `src/highlight.rs` | Highlight clips from kill events |
|
||||
| `src/export.rs` | ffmpeg clip export, the clips folder it fills and its miniatures |
|
||||
| `src/os.rs` | Run key, toasts, tray icon and menu |
|
||||
| `src/ui.rs` | Colours, cards, switches, sliders, buttons |
|
||||
| `src/screens/` | Settings, match history, clips, game review, the recording in progress |
|
||||
|
||||
## Where this stands against TODO.txt
|
||||
|
||||
1. Skeleton: done. Rune is pinned to `4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1`; the window
|
||||
opens and `--snap` writes PNGs.
|
||||
2. Pipe client: done and checked against the running daemon here: `--probe` prints status,
|
||||
settings, encoders and audio devices, and parses the settings reply with the app's model.
|
||||
Requests are typed (`Command`), the worker thread keeps the UI off tokio, and the same types
|
||||
are tested against the daemon's serde names.
|
||||
3. Settings: done. General, recording, audio and daemon tabs; device and encoder lists come from
|
||||
`getAudioDevices` and `getEncoders`; changes go out through `updateSettings`, and each
|
||||
application volume slider sends `updateAudioSource` as it moves. The recordings folder is
|
||||
shown, not typed, on the quick and recording tabs: `Select folder` asks the system for
|
||||
one, through the `native-file-dialog` feature `Cargo.toml` turns on, and headless runs
|
||||
answer it from a script. Every path the settings show is cut in the middle against the
|
||||
row it sits in, so a narrow window elides and a wide one shows the whole thing.
|
||||
4. Match history: done. Cards read `GameHistory.vue`'s fields (result, champion portrait,
|
||||
queue, KDA, CS/m, gold/m, LP change) from the raw API responses in each timeline, with the
|
||||
queue filters. Portraits come from Data Dragon and are cached on disk (`src/portraits.rs`).
|
||||
The list holds rows, not timelines: `history::summaries` parses each file, keeps a
|
||||
`Summary`, and drops the timeline with its events and raw responses, 20 rows at a time as
|
||||
the list scrolls. Opening a row reads that one timeline again, on a thread, and the review
|
||||
screen fills in when it arrives. Peak over 313 recordings: 165 MB, down from 2.1 GB.
|
||||
5. Video: not libmpv. Rune ships a `Player` with a native surface and frame seeking
|
||||
(`Player::file`, `seek`, `duration`), which removes the OpenGL and wgpu interop question the
|
||||
TODO opened. The review screen uses it. If clip-accurate seeking turns out to be worse than
|
||||
mpv's, the three options in TODO.txt still apply; `Player` is confined to `screens/review.rs`.
|
||||
6. Game review: done. The clip fills the window at 16:9, with play/pause, +/-10 s, and a
|
||||
scrubber that marks every event; highlights (play, export) and the timeline sit in a side
|
||||
panel, one press away. ffmpeg exports each highlight. The Full screen button beside the
|
||||
volume, a double press on the picture, or F takes the whole display: the picture fills the
|
||||
screen and the controls fade in over its bottom while the pointer is on them, gone 400 ms
|
||||
after it leaves. Escape goes back.
|
||||
7. Audio channels: the recorder writes one audio stream per source, and the review screen opens
|
||||
one player per stream (`export::extract_tracks` copies each into the audio cache). Toggles
|
||||
under the transport mute a channel for listening, and clip and highlight exports mix only
|
||||
the channels left on. Recordings made before the split play as one mixed track.
|
||||
8. OS integration: tray icon with open/hide/record/quit, launch at login through the Run key,
|
||||
single instance, and toasts on recording start and stop.
|
||||
9. Installer: `packager.toml` targets NSIS and copies the daemon, its OBS files and the VC++
|
||||
runtime beside the exe. `cargo install cargo-packager --locked && cargo packager --release`.
|
||||
On the first run the app downloads ffmpeg (`--fetch-ffmpeg` does it from a shell), so clip
|
||||
export is ready before the first clip. The installer has not been run on a clean VM yet.
|
||||
|
||||
### The recording screen
|
||||
|
||||
While the daemon records, the app opens on the game it is recording and can stop it. The
|
||||
daemon's protocol answers about the daemon only — recording or not, and which game id — so the
|
||||
screen reads the game where it is: `/liveclientdata/allgamedata` on `https://127.0.0.1:2999`,
|
||||
the endpoint the daemon itself polls for its events, which needs no login. It is read once a
|
||||
second on a thread of its own, together with the timeline the recorder opened for this game
|
||||
(the champion, the queue and the summoner it fetched at the start) and the clip being written
|
||||
in the recordings folder. Without the game's answer the screen still shows what it has, and
|
||||
says it is waiting.
|
||||
|
||||
Stopping over the protocol is not the stop the recorder gives a game that ends by itself: the
|
||||
recorder writes the video into a new timeline and leaves the open one behind, which would show
|
||||
in Match history as a game that never happened, next to one with no champion. The app closes
|
||||
the open timeline into the one holding the video (`history::close_stopped`), and "Stop and
|
||||
delete" removes the clip and both.
|
||||
|
||||
### Known gaps
|
||||
|
||||
- Item images are not drawn. Champion portraits download from Data Dragon on first sight and are
|
||||
cached under the user's cache directory; offline, a card falls back to initials on the
|
||||
champion's colour.
|
||||
- The installer has not been run on a clean VM, and it is unsigned: SmartScreen will warn on
|
||||
every download until it is signed. The VC++ runtime travels with it (`vendor/vcruntime`),
|
||||
because Windows ships the UCRT but not `VCRUNTIME140.dll`, `VCRUNTIME140_1.dll` or
|
||||
`MSVCP140.dll`, and the app, the daemon and every OBS plugin import them.
|
||||
|
||||
## The vendored crates
|
||||
|
||||
`vendor/` also holds `vcruntime/`: the three redistributable DLLs the installer puts beside
|
||||
the exes, copied from a machine with Visual Studio's runtime installed.
|
||||
|
||||
`vendor/` holds three crates copied from rune's own `vendor/`: `wgpu-hal`, `winit` and
|
||||
`parley_engine`. Rune builds against patched copies of these, and a dependency's
|
||||
`[patch.crates-io]` does not apply to the app that depends on it, so `Cargo.toml` repeats the
|
||||
patches here. They match the rune rev above; when the rev moves, refresh them from that checkout:
|
||||
|
||||
```sh
|
||||
cp -r ../rune/vendor/{wgpu-hal,winit,parley_engine} vendor/
|
||||
```
|
||||
@@ -0,0 +1,72 @@
|
||||
Rune app
|
||||
|
||||
Decided
|
||||
- UI framework: rune (github.com/anomalyco/rune, pin a dev rev). gpui is the
|
||||
fallback if rune fights back. Decide via a time-boxed spike on the Settings
|
||||
screen; it exercises switches, dropdowns, tables and text input.
|
||||
- Video: libmpv2 crate (repo kohsine/libmpv-rs, v7.0.1, render feature on by
|
||||
default). Requires libmpv >= 2.0 (mpv 0.35+); bundle libmpv-2.dll from the
|
||||
shinchiro mpv-winbuild mpv-dev archive, same as we bundle obs.dll.
|
||||
- Installers: cargo-packager (CrabNebula), NSIS target. Replaces what the
|
||||
Tauri bundler gave us. Revisit plain NSIS or Inno in CI if cargo-packager
|
||||
lags.
|
||||
|
||||
Open question before the spike commits to a render path
|
||||
- libmpv2's render API is OpenGL-based (anlumo's example renders to an SDL2
|
||||
GL window) and rune/gpui render with wgpu. Options, in order:
|
||||
1. software render into an RGBA buffer, upload as a texture each frame;
|
||||
need to verify libmpv2 exposes MPV_RENDER_PARAM_SW (its docs only show
|
||||
the GL path)
|
||||
2. share the GL texture with wgpu (external texture interop, painful)
|
||||
3. embed a native child window with --wid and drive mpv over JSON IPC
|
||||
(mpvipc crate); this is FFI-free but mpv then owns the video surface
|
||||
Spike 1 first, fall back to 3. All recordings are H.264 today
|
||||
(jim_nvenc, amd_amf_h264, qsv, x264) so every path can decode them.
|
||||
|
||||
Initial plan
|
||||
Each phase ends with something that runs. Phase 1 doubles as the
|
||||
rune-vs-gpui decision: if the Settings screen keeps fighting the
|
||||
framework, stop and switch to gpui before writing anything else.
|
||||
|
||||
1. Skeleton: new app/ crate, rune pinned to one dev rev, window opens
|
||||
on Windows and renders headlessly to PNG.
|
||||
2. Pipe client: port daemon_ipc.rs, keep the serde types identical to
|
||||
record-daemon/src/ipc/protocol.rs. Done when the app reads settings
|
||||
and status from a running daemon.
|
||||
3. Settings screen: general, recording and audio source tabs; device
|
||||
dropdowns from getAudioDevices; volume sliders. Done when changes
|
||||
save through updateSettings and survive a daemon restart.
|
||||
4. Game history: port get_game_history, list games from the timeline
|
||||
JSON in the recordings dir. Done when it matches GameHistory.vue.
|
||||
5. Video spike: libmpv2 in a standalone example first, software render
|
||||
to RGBA and upload as a texture. Done when a clip plays and
|
||||
frame-seeks to a timestamp. Fall back to --wid plus mpvipc if the
|
||||
software path is not exposed.
|
||||
6. Game review: timeline scrubber with event markers over the video.
|
||||
Done when clicking an event seeks the video to that timestamp.
|
||||
7. OS integration: tray icon, autostart via the registry Run key,
|
||||
single instance, notifications for recording start and end.
|
||||
8. Installer: cargo-packager NSIS target with the bundle list below.
|
||||
Done when the installer works on a clean Windows VM and the app
|
||||
records a real game end to end.
|
||||
|
||||
Stable contracts
|
||||
- record-daemon does not change. The IPC protocol (IpcCommand serde types
|
||||
over named pipes) is the versioned interface between app and daemon.
|
||||
- The pipe client came from the old Tauri app's daemon_ipc.rs (645 lines),
|
||||
ported into app/ nearly as-is; it is plain Rust + tokio.
|
||||
- The disk-side helpers came from its lib.rs: get_game_history, export_clip,
|
||||
find_video_file and the ffmpeg_sidecar download logic.
|
||||
|
||||
Installer contents
|
||||
- app exe, record-daemon.exe, obs.dll, ffmpeg sidecar, libmpv-2.dll.
|
||||
- NSIS fits our layout (small install, OBS and ffmpeg downloaded at first
|
||||
run). MSI would want a self-contained package; skip unless we need AD
|
||||
deployment.
|
||||
- Code signing: unsigned exes that hook games and open named pipes hit
|
||||
SmartScreen. Budget for an EV cert or Azure Trusted Signing before
|
||||
shipping installers.
|
||||
|
||||
OS integration to reimplement (was Tauri plugins)
|
||||
- tray icon, launch at Windows startup (registry Run key or Startup folder
|
||||
shortcut), single instance, notifications for recording start/end.
|
||||
@@ -0,0 +1,11 @@
|
||||
//! Bakes `icons/icon.ico` into the exe as its resource, so Explorer, shortcuts and the
|
||||
//! installer show the medallion the window and the tray also draw.
|
||||
|
||||
fn main() {
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
}
|
||||
let mut resource = winresource::WindowsResource::new();
|
||||
resource.set_icon("icons/icon.ico");
|
||||
resource.compile().expect("the icon resource compiles");
|
||||
}
|
||||
File renamed without changes.
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 37 KiB |
File renamed without changes.
|
Before Width: | Height: | Size: 66 KiB After Width: | Height: | Size: 66 KiB |
File renamed without changes.
|
Before Width: | Height: | Size: 797 KiB After Width: | Height: | Size: 797 KiB |
@@ -0,0 +1,42 @@
|
||||
# cargo-packager configuration for the NSIS installer (`cargo packager --release`).
|
||||
#
|
||||
# The app exe is the cargo binary. Everything the daemon needs at run time sits beside it in the
|
||||
# install root: the daemon, OBS and its data are built into record-daemon/target/release by the
|
||||
# daemon's own build and copied from there. The app downloads ffmpeg itself on the first export.
|
||||
"$schema" = "https://raw.githubusercontent.com/crabnebula-dev/cargo-packager/main/crates/packager/schema.json"
|
||||
|
||||
name = "leaguerecorder"
|
||||
product-name = "League Recorder"
|
||||
identifier = "v.leaguerecorder"
|
||||
version = "0.3.3"
|
||||
description = "Records League of Legends games through the record-daemon."
|
||||
out-dir = "dist"
|
||||
# A config file is not read from Cargo.toml, so the binary has to be named. The app crate
|
||||
# builds one.
|
||||
binaries-dir = "target/release"
|
||||
binaries = [{ path = "leaguerecorder", main = true }]
|
||||
before-packaging-command = "cargo build --release && cargo build --release --manifest-path ../record-daemon/Cargo.toml"
|
||||
formats = ["nsis"]
|
||||
icons = ["icons/icon.ico"]
|
||||
|
||||
# Everything the daemon loads from beside its exe: the binary, obs.dll and the DLLs it pulls in
|
||||
# (ffmpeg, x264, curl, srt, …), the module data and the plugins with their data. Shipping the
|
||||
# whole set keeps a first run offline; the daemon can also fetch OBS when a piece is missing.
|
||||
resources = [
|
||||
{ src = "../record-daemon/target/release/record-daemon.exe", target = "record-daemon.exe" },
|
||||
{ src = "../record-daemon/target/release/*.dll", target = "." },
|
||||
{ src = "../record-daemon/target/release/obs-*.exe", target = "." },
|
||||
{ src = "../record-daemon/target/release/data", target = "data" },
|
||||
{ src = "../record-daemon/target/release/obs-plugins", target = "obs-plugins" },
|
||||
{ src = "../record-daemon/target/release/win-capture", target = "win-capture" },
|
||||
{ src = "../record-daemon/target/release/rtmp-services", target = "rtmp-services" },
|
||||
{ src = "../record-daemon/target/release/iconengines", target = "iconengines" },
|
||||
{ src = "../record-daemon/target/release/styles", target = "styles" },
|
||||
# The C++ runtime the exes and every OBS plugin import. Windows ships the UCRT but not these,
|
||||
# so a machine without the VC++ redistributable would not start the app.
|
||||
{ src = "vendor/vcruntime/*.dll", target = "." },
|
||||
]
|
||||
|
||||
[nsis]
|
||||
compression = "lzma"
|
||||
installer-mode = "currentUser"
|
||||
+1567
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,270 @@
|
||||
//! Finding, starting and logging the record-daemon process.
|
||||
//!
|
||||
//! Ported from the old Tauri app's `daemon_ipc.rs`. The daemon binary ships next to the
|
||||
//! app; inside a checkout it is found in `record-daemon/target/{release,debug}`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::ipc::Client;
|
||||
|
||||
/// Set this to point the app and the daemon at a scratch directory, as scripts do.
|
||||
pub const HOME_ENV: &str = "RECORD_DAEMON_HOME";
|
||||
|
||||
/// Where the review screen keeps one audio file per track of a clip.
|
||||
pub fn audio_cache_dir() -> PathBuf {
|
||||
data_dir()
|
||||
.map(|p| p.join("audio-cache"))
|
||||
.unwrap_or_else(|| PathBuf::from("./audio-cache"))
|
||||
}
|
||||
|
||||
/// The daemon's data directory, shared with the daemon itself.
|
||||
pub fn data_dir() -> Option<PathBuf> {
|
||||
if let Some(home) = std::env::var_os(HOME_ENV).filter(|value| !value.is_empty()) {
|
||||
return Some(PathBuf::from(home).join("data"));
|
||||
}
|
||||
directories::ProjectDirs::from("com", "leaguerecorder", "record-daemon")
|
||||
.map(|dirs| dirs.data_dir().to_path_buf())
|
||||
}
|
||||
|
||||
/// Where recordings and timelines live.
|
||||
pub fn recordings_dir() -> PathBuf {
|
||||
data_dir()
|
||||
.map(|p| p.join("recordings"))
|
||||
.unwrap_or_else(|| PathBuf::from("./recordings"))
|
||||
}
|
||||
|
||||
/// The folder the daemon keeps its daily logs in.
|
||||
pub fn log_dir() -> Option<PathBuf> {
|
||||
let dir = data_dir()?.join("logs");
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
Some(dir)
|
||||
}
|
||||
|
||||
/// The `--log-file` the app starts the daemon with.
|
||||
///
|
||||
/// The daemon takes the stem of the path and adds the date and the extension (see `init_logging`
|
||||
/// in `record-daemon/src/main.rs`), so it writes `daemon.YYYY-MM-DD.log` beside this path
|
||||
/// rather than the path itself.
|
||||
pub fn log_file() -> Option<PathBuf> {
|
||||
Some(log_dir()?.join("daemon.log"))
|
||||
}
|
||||
|
||||
/// Find the record-daemon binary next to the app, in an installed `resources` folder, or in a
|
||||
/// development checkout.
|
||||
///
|
||||
/// A checkout can hold both `target/debug` and `target/release`, one of them stale; the newest
|
||||
/// build wins, so the app talks to the daemon that was built last ("cargo build" then "cargo
|
||||
/// run", rather than a release build from another week).
|
||||
pub fn find_binary() -> Option<PathBuf> {
|
||||
let name = if cfg!(windows) {
|
||||
"record-daemon.exe"
|
||||
} else {
|
||||
"record-daemon"
|
||||
};
|
||||
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
let exe_dir = exe.parent()?;
|
||||
let beside = exe_dir.join(name);
|
||||
if beside.exists() {
|
||||
return Some(beside);
|
||||
}
|
||||
if let Some(parent) = exe_dir.parent() {
|
||||
let resources = parent.join("resources").join(name);
|
||||
if resources.exists() {
|
||||
return Some(resources);
|
||||
}
|
||||
}
|
||||
if let Some(found) = newest_build(exe_dir, name) {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
|
||||
newest_build(&std::env::current_dir().ok()?, name)
|
||||
}
|
||||
|
||||
/// The most recently built daemon in a checkout, walking up from `start`.
|
||||
fn newest_build(start: &Path, name: &str) -> Option<PathBuf> {
|
||||
let mut dir = start.to_path_buf();
|
||||
for _ in 0..6 {
|
||||
let candidates = [
|
||||
dir.join("record-daemon/target/release").join(name),
|
||||
dir.join("record-daemon/target/debug").join(name),
|
||||
];
|
||||
if let Some(found) = candidates
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
let modified = std::fs::metadata(&path).ok()?.modified().ok()?;
|
||||
Some((modified, path))
|
||||
})
|
||||
.max_by_key(|(modified, _)| *modified)
|
||||
.map(|(_, path)| path)
|
||||
{
|
||||
return Some(found);
|
||||
}
|
||||
if !dir.pop() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// Start the daemon detached, so it outlives the app.
|
||||
pub fn spawn() -> Result<PathBuf, String> {
|
||||
let binary = find_binary().ok_or_else(|| {
|
||||
"record-daemon was not found next to the app or in record-daemon/target".to_string()
|
||||
})?;
|
||||
let log = log_file().ok_or_else(|| "no data directory for the daemon log".to_string())?;
|
||||
|
||||
let mut command = std::process::Command::new(&binary);
|
||||
command.arg("--foreground").arg("--log-file").arg(&log);
|
||||
if let Some(dir) = binary.parent() {
|
||||
// The daemon finds its bundled OBS plugin data relative to itself.
|
||||
command.current_dir(dir);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
// CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
|
||||
command.creation_flags(0x0000_0200 | 0x0000_0008);
|
||||
}
|
||||
command
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null());
|
||||
command
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start record-daemon: {e}"))?;
|
||||
Ok(binary)
|
||||
}
|
||||
|
||||
/// Wait up to `timeout` for the daemon to answer, starting it if it isn't running yet.
|
||||
pub async fn ensure_running() -> Result<(), String> {
|
||||
let client = Client::new();
|
||||
if client.is_running().await {
|
||||
return Ok(());
|
||||
}
|
||||
spawn()?;
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
if client.is_running().await {
|
||||
return Ok(());
|
||||
}
|
||||
if std::time::Instant::now() >= deadline {
|
||||
return Err("record-daemon did not answer within 30 s".to_string());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The last `n` lines of the log the daemon is writing now.
|
||||
pub fn read_logs(n: usize) -> Result<String, String> {
|
||||
let path = current_log().ok_or_else(|| "the recorder has written no log yet".to_string())?;
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|e| format!("cannot read {}: {e}", path.display()))?;
|
||||
let lines: Vec<String> = text.lines().rev().take(n).map(strip_ansi).collect();
|
||||
Ok(lines.into_iter().rev().collect::<Vec<_>>().join("\n"))
|
||||
}
|
||||
|
||||
/// What a log line says without the color codes.
|
||||
///
|
||||
/// The daemon used to write ANSI escapes into the file, so lines from before that fix carry
|
||||
/// them. `ESC [ params final` is the only form tracing emitted.
|
||||
fn strip_ansi(line: &str) -> String {
|
||||
if !line.contains('\u{1b}') {
|
||||
return line.to_string();
|
||||
}
|
||||
let mut out = String::with_capacity(line.len());
|
||||
let mut chars = line.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c != '\u{1b}' {
|
||||
out.push(c);
|
||||
} else if chars.next() == Some('[') {
|
||||
for c in chars.by_ref() {
|
||||
if ('@'..='~').contains(&c) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The log file the daemon is appending to now, as text for the Advanced tab.
|
||||
pub fn log_path() -> String {
|
||||
current_log()
|
||||
.map(|p| p.display().to_string())
|
||||
.unwrap_or_else(|| "None yet".to_string())
|
||||
}
|
||||
|
||||
/// The log file the daemon is appending to now.
|
||||
pub fn current_log() -> Option<PathBuf> {
|
||||
let dir = data_dir()?.join("logs");
|
||||
newest_log(&dir)
|
||||
}
|
||||
|
||||
/// The newest daily file in the logs folder.
|
||||
///
|
||||
/// The daemon rolls the log over at midnight, so the folder holds one file per day and the
|
||||
/// newest is the one still being written. The date in the name is in ISO order, so comparing
|
||||
/// names finds it without reading each file's timestamp.
|
||||
fn newest_log(dir: &Path) -> Option<PathBuf> {
|
||||
std::fs::read_dir(dir)
|
||||
.ok()?
|
||||
.filter_map(|entry| {
|
||||
let path = entry.ok()?.path();
|
||||
let name = path.file_name()?.to_str()?;
|
||||
let date = name.strip_prefix("daemon.")?.strip_suffix(".log")?;
|
||||
date.starts_with(|c: char| c.is_ascii_digit())
|
||||
.then_some(path)
|
||||
})
|
||||
.max()
|
||||
}
|
||||
|
||||
/// Open a folder.
|
||||
pub fn open_folder(path: &Path) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = std::process::Command::new("explorer").arg(path).spawn();
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = path;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_dir() -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_day_is_the_log_the_daemon_writes() {
|
||||
let dir = temp_dir();
|
||||
std::fs::write(dir.join("daemon.2026-11-21.log"), "yesterday").unwrap();
|
||||
let today = dir.join("daemon.2026-11-22.log");
|
||||
std::fs::write(&today, "today").unwrap();
|
||||
std::fs::write(dir.join("notes.txt"), "not a log").unwrap();
|
||||
assert_eq!(newest_log(&dir), Some(today));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_without_a_log_has_no_log_to_read() {
|
||||
let dir = temp_dir();
|
||||
assert_eq!(newest_log(&dir), None);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_log_line_loses_its_color_codes() {
|
||||
let line =
|
||||
"\u{1b}[2m2026-11-23T23:06:51Z\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m record_daemon: ready";
|
||||
assert_eq!(
|
||||
strip_ansi(line),
|
||||
"2026-11-23T23:06:51Z INFO record_daemon: ready"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
//! Clip export with ffmpeg, ported from `export_clip` and `export_clip_precise` in
|
||||
//! the old Tauri app's `lib.rs`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use ffmpeg_sidecar::command::{FfmpegCommand, ffmpeg_is_installed};
|
||||
use ffmpeg_sidecar::download::{
|
||||
FfmpegDownloadProgressEvent, download_ffmpeg_package_with_progress, ffmpeg_download_url,
|
||||
unpack_ffmpeg_without_extras,
|
||||
};
|
||||
use ffmpeg_sidecar::event::{FfmpegEvent, LogLevel};
|
||||
use ffmpeg_sidecar::paths::{sidecar_dir, sidecar_path};
|
||||
|
||||
use std::time::SystemTime;
|
||||
|
||||
use crate::daemon;
|
||||
|
||||
/// A clip the user exported: one file in the clips folder.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Clip {
|
||||
/// The file's name without `.mp4`, as the export named it: often `{recording}-clip`.
|
||||
pub name: String,
|
||||
/// The file, for playing it and for deleting it.
|
||||
pub path: PathBuf,
|
||||
/// When the export finished: the file's modified time.
|
||||
pub exported: Option<SystemTime>,
|
||||
/// Bytes on disk.
|
||||
pub bytes: u64,
|
||||
/// The miniature cut from the video, when one is on disk and as new as the clip.
|
||||
pub thumb: Option<PathBuf>,
|
||||
/// The recording the clip was cut from, from the file a rename leaves beside it. A clip
|
||||
/// still named as it was exported carries the id in its name instead.
|
||||
pub recording_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Where the clips' miniatures live, beside the clips.
|
||||
pub fn thumbs_dir() -> PathBuf {
|
||||
let dir = clips_dir().join("thumbs");
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
/// Where `clip`'s miniature lives. A clip that names no file is demo data: its miniature
|
||||
/// stays in the temp folder, so the clips folder keeps only what the user exported.
|
||||
pub fn thumb_path(clip: &Clip) -> PathBuf {
|
||||
if clip.path.as_os_str().is_empty() {
|
||||
std::env::temp_dir()
|
||||
.join("leaguerecorder-demo")
|
||||
.join("thumbs")
|
||||
.join(format!("{}.jpg", clip.name))
|
||||
} else {
|
||||
thumbs_dir().join(format!("{}.jpg", clip.name))
|
||||
}
|
||||
}
|
||||
|
||||
/// The miniature when it is on disk and as new as the clip: a stale one reads as none, so
|
||||
/// the thumbnail pass cuts it again. The texture under an old path is cached by path alone,
|
||||
/// so a clip re-exported over the same name keeps its old picture until the app restarts.
|
||||
pub fn thumb_of(clip: &Clip) -> Option<PathBuf> {
|
||||
let thumb = thumb_path(clip);
|
||||
let at = std::fs::metadata(&thumb).ok()?.modified().ok()?;
|
||||
let clip_at = clip.exported?;
|
||||
(at >= clip_at).then_some(thumb)
|
||||
}
|
||||
|
||||
/// The video a miniature is cut from. A clip that names no file is demo data: its video is
|
||||
/// synthesized once into the temp folder, so a snapshot has something to show.
|
||||
pub fn source_of(clip: &Clip) -> Option<PathBuf> {
|
||||
if !clip.path.as_os_str().is_empty() {
|
||||
return clip.path.is_file().then(|| clip.path.clone());
|
||||
}
|
||||
let demo = std::env::temp_dir()
|
||||
.join("leaguerecorder-demo")
|
||||
.join(format!("{}.mp4", clip.name));
|
||||
if demo.is_file() {
|
||||
return Some(demo);
|
||||
}
|
||||
let _ = std::fs::create_dir_all(demo.parent()?);
|
||||
let Ok(child) = FfmpegCommand::new()
|
||||
.arg("-y")
|
||||
.arg("-f")
|
||||
.arg("lavfi")
|
||||
.arg("-i")
|
||||
.arg("testsrc2=size=640x360:rate=30:duration=2")
|
||||
.arg("-c:v")
|
||||
.arg("libx264")
|
||||
.arg("-preset")
|
||||
.arg("ultrafast")
|
||||
.arg("-pix_fmt")
|
||||
.arg("yuv420p")
|
||||
.arg(demo.to_string_lossy().to_string())
|
||||
.spawn()
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let mut child = child;
|
||||
child.wait().ok()?.success().then_some(demo)
|
||||
}
|
||||
|
||||
/// Cut the first frame of `video` into `thumb`, at card size. True when the file is there
|
||||
/// after: the frame lands beside a `.part.jpg` file that only a good cut renames on.
|
||||
pub fn make_thumb(video: &Path, thumb: &Path) -> bool {
|
||||
if let Some(parent) = thumb.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
if ffmpeg_is_installed() {
|
||||
let part = thumb.with_extension("part.jpg");
|
||||
let cut = FfmpegCommand::new()
|
||||
.arg("-y")
|
||||
.arg("-i")
|
||||
.arg(video.to_string_lossy().to_string())
|
||||
.arg("-frames:v")
|
||||
.arg("1")
|
||||
.arg("-vf")
|
||||
.arg("scale=640:-2")
|
||||
.arg("-q:v")
|
||||
.arg("4")
|
||||
.arg(part.to_string_lossy().to_string())
|
||||
.spawn()
|
||||
.and_then(|mut child| child.wait());
|
||||
let ok = cut.map(|status| status.success()).unwrap_or(false) && part.is_file();
|
||||
if ok && std::fs::rename(&part, thumb).is_ok() {
|
||||
return true;
|
||||
}
|
||||
let _ = std::fs::remove_file(&part);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Every clip in the clips folder, newest export first. Only `.mp4` counts: the folder is
|
||||
/// where a half-finished export writes too, and a clip without its pictures is no clip.
|
||||
pub fn list_clips() -> Vec<Clip> {
|
||||
let Ok(entries) = std::fs::read_dir(clips_dir()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut clips: Vec<Clip> = entries
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let path = entry.path();
|
||||
if path.extension().and_then(|ext| ext.to_str()) != Some("mp4") {
|
||||
return None;
|
||||
}
|
||||
let meta = entry.metadata().ok()?;
|
||||
let mut clip = Clip {
|
||||
name: path.file_stem()?.to_string_lossy().into_owned(),
|
||||
path: path.clone(),
|
||||
exported: meta.modified().ok(),
|
||||
bytes: meta.len(),
|
||||
thumb: None,
|
||||
recording_id: recording_link(&path),
|
||||
};
|
||||
clip.thumb = thumb_of(&clip);
|
||||
Some(clip)
|
||||
})
|
||||
.collect();
|
||||
clips.sort_by_key(|clip| std::cmp::Reverse(clip.exported));
|
||||
clips
|
||||
}
|
||||
|
||||
/// The file beside a clip that names the recording it was cut from.
|
||||
///
|
||||
/// The export writes the recording's id into the clip's name, and the name is the user's to
|
||||
/// change. A clip renamed in the app carries this file instead, so a screen that leads back to
|
||||
/// the game still finds it.
|
||||
pub fn link_path(clip: &Path) -> PathBuf {
|
||||
clip.with_extension("json")
|
||||
}
|
||||
|
||||
/// Name the recording beside `clip`. True when the file landed.
|
||||
pub fn link_recording(clip: &Path, recording_id: &str) -> bool {
|
||||
let text = serde_json::json!({ "recording_id": recording_id }).to_string();
|
||||
std::fs::write(link_path(clip), text).is_ok()
|
||||
}
|
||||
|
||||
/// The recording `clip`'s link file names, when one sits beside it.
|
||||
pub fn recording_link(clip: &Path) -> Option<String> {
|
||||
let text = std::fs::read_to_string(link_path(clip)).ok()?;
|
||||
let value: serde_json::Value = serde_json::from_str(&text).ok()?;
|
||||
value.get("recording_id")?.as_str().map(str::to_string)
|
||||
}
|
||||
|
||||
/// The clips folder beside the recordings.
|
||||
pub fn clips_dir() -> PathBuf {
|
||||
let dir = daemon::recordings_dir().join("clips");
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
/// Set while `fetch` runs, so an export during the download does not start a second one that
|
||||
/// unpacks over the first.
|
||||
static FETCHING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// One cut at a time. Reopening a row while its tracks are still being cut would otherwise
|
||||
/// have two ffmpeg processes writing the same cache file.
|
||||
static CUTTING: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// What `fetch` reports while it runs.
|
||||
pub enum FetchEvent {
|
||||
/// Bytes of the download so far, of the total the server announced.
|
||||
Bytes { done: u64, total: u64 },
|
||||
/// The archive is complete and being unpacked beside the exe.
|
||||
Unpacking,
|
||||
/// The work is over, with its outcome.
|
||||
Finished(Result<(), String>),
|
||||
}
|
||||
|
||||
/// Whether ffmpeg still has to be downloaded: it lives beside the exe. The presence of the file
|
||||
/// is enough here; `ffmpeg -version` is left to the export that needs it.
|
||||
pub fn missing() -> bool {
|
||||
sidecar_path().map(|path| !path.exists()).unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Whether a download is running right now.
|
||||
pub fn fetching() -> bool {
|
||||
FETCHING.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Download ffmpeg beside the exe, reporting progress. Blocks: call it on a thread.
|
||||
///
|
||||
/// Only `ffmpeg.exe` is unpacked. The archive carries `ffplay` and `ffprobe` too, and the
|
||||
/// export paths call neither; unpacking all three would add 200 MB to every install.
|
||||
pub fn fetch(report: impl Fn(FetchEvent)) -> Result<(), String> {
|
||||
if ffmpeg_is_installed() {
|
||||
return Ok(());
|
||||
}
|
||||
FETCHING.store(true, Ordering::SeqCst);
|
||||
let result = download(&report);
|
||||
FETCHING.store(false, Ordering::SeqCst);
|
||||
report(FetchEvent::Finished(result.clone()));
|
||||
result
|
||||
}
|
||||
|
||||
fn download(report: &impl Fn(FetchEvent)) -> Result<(), String> {
|
||||
let url = ffmpeg_download_url().map_err(|e| format!("cannot find a build to download: {e}"))?;
|
||||
let dir = sidecar_dir().map_err(|e| format!("cannot find where to put ffmpeg: {e}"))?;
|
||||
let archive = download_ffmpeg_package_with_progress(url, &dir, |event| {
|
||||
if let FfmpegDownloadProgressEvent::Downloading {
|
||||
total_bytes,
|
||||
downloaded_bytes,
|
||||
} = event
|
||||
{
|
||||
report(FetchEvent::Bytes {
|
||||
done: downloaded_bytes,
|
||||
total: total_bytes,
|
||||
});
|
||||
}
|
||||
})
|
||||
.map_err(|e| format!("cannot download ffmpeg: {e}"))?;
|
||||
report(FetchEvent::Unpacking);
|
||||
unpack_ffmpeg_without_extras(&archive, &dir)
|
||||
.map_err(|e| format!("cannot unpack ffmpeg: {e}"))?;
|
||||
if !ffmpeg_is_installed() {
|
||||
return Err("ffmpeg did not end up beside the app".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Download the ffmpeg sidecar on first use.
|
||||
pub fn ensure_ffmpeg() -> Result<(), String> {
|
||||
if ffmpeg_is_installed() {
|
||||
return Ok(());
|
||||
}
|
||||
if fetching() {
|
||||
return Err("ffmpeg is still downloading; try the export again in a moment".to_string());
|
||||
}
|
||||
fetch(|_| {})
|
||||
}
|
||||
|
||||
/// Export `start..end` of `video`. Stream copy is fast and keyframe-aligned; `precise` re-encodes
|
||||
/// with x264 for exact cuts. `audio` names the audio streams the clip keeps, empty for all of
|
||||
/// them as they are.
|
||||
pub fn export_clip(
|
||||
video: &str,
|
||||
start: f64,
|
||||
end: f64,
|
||||
output_name: &str,
|
||||
precise: bool,
|
||||
quality: &str,
|
||||
audio: &[usize],
|
||||
) -> Result<String, String> {
|
||||
ensure_ffmpeg()?;
|
||||
if !PathBuf::from(video).exists() {
|
||||
return Err(format!("video file not found: {video}"));
|
||||
}
|
||||
let output = clips_dir().join(format!("{}.mp4", sanitize(output_name)));
|
||||
let duration = (end - start).max(0.0);
|
||||
if duration <= 0.0 {
|
||||
return Err("the clip has no length".into());
|
||||
}
|
||||
|
||||
let mut command = FfmpegCommand::new();
|
||||
command
|
||||
.arg("-y")
|
||||
.arg("-ss")
|
||||
.arg(format!("{start:.3}"))
|
||||
.arg("-i")
|
||||
.arg(video)
|
||||
.arg("-t")
|
||||
.arg(format!("{duration:.3}"));
|
||||
|
||||
// Which tracks the clip keeps. One track is mapped whole; several are mixed into a single
|
||||
// stereo track, because a clip is meant to be played, not to carry a track picker.
|
||||
let kept: Vec<String> = audio
|
||||
.iter()
|
||||
.map(|stream| format!("[0:a:{stream}]"))
|
||||
.collect();
|
||||
if kept.len() > 1 {
|
||||
command
|
||||
.arg("-filter_complex")
|
||||
.arg(format!(
|
||||
"{}amix=inputs={}:normalize=0[out]",
|
||||
kept.concat(),
|
||||
kept.len()
|
||||
))
|
||||
.arg("-map")
|
||||
.arg("0:v")
|
||||
.arg("-map")
|
||||
.arg("[out]")
|
||||
.arg("-c:a")
|
||||
.arg("aac")
|
||||
.arg("-b:a")
|
||||
.arg("160k");
|
||||
} else if let Some(stream) = audio.first() {
|
||||
command
|
||||
.arg("-map")
|
||||
.arg("0:v")
|
||||
.arg("-map")
|
||||
.arg(format!("0:a:{stream}"));
|
||||
}
|
||||
|
||||
if precise || kept.len() > 1 {
|
||||
let crf = match quality {
|
||||
"low" => "28",
|
||||
"high" => "18",
|
||||
_ => "23",
|
||||
};
|
||||
command
|
||||
.arg("-c:v")
|
||||
.arg("libx264")
|
||||
.arg("-crf")
|
||||
.arg(crf)
|
||||
.arg("-preset")
|
||||
.arg("fast")
|
||||
.arg("-c:a")
|
||||
.arg("aac")
|
||||
.arg("-b:a")
|
||||
.arg("128k");
|
||||
} else {
|
||||
command
|
||||
.arg("-c")
|
||||
.arg("copy")
|
||||
.arg("-avoid_negative_ts")
|
||||
.arg("make_zero");
|
||||
}
|
||||
let iter = command
|
||||
.arg(output.to_string_lossy().to_string())
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start ffmpeg: {e}"))?
|
||||
.iter()
|
||||
.map_err(|e| format!("cannot read ffmpeg output: {e}"))?;
|
||||
|
||||
let mut errors = Vec::new();
|
||||
for event in iter {
|
||||
match event {
|
||||
FfmpegEvent::Error(e) => errors.push(e),
|
||||
FfmpegEvent::Log(LogLevel::Error, msg) => errors.push(msg),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let size = std::fs::metadata(&output).map(|m| m.len()).unwrap_or(0);
|
||||
if size == 0 {
|
||||
return Err(if errors.is_empty() {
|
||||
"ffmpeg produced no output".to_string()
|
||||
} else {
|
||||
errors.join("; ")
|
||||
});
|
||||
}
|
||||
Ok(output.display().to_string())
|
||||
}
|
||||
|
||||
/// Copy each audio track of `video` into a file of its own, so a player can be opened per
|
||||
/// track. Files are kept between sessions; a track older than the clip is cut again.
|
||||
pub fn extract_tracks(video: &str, stem: &str, count: usize) -> Result<Vec<PathBuf>, String> {
|
||||
ensure_ffmpeg()?;
|
||||
let _cutting = CUTTING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let dir = crate::daemon::audio_cache_dir().join(sanitize(stem));
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
||||
let clip_time = std::fs::metadata(video)
|
||||
.and_then(|m| m.modified())
|
||||
.map_err(|e| format!("cannot read {video}: {e}"))?;
|
||||
|
||||
let mut paths = Vec::new();
|
||||
for track in 0..count {
|
||||
let path = dir.join(format!("track-{track}.m4a"));
|
||||
let fresh = std::fs::metadata(&path)
|
||||
.and_then(|m| m.modified())
|
||||
.map(|time| time >= clip_time)
|
||||
.unwrap_or(false);
|
||||
if !fresh {
|
||||
// The stream copy takes seconds where re-encoding takes minutes; a track whose
|
||||
// codec an m4a cannot hold is cut again as AAC.
|
||||
cut_track(video, track, &path, true)
|
||||
.or_else(|_| cut_track(video, track, &path, false))?;
|
||||
}
|
||||
paths.push(path);
|
||||
}
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
/// Cut `track` out of `video` into `path`, keeping the stream as it is (`copy`) or re-encoding
|
||||
/// it as AAC.
|
||||
fn cut_track(video: &str, track: usize, path: &Path, copy: bool) -> Result<(), String> {
|
||||
let mut command = FfmpegCommand::new();
|
||||
command
|
||||
.arg("-y")
|
||||
.arg("-i")
|
||||
.arg(video)
|
||||
.arg("-map")
|
||||
.arg(format!("0:a:{track}"))
|
||||
.arg("-vn");
|
||||
if copy {
|
||||
command.arg("-c:a").arg("copy");
|
||||
} else {
|
||||
command.arg("-c:a").arg("aac").arg("-b:a").arg("160k");
|
||||
}
|
||||
command.arg(path.to_string_lossy().to_string());
|
||||
|
||||
let mut errors = Vec::new();
|
||||
for event in command
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start ffmpeg: {e}"))?
|
||||
.iter()
|
||||
.map_err(|e| format!("cannot read ffmpeg output: {e}"))?
|
||||
{
|
||||
match event {
|
||||
FfmpegEvent::Error(e) => errors.push(e),
|
||||
FfmpegEvent::Log(LogLevel::Error, msg) => errors.push(msg),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
|
||||
if size == 0 {
|
||||
return Err(if errors.is_empty() {
|
||||
format!("audio track {track} came out empty")
|
||||
} else {
|
||||
errors.join("; ")
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sanitize(name: &str) -> String {
|
||||
name.chars()
|
||||
.map(|c| {
|
||||
if c.is_alphanumeric() || matches!(c, '-' | '_' | '.') {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{link_path, link_recording, recording_link};
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn a_link_file_names_the_recording_beside_its_clip() {
|
||||
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let clip = dir.join("My Ace.mp4");
|
||||
std::fs::write(&clip, b"").unwrap();
|
||||
assert_eq!(link_path(&clip), Path::new(&dir).join("My Ace.json"));
|
||||
assert_eq!(recording_link(&clip), None);
|
||||
assert!(link_recording(&clip, "demo-1"));
|
||||
assert_eq!(recording_link(&clip).as_deref(), Some("demo-1"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
//! Text formatting shared by the screens, matching the old Tauri app's `types/timeline.ts`.
|
||||
|
||||
use chrono::{DateTime, Local, Utc};
|
||||
|
||||
pub fn duration(secs: f64) -> String {
|
||||
let total = secs.max(0.0).round() as u64;
|
||||
format!("{}:{:02}", total / 60, total % 60)
|
||||
}
|
||||
|
||||
pub fn clock(secs: f64) -> String {
|
||||
let total = secs.max(0.0) as u64;
|
||||
format!("{}:{:02}", total / 60, total % 60)
|
||||
}
|
||||
|
||||
/// How long ago an exported file's stamp was: `2 hours ago`. A stamp that could not be read
|
||||
/// reads `earlier`.
|
||||
pub fn age(at: Option<std::time::SystemTime>) -> String {
|
||||
at.map(|at| relative_time(at.into()))
|
||||
.unwrap_or_else(|| "earlier".to_string())
|
||||
}
|
||||
|
||||
pub fn relative_time(when: DateTime<Utc>) -> String {
|
||||
let now = Utc::now();
|
||||
let delta = now.signed_duration_since(when);
|
||||
let days = delta.num_days();
|
||||
let local = when.with_timezone(&Local);
|
||||
if days > 7 {
|
||||
return local.format("%b %e, %Y, %H:%M").to_string();
|
||||
}
|
||||
if days > 0 {
|
||||
return format!("{days} day{} ago", plural(days));
|
||||
}
|
||||
let hours = delta.num_hours();
|
||||
if hours > 0 {
|
||||
return format!("{hours} hour{} ago", plural(hours));
|
||||
}
|
||||
let minutes = delta.num_minutes();
|
||||
if minutes > 0 {
|
||||
return format!("{minutes} minute{} ago", plural(minutes));
|
||||
}
|
||||
"Just now".into()
|
||||
}
|
||||
|
||||
pub fn game_start(when: DateTime<Utc>) -> String {
|
||||
let local = when.with_timezone(&Local);
|
||||
let now = Local::now();
|
||||
let day = local.date_naive();
|
||||
let time = local.format("%H:%M").to_string();
|
||||
if day == now.date_naive() {
|
||||
format!("Today at {time}")
|
||||
} else if day == now.date_naive() - chrono::Days::new(1) {
|
||||
format!("Yesterday at {time}")
|
||||
} else {
|
||||
format!("{} at {time}", local.format("%b %e"))
|
||||
}
|
||||
}
|
||||
|
||||
fn plural(n: i64) -> &'static str {
|
||||
if n == 1 { "" } else { "s" }
|
||||
}
|
||||
|
||||
pub fn kda_ratio(kills: u32, deaths: u32, assists: u32) -> String {
|
||||
let value = if deaths == 0 {
|
||||
(kills + assists) as f64
|
||||
} else {
|
||||
(kills + assists) as f64 / deaths as f64
|
||||
};
|
||||
format!("{value:.1}")
|
||||
}
|
||||
|
||||
pub fn cs_per_min(stats: &crate::history::Stats) -> String {
|
||||
if stats.game_duration == 0 {
|
||||
return "0.0".into();
|
||||
}
|
||||
format!(
|
||||
"{:.1}",
|
||||
stats.creep_score as f64 / (stats.game_duration as f64 / 60.0)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn gold_per_min(stats: &crate::history::Stats) -> String {
|
||||
if stats.game_duration == 0 {
|
||||
return "0".into();
|
||||
}
|
||||
let value = stats.gold_earned as f64 / (stats.game_duration as f64 / 60.0);
|
||||
number(value.round() as u64)
|
||||
}
|
||||
|
||||
/// A file size in round units: `14.2 MB`, or `812 kB` under a megabyte.
|
||||
pub fn bytes(n: u64) -> String {
|
||||
let mb = n as f64 / (1024.0 * 1024.0);
|
||||
if mb >= 1.0 {
|
||||
format!("{mb:.1} MB")
|
||||
} else {
|
||||
format!("{:.0} kB", n as f64 / 1024.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn number(n: u64) -> String {
|
||||
if n >= 1_000_000 {
|
||||
format!("{:.1}M", n as f64 / 1_000_000.0)
|
||||
} else if n >= 1_000 {
|
||||
format!("{:.1}K", n as f64 / 1_000.0)
|
||||
} else {
|
||||
n.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rank(tier: &str, division: &str) -> String {
|
||||
if tier.is_empty() || tier == "UNRANKED" {
|
||||
return "Unranked".into();
|
||||
}
|
||||
let mut chars = tier.chars();
|
||||
let tidy = match chars.next() {
|
||||
Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
|
||||
None => String::new(),
|
||||
};
|
||||
if division.is_empty() {
|
||||
tidy
|
||||
} else {
|
||||
format!("{tidy} {division}")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lp_delta(delta: i64) -> String {
|
||||
if delta > 0 {
|
||||
format!("+{delta}")
|
||||
} else {
|
||||
delta.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::history::Stats;
|
||||
|
||||
#[test]
|
||||
fn durations_read_as_minutes_and_seconds() {
|
||||
assert_eq!(duration(1830.0), "30:30");
|
||||
assert_eq!(duration(65.4), "1:05");
|
||||
assert_eq!(duration(-3.0), "0:00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kda_ratio_survives_zero_deaths() {
|
||||
assert_eq!(kda_ratio(9, 3, 7), "5.3");
|
||||
assert_eq!(kda_ratio(9, 0, 7), "16.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranks_are_tidied_for_people() {
|
||||
assert_eq!(rank("EMERALD", "II"), "Emerald II");
|
||||
assert_eq!(rank("UNRANKED", ""), "Unranked");
|
||||
assert_eq!(rank("GOLD", ""), "Gold");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_minute_stats_use_the_game_length() {
|
||||
let stats = Stats {
|
||||
creep_score: 200,
|
||||
gold_earned: 12_000,
|
||||
game_duration: 1200,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(cs_per_min(&stats), "10.0");
|
||||
assert_eq!(gold_per_min(&stats), "600");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
//! Highlight clips from timeline events, ported from `computeHighlights` in
|
||||
//! the old Tauri app's `types/timeline.ts`.
|
||||
|
||||
use crate::history::{Timeline, TimelineEvent};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Kill,
|
||||
Death,
|
||||
Assist,
|
||||
MultiKill,
|
||||
TradeKill,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Kill => "Kill",
|
||||
Kind::Death => "Death",
|
||||
Kind::Assist => "Assist",
|
||||
Kind::MultiKill => "Multi kill",
|
||||
Kind::TradeKill => "Trade kill",
|
||||
}
|
||||
}
|
||||
|
||||
fn priority(self) -> u8 {
|
||||
match self {
|
||||
Kind::MultiKill => 0,
|
||||
Kind::TradeKill => 1,
|
||||
Kind::Kill => 2,
|
||||
Kind::Death => 3,
|
||||
Kind::Assist => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Highlight {
|
||||
pub start: f64,
|
||||
pub end: f64,
|
||||
pub kind: Kind,
|
||||
pub title: String,
|
||||
pub subtitle: String,
|
||||
/// Timestamps of the events inside the clip, for markers.
|
||||
pub events: Vec<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Options {
|
||||
pub before: f64,
|
||||
pub after: f64,
|
||||
pub min_duration: f64,
|
||||
pub merge_overlapping: bool,
|
||||
pub merge_gap: f64,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
before: 10.0,
|
||||
after: 3.0,
|
||||
min_duration: 5.0,
|
||||
merge_overlapping: true,
|
||||
merge_gap: 5.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn string_at<'a>(event: &'a TimelineEvent, key: &str) -> Option<&'a str> {
|
||||
event.raw_data.get(key).and_then(|v| v.as_str())
|
||||
}
|
||||
|
||||
/// Whether a name from the live client data is the player. The timeline's summoner carries a
|
||||
/// `#TAG` (`Kai'Sa#EUW`) that the live client data's `KillerName` does not, so the tag is
|
||||
/// dropped before comparing.
|
||||
fn same_player(name: &str, player: &str) -> bool {
|
||||
fn base(n: &str) -> &str {
|
||||
n.split('#').next().unwrap_or(n).trim()
|
||||
}
|
||||
base(name).eq_ignore_ascii_case(base(player))
|
||||
}
|
||||
|
||||
/// How the player took part in a kill event, if at all.
|
||||
pub fn involvement(event: &TimelineEvent, player: &str) -> Option<Kind> {
|
||||
if string_at(event, "KillerName").is_some_and(|name| same_player(name, player)) {
|
||||
return Some(Kind::Kill);
|
||||
}
|
||||
if string_at(event, "VictimName").is_some_and(|name| same_player(name, player)) {
|
||||
return Some(Kind::Death);
|
||||
}
|
||||
let assist = event
|
||||
.raw_data
|
||||
.get("Assisters")
|
||||
.and_then(|v| v.as_array())
|
||||
.is_some_and(|names| {
|
||||
names
|
||||
.iter()
|
||||
.filter_map(|name| name.as_str())
|
||||
.any(|name| same_player(name, player))
|
||||
});
|
||||
if assist {
|
||||
return Some(Kind::Assist);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// One clip per involvement, then multi-kills, then a merge pass.
|
||||
pub fn compute(timeline: &Timeline, player: Option<&str>, options: Options) -> Vec<Highlight> {
|
||||
let Some(player) = player else {
|
||||
return Vec::new();
|
||||
};
|
||||
let duration = timeline.duration_secs.max(0) as f64;
|
||||
let kills = timeline.events.iter().filter(|e| e.event_type == "kill");
|
||||
|
||||
let mut clips: Vec<Highlight> = Vec::new();
|
||||
let mut player_kills: Vec<f64> = Vec::new();
|
||||
let mut player_deaths: Vec<f64> = Vec::new();
|
||||
|
||||
for event in kills {
|
||||
let Some(kind) = involvement(event, player) else {
|
||||
continue;
|
||||
};
|
||||
let at = event.time();
|
||||
let (title, subtitle) = match kind {
|
||||
Kind::Kill => (
|
||||
"Kill".to_string(),
|
||||
format!(
|
||||
"Killed {}",
|
||||
string_at(event, "VictimName").unwrap_or("an enemy")
|
||||
),
|
||||
),
|
||||
Kind::Death => (
|
||||
"Death".to_string(),
|
||||
format!(
|
||||
"Killed by {}",
|
||||
string_at(event, "KillerName").unwrap_or("an enemy")
|
||||
),
|
||||
),
|
||||
_ => (
|
||||
"Assist".to_string(),
|
||||
format!(
|
||||
"Assisted {} against {}",
|
||||
string_at(event, "KillerName").unwrap_or("an ally"),
|
||||
string_at(event, "VictimName").unwrap_or("an enemy")
|
||||
),
|
||||
),
|
||||
};
|
||||
match kind {
|
||||
Kind::Kill => player_kills.push(at),
|
||||
Kind::Death => player_deaths.push(at),
|
||||
_ => {}
|
||||
}
|
||||
clips.push(Highlight {
|
||||
start: (at - options.before).max(0.0),
|
||||
end: (at + options.after).min(if duration > 0.0 { duration } else { f64::MAX }),
|
||||
kind,
|
||||
title,
|
||||
subtitle,
|
||||
events: vec![at],
|
||||
});
|
||||
}
|
||||
|
||||
// Multi-kills: two or more of the player's kills within 12 s.
|
||||
player_kills.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
let mut i = 0;
|
||||
while i < player_kills.len() {
|
||||
let mut j = i;
|
||||
while j + 1 < player_kills.len() && player_kills[j + 1] - player_kills[j] <= 12.0 {
|
||||
j += 1;
|
||||
}
|
||||
let count = j - i + 1;
|
||||
if count >= 2 {
|
||||
let first = player_kills[i];
|
||||
let last = player_kills[j];
|
||||
let died = player_deaths
|
||||
.iter()
|
||||
.any(|d| *d >= first && *d <= last + 12.0);
|
||||
let (kind, title) = if died {
|
||||
(Kind::TradeKill, "Trade kill".to_string())
|
||||
} else {
|
||||
(Kind::MultiKill, multi_kill_label(count))
|
||||
};
|
||||
let subtitle = if died {
|
||||
format!("{count} kills but died in the trade")
|
||||
} else {
|
||||
format!("{count} kills in quick succession")
|
||||
};
|
||||
let mut events: Vec<f64> = player_kills[i..=j].to_vec();
|
||||
if died {
|
||||
events.extend(
|
||||
player_deaths
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|d| *d >= first && *d <= last + 12.0),
|
||||
);
|
||||
}
|
||||
let end = events.iter().cloned().fold(last, f64::max) + options.after;
|
||||
clips.push(Highlight {
|
||||
start: (first - options.before).max(0.0),
|
||||
end: end.min(if duration > 0.0 { duration } else { f64::MAX }),
|
||||
kind,
|
||||
title,
|
||||
subtitle,
|
||||
events,
|
||||
});
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
|
||||
clips.sort_by(|a, b| a.start.partial_cmp(&b.start).unwrap());
|
||||
|
||||
let mut merged: Vec<Highlight> = Vec::new();
|
||||
let mut iter = clips.into_iter();
|
||||
let Some(mut current) = iter.next() else {
|
||||
return Vec::new();
|
||||
};
|
||||
for next in iter {
|
||||
let joins = options.merge_overlapping && next.start <= current.end + options.merge_gap;
|
||||
if joins {
|
||||
current.end = current.end.max(next.end);
|
||||
current.events.extend(next.events.iter().copied());
|
||||
if next.kind.priority() < current.kind.priority() {
|
||||
current.kind = next.kind;
|
||||
current.title = next.title;
|
||||
current.subtitle = next.subtitle;
|
||||
}
|
||||
} else {
|
||||
merged.push(current);
|
||||
current = next;
|
||||
}
|
||||
}
|
||||
merged.push(current);
|
||||
|
||||
merged.retain(|c| c.end - c.start >= options.min_duration);
|
||||
merged
|
||||
}
|
||||
|
||||
fn multi_kill_label(count: usize) -> String {
|
||||
match count {
|
||||
2 => "Double kill".into(),
|
||||
3 => "Triple kill".into(),
|
||||
4 => "Quadra kill".into(),
|
||||
5 => "Penta kill".into(),
|
||||
n => format!("{n}x kill"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_sample_game_has_a_clip_for_each_involvement() {
|
||||
let game = &crate::history::sample()[0];
|
||||
let clips = compute(game, Some("Demo#EUW"), Options::default());
|
||||
assert_eq!(clips.len(), 3, "{clips:#?}");
|
||||
assert!(clips.iter().any(|c| c.kind == Kind::Death));
|
||||
assert!(clips.iter().all(|c| c.end > c.start));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tag_in_the_summoner_does_not_hide_the_player() {
|
||||
let game = &crate::history::sample()[0];
|
||||
let clips = compute(game, Some("Demo"), Options::default());
|
||||
assert_eq!(
|
||||
clips.len(),
|
||||
3,
|
||||
"the live client names carry no tag: {clips:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobody_named_means_no_clips() {
|
||||
let game = &crate::history::sample()[0];
|
||||
assert!(compute(game, None, Options::default()).is_empty());
|
||||
}
|
||||
}
|
||||
+1168
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,72 @@
|
||||
//! The few shapes the app draws itself: transport arrows, a play triangle and pause bars.
|
||||
//!
|
||||
//! Rune renders an [`Icon`] from SVG paths tinted with the element's colour, so these are plain
|
||||
//! geometry at a 16 point box and need no font behind them.
|
||||
|
||||
use rune::Icon;
|
||||
|
||||
pub static PLAY: Icon = Icon {
|
||||
name: "app-play",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M5.4 3.4 12.6 8 5.4 12.6Z" fill="currentColor"/>"#,
|
||||
};
|
||||
|
||||
pub static PAUSE: Icon = Icon {
|
||||
name: "app-pause",
|
||||
view: 16.0,
|
||||
body: r#"<rect x="5" y="3.6" width="2.4" height="8.8" rx="0.6" fill="currentColor"/><rect x="8.6" y="3.6" width="2.4" height="8.8" rx="0.6" fill="currentColor"/>"#,
|
||||
};
|
||||
|
||||
/// Two triangles pointing back: a step of ten seconds, as the button says.
|
||||
pub static BACK: Icon = Icon {
|
||||
name: "app-back",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M2.8 8 7.2 4.6v6.8Z" fill="currentColor"/><path d="M7.6 8 12 4.6v6.8Z" fill="currentColor"/>"#,
|
||||
};
|
||||
|
||||
pub static FORWARD: Icon = Icon {
|
||||
name: "app-forward",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M13.2 8 8.8 4.6v6.8Z" fill="currentColor"/><path d="M8.4 8 4 4.6v6.8Z" fill="currentColor"/>"#,
|
||||
};
|
||||
|
||||
/// One end of the clip: a single chevron, drawn on the scrubber over the knob.
|
||||
pub static CHEVRON_LEFT: Icon = Icon {
|
||||
name: "app-chevron-left",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M10 3.6 5.4 8 10 12.4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>"#,
|
||||
};
|
||||
|
||||
pub static CHEVRON_RIGHT: Icon = Icon {
|
||||
name: "app-chevron-right",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M6 3.6 10.6 8 6 12.4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>"#,
|
||||
};
|
||||
|
||||
/// A box with an arrow out of the top: the button that will share a clip.
|
||||
pub static SHARE: Icon = Icon {
|
||||
name: "app-share",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M8 9.4V2.4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M5.3 4.7 8 2l2.7 2.7" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M5.7 6.9H4.8c-1 0-1.8.8-1.8 1.8v3.5c0 1 .8 1.8 1.8 1.8h6.4c1 0 1.8-.8 1.8-1.8V8.7c0-1-.8-1.8-1.8-1.8h-.9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>"#,
|
||||
};
|
||||
|
||||
/// A speaker with sound waves: the clip plays its sound.
|
||||
pub static VOLUME: Icon = Icon {
|
||||
name: "app-volume",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M2.8 6.2h2.2L8 3.6v8.8L5 9.8H2.8Z" fill="currentColor"/><path d="M10.2 5.6a3.4 3.4 0 0 1 0 4.8" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><path d="M12 3.8a5.8 5.8 0 0 1 0 8.4" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/>"#,
|
||||
};
|
||||
|
||||
/// The same speaker crossed out: the clip is muted.
|
||||
pub static VOLUME_OFF: Icon = Icon {
|
||||
name: "app-volume-off",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M2.8 6.2h2.2L8 3.6v8.8L5 9.8H2.8Z" fill="currentColor"/><path d="M10.4 6 13.8 9.4M13.8 6 10.4 9.4" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/>"#,
|
||||
};
|
||||
|
||||
/// Three vertical dots: the button that opens a card's menu of actions.
|
||||
pub static DOTS: Icon = Icon {
|
||||
name: "app-dots",
|
||||
view: 16.0,
|
||||
body: r#"<circle cx="8" cy="3.6" r="1.7" fill="currentColor"/><circle cx="8" cy="8" r="1.7" fill="currentColor"/><circle cx="8" cy="12.4" r="1.7" fill="currentColor"/>"#,
|
||||
};
|
||||
+498
@@ -0,0 +1,498 @@
|
||||
//! Client for the record-daemon's IPC protocol.
|
||||
//!
|
||||
//! Ported from the old Tauri app's `daemon_ipc.rs`. The wire format is the daemon's
|
||||
//! (`record-daemon/src/ipc/protocol.rs`): one JSON object per line over a named pipe, a
|
||||
//! `request` answered by one `response` with the same id.
|
||||
//!
|
||||
//! Requests are async (tokio). The UI runs on rune's thread and never blocks, so a worker thread
|
||||
//! owns a current-thread runtime, executes one request at a time and pushes results into a queue
|
||||
//! that `poll` drains.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Protocol
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Message type, as the daemon's `MessageType`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MessageType {
|
||||
Request,
|
||||
Response,
|
||||
Notification,
|
||||
}
|
||||
|
||||
/// Commands the daemon accepts (`IpcCommand`, camelCase).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Command {
|
||||
GetSettings,
|
||||
UpdateSettings,
|
||||
ResetSettings,
|
||||
GetStatus,
|
||||
GetEncoders,
|
||||
GetAudioDevices,
|
||||
AddAudioSource,
|
||||
RemoveAudioSource { id: String },
|
||||
UpdateAudioSource,
|
||||
StartRecording,
|
||||
StopRecording,
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
/// Request envelope.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct IpcMessage {
|
||||
#[serde(rename = "type")]
|
||||
pub message_type: MessageType,
|
||||
pub id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub command: Option<Command>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub payload: Option<Value>,
|
||||
}
|
||||
|
||||
/// Response envelope.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct IpcResponse {
|
||||
pub request_id: String,
|
||||
pub success: bool,
|
||||
#[serde(default)]
|
||||
pub data: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// The pipe the daemon listens on. A scratch home, as scripts set, gets a pipe of its own.
|
||||
pub fn default_socket_path() -> PathBuf {
|
||||
let scratch = std::env::var_os(crate::daemon::HOME_ENV).is_some_and(|value| !value.is_empty());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if scratch {
|
||||
return PathBuf::from(r"\\.\pipe\record-daemon-scratch");
|
||||
}
|
||||
PathBuf::from(r"\\.\pipe\record-daemon")
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let name = if scratch {
|
||||
"record-daemon-scratch.sock"
|
||||
} else {
|
||||
"record-daemon.sock"
|
||||
};
|
||||
let dir = std::env::var("XDG_RUNTIME_DIR").unwrap_or_else(|_| "/tmp".into());
|
||||
Path::new(&dir).join(name)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Client
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub struct Client {
|
||||
path: PathBuf,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
path: default_socket_path(),
|
||||
timeout: Duration::from_secs(5),
|
||||
}
|
||||
}
|
||||
|
||||
/// Send one command and wait for its answer.
|
||||
pub async fn call(&self, command: Command, payload: Option<Value>) -> Result<Value, String> {
|
||||
let message = IpcMessage {
|
||||
message_type: MessageType::Request,
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
command: Some(command),
|
||||
payload,
|
||||
};
|
||||
let json = serde_json::to_string(&message).map_err(|e| format!("serialize: {e}"))?;
|
||||
let line = self.round_trip(&json).await?;
|
||||
let response: IpcResponse =
|
||||
serde_json::from_str(&line).map_err(|e| format!("parse response: {e}"))?;
|
||||
if response.success {
|
||||
Ok(response.data.unwrap_or(Value::Null))
|
||||
} else {
|
||||
Err(response
|
||||
.error
|
||||
.unwrap_or_else(|| "daemon returned an error".into()))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn is_running(&self) -> bool {
|
||||
self.call(Command::GetStatus, None).await.is_ok()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
async fn round_trip(&self, message: &str) -> Result<String, String> {
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::windows::named_pipe::ClientOptions;
|
||||
|
||||
let pipe = self.path.to_string_lossy().to_string();
|
||||
let client = tokio::time::timeout(self.timeout, async {
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
match ClientOptions::new().open(&pipe) {
|
||||
Ok(client) => return Ok(client),
|
||||
// ERROR_PIPE_BUSY: every instance is serving another client.
|
||||
Err(e) if e.raw_os_error() == Some(231) => {
|
||||
attempts += 1;
|
||||
if attempts > 5 {
|
||||
return Err(format!("daemon pipe busy: {e}"));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Err(e) => return Err(format!("cannot connect to daemon: {e}")),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "connecting to the daemon timed out".to_string())??;
|
||||
|
||||
let (reader, mut writer) = tokio::io::split(client);
|
||||
writer
|
||||
.write_all(message.as_bytes())
|
||||
.await
|
||||
.map_err(|e| format!("write: {e}"))?;
|
||||
writer
|
||||
.write_all(b"\n")
|
||||
.await
|
||||
.map_err(|e| format!("write: {e}"))?;
|
||||
writer.flush().await.map_err(|e| format!("flush: {e}"))?;
|
||||
|
||||
let mut lines = BufReader::new(reader).lines();
|
||||
let line = tokio::time::timeout(self.timeout, lines.next_line())
|
||||
.await
|
||||
.map_err(|_| "the daemon did not answer in time".to_string())?
|
||||
.map_err(|e| format!("read: {e}"))?;
|
||||
line.ok_or_else(|| "the daemon closed the pipe without answering".to_string())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
async fn round_trip(&self, message: &str) -> Result<String, String> {
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
let stream = tokio::time::timeout(self.timeout, UnixStream::connect(&self.path))
|
||||
.await
|
||||
.map_err(|_| "connecting to the daemon timed out".to_string())?
|
||||
.map_err(|e| format!("cannot connect to daemon: {e}"))?;
|
||||
let (reader, mut writer) = stream.into_split();
|
||||
writer
|
||||
.write_all(message.as_bytes())
|
||||
.await
|
||||
.map_err(|e| format!("write: {e}"))?;
|
||||
writer
|
||||
.write_all(b"\n")
|
||||
.await
|
||||
.map_err(|e| format!("write: {e}"))?;
|
||||
writer.flush().await.map_err(|e| format!("flush: {e}"))?;
|
||||
let mut lines = BufReader::new(reader).lines();
|
||||
let line = tokio::time::timeout(self.timeout, lines.next_line())
|
||||
.await
|
||||
.map_err(|_| "the daemon did not answer in time".to_string())?
|
||||
.map_err(|e| format!("read: {e}"))?;
|
||||
line.ok_or_else(|| "the daemon closed the socket without answering".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Background worker
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// What a queued request is for, so `poll` can route its answer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Request {
|
||||
EnsureRunning,
|
||||
Settings,
|
||||
SaveSettings,
|
||||
ResetSettings,
|
||||
Status,
|
||||
Encoders,
|
||||
AudioDevices,
|
||||
AddAudioSource,
|
||||
RemoveAudioSource,
|
||||
UpdateAudioSource,
|
||||
StartRecording,
|
||||
StopRecording,
|
||||
Shutdown,
|
||||
Logs,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
request: Request,
|
||||
command: Command,
|
||||
payload: Option<Value>,
|
||||
}
|
||||
|
||||
/// An answer from the worker thread.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Event {
|
||||
pub request: Request,
|
||||
pub result: Result<Value, String>,
|
||||
}
|
||||
|
||||
/// A cloneable handle to the worker thread.
|
||||
#[derive(Clone)]
|
||||
pub struct Daemon {
|
||||
jobs: Sender<Job>,
|
||||
events: Arc<Mutex<Receiver<Event>>>,
|
||||
waker: Arc<Mutex<Option<rune::Waker>>>,
|
||||
/// Headless runs keep no worker and send nothing.
|
||||
off: bool,
|
||||
}
|
||||
|
||||
impl Daemon {
|
||||
/// Start the worker. It also brings the daemon process up on first use.
|
||||
/// A headless run (`--snap` and friends) starts nothing and talks to nobody.
|
||||
pub fn start(headless: bool) -> Self {
|
||||
let (job_tx, job_rx) = channel::<Job>();
|
||||
let (event_tx, event_rx) = channel::<Event>();
|
||||
let waker: Arc<Mutex<Option<rune::Waker>>> = Arc::new(Mutex::new(None));
|
||||
let worker_waker = waker.clone();
|
||||
if headless {
|
||||
return Self {
|
||||
jobs: job_tx,
|
||||
events: Arc::new(Mutex::new(event_rx)),
|
||||
waker,
|
||||
off: true,
|
||||
};
|
||||
}
|
||||
|
||||
std::thread::Builder::new()
|
||||
.name("daemon-ipc".into())
|
||||
.spawn(move || {
|
||||
let runtime = match tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
{
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
let _ = event_tx.send(Event {
|
||||
request: Request::EnsureRunning,
|
||||
result: Err(format!("no async runtime: {e}")),
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
let client = Client::new();
|
||||
// Bring the daemon up before the first request. It takes a few seconds to
|
||||
// initialise OBS, so this must not run on the UI thread.
|
||||
let started = runtime
|
||||
.block_on(crate::daemon::ensure_running())
|
||||
.map(|_| Value::Null);
|
||||
let _ = event_tx.send(Event {
|
||||
request: Request::EnsureRunning,
|
||||
result: started,
|
||||
});
|
||||
wake(&worker_waker);
|
||||
|
||||
while let Ok(job) = job_rx.recv() {
|
||||
let result = match job.request {
|
||||
Request::EnsureRunning => runtime
|
||||
.block_on(crate::daemon::ensure_running())
|
||||
.map(|_| Value::Null),
|
||||
Request::Logs => crate::daemon::read_logs(200).map(Value::String),
|
||||
_ => runtime.block_on(client.call(job.command, job.payload)),
|
||||
};
|
||||
let _ = event_tx.send(Event {
|
||||
request: job.request,
|
||||
result,
|
||||
});
|
||||
wake(&worker_waker);
|
||||
}
|
||||
})
|
||||
.expect("spawn daemon worker");
|
||||
|
||||
Self {
|
||||
jobs: job_tx,
|
||||
events: Arc::new(Mutex::new(event_rx)),
|
||||
waker,
|
||||
off: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The waker rune hands to `AppSpec::setup`.
|
||||
pub fn set_waker(&self, waker: rune::Waker) {
|
||||
*self.waker.lock().unwrap() = Some(waker);
|
||||
}
|
||||
|
||||
fn send(&self, request: Request, command: Command, payload: Option<Value>) {
|
||||
if self.off {
|
||||
return;
|
||||
}
|
||||
let _ = self.jobs.send(Job {
|
||||
request,
|
||||
command,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn get_settings(&self) {
|
||||
self.send(Request::Settings, Command::GetSettings, None);
|
||||
}
|
||||
|
||||
pub fn save_settings(&self, settings: Value) {
|
||||
self.send(
|
||||
Request::SaveSettings,
|
||||
Command::UpdateSettings,
|
||||
Some(settings),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn reset_settings(&self) {
|
||||
self.send(Request::ResetSettings, Command::ResetSettings, None);
|
||||
}
|
||||
|
||||
pub fn get_status(&self) {
|
||||
self.send(Request::Status, Command::GetStatus, None);
|
||||
}
|
||||
|
||||
pub fn get_encoders(&self) {
|
||||
self.send(Request::Encoders, Command::GetEncoders, None);
|
||||
}
|
||||
|
||||
pub fn get_audio_devices(&self) {
|
||||
self.send(Request::AudioDevices, Command::GetAudioDevices, None);
|
||||
}
|
||||
|
||||
pub fn add_audio_source(&self, source: Value) {
|
||||
self.send(
|
||||
Request::AddAudioSource,
|
||||
Command::AddAudioSource,
|
||||
Some(source),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn remove_audio_source(&self, id: &str) {
|
||||
self.send(
|
||||
Request::RemoveAudioSource,
|
||||
Command::RemoveAudioSource { id: id.to_string() },
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn update_audio_source(&self, source: Value) {
|
||||
self.send(
|
||||
Request::UpdateAudioSource,
|
||||
Command::UpdateAudioSource,
|
||||
Some(source),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn start_recording(&self) {
|
||||
self.send(Request::StartRecording, Command::StartRecording, None);
|
||||
}
|
||||
|
||||
pub fn stop_recording(&self) {
|
||||
self.send(Request::StopRecording, Command::StopRecording, None);
|
||||
}
|
||||
|
||||
pub fn shutdown(&self) {
|
||||
self.send(Request::Shutdown, Command::Shutdown, None);
|
||||
}
|
||||
|
||||
pub fn ensure_running(&self) {
|
||||
self.send(Request::EnsureRunning, Command::GetStatus, None);
|
||||
}
|
||||
|
||||
pub fn logs(&self) {
|
||||
self.send(Request::Logs, Command::GetStatus, None);
|
||||
}
|
||||
|
||||
/// Answers that arrived since the last frame, without blocking.
|
||||
pub fn drain(&self) -> Vec<Event> {
|
||||
let rx = self.events.lock().unwrap();
|
||||
let mut out = Vec::new();
|
||||
while let Ok(event) = rx.try_recv() {
|
||||
out.push(event);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn wake(waker: &Mutex<Option<rune::Waker>>) {
|
||||
if let Some(w) = waker.lock().unwrap().as_ref() {
|
||||
w();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn request(command: Command, payload: Option<Value>) -> Value {
|
||||
let message = IpcMessage {
|
||||
message_type: MessageType::Request,
|
||||
id: "00000000-0000-4000-8000-000000000000".into(),
|
||||
command: Some(command),
|
||||
payload,
|
||||
};
|
||||
serde_json::to_value(message).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_unit_command_is_a_plain_string() {
|
||||
assert_eq!(
|
||||
request(Command::GetSettings, None),
|
||||
json!({
|
||||
"type": "request",
|
||||
"id": "00000000-0000-4000-8000-000000000000",
|
||||
"command": "getSettings"
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_with_a_field_is_an_object() {
|
||||
assert_eq!(
|
||||
request(Command::RemoveAudioSource { id: "abc".into() }, None),
|
||||
json!({
|
||||
"type": "request",
|
||||
"id": "00000000-0000-4000-8000-000000000000",
|
||||
"command": {"removeAudioSource": {"id": "abc"}}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_go_in_the_payload_untouched() {
|
||||
let payload = json!({"video": {"frame_rate": 60}});
|
||||
assert_eq!(
|
||||
request(Command::UpdateSettings, Some(payload.clone()))["payload"],
|
||||
payload
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responses_parse_with_and_without_data() {
|
||||
let ok: IpcResponse =
|
||||
serde_json::from_str(r#"{"request_id":"x","success":true,"data":{"a":1}}"#).unwrap();
|
||||
assert!(ok.success);
|
||||
assert_eq!(ok.data.unwrap()["a"], 1);
|
||||
|
||||
let err: IpcResponse =
|
||||
serde_json::from_str(r#"{"request_id":"x","success":false,"error":"nope"}"#).unwrap();
|
||||
assert!(!err.success);
|
||||
assert_eq!(err.error.as_deref(), Some("nope"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pipe_name_matches_the_daemon() {
|
||||
assert_eq!(
|
||||
default_socket_path().to_string_lossy(),
|
||||
r"\\.\pipe\record-daemon"
|
||||
);
|
||||
}
|
||||
}
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
//! League Recorder: a native desktop app for the record-daemon.
|
||||
//!
|
||||
//! Replaces the old Tauri app. The daemon keeps its IPC protocol; this app is a client of it.
|
||||
//! `cargo run` opens the window; `cargo run -- --snap out.png` renders it headless.
|
||||
//!
|
||||
//! The binary is a windowed app on Windows, so launching it from Explorer, the Run key or the
|
||||
//! login item never opens a console. The printing modes (`--games`, `--probe`, `--snap`) borrow
|
||||
//! the console of the shell that started them (`attach_console`).
|
||||
#![cfg_attr(target_os = "windows", windows_subsystem = "windows")]
|
||||
|
||||
mod app;
|
||||
mod daemon;
|
||||
mod export;
|
||||
mod format;
|
||||
mod highlight;
|
||||
mod history;
|
||||
mod icons;
|
||||
mod ipc;
|
||||
mod os;
|
||||
mod portraits;
|
||||
mod process;
|
||||
mod screens;
|
||||
mod settings;
|
||||
mod theme;
|
||||
mod ui;
|
||||
|
||||
/// Print to the shell that started this app, when there is one.
|
||||
///
|
||||
/// A windowed process has no console of its own, so `println!` from `--probe` or `--snap` would
|
||||
/// go nowhere under `cmd`. The shell's console is still there to attach to; when the app is
|
||||
/// started from Explorer or the login item there is none and this does nothing.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn attach_console() {
|
||||
use windows::Win32::System::Console::{ATTACH_PARENT_PROCESS, AttachConsole};
|
||||
unsafe {
|
||||
let _ = AttachConsole(ATTACH_PARENT_PROCESS);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn attach_console() {}
|
||||
|
||||
use rune::AppSpec;
|
||||
|
||||
/// `--scene recording-live`: the daemon recording, with the sample game on the screen.
|
||||
fn demo_recording(app: &mut app::App) {
|
||||
app.status = app::Status {
|
||||
status: "recording".into(),
|
||||
is_recording: true,
|
||||
current_game_id: Some(7_000_000),
|
||||
client_connected: true,
|
||||
};
|
||||
screens::recording::demo(app);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
attach_console();
|
||||
if std::env::args().any(|arg| arg == "--games") {
|
||||
println!("{} timelines", crate::history::timeline_paths().len());
|
||||
return;
|
||||
}
|
||||
if std::env::args().any(|arg| arg == "--probe") {
|
||||
probe();
|
||||
return;
|
||||
}
|
||||
// `--fetch-ffmpeg`: download ffmpeg beside the exe and exit, 0 when it is ready. The app
|
||||
// does this itself on the first run; this is the same fetch, for a shortcut or a script.
|
||||
if std::env::args().any(|arg| arg == "--fetch-ffmpeg") {
|
||||
fetch_ffmpeg();
|
||||
return;
|
||||
}
|
||||
// A second launch hands its arguments to the first and exits; the tooling modes
|
||||
// (`--snap`, `--tree`, that sort of thing) render or print and exit, so they never forward.
|
||||
if !app::headless() && !rune::single_instance(os::APP_ID) {
|
||||
return;
|
||||
}
|
||||
os::set_app_icon();
|
||||
os::register_notifications();
|
||||
rune_notify::on_click(|_| rune_notify::bring_to_front());
|
||||
|
||||
let mut hidden = false;
|
||||
let args: Vec<String> = std::env::args()
|
||||
.filter(|arg| {
|
||||
if arg == "--hidden" {
|
||||
hidden = true;
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
rune::App::new(AppSpec {
|
||||
scenes: &[
|
||||
("history", |_app: &mut app::App| {}),
|
||||
("recording-live", |app| {
|
||||
demo_recording(app);
|
||||
app.jump(app::Screen::Recording);
|
||||
}),
|
||||
("recording-live-delete", |app| {
|
||||
demo_recording(app);
|
||||
app.jump(app::Screen::Recording);
|
||||
app.recording.confirm_delete = true;
|
||||
}),
|
||||
("recording-idle", |app| app.jump(app::Screen::Recording)),
|
||||
("settings", |app| app.jump(app::Screen::Settings)),
|
||||
("recording", |app| {
|
||||
app.jump(app::Screen::Settings);
|
||||
app.settings_tab = app::SettingsTab::Recording;
|
||||
}),
|
||||
("audio", |app| {
|
||||
app.jump(app::Screen::Settings);
|
||||
app.settings_tab = app::SettingsTab::Audio;
|
||||
}),
|
||||
("add-app", |app| {
|
||||
app.jump(app::Screen::Settings);
|
||||
app.settings_tab = app::SettingsTab::Audio;
|
||||
app.form.open_add();
|
||||
app.form.source_name = rune::TextEdit::new("Discord");
|
||||
app.form.source_device = rune::TextEdit::new("Discord.exe");
|
||||
}),
|
||||
("delete", |app| {
|
||||
app.confirm_delete = app.games.first().map(|game| game.recording_id.clone());
|
||||
}),
|
||||
("daemon", |app| {
|
||||
app.jump(app::Screen::Settings);
|
||||
app.settings_tab = app::SettingsTab::Advanced;
|
||||
}),
|
||||
("review", |app| app::demo_review(app)),
|
||||
("details", |app| {
|
||||
app::demo_review(app);
|
||||
app.review.show_details = true;
|
||||
}),
|
||||
("review-full", |app| {
|
||||
app::demo_review(app);
|
||||
app.review.fullscreen = true;
|
||||
}),
|
||||
("clips-empty", |app| {
|
||||
app.jump(app::Screen::Clips);
|
||||
app.clips.clear();
|
||||
app.clips_loaded = true;
|
||||
}),
|
||||
("clips", |app| {
|
||||
app.jump(app::Screen::Clips);
|
||||
app.clips_menu_open = None;
|
||||
app.spawn_thumbs();
|
||||
}),
|
||||
("clip", |app| {
|
||||
// Demo clips come with the app; live ones need the folder listed first.
|
||||
if app.clips.is_empty() {
|
||||
app.refresh_clips();
|
||||
}
|
||||
// The grid is where a clip is opened from: the back arrow leads to it.
|
||||
app.jump(app::Screen::Clips);
|
||||
app.spawn_thumbs();
|
||||
if let Some(first) = app.clips.first().cloned() {
|
||||
screens::clip::open(app, &first.name);
|
||||
}
|
||||
}),
|
||||
("clips-many", |app| {
|
||||
app.jump(app::Screen::Clips);
|
||||
app.spawn_thumbs();
|
||||
app.clips = (0..12)
|
||||
.flat_map(|page| {
|
||||
[
|
||||
app::App::demo_clip(format!("page-{page}-clip"), page, 18_000_000),
|
||||
app::App::demo_clip(format!("baron-{page}"), page, 8_400_000),
|
||||
app::App::demo_clip(format!("drake-{page}"), page, 11_100_000),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
app.clips_loaded = true;
|
||||
}),
|
||||
("clips-delete", |app| {
|
||||
app.jump(app::Screen::Clips);
|
||||
app.spawn_thumbs();
|
||||
app.confirm_clip_delete = app.clips.first().map(|clip| clip.name.clone());
|
||||
}),
|
||||
("many", |app| {
|
||||
app.jump(app::Screen::History);
|
||||
app.games = (0..30)
|
||||
.flat_map(|_| crate::history::sample())
|
||||
.map(|game| game.summary())
|
||||
.collect();
|
||||
app.games_loaded = true;
|
||||
}),
|
||||
],
|
||||
setup: Some(app::setup),
|
||||
poll: Some(app::poll),
|
||||
on_key: Some(app::on_key),
|
||||
// Narrower than this, the title bar's own buttons would run under the window's
|
||||
// caption buttons.
|
||||
min_size: Some((640.0, 480.0)),
|
||||
..AppSpec::new("League Recorder", (1200.0, 800.0), app::App::new, app::view)
|
||||
})
|
||||
.args(args)
|
||||
// The app draws the title bar itself, so the window keeps no native caption: Rune draws the
|
||||
// caption buttons over the bar's right edge and keeps Windows' resize edges and snap.
|
||||
.titlebar(rune::Titlebar::new(app::TITLEBAR_HEIGHT))
|
||||
.keep_running()
|
||||
.on_close(app::window_closed)
|
||||
.on_quit(app::window_closed)
|
||||
.on_ready(move |handle| {
|
||||
app::remember_window(handle);
|
||||
if hidden {
|
||||
handle.hide();
|
||||
}
|
||||
})
|
||||
.run();
|
||||
}
|
||||
|
||||
/// `--fetch-ffmpeg`: download ffmpeg with the same code the first run uses, printing progress.
|
||||
fn fetch_ffmpeg() {
|
||||
let shown = std::cell::Cell::new(u64::MAX);
|
||||
let result = export::fetch(|event| match event {
|
||||
export::FetchEvent::Bytes { done, total } => {
|
||||
let pct = (done * 100).checked_div(total).unwrap_or(0);
|
||||
if pct != shown.get() {
|
||||
shown.set(pct);
|
||||
println!("ffmpeg: {pct}%");
|
||||
}
|
||||
}
|
||||
export::FetchEvent::Unpacking => println!("ffmpeg: unpacking"),
|
||||
export::FetchEvent::Finished(_) => {}
|
||||
});
|
||||
match result {
|
||||
Ok(()) => println!("ffmpeg: ready"),
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `--probe`: bring the daemon up and print what it answers, then exit. A quick check that the
|
||||
/// IPC client and the daemon agree without opening a window.
|
||||
fn probe() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("async runtime");
|
||||
runtime.block_on(async {
|
||||
match daemon::ensure_running().await {
|
||||
Ok(()) => println!("daemon: ready"),
|
||||
Err(e) => {
|
||||
println!("daemon: {e}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
let client = ipc::Client::new();
|
||||
for (name, command) in [
|
||||
("status", ipc::Command::GetStatus),
|
||||
("settings", ipc::Command::GetSettings),
|
||||
("encoders", ipc::Command::GetEncoders),
|
||||
("audioDevices", ipc::Command::GetAudioDevices),
|
||||
] {
|
||||
match client.call(command, None).await {
|
||||
Ok(data) => println!("{name}: {data}"),
|
||||
Err(e) => println!("{name}: error: {e}"),
|
||||
}
|
||||
}
|
||||
// Parse with the app model, which is what the settings screen receives.
|
||||
match client.call(ipc::Command::GetSettings, None).await {
|
||||
Ok(data) => match crate::settings::from_response(&data) {
|
||||
Ok(settings) => println!(
|
||||
"parsed: {} fps, {:?}, {} application sources, encoder {}",
|
||||
settings.video.frame_rate,
|
||||
settings.video.quality,
|
||||
settings.audio.capture_apps.len(),
|
||||
settings.video.encoder_preset.encoder_id(),
|
||||
),
|
||||
Err(e) => println!("parsed: failed: {e}"),
|
||||
},
|
||||
Err(e) => println!("parsed: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
//! Windows integration that the old Tauri app got from plugins: launch at login, one instance,
|
||||
//! toast notifications and the tray icon.
|
||||
|
||||
/// The app's reverse-DNS id, used for single-instance and notifications.
|
||||
pub const APP_ID: &str = "v.leaguerecorder";
|
||||
pub const APP_NAME: &str = "League Recorder";
|
||||
|
||||
#[cfg(windows)]
|
||||
const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
|
||||
#[cfg(windows)]
|
||||
const RUN_VALUE: &str = "LeagueRecorder";
|
||||
|
||||
/// Launch at login writes the executable into the user's `Run` key.
|
||||
#[cfg(windows)]
|
||||
pub fn autostart_enabled() -> bool {
|
||||
use winreg::RegKey;
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
let Ok(key) = RegKey::predef(HKEY_CURRENT_USER).open_subkey(RUN_KEY) else {
|
||||
return false;
|
||||
};
|
||||
key.get_value::<String, _>(RUN_VALUE).is_ok()
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn autostart_enabled() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set_autostart(on: bool) -> Result<(), String> {
|
||||
use winreg::RegKey;
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
let (key, _) = hkcu
|
||||
.create_subkey(RUN_KEY)
|
||||
.map_err(|e| format!("cannot open the Run key: {e}"))?;
|
||||
if on {
|
||||
let exe =
|
||||
std::env::current_exe().map_err(|e| format!("cannot find the executable: {e}"))?;
|
||||
let value = format!("\"{}\" --hidden", exe.display());
|
||||
key.set_value(RUN_VALUE, &value)
|
||||
.map_err(|e| format!("cannot write the Run key: {e}"))
|
||||
} else {
|
||||
match key.delete_value(RUN_VALUE) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(e) => Err(format!("cannot remove the Run value: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn set_autostart(_on: bool) -> Result<(), String> {
|
||||
Err("launch at login is implemented for Windows only".into())
|
||||
}
|
||||
|
||||
/// Register the app so Windows can show its toasts, and group its windows on the taskbar.
|
||||
pub fn register_notifications() {
|
||||
let identity = rune_notify::Identity::new(APP_ID, APP_NAME);
|
||||
if let Err(e) = rune_notify::register(&identity) {
|
||||
eprintln!("notifications unavailable: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Post a toast, unless a window already has the user's attention.
|
||||
pub fn notify(id: &str, title: &str, body: &str) {
|
||||
if rune_notify::app_focused() {
|
||||
return;
|
||||
}
|
||||
let notification = rune_notify::Notification::new(id, title).body(body);
|
||||
rune_notify::post(¬ification);
|
||||
}
|
||||
|
||||
/// The app's icon for the title bar, the taskbar and Alt+Tab: the same medallion the exe
|
||||
/// carries and the installer shows. Call once at startup, before the event loop; rune sizes
|
||||
/// it for each use and a headless run sets nothing.
|
||||
pub fn set_app_icon() {
|
||||
let bytes = include_bytes!("../icons/icon_full.png").as_slice();
|
||||
if let Err(e) = rune::set_app_icon(bytes) {
|
||||
eprintln!("app icon unavailable: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A 32 px tray icon: the app's medallion, or a plain red disc while the daemon records.
|
||||
pub fn tray_icon(recording: bool) -> rune::TrayIcon {
|
||||
let (width, height, pixels) = if recording {
|
||||
recording_pixels()
|
||||
} else {
|
||||
medallion_pixels()
|
||||
};
|
||||
rune::TrayIcon::rgba(width, height, pixels)
|
||||
}
|
||||
|
||||
/// The medallion at its bundled 32 px: straight RGBA rows for [`rune::TrayIcon`].
|
||||
fn medallion_pixels() -> (u32, u32, Vec<u8>) {
|
||||
let image = image::load_from_memory(include_bytes!("../icons/32x32.png"))
|
||||
.expect("the bundled tray icon decodes")
|
||||
.into_rgba8();
|
||||
(image.width(), image.height(), image.into_raw())
|
||||
}
|
||||
|
||||
/// A red disc on clear pixels. The edge gets one pixel of coverage, so a tray that scales the
|
||||
/// icon down to 16 px does not show a jagged ring.
|
||||
fn recording_pixels() -> (u32, u32, Vec<u8>) {
|
||||
const SIZE: u32 = 32;
|
||||
const RADIUS: f32 = 11.0;
|
||||
const RED: [u8; 3] = [220, 38, 38];
|
||||
let center = SIZE as f32 / 2.0;
|
||||
let mut pixels = Vec::with_capacity((SIZE * SIZE * 4) as usize);
|
||||
for y in 0..SIZE {
|
||||
for x in 0..SIZE {
|
||||
let dx = x as f32 + 0.5 - center;
|
||||
let dy = y as f32 + 0.5 - center;
|
||||
let distance = (dx * dx + dy * dy).sqrt();
|
||||
let alpha = ((RADIUS + 0.5 - distance).clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
pixels.extend_from_slice(&[RED[0], RED[1], RED[2], alpha]);
|
||||
}
|
||||
}
|
||||
(SIZE, SIZE, pixels)
|
||||
}
|
||||
|
||||
/// The tray menu. `recording` flips the record item's label.
|
||||
pub fn tray_menu(recording: bool) -> Vec<rune::TrayItem> {
|
||||
vec![
|
||||
rune::TrayItem::action("show", "Open League Recorder"),
|
||||
rune::TrayItem::action("hide", "Hide window"),
|
||||
rune::TrayItem::Separator,
|
||||
rune::TrayItem::action(
|
||||
"record",
|
||||
if recording {
|
||||
"Stop recording"
|
||||
} else {
|
||||
"Start recording"
|
||||
},
|
||||
),
|
||||
rune::TrayItem::Separator,
|
||||
rune::TrayItem::action("quit", "Quit"),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_tray_icon_decodes_to_32_px_of_rgba() {
|
||||
let (width, height, pixels) = medallion_pixels();
|
||||
assert_eq!((width, height), (32, 32));
|
||||
assert_eq!(pixels.len(), (32 * 32 * 4) as usize);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_recording_icon_is_a_red_disc_on_a_clear_square() {
|
||||
let (width, height, pixels) = recording_pixels();
|
||||
assert_eq!((width, height), (32, 32));
|
||||
let at = |x: usize, y: usize| {
|
||||
let i = (y * 32 + x) * 4;
|
||||
[pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
|
||||
};
|
||||
assert_eq!(at(16, 16), [220, 38, 38, 255]);
|
||||
assert_eq!(at(0, 0)[3], 0);
|
||||
assert_eq!(at(31, 16)[3], 0);
|
||||
assert!(
|
||||
pixels
|
||||
.chunks_exact(4)
|
||||
.filter(|p| p[3] == 255)
|
||||
.all(|p| p[..3] == [220, 38, 38])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Champion portraits, fetched from Data Dragon and cached on disk.
|
||||
//!
|
||||
//! Rune decodes images but has no HTTP client on native, so the bytes come down here first. A
|
||||
//! portrait is drawn as soon as it is on disk, and the app redraws when a download lands.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Riot's public asset CDN.
|
||||
const HOST: &str = "https://ddragon.leagueoflegends.com";
|
||||
|
||||
/// The champion list: Data Dragon ids ("Kaisa") by display name ("Kai'Sa"), for one patch.
|
||||
#[derive(Clone, serde::Deserialize, serde::Serialize)]
|
||||
struct Catalog {
|
||||
version: String,
|
||||
ids: HashMap<String, String>,
|
||||
}
|
||||
|
||||
/// Where the portraits and the champion list are cached.
|
||||
fn cache_dir() -> PathBuf {
|
||||
directories::ProjectDirs::from("com", "leaguerecorder", "leaguerecorder")
|
||||
.map(|dirs| dirs.cache_dir().join("portraits"))
|
||||
.unwrap_or_else(|| PathBuf::from("./portraits"))
|
||||
}
|
||||
|
||||
/// Champion portraits drawn from the cache, with the missing ones fetched in the background.
|
||||
pub struct Portraits {
|
||||
dir: PathBuf,
|
||||
images: rune::ImageCache,
|
||||
catalog: Arc<Mutex<Option<Catalog>>>,
|
||||
asked: Mutex<HashSet<String>>,
|
||||
tx: Sender<String>,
|
||||
}
|
||||
|
||||
impl Portraits {
|
||||
pub fn new(waker: rune::Waker) -> Self {
|
||||
let dir = cache_dir();
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let catalog = Arc::new(Mutex::new(read_catalog(&dir)));
|
||||
let (tx, rx) = channel();
|
||||
let worker = Worker {
|
||||
dir: dir.clone(),
|
||||
catalog: catalog.clone(),
|
||||
wake: waker.clone(),
|
||||
};
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("portraits".into())
|
||||
.spawn(move || worker.run(rx));
|
||||
if spawned.is_err() {
|
||||
eprintln!("portrait downloads are unavailable");
|
||||
}
|
||||
Self {
|
||||
dir,
|
||||
images: rune::ImageCache::new(waker),
|
||||
catalog,
|
||||
asked: Mutex::new(HashSet::new()),
|
||||
tx,
|
||||
}
|
||||
}
|
||||
|
||||
/// The portrait for a champion's display name at `size` points, once it is on disk. A
|
||||
/// missing one is queued and the app redraws when it arrives.
|
||||
pub fn image(&self, champion: &str, size: f32, scale: f32) -> Option<rune::Image> {
|
||||
let champion = champion.trim();
|
||||
if champion.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = {
|
||||
let catalog = self.catalog.lock().unwrap();
|
||||
let Some(catalog) = catalog.as_ref() else {
|
||||
drop(catalog);
|
||||
self.ask(champion);
|
||||
return None;
|
||||
};
|
||||
let id = catalog.ids.get(champion)?;
|
||||
self.dir.join(format!("{id}.png"))
|
||||
};
|
||||
if !path.is_file() {
|
||||
self.ask(champion);
|
||||
return None;
|
||||
}
|
||||
Some(self.images.file(&path, size, scale))
|
||||
}
|
||||
|
||||
fn ask(&self, champion: &str) {
|
||||
if self.asked.lock().unwrap().insert(champion.to_string()) {
|
||||
let _ = self.tx.send(champion.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The cache's background thread: the champion list first, then one portrait at a time.
|
||||
struct Worker {
|
||||
dir: PathBuf,
|
||||
catalog: Arc<Mutex<Option<Catalog>>>,
|
||||
wake: rune::Waker,
|
||||
}
|
||||
|
||||
impl Worker {
|
||||
fn run(self, rx: Receiver<String>) {
|
||||
if self.catalog.lock().unwrap().is_none() {
|
||||
match self.ensure_catalog() {
|
||||
Some(catalog) => {
|
||||
*self.catalog.lock().unwrap() = Some(catalog);
|
||||
(self.wake)();
|
||||
}
|
||||
None => eprintln!("champion list unavailable; drawing initials instead"),
|
||||
}
|
||||
}
|
||||
while let Ok(name) = rx.recv() {
|
||||
self.download(&name);
|
||||
}
|
||||
}
|
||||
|
||||
/// The cached champion list, or a fresh one written next to the portraits.
|
||||
fn ensure_catalog(&self) -> Option<Catalog> {
|
||||
if let Some(catalog) = read_catalog(&self.dir) {
|
||||
return Some(catalog);
|
||||
}
|
||||
let catalog = fetch_catalog()?;
|
||||
let text = serde_json::to_vec(&catalog).ok()?;
|
||||
let path = self.dir.join("catalog.json");
|
||||
let _ = std::fs::write(path.with_extension("part"), text);
|
||||
let _ = std::fs::rename(path.with_extension("part"), &path);
|
||||
Some(catalog)
|
||||
}
|
||||
|
||||
fn download(&self, champion: &str) {
|
||||
let (id, version) = {
|
||||
let catalog = self.catalog.lock().unwrap();
|
||||
let Some(catalog) = catalog.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let Some(id) = catalog.ids.get(champion).cloned() else {
|
||||
return;
|
||||
};
|
||||
(id, catalog.version.clone())
|
||||
};
|
||||
let path = self.dir.join(format!("{id}.png"));
|
||||
if path.is_file() {
|
||||
return;
|
||||
}
|
||||
let url = format!("{HOST}/cdn/{version}/img/champion/{id}.png");
|
||||
let Some(bytes) = get(&url) else {
|
||||
return;
|
||||
};
|
||||
if bytes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let part = path.with_extension("part");
|
||||
if std::fs::write(&part, bytes).is_ok() && std::fs::rename(&part, &path).is_ok() {
|
||||
(self.wake)();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_catalog(dir: &std::path::Path) -> Option<Catalog> {
|
||||
let bytes = std::fs::read(dir.join("catalog.json")).ok()?;
|
||||
serde_json::from_slice(&bytes).ok()
|
||||
}
|
||||
|
||||
/// The champion list of the latest patch: display names to Data Dragon ids.
|
||||
fn fetch_catalog() -> Option<Catalog> {
|
||||
let versions: Vec<String> =
|
||||
serde_json::from_slice(&get(&format!("{HOST}/api/versions.json"))?).ok()?;
|
||||
let version = versions.into_iter().next()?;
|
||||
let url = format!("{HOST}/cdn/{version}/data/en_US/champion.json");
|
||||
let data: serde_json::Value = serde_json::from_slice(&get(&url)?).ok()?;
|
||||
let mut ids = HashMap::new();
|
||||
for (id, champion) in data.get("data")?.as_object()? {
|
||||
if let Some(name) = champion.get("name").and_then(|name| name.as_str()) {
|
||||
ids.insert(name.to_string(), id.clone());
|
||||
}
|
||||
}
|
||||
(!ids.is_empty()).then_some(Catalog { version, ids })
|
||||
}
|
||||
|
||||
fn get(url: &str) -> Option<Vec<u8>> {
|
||||
let mut response = ureq::get(url)
|
||||
.config()
|
||||
.timeout_global(Some(Duration::from_secs(20)))
|
||||
.build()
|
||||
.call()
|
||||
.ok()?;
|
||||
let mut bytes = Vec::new();
|
||||
response
|
||||
.body_mut()
|
||||
.as_reader()
|
||||
.read_to_end(&mut bytes)
|
||||
.ok()?;
|
||||
Some(bytes)
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! Which processes are running, and where their executable lives.
|
||||
//!
|
||||
//! The audio sources name a process (`Discord.exe`); the settings screen wants to say whether
|
||||
//! that process is up and draw its icon. One snapshot of the process table answers both.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// What the settings screen knows about one named process.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Found {
|
||||
pub running: bool,
|
||||
/// The executable to read the icon from, when the snapshot could open the process.
|
||||
pub path: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
/// Running processes by normalised name: lowercase, without the `.exe`.
|
||||
pub type Processes = HashMap<String, Found>;
|
||||
|
||||
/// `Discord.exe` and `discord` are the same process.
|
||||
pub fn normalize(name: &str) -> String {
|
||||
let name = name.trim().to_ascii_lowercase();
|
||||
name.strip_suffix(".exe").unwrap_or(&name).to_string()
|
||||
}
|
||||
|
||||
/// One pass over the process table, keeping only `names`.
|
||||
///
|
||||
/// A name that is not running maps to a `Found` with `running: false`, so the screen can tell
|
||||
/// "not running" from "not asked about yet".
|
||||
pub fn snapshot(names: impl IntoIterator<Item = String>) -> Processes {
|
||||
let wanted: HashMap<String, Found> = names
|
||||
.into_iter()
|
||||
.map(|name| (normalize(&name), Found::default()))
|
||||
.collect();
|
||||
if wanted.is_empty() {
|
||||
return wanted;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows_snapshot(wanted)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
wanted
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn windows_snapshot(mut wanted: Processes) -> Processes {
|
||||
use windows::Win32::Foundation::CloseHandle;
|
||||
use windows::Win32::System::Diagnostics::ToolHelp::{
|
||||
CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW,
|
||||
TH32CS_SNAPPROCESS,
|
||||
};
|
||||
|
||||
// SAFETY: the snapshot handle is closed below, and `entry` is a plain struct the calls fill.
|
||||
unsafe {
|
||||
let Ok(snapshot) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) else {
|
||||
return wanted;
|
||||
};
|
||||
let mut entry = PROCESSENTRY32W {
|
||||
dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
let mut more = Process32FirstW(snapshot, &mut entry).is_ok();
|
||||
while more {
|
||||
if let Some(found) = wanted.get_mut(&normalize(&exe_name(&entry))) {
|
||||
found.running = true;
|
||||
if found.path.is_none() {
|
||||
found.path = exe_path(entry.th32ProcessID);
|
||||
}
|
||||
}
|
||||
// A process can exit mid-walk, which ends the enumeration early on some builds.
|
||||
more = Process32NextW(snapshot, &mut entry).is_ok();
|
||||
}
|
||||
let _ = CloseHandle(snapshot);
|
||||
}
|
||||
// A program that is not open has no process to read its icon from, so look where Windows
|
||||
// keeps it.
|
||||
for (name, found) in wanted.iter_mut() {
|
||||
if found.path.is_none() {
|
||||
found.path = locate(name);
|
||||
}
|
||||
}
|
||||
wanted
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn exe_name(entry: &windows::Win32::System::Diagnostics::ToolHelp::PROCESSENTRY32W) -> String {
|
||||
let len = entry
|
||||
.szExeFile
|
||||
.iter()
|
||||
.position(|&c| c == 0)
|
||||
.unwrap_or(entry.szExeFile.len());
|
||||
String::from_utf16_lossy(&entry.szExeFile[..len])
|
||||
}
|
||||
|
||||
/// The full path of a process's executable, when it can be opened.
|
||||
#[cfg(windows)]
|
||||
fn exe_path(pid: u32) -> Option<std::path::PathBuf> {
|
||||
use windows::Win32::Foundation::CloseHandle;
|
||||
use windows::Win32::System::Threading::{
|
||||
OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,
|
||||
QueryFullProcessImageNameW,
|
||||
};
|
||||
use windows::core::PWSTR;
|
||||
|
||||
let mut buffer = [0u16; 512];
|
||||
let mut len = buffer.len() as u32;
|
||||
// SAFETY: `buffer` outlives the call, and `len` carries its capacity in and the written
|
||||
// length out.
|
||||
unsafe {
|
||||
let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?;
|
||||
let query = QueryFullProcessImageNameW(
|
||||
handle,
|
||||
PROCESS_NAME_WIN32,
|
||||
PWSTR(buffer.as_mut_ptr()),
|
||||
&mut len,
|
||||
);
|
||||
let _ = CloseHandle(handle);
|
||||
query.ok()?;
|
||||
}
|
||||
Some(std::path::PathBuf::from(String::from_utf16_lossy(
|
||||
&buffer[..len as usize],
|
||||
)))
|
||||
}
|
||||
|
||||
/// Where a program that is not running might be installed, so its icon can still be drawn.
|
||||
///
|
||||
/// The search is bounded (a few thousand directories, five levels) and remembers its misses, so
|
||||
/// a name costs at most one walk per run of the app.
|
||||
fn locate(name: &str) -> Option<std::path::PathBuf> {
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
static CACHE: OnceLock<Mutex<HashMap<String, Option<std::path::PathBuf>>>> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
if let Some(hit) = cache.lock().ok()?.get(name) {
|
||||
return hit.clone();
|
||||
}
|
||||
let file = format!("{name}.exe");
|
||||
let roots = [
|
||||
"ProgramFiles",
|
||||
"ProgramFiles(x86)",
|
||||
"LOCALAPPDATA",
|
||||
"APPDATA",
|
||||
"ProgramData",
|
||||
];
|
||||
let mut budget = 20_000usize;
|
||||
let found = roots
|
||||
.iter()
|
||||
.filter_map(|var| std::env::var_os(var).map(std::path::PathBuf::from))
|
||||
.find_map(|root| walk(&root, &file, 5, &mut budget));
|
||||
if let Ok(mut cache) = cache.lock() {
|
||||
cache.insert(name.to_string(), found.clone());
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn walk(
|
||||
dir: &std::path::Path,
|
||||
file: &str,
|
||||
depth: u32,
|
||||
budget: &mut usize,
|
||||
) -> Option<std::path::PathBuf> {
|
||||
if depth == 0 || *budget == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut below = Vec::new();
|
||||
for entry in std::fs::read_dir(dir).ok()?.flatten() {
|
||||
*budget = budget.saturating_sub(1);
|
||||
if *budget == 0 {
|
||||
break;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
|
||||
let path = entry.path();
|
||||
if name == file {
|
||||
return Some(path);
|
||||
}
|
||||
if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
|
||||
below.push(path);
|
||||
}
|
||||
}
|
||||
below
|
||||
.into_iter()
|
||||
.find_map(|dir| walk(&dir, file, depth - 1, budget))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_process_name_ignores_case_and_the_exe_suffix() {
|
||||
assert_eq!(normalize("Discord.exe"), "discord");
|
||||
assert_eq!(normalize(" discord.EXE "), "discord");
|
||||
assert_eq!(normalize("chrome"), "chrome");
|
||||
assert_eq!(normalize(""), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_that_are_not_asked_about_are_not_in_the_snapshot() {
|
||||
let found = snapshot(Vec::new());
|
||||
assert!(found.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_process_table_finds_this_test_binary() {
|
||||
let exe = std::env::current_exe().expect("the test binary's path");
|
||||
let name = exe
|
||||
.file_name()
|
||||
.expect("the test binary's name")
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
let found = snapshot(vec![name.clone()]);
|
||||
let found = found
|
||||
.get(&normalize(&name))
|
||||
.expect("the name was asked about");
|
||||
assert!(found.running, "{name} runs: this test is it");
|
||||
assert!(
|
||||
found.path.as_ref().is_some_and(|path| path.is_file()),
|
||||
"{name} resolves to its executable"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_process_that_is_not_running_is_not_found() {
|
||||
let found = snapshot(vec!["definitely-not-a-process-1f3a.exe".to_string()]);
|
||||
let found = found.values().next().expect("the name was asked about");
|
||||
assert!(!found.running);
|
||||
assert!(found.path.is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,856 @@
|
||||
//! The clip view: one clip playing, its title being set, and its share.
|
||||
//!
|
||||
//! The grid opens it on a card, and an export opens it when the clip lands. The title is
|
||||
//! the file's name: saving renames the clip, and the grid follows.
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use rune::tok::{radius, space, type_};
|
||||
use rune::{
|
||||
ClipboardContent, Color, El, Player, PlayerState, SurfaceFit, TextEdit, Tx, auto_grow, col, el,
|
||||
row, text, text_input,
|
||||
};
|
||||
|
||||
use crate::app::{App, Screen};
|
||||
use crate::export::{self, Clip};
|
||||
use crate::format;
|
||||
use crate::history::{self, Outcome, Summary};
|
||||
use crate::icons;
|
||||
use crate::ui::{self, Paint, body, heading};
|
||||
|
||||
/// The open clip: which file it is, the title being edited for it, and its player.
|
||||
pub struct ClipView {
|
||||
/// The clip's name in the grid: its file stem, and its title until renamed.
|
||||
pub name: String,
|
||||
/// The title as it is being typed. Saving turns it into the file's name.
|
||||
pub title: TextEdit,
|
||||
/// The recording the clip was cut from, once it is found: the card in the side panel shows
|
||||
/// it, and the card leads back to it. Kept here so a renamed clip keeps the way back.
|
||||
pub game: Option<Summary>,
|
||||
pub player: Option<Player>,
|
||||
/// Shown over the stage when the file refuses to play.
|
||||
pub error: Option<String>,
|
||||
/// Whether the clip plays without sound. A clip opens with its sound on.
|
||||
pub muted: bool,
|
||||
/// The time bar width in points, from its layout, so a drag can read the pointer.
|
||||
pub bar_width: f32,
|
||||
/// Where the player is and how long the clip is, read in `tick` so the bar and clock move.
|
||||
pub at: f64,
|
||||
pub long: f64,
|
||||
}
|
||||
|
||||
/// Open a clip by name, from the grid's list. The screen switches here and the clip plays,
|
||||
/// with sound and looping, until the view is left.
|
||||
pub fn open(app: &mut App, name: &str) {
|
||||
if !app.clips.iter().any(|clip| clip.name == name) {
|
||||
app.refresh_clips();
|
||||
}
|
||||
let Some(clip) = app.clips.iter().find(|clip| clip.name == name).cloned() else {
|
||||
app.notify_error(format!("No clip named {name} in the clips folder"));
|
||||
return;
|
||||
};
|
||||
// Demo clips name no file until their stand-in video is synthesized; real clips need
|
||||
// only the file to be there.
|
||||
let Some(video) = export::source_of(&clip) else {
|
||||
app.notify_error("The clip's video is missing from the clips folder");
|
||||
return;
|
||||
};
|
||||
let player = Player::file(&video);
|
||||
player.set_looping(true);
|
||||
player.set_muted(false);
|
||||
if let Some(waker) = &app.waker {
|
||||
player.set_waker(waker.clone());
|
||||
}
|
||||
player.play();
|
||||
app.clip = Some(ClipView {
|
||||
name: clip.name.clone(),
|
||||
title: TextEdit::new(clip.name.clone()),
|
||||
game: recording_of(app, &clip),
|
||||
player: Some(player),
|
||||
error: None,
|
||||
muted: false,
|
||||
bar_width: 0.0,
|
||||
at: 0.0,
|
||||
long: 0.0,
|
||||
});
|
||||
app.go(Screen::Clip);
|
||||
}
|
||||
|
||||
/// The recording a clip was cut from.
|
||||
///
|
||||
/// A clip the app renamed carries a file naming its recording; one still named as the export
|
||||
/// left it carries the id in the name. Either way the row comes from the loaded history when it
|
||||
/// is there, and from the timeline itself when the history has not paged that far, so an old
|
||||
/// clip still leads back to its game.
|
||||
fn recording_of(app: &App, clip: &Clip) -> Option<Summary> {
|
||||
let id = match &clip.recording_id {
|
||||
Some(id) => id.clone(),
|
||||
None => recording_id_in_export_name(app, &clip.name)?,
|
||||
};
|
||||
if let Some(game) = app.games.iter().find(|game| game.recording_id == id) {
|
||||
return Some(game.clone());
|
||||
}
|
||||
history::load(&id).map(|game| game.summary())
|
||||
}
|
||||
|
||||
/// The recording a clip's export name carries. The export writes the id into the name, so the
|
||||
/// id is a substring of it; a clip renamed away from that name carries a link file instead.
|
||||
fn recording_id_in_export_name(app: &App, clip_name: &str) -> Option<String> {
|
||||
if let Some(game) = app
|
||||
.games
|
||||
.iter()
|
||||
.find(|game| clip_name.contains(&game.recording_id))
|
||||
{
|
||||
return Some(game.recording_id.clone());
|
||||
}
|
||||
let paths = if app.games_paths.is_empty() {
|
||||
history::timeline_paths()
|
||||
} else {
|
||||
app.games_paths.clone()
|
||||
};
|
||||
let ids = paths
|
||||
.iter()
|
||||
.filter_map(|path| path.file_stem().and_then(|stem| stem.to_str()));
|
||||
recording_id(clip_name, ids).map(str::to_string)
|
||||
}
|
||||
|
||||
/// The recording a name carries, from ids the caller has. A substring check: the export appends
|
||||
/// to the id, and no two ids share a prefix.
|
||||
fn recording_id<'a>(clip_name: &str, ids: impl Iterator<Item = &'a str>) -> Option<&'a str> {
|
||||
ids.into_iter().find(|id| clip_name.contains(id))
|
||||
}
|
||||
|
||||
/// Follow the clip's clock so the bar and the time move, and hand a pending share to the
|
||||
/// clipboard worker.
|
||||
pub fn tick(app: &mut App, tx: &mut Tx) -> bool {
|
||||
let mut changed = false;
|
||||
if let Some(view) = &mut app.clip {
|
||||
let state = view
|
||||
.player
|
||||
.as_ref()
|
||||
.map(|player| (player.time(), player.duration(), player.is_playing()));
|
||||
if let Some((at, long, playing)) = state {
|
||||
if (at - view.at).abs() > 0.001 {
|
||||
view.at = at;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(long) = long
|
||||
&& long > 0.0
|
||||
&& (long - view.long).abs() > 0.05
|
||||
{
|
||||
view.long = long;
|
||||
changed = true;
|
||||
}
|
||||
// The picture only moves when the window draws it, so keep drawing while it plays.
|
||||
if playing {
|
||||
tx.wake_after(Duration::from_millis(33));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(path) = app.share_clip.take() else {
|
||||
return changed;
|
||||
};
|
||||
tx.copy_rich(ClipboardContent::default().with_files([path]));
|
||||
app.notify("Clip copied. Paste it anywhere.");
|
||||
true
|
||||
}
|
||||
|
||||
/// Ask for a clip's file on the clipboard. The worker gets it in `tick`, off the handler.
|
||||
pub fn request_share(app: &mut App, name: &str) {
|
||||
let Some(clip) = app.clips.iter().find(|clip| clip.name == name) else {
|
||||
return;
|
||||
};
|
||||
if clip.path.as_os_str().is_empty() {
|
||||
app.notify_error("This demo clip has no file to share");
|
||||
return;
|
||||
}
|
||||
app.share_clip = Some(clip.path.clone());
|
||||
}
|
||||
|
||||
/// Turn the edited title into the file's name. The grid, the miniature and the view follow.
|
||||
pub fn save_title(app: &mut App) {
|
||||
let Some(view) = app.clip.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let wanted = title_name(&view.title.text);
|
||||
let current = view.name.clone();
|
||||
if wanted.is_empty() {
|
||||
app.notify_error("Give the clip a title first");
|
||||
return;
|
||||
}
|
||||
if wanted == current {
|
||||
return;
|
||||
}
|
||||
let Some(index) = app.clips.iter().position(|clip| clip.name == current) else {
|
||||
return;
|
||||
};
|
||||
let clip = app.clips[index].clone();
|
||||
if clip.path.as_os_str().is_empty() {
|
||||
app.notify_error("This demo clip has no file to rename");
|
||||
return;
|
||||
}
|
||||
let to = export::clips_dir().join(format!("{}.mp4", wanted));
|
||||
if to.exists() {
|
||||
app.notify_error("A clip with that name exists already");
|
||||
return;
|
||||
}
|
||||
if let Err(error) = std::fs::rename(&clip.path, &to) {
|
||||
app.notify_error(format!("Could not rename the clip: {error}"));
|
||||
return;
|
||||
}
|
||||
// The miniature follows the file; without one the thumbnail pass cuts it fresh.
|
||||
let renamed = Clip {
|
||||
name: wanted.clone(),
|
||||
..clip.clone()
|
||||
};
|
||||
let (from_thumb, to_thumb) = (export::thumb_path(&clip), export::thumb_path(&renamed));
|
||||
let _ = std::fs::rename(from_thumb, &to_thumb);
|
||||
// The link to the recording follows the file: a new name no longer names it.
|
||||
let recording = app
|
||||
.clip
|
||||
.as_ref()
|
||||
.and_then(|view| view.game.as_ref())
|
||||
.map(|game| game.recording_id.clone())
|
||||
.or_else(|| clip.recording_id.clone());
|
||||
keep_link(&clip.path, &to, recording.as_deref());
|
||||
let entry = &mut app.clips[index];
|
||||
entry.name = wanted.clone();
|
||||
entry.path = to;
|
||||
entry.thumb = to_thumb.exists().then_some(to_thumb);
|
||||
entry.recording_id = recording;
|
||||
let view = app.clip.as_mut().expect("checked above");
|
||||
view.name = wanted;
|
||||
view.title = TextEdit::new(view.name.clone());
|
||||
app.notify("Clip renamed");
|
||||
app.spawn_thumbs();
|
||||
}
|
||||
|
||||
/// Keep a clip's link to its recording through a move. One already beside the old file moves
|
||||
/// with it; a clip that has none gets one from `recording`, while the view still knows it.
|
||||
fn keep_link(from: &Path, to: &Path, recording: Option<&str>) {
|
||||
if std::fs::rename(export::link_path(from), export::link_path(to)).is_err()
|
||||
&& let Some(id) = recording
|
||||
{
|
||||
export::link_recording(to, id);
|
||||
}
|
||||
}
|
||||
|
||||
/// The file name for a typed title. Characters a Windows file cannot carry become dashes,
|
||||
/// the edges lose their stray spaces and dots, and the whole stays short enough to show.
|
||||
fn title_name(title: &str) -> String {
|
||||
let cleaned: String = title
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*' => '-',
|
||||
c if c.is_control() => '-',
|
||||
c => c,
|
||||
})
|
||||
.collect();
|
||||
let short: String = cleaned.chars().take(80).collect();
|
||||
short.trim_matches(|c| c == ' ' || c == '.').to_string()
|
||||
}
|
||||
|
||||
pub fn view(app: &App, p: Paint) -> El {
|
||||
let Some(view) = &app.clip else {
|
||||
return col().key("clip-view").padding(space::S6).child(
|
||||
text("No clip open.")
|
||||
.key("clip-none")
|
||||
.font(body(13.0))
|
||||
.color(p.muted()),
|
||||
);
|
||||
};
|
||||
let clip = app.clips.iter().find(|clip| clip.name == view.name);
|
||||
let game = view.game.as_ref();
|
||||
let title = game
|
||||
.map(|game| game.champion().unwrap_or_else(|| view.name.clone()))
|
||||
.unwrap_or_else(|| view.name.clone());
|
||||
// The card below says what the game was; this line is what the file is.
|
||||
let detail = clip
|
||||
.map(|clip| {
|
||||
format!(
|
||||
"{} · {}",
|
||||
format::bytes(clip.bytes),
|
||||
format::age(clip.exported)
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
// The player takes the window; the side panel holds the title, the share, and the card
|
||||
// that leads back to the game the clip was cut from.
|
||||
let body = row()
|
||||
.key("clip-body")
|
||||
.w_full()
|
||||
.grow(1.0)
|
||||
.min_h(0.0)
|
||||
.gap(space::S3)
|
||||
.child(
|
||||
col()
|
||||
.key("player")
|
||||
.grow(1.0)
|
||||
.min_w(0.0)
|
||||
.min_h(0.0)
|
||||
.child(video_stage(app, p)),
|
||||
)
|
||||
.child(
|
||||
col()
|
||||
.key("side")
|
||||
.w(300.0)
|
||||
.shrink()
|
||||
.gap(space::S3)
|
||||
.items_start()
|
||||
.child(
|
||||
col()
|
||||
.key("who")
|
||||
.w_full()
|
||||
.gap(1.0)
|
||||
.child(
|
||||
text(title)
|
||||
.key("clip-title")
|
||||
.font(heading(15.0))
|
||||
.color(p.t.text)
|
||||
.shrink()
|
||||
.truncate(),
|
||||
)
|
||||
.child(
|
||||
text(detail)
|
||||
.key("clip-detail")
|
||||
.font(body(11.0))
|
||||
.color(p.muted())
|
||||
.shrink()
|
||||
.truncate(),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
text("Title")
|
||||
.key("title-label")
|
||||
.font(type_::LABEL)
|
||||
.color(p.muted()),
|
||||
)
|
||||
.child(
|
||||
// A file's name can run long: the field wraps instead of widening the
|
||||
// panel, one to two lines tall, scrolling inside when there is more.
|
||||
// Return makes a new line here, so the button is what saves the title.
|
||||
auto_grow(
|
||||
text_input(&view.title, type_::BODY)
|
||||
.key("title-field")
|
||||
.placeholder("Clip title", p.muted())
|
||||
.on_edit(|app: &mut App| {
|
||||
&mut app
|
||||
.clip
|
||||
.as_mut()
|
||||
.expect("the field lives on the open clip")
|
||||
.title
|
||||
}),
|
||||
1,
|
||||
2,
|
||||
)
|
||||
.placeholder("Clip title", p.muted())
|
||||
.on_edit(|app: &mut App| {
|
||||
&mut app
|
||||
.clip
|
||||
.as_mut()
|
||||
.expect("the field lives on the open clip")
|
||||
.title
|
||||
})
|
||||
.on_submit(|app: &mut App, _tx: &mut Tx| save_title(app)),
|
||||
)
|
||||
.child(
|
||||
row()
|
||||
.key("side-actions")
|
||||
.gap(space::S2)
|
||||
.child(ui::button(
|
||||
p,
|
||||
"save-title",
|
||||
"Save title",
|
||||
false,
|
||||
|app: &mut App| {
|
||||
save_title(app);
|
||||
},
|
||||
))
|
||||
.child(ui::button(p, "share", "Share", true, |app: &mut App| {
|
||||
let name = app
|
||||
.clip
|
||||
.as_ref()
|
||||
.map(|view| view.name.clone())
|
||||
.unwrap_or_default();
|
||||
request_share(app, &name);
|
||||
})),
|
||||
)
|
||||
.children(game.map(|game| game_card(app, p, game))),
|
||||
);
|
||||
col()
|
||||
.key("clip-view")
|
||||
.w_full()
|
||||
.grow(1.0)
|
||||
.min_h(0.0)
|
||||
.padding(space::S6)
|
||||
.child(body)
|
||||
}
|
||||
|
||||
/// The card at the foot of the side panel: the champion the clip stars, the scoreline, and the
|
||||
/// game the clip was cut from. The whole card opens that recording; the arrow marks it as a link.
|
||||
fn game_card(app: &App, p: Paint, game: &Summary) -> El {
|
||||
let champion = game.champion().unwrap_or_else(|| "Unknown champion".into());
|
||||
let outcome = game.outcome();
|
||||
let ink = match outcome {
|
||||
Outcome::Victory => p.success,
|
||||
Outcome::Defeat => p.danger,
|
||||
Outcome::Terminated => p.muted(),
|
||||
};
|
||||
let stats = game.stats();
|
||||
let score = stats.as_ref().map_or_else(
|
||||
|| "0/0/0".to_string(),
|
||||
|s| format!("{}/{}/{}", s.kills, s.deaths, s.assists),
|
||||
);
|
||||
let ratio = stats.as_ref().map_or_else(
|
||||
|| "0.0".to_string(),
|
||||
|s| format::kda_ratio(s.kills, s.deaths, s.assists),
|
||||
);
|
||||
let queue = game.queue_label().to_string();
|
||||
let length = format::duration(game.duration_secs.max(0) as f64);
|
||||
let id = game.recording_id.clone();
|
||||
let label = format!("Open the game this clip came from: {champion}, {score}, {queue}");
|
||||
col()
|
||||
.key("game-card")
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.w_full()
|
||||
.padding(space::S3)
|
||||
.gap(space::S2)
|
||||
.radius(radius::LG)
|
||||
.fill(p.t.card)
|
||||
.border(p.hair, p.t.card_border)
|
||||
.shadow(1.0, 2.0, p.t.shadow)
|
||||
.shadow(8.0, 24.0, p.t.shadow_soft)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(move |app: &mut App| crate::screens::review::open(app, &id))
|
||||
.child(
|
||||
row()
|
||||
.key("card-head")
|
||||
.w_full()
|
||||
.gap(space::S2)
|
||||
.center_y()
|
||||
.child(ui::champion_portrait(
|
||||
app,
|
||||
p,
|
||||
game.champion().as_deref(),
|
||||
40.0,
|
||||
))
|
||||
.child(
|
||||
col()
|
||||
.key("card-who")
|
||||
.grow(1.0)
|
||||
.min_w(0.0)
|
||||
.gap(1.0)
|
||||
.child(
|
||||
text(champion)
|
||||
.key("card-champion")
|
||||
.font(heading(14.0))
|
||||
.color(p.t.text)
|
||||
.shrink()
|
||||
.truncate(),
|
||||
)
|
||||
.child(
|
||||
text(format!("{queue} · {length}"))
|
||||
.key("card-queue")
|
||||
.font(body(11.0))
|
||||
.color(p.muted())
|
||||
.shrink()
|
||||
.truncate(),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
text(outcome.label())
|
||||
.key("card-outcome")
|
||||
.font(type_::LABEL)
|
||||
.color(ink),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
row()
|
||||
.key("card-score")
|
||||
.w_full()
|
||||
.center_y()
|
||||
.gap(space::S2)
|
||||
.child(
|
||||
text(score)
|
||||
.key("card-kda")
|
||||
.font(heading(17.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(format!("{ratio} KDA"))
|
||||
.key("card-ratio")
|
||||
.font(body(11.0))
|
||||
.color(p.muted()),
|
||||
)
|
||||
.child(el().grow(1.0))
|
||||
.child(
|
||||
text(format::relative_time(game.start_time))
|
||||
.key("card-when")
|
||||
.font(body(11.0))
|
||||
.color(p.muted())
|
||||
.shrink()
|
||||
.truncate(),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
el().key("card-sep")
|
||||
.w_full()
|
||||
.h(p.hair)
|
||||
.fill(p.t.separator)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
row()
|
||||
.key("card-open")
|
||||
.w_full()
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.child(
|
||||
text("Original game")
|
||||
.key("card-open-label")
|
||||
.font(type_::LABEL)
|
||||
.color(p.accent),
|
||||
)
|
||||
.child(
|
||||
text("→")
|
||||
.key("card-open-arrow")
|
||||
.font(heading(14.0))
|
||||
.color(p.accent)
|
||||
.a11y_hidden(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// The stage: the clip on black, the largest 16:9 box that fits, with the controls drawn over
|
||||
/// it.
|
||||
fn video_stage(app: &App, p: Paint) -> El {
|
||||
let stage = col()
|
||||
.key("stage")
|
||||
.w_full()
|
||||
.grow(1.0)
|
||||
.min_h(0.0)
|
||||
.fill(Color::BLACK)
|
||||
.radius(radius::LG)
|
||||
.clip_soft(radius::LG)
|
||||
.hover_group()
|
||||
.center();
|
||||
let Some(view) = &app.clip else {
|
||||
return stage;
|
||||
};
|
||||
let Some(player) = &view.player else {
|
||||
return stage.child(
|
||||
text(view.error.clone().unwrap_or_else(|| "No clip open.".into()))
|
||||
.key("stage-message")
|
||||
.font(body(13.0))
|
||||
.color(p.muted()),
|
||||
);
|
||||
};
|
||||
if let PlayerState::Failed(message) = player.state() {
|
||||
return stage.child(
|
||||
text(format!("The clip does not play: {message}"))
|
||||
.key("stage-error")
|
||||
.font(body(13.0))
|
||||
.color(p.muted()),
|
||||
);
|
||||
}
|
||||
stage.child(
|
||||
el().key("player-frame")
|
||||
.aspect_fit(16.0 / 9.0)
|
||||
.radius(radius::LG)
|
||||
.clip_soft(radius::LG)
|
||||
.fill(Color::BLACK)
|
||||
.child(
|
||||
el().key("video")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.video(player, SurfaceFit::Fill),
|
||||
)
|
||||
.child(controls(app, p, player)),
|
||||
)
|
||||
}
|
||||
|
||||
/// The controls over the bottom of the picture: the time bar, play and pause, a couple of
|
||||
/// seconds either way, and the sound. They rest visible while the clip stands still and hide
|
||||
/// while it plays, showing again when the pointer comes over the player.
|
||||
fn controls(app: &App, p: Paint, player: &Player) -> El {
|
||||
let playing = player.is_playing();
|
||||
let muted = app.clip.as_ref().is_some_and(|view| view.muted);
|
||||
let at = app.clip.as_ref().map_or(0.0, |view| view.at);
|
||||
let long = app.clip.as_ref().map_or(0.0, |view| view.long);
|
||||
col()
|
||||
.key("controls")
|
||||
.pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0))
|
||||
.justify_end()
|
||||
.gap(space::S2)
|
||||
.px(16.0)
|
||||
.pb(space::S3)
|
||||
.gradient(Color::TRANSPARENT, Color::BLACK.alpha(0.68))
|
||||
.group_opacity(if playing { 0.0 } else { 1.0 }, 1.0)
|
||||
.child(time_bar(app, p, at, long))
|
||||
.child(
|
||||
row()
|
||||
.key("transport")
|
||||
.w_full()
|
||||
.center_y()
|
||||
.gap(space::S2)
|
||||
.child(overlay_button(
|
||||
p,
|
||||
"rewind",
|
||||
&icons::BACK,
|
||||
"Back 2 seconds",
|
||||
false,
|
||||
|app: &mut App| seek(app, -2.0),
|
||||
))
|
||||
.child(overlay_button(
|
||||
p,
|
||||
"play-pause",
|
||||
if playing { &icons::PAUSE } else { &icons::PLAY },
|
||||
if playing { "Pause" } else { "Play" },
|
||||
true,
|
||||
|app: &mut App| {
|
||||
if let Some(player) =
|
||||
app.clip.as_ref().and_then(|view| view.player.as_ref())
|
||||
{
|
||||
if player.is_playing() {
|
||||
player.pause();
|
||||
} else {
|
||||
player.play();
|
||||
}
|
||||
}
|
||||
},
|
||||
))
|
||||
.child(overlay_button(
|
||||
p,
|
||||
"advance",
|
||||
&icons::FORWARD,
|
||||
"Forward 2 seconds",
|
||||
false,
|
||||
|app: &mut App| seek(app, 2.0),
|
||||
))
|
||||
.child(
|
||||
text(format!("{} / {}", format::clock(at), format::clock(long)))
|
||||
.key("clock")
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(Color::WHITE.alpha(0.9)),
|
||||
)
|
||||
.child(el().grow(1.0))
|
||||
.child(overlay_button(
|
||||
p,
|
||||
"mute",
|
||||
if muted {
|
||||
&icons::VOLUME_OFF
|
||||
} else {
|
||||
&icons::VOLUME
|
||||
},
|
||||
if muted { "Unmute" } else { "Mute" },
|
||||
false,
|
||||
|app: &mut App| {
|
||||
if let Some(view) = &mut app.clip {
|
||||
view.muted = !view.muted;
|
||||
if let Some(player) = &view.player {
|
||||
player.set_muted(view.muted);
|
||||
}
|
||||
}
|
||||
},
|
||||
)),
|
||||
)
|
||||
}
|
||||
|
||||
/// An icon button for the dark picture: the theme's control colours are made for surfaces,
|
||||
/// and the picture is black in either appearance.
|
||||
fn overlay_button(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
icon: &'static rune::Icon,
|
||||
label: &str,
|
||||
primary: bool,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
let ink = if primary { p.accent_ink } else { Color::WHITE };
|
||||
el().key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.size(32.0, 32.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(if primary {
|
||||
p.accent
|
||||
} else {
|
||||
Color::WHITE.alpha(0.16)
|
||||
})
|
||||
.hover(Color::WHITE.alpha(0.1))
|
||||
.press(Color::WHITE.alpha(0.18))
|
||||
.on_press(on_press)
|
||||
.child(rune::icon(icon, 16.0).color(ink).a11y_hidden())
|
||||
}
|
||||
|
||||
/// The clip's progress, over the picture. A press or a drag anywhere on it seeks.
|
||||
fn time_bar(app: &App, p: Paint, at: f64, long: f64) -> El {
|
||||
// The width the bar was last given; a drag reads the pointer against it.
|
||||
let width = app.clip.as_ref().map_or(0.0, |view| view.bar_width);
|
||||
let w = if width > 0.0 { width } else { 600.0 };
|
||||
let progress = if long > 0.0 {
|
||||
(at / long).clamp(0.0, 1.0) as f32
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let (height, bar, knob) = (18.0, 4.0, 11.0);
|
||||
el().key("time-bar")
|
||||
.role("slider")
|
||||
.label("Playback position")
|
||||
.range_value(at, 0.0, long.max(0.001))
|
||||
.range_step(5.0)
|
||||
.w_full()
|
||||
.h(height)
|
||||
.on_layout(|app: &mut App, [_, _, w, _]| {
|
||||
if let Some(view) = &mut app.clip {
|
||||
view.bar_width = w;
|
||||
}
|
||||
})
|
||||
.on_step(|app: &mut App, steps, _| seek(app, steps as f64 * 5.0))
|
||||
.on_drag(|app: &mut App, d: &mut rune::Drag, tx| {
|
||||
let long = app.clip.as_ref().map_or(0.0, |view| view.long);
|
||||
let width = app
|
||||
.clip
|
||||
.as_ref()
|
||||
.map_or(0.0, |view| view.bar_width)
|
||||
.max(1.0);
|
||||
if long <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let at = (d.x / width).clamp(0.0, 1.0) as f64 * long;
|
||||
if let Some(player) = app.clip.as_ref().and_then(|view| view.player.as_ref()) {
|
||||
player.seek(at);
|
||||
}
|
||||
if let Some(view) = &mut app.clip {
|
||||
view.at = at;
|
||||
}
|
||||
tx.instant();
|
||||
})
|
||||
.child(
|
||||
el().key("track")
|
||||
.w_full()
|
||||
.h(bar)
|
||||
.absolute(0.0, (height - bar) / 2.0)
|
||||
.radius(bar / 2.0)
|
||||
.fill(Color::WHITE.alpha(0.22))
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
el().key("played")
|
||||
.w(w * progress)
|
||||
.h(bar)
|
||||
.absolute(0.0, (height - bar) / 2.0)
|
||||
.radius(bar / 2.0)
|
||||
.fill(p.accent.alpha(0.9))
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
el().key("knob")
|
||||
.size(knob, knob)
|
||||
.absolute(
|
||||
(progress * (w - knob)).clamp(0.0, (w - knob).max(1.0)),
|
||||
(height - knob) / 2.0,
|
||||
)
|
||||
.radius(knob / 2.0)
|
||||
.fill(Color::WHITE)
|
||||
.shadow(0.0, 1.0, Color::BLACK.alpha(0.35))
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Move the clip's player by `seconds`, held to the clip's length.
|
||||
fn seek(app: &mut App, seconds: f64) {
|
||||
let at = app
|
||||
.clip
|
||||
.as_ref()
|
||||
.and_then(|view| view.player.as_ref())
|
||||
.map(|player| {
|
||||
let long = player.duration().unwrap_or(0.0);
|
||||
let at = (player.time() + seconds).clamp(0.0, long);
|
||||
player.seek(at);
|
||||
at
|
||||
});
|
||||
if let (Some(at), Some(view)) = (at, app.clip.as_mut()) {
|
||||
view.at = at;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{keep_link, recording_id, title_name};
|
||||
use crate::export::{link_path, link_recording, recording_link};
|
||||
|
||||
#[test]
|
||||
fn a_renamed_clip_keeps_the_link_to_its_recording() {
|
||||
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let from = dir.join("demo-1-clip.mp4");
|
||||
let to = dir.join("My Ace.mp4");
|
||||
std::fs::write(&from, b"").unwrap();
|
||||
std::fs::write(&to, b"").unwrap();
|
||||
|
||||
// A link from an earlier rename moves with the file.
|
||||
link_recording(&from, "demo-1");
|
||||
keep_link(&from, &to, Some("ignored"));
|
||||
assert_eq!(recording_link(&to).as_deref(), Some("demo-1"));
|
||||
|
||||
// A clip exported before links existed gets one from the game the view knows.
|
||||
std::fs::remove_file(link_path(&to)).unwrap();
|
||||
keep_link(&from, &to, Some("demo-2"));
|
||||
assert_eq!(recording_link(&to).as_deref(), Some("demo-2"));
|
||||
|
||||
// With no game known there is nothing to write.
|
||||
std::fs::remove_file(link_path(&to)).unwrap();
|
||||
keep_link(&from, &to, None);
|
||||
assert_eq!(recording_link(&to), None);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_name_carries_the_recording_it_was_cut_from() {
|
||||
let ids = ["demo-1", "demo-2"].into_iter();
|
||||
assert_eq!(
|
||||
recording_id("demo-1-clip", ids.clone()),
|
||||
Some("demo-1"),
|
||||
"the export appends to the id"
|
||||
);
|
||||
assert_eq!(
|
||||
recording_id("demo-2-highlight-3", ids.clone()),
|
||||
Some("demo-2"),
|
||||
"a highlight carries it too"
|
||||
);
|
||||
assert_eq!(
|
||||
recording_id("pentakill", ids),
|
||||
None,
|
||||
"a renamed clip names no recording"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_title_keeps_its_letters_and_spaces() {
|
||||
assert_eq!(title_name("My Ace!"), "My Ace!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn characters_a_file_cannot_carry_become_dashes() {
|
||||
assert_eq!(title_name("Kai'Sa: pentakill?"), "Kai'Sa- pentakill-");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edges_lose_their_stray_space_and_dots() {
|
||||
assert_eq!(title_name(" .clip. "), "clip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_title_stays_short_enough_to_show() {
|
||||
assert_eq!(title_name(&"x".repeat(90)).len(), 80);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
//! Clips: every clip the user has exported, newest first, in a grid of cards.
|
||||
//!
|
||||
//! A card is the clip file: its pictures as the main body once they load, and under it the
|
||||
//! clip's name and, when the recording is in the loaded history, the champion it stars and
|
||||
//! the game it came from. Share and the actions menu sit beside.
|
||||
|
||||
use rune::tok::{radius, space};
|
||||
use rune::{Color, El, col, el, row, text};
|
||||
|
||||
use crate::app::App;
|
||||
use crate::export::Clip;
|
||||
use crate::format;
|
||||
use crate::icons;
|
||||
use crate::ui::{self, Paint, body, heading};
|
||||
|
||||
use rune_kit::{Kit, Menu, MenuItem, Placement};
|
||||
|
||||
/// Cards across, at the window's current width. Reflowing at other widths comes later.
|
||||
const COLS: usize = 3;
|
||||
|
||||
pub fn view(app: &App, p: Paint, layer: &mut Vec<El>) -> El {
|
||||
let kit = rune_kit::Kit::neutral(app.dark);
|
||||
|
||||
// The scroll bar gets its own strip at the end, clear of the cards.
|
||||
let mut grid = col().key("clips-grid").w_full().gap(space::S3).pr(14.0);
|
||||
if app.clips.is_empty() {
|
||||
grid = grid.child(empty(
|
||||
p,
|
||||
"No clips yet",
|
||||
"Export a clip from a recording's page and it lands here.",
|
||||
));
|
||||
} else {
|
||||
for (row_index, row_clips) in app.clips.chunks(COLS).enumerate() {
|
||||
let mut cards = row()
|
||||
.key(format!("clips-row-{row_index}"))
|
||||
.w_full()
|
||||
.gap(space::S3)
|
||||
.items_start();
|
||||
for (cell, clip) in row_clips.iter().enumerate() {
|
||||
let index = row_index * COLS + cell;
|
||||
cards = cards.child(clip_card(app, p, &kit, layer, clip, index));
|
||||
}
|
||||
// Empty cells keep the row's cards at their column width.
|
||||
for cell in row_clips.len()..COLS {
|
||||
cards = cards.child(el().key(format!("filler-{row_index}-{cell}")).grow(1.0));
|
||||
}
|
||||
grid = grid.child(cards);
|
||||
}
|
||||
}
|
||||
|
||||
col()
|
||||
.key("clips")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.padding(space::S6)
|
||||
.gap(space::S3)
|
||||
.child(
|
||||
col()
|
||||
.key("clips-title")
|
||||
.gap(2.0)
|
||||
.child(
|
||||
text("Clips")
|
||||
.key("title")
|
||||
.font(heading(20.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(count_label(app))
|
||||
.key("count")
|
||||
.font(body(11.5))
|
||||
.color(p.muted()),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
app.clips_scroll.follow(
|
||||
"clips-scroller",
|
||||
col()
|
||||
.w_full()
|
||||
.grow(1.0)
|
||||
.min_h(0.0)
|
||||
.scroll(rune::ScrollSpec {
|
||||
stick_bottom: false,
|
||||
})
|
||||
.child(grid),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// How many clips the grid holds and how much disk they take.
|
||||
fn count_label(app: &App) -> String {
|
||||
if app.clips.is_empty() {
|
||||
return "No clips".to_string();
|
||||
}
|
||||
let bytes = app.clips.iter().map(|clip| clip.bytes).sum::<u64>();
|
||||
format!("{} clips · {}", app.clips.len(), format::bytes(bytes))
|
||||
}
|
||||
|
||||
fn empty(p: Paint, title: &str, detail: &str) -> El {
|
||||
col()
|
||||
.key("empty")
|
||||
.w_full()
|
||||
.py(64.0)
|
||||
.gap(6.0)
|
||||
.center()
|
||||
.child(
|
||||
text(title)
|
||||
.key("empty-title")
|
||||
.font(heading(15.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(detail)
|
||||
.key("empty-detail")
|
||||
.font(body(12.0))
|
||||
.color(p.muted()),
|
||||
)
|
||||
}
|
||||
|
||||
/// What a card says under its stage: its position, the title, the line under it, and the
|
||||
/// champion it stars when its recording is in the loaded history.
|
||||
struct Card {
|
||||
index: usize,
|
||||
title: String,
|
||||
detail: String,
|
||||
champion: Option<String>,
|
||||
}
|
||||
|
||||
impl Card {
|
||||
/// The card for one clip. The game the clip was cut from, when its recording is in the
|
||||
/// loaded history, names the card; otherwise the file does. The recording comes from the
|
||||
/// clip's link file, or from the export name, which carries the id.
|
||||
fn of(app: &App, clip: &Clip, index: usize) -> Card {
|
||||
let game = clip
|
||||
.recording_id
|
||||
.as_deref()
|
||||
.and_then(|id| app.games.iter().find(|game| game.recording_id == id))
|
||||
.or_else(|| {
|
||||
app.games
|
||||
.iter()
|
||||
.find(|game| clip.name.contains(&game.recording_id))
|
||||
});
|
||||
let when = format::age(clip.exported);
|
||||
match game {
|
||||
Some(game) => Card {
|
||||
index,
|
||||
title: game.champion().unwrap_or_else(|| clip.name.clone()),
|
||||
detail: format!("{} · {}", game.queue_label(), when),
|
||||
champion: game.champion(),
|
||||
},
|
||||
None => Card {
|
||||
index,
|
||||
title: clip.name.clone(),
|
||||
detail: format!("{} · {}", format::bytes(clip.bytes), when),
|
||||
champion: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn clip_card(app: &App, p: Paint, k: &Kit, layer: &mut Vec<El>, clip: &Clip, index: usize) -> El {
|
||||
let card = Card::of(app, clip, index);
|
||||
let name = clip.name.clone();
|
||||
el().key(format!("clip-{index}"))
|
||||
.role("button")
|
||||
.label(format!("Clip {}", clip.name))
|
||||
.on_press(move |app: &mut App| crate::screens::clip::open(app, &name))
|
||||
.grow(1.0)
|
||||
.min_w(0.0)
|
||||
.radius(radius::LG)
|
||||
.clip_rounded(radius::LG)
|
||||
.fill(p.t.card)
|
||||
.border(p.hair, p.t.card_border)
|
||||
.shadow(1.0, 2.0, p.t.shadow)
|
||||
.shadow(8.0, 24.0, p.t.shadow_soft)
|
||||
.hover(p.t.hover)
|
||||
.child(
|
||||
col()
|
||||
.key("card")
|
||||
.w_full()
|
||||
.child(stage(app, p, clip))
|
||||
.child(footer(app, p, k, layer, clip, &card)),
|
||||
)
|
||||
}
|
||||
|
||||
/// The clip itself: the 16:9 box the card gives. The miniature the thumbnail pass cuts fills
|
||||
/// it once it has landed; before that the stage is black.
|
||||
fn stage(app: &App, p: Paint, clip: &Clip) -> El {
|
||||
let mut stage = col()
|
||||
.key("stage")
|
||||
.aspect_ratio(16.0 / 9.0)
|
||||
.w_full()
|
||||
.fill(Color::BLACK);
|
||||
if let (Some(path), Some(thumbs)) = (&clip.thumb, &app.thumbs) {
|
||||
let image = thumbs.file(path, 360.0, p.scale);
|
||||
stage = stage.child(
|
||||
el().key("thumb")
|
||||
.absolute(0.0, 0.0)
|
||||
.w_full()
|
||||
.h_full()
|
||||
.a11y_hidden()
|
||||
.pixels(image.pixels()),
|
||||
);
|
||||
}
|
||||
stage
|
||||
}
|
||||
|
||||
/// Who the clip stars and what game it came from, with share and the actions menu beside.
|
||||
fn footer(app: &App, p: Paint, k: &Kit, layer: &mut Vec<El>, clip: &Clip, card: &Card) -> El {
|
||||
let share_name = clip.name.clone();
|
||||
let Card {
|
||||
index,
|
||||
title,
|
||||
detail,
|
||||
champion,
|
||||
} = card;
|
||||
let (index, title, champion) = (*index, title.as_str(), champion.as_deref());
|
||||
row()
|
||||
.key("footer")
|
||||
.w_full()
|
||||
.px(space::S3)
|
||||
.py(space::S2)
|
||||
.gap(space::S2)
|
||||
.center_y()
|
||||
.child(ui::champion_portrait(app, p, champion, 32.0))
|
||||
.child(
|
||||
col()
|
||||
.key("labels")
|
||||
.grow(1.0)
|
||||
.min_w(0.0)
|
||||
.gap(1.0)
|
||||
.child(
|
||||
text(title)
|
||||
.key("title")
|
||||
.font(heading(13.0))
|
||||
.color(p.t.text)
|
||||
.shrink()
|
||||
.truncate(),
|
||||
)
|
||||
.child(
|
||||
text(detail)
|
||||
.key("game")
|
||||
.font(body(11.0))
|
||||
.color(p.muted())
|
||||
.shrink()
|
||||
.truncate(),
|
||||
),
|
||||
)
|
||||
.child(ui::menu_button(
|
||||
p,
|
||||
format!("share-{index}"),
|
||||
&icons::SHARE,
|
||||
"Share clip",
|
||||
move |app: &mut App| crate::screens::clip::request_share(app, &share_name),
|
||||
))
|
||||
.child(clip_menu(app, k, layer, p, clip, index))
|
||||
}
|
||||
|
||||
/// The dots at the end of a card: the menu of actions a clip offers, `Delete` for now. The
|
||||
/// menu is drawn over this window, so it stays inside it. Keyed by the card's position, like
|
||||
/// the history rows, so rows stay distinct.
|
||||
fn clip_menu(app: &App, k: &Kit, layer: &mut Vec<El>, p: Paint, clip: &Clip, index: usize) -> El {
|
||||
let name = clip.name.clone();
|
||||
Menu::new(format!("clips-menu-{index}"))
|
||||
.trigger(ui::menu_button(
|
||||
p,
|
||||
format!("clips-menu-{index}"),
|
||||
&icons::DOTS,
|
||||
"Clip options",
|
||||
move |app: &mut App| app.clips_menu_open = Some(index),
|
||||
))
|
||||
.placement(Placement::BottomEnd)
|
||||
.open(app.clips_menu_open == Some(index))
|
||||
.on_close(|app: &mut App| app.clips_menu_open = None)
|
||||
.item(
|
||||
MenuItem::new("Delete")
|
||||
.danger(true)
|
||||
.on_select(move |app: &mut App| {
|
||||
app.clips_menu_open = None;
|
||||
app.confirm_clip_delete = Some(name.clone());
|
||||
}),
|
||||
)
|
||||
.build(k, layer)
|
||||
}
|
||||
|
||||
/// The confirmation the menu's Delete opens: the clip leaves the grid, and the recording and
|
||||
/// its files stay. `app::view` draws it over the whole window, title bar included.
|
||||
pub fn delete_dialog(app: &App, p: Paint, layer: &mut Vec<El>) {
|
||||
let panel = col()
|
||||
.key("clip-delete-dialog")
|
||||
.role("dialog")
|
||||
.label("Delete this clip")
|
||||
.w(380.0)
|
||||
.padding(space::S6)
|
||||
.gap(space::S3)
|
||||
.radius(radius::LG)
|
||||
.fill(p.t.card)
|
||||
.border(p.hair, p.t.card_border)
|
||||
.shadow(4.0, 12.0, p.t.shadow)
|
||||
.shadow(24.0, 48.0, p.t.shadow_soft)
|
||||
.modal(true, |app: &mut App| app.confirm_clip_delete = None)
|
||||
.child(
|
||||
text("Delete this clip?")
|
||||
.key("delete-question")
|
||||
.font(heading(15.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text("This will delete the file from disk. The recording stays.")
|
||||
.key("delete-note")
|
||||
.font(body(12.0))
|
||||
.color(p.muted()),
|
||||
)
|
||||
.child(
|
||||
row()
|
||||
.key("delete-actions")
|
||||
.w_full()
|
||||
.gap(space::S2)
|
||||
.justify_end()
|
||||
.child(ui::button(p, "delete-no", "No", false, |app: &mut App| {
|
||||
app.confirm_clip_delete = None;
|
||||
}))
|
||||
.child(ui::button_danger(
|
||||
p,
|
||||
"delete-yes",
|
||||
"Delete",
|
||||
|app: &mut App| {
|
||||
delete_confirmed(app);
|
||||
},
|
||||
)),
|
||||
);
|
||||
|
||||
layer.push(
|
||||
el().key("delete-scrim")
|
||||
.absolute(0.0, 0.0)
|
||||
.w_full()
|
||||
.h_full()
|
||||
.fill(Color::BLACK.alpha(if app.dark { 0.55 } else { 0.28 }))
|
||||
.a11y_hidden(),
|
||||
);
|
||||
layer.push(
|
||||
el().key("delete-layer")
|
||||
.absolute(0.0, 0.0)
|
||||
.w_full()
|
||||
.h_full()
|
||||
.padding(16.0)
|
||||
.center()
|
||||
.child(panel),
|
||||
);
|
||||
}
|
||||
|
||||
/// Yes on the dialog: the file goes, and the card with it. The recording keeps its files.
|
||||
fn delete_confirmed(app: &mut App) {
|
||||
let Some(name) = app.confirm_clip_delete.take() else {
|
||||
return;
|
||||
};
|
||||
let Some(index) = app.clips.iter().position(|clip| clip.name == name) else {
|
||||
return;
|
||||
};
|
||||
let clip = app.clips.remove(index);
|
||||
let _ = std::fs::remove_file(crate::export::thumb_path(&clip));
|
||||
if !clip.path.as_os_str().is_empty() {
|
||||
let _ = std::fs::remove_file(crate::export::link_path(&clip.path));
|
||||
}
|
||||
match std::fs::remove_file(&clip.path) {
|
||||
Ok(()) => app.notify("Clip deleted"),
|
||||
Err(error) => {
|
||||
app.notify(format!("Could not delete the clip: {error}"));
|
||||
app.clips.insert(index, clip);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
//! Match history: the timelines on disk, newest first, filtered by queue.
|
||||
//!
|
||||
//! The card reads like `GameHistory.vue`: result banner, champion portrait, queue, KDA and
|
||||
//! per-minute stats. Items are not shown: the timeline does not carry them.
|
||||
|
||||
use rune::tok::{radius, space, type_};
|
||||
use rune::{Color, El, col, el, row, text};
|
||||
|
||||
use crate::app::App;
|
||||
use crate::format;
|
||||
use crate::history::{self, Outcome, QueueCategory, Summary};
|
||||
use crate::icons;
|
||||
use crate::screens::review;
|
||||
use crate::ui::{self, Paint, body, heading};
|
||||
|
||||
use rune_kit::{Kit, Menu, MenuItem, Placement};
|
||||
|
||||
const FILTERS: [Option<QueueCategory>; 6] = [
|
||||
None,
|
||||
Some(QueueCategory::RankedSolo),
|
||||
Some(QueueCategory::RankedFlex),
|
||||
Some(QueueCategory::Normals),
|
||||
Some(QueueCategory::Aram),
|
||||
Some(QueueCategory::Custom),
|
||||
];
|
||||
|
||||
fn filter_label(filter: Option<QueueCategory>) -> &'static str {
|
||||
filter.map_or("All", QueueCategory::label)
|
||||
}
|
||||
|
||||
fn outcome_color(p: Paint, outcome: Outcome) -> Color {
|
||||
match outcome {
|
||||
Outcome::Victory => p.success,
|
||||
Outcome::Defeat => p.danger,
|
||||
Outcome::Terminated => p.muted(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view(app: &App, p: Paint, layer: &mut Vec<El>) -> El {
|
||||
let kit = rune_kit::Kit::neutral(app.dark);
|
||||
let filtered: Vec<&Summary> = app
|
||||
.games
|
||||
.iter()
|
||||
.filter(|g| app.filter.is_none_or(|f| g.category() == f))
|
||||
.collect();
|
||||
|
||||
// The scroll bar gets its own strip at the end, clear of the cards.
|
||||
let mut list = col().key("games").w_full().gap(space::S2).pr(14.0);
|
||||
if !app.games_loaded {
|
||||
list = list.child(
|
||||
text("Loading match history…")
|
||||
.key("loading")
|
||||
.font(body(13.0))
|
||||
.color(p.muted())
|
||||
.padding(space::S6),
|
||||
);
|
||||
} else if app.games.is_empty() {
|
||||
list = list.child(empty(
|
||||
p,
|
||||
"No games recorded",
|
||||
"Start playing: the daemon records each game and it shows up here.",
|
||||
));
|
||||
} else if filtered.is_empty() {
|
||||
list = list.child(empty(
|
||||
p,
|
||||
"No games match this filter",
|
||||
"Pick another queue above.",
|
||||
));
|
||||
} else {
|
||||
for (index, game) in filtered.iter().enumerate() {
|
||||
list = list.child(game_card(app, p, &kit, layer, game, index));
|
||||
}
|
||||
}
|
||||
|
||||
let mut filters = row().key("filters").gap(4.0).center_y();
|
||||
for filter in FILTERS {
|
||||
let selected = app.filter == filter;
|
||||
filters = filters.child(ui::tab(
|
||||
p,
|
||||
filter_label(filter),
|
||||
filter_label(filter),
|
||||
selected,
|
||||
move |app: &mut App| app.filter = filter,
|
||||
));
|
||||
}
|
||||
|
||||
col()
|
||||
.key("history")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.padding(space::S6)
|
||||
.gap(space::S3)
|
||||
.child(
|
||||
row()
|
||||
.key("history-header")
|
||||
.w_full()
|
||||
.justify_between()
|
||||
.center_y()
|
||||
.child(
|
||||
col()
|
||||
.key("history-title")
|
||||
.gap(2.0)
|
||||
.child(
|
||||
text("Match history")
|
||||
.key("title")
|
||||
.font(heading(20.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(count_label(app))
|
||||
.key("count")
|
||||
.font(body(11.5))
|
||||
.color(p.muted()),
|
||||
),
|
||||
)
|
||||
.child(filters),
|
||||
)
|
||||
.child(
|
||||
app.scroll.follow(
|
||||
"list-scroller",
|
||||
col()
|
||||
.w_full()
|
||||
.grow(1.0)
|
||||
.min_h(0.0)
|
||||
.scroll(rune::ScrollSpec {
|
||||
stick_bottom: false,
|
||||
})
|
||||
.child(list),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// The line under the title: how many recordings there are, and how many have been read.
|
||||
///
|
||||
/// The list reads a page at a time, so the two differ while it is filling up.
|
||||
fn count_label(app: &App) -> String {
|
||||
let total = app.games_paths.len().max(app.games.len());
|
||||
if app.more_games() {
|
||||
format!("{} recordings · {} loaded", total, app.games.len())
|
||||
} else {
|
||||
format!("{total} recordings")
|
||||
}
|
||||
}
|
||||
|
||||
fn empty(p: Paint, title: &str, detail: &str) -> El {
|
||||
col()
|
||||
.key("empty")
|
||||
.w_full()
|
||||
.py(64.0)
|
||||
.gap(6.0)
|
||||
.center()
|
||||
.child(
|
||||
text(title)
|
||||
.key("empty-title")
|
||||
.font(heading(15.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(detail)
|
||||
.key("empty-detail")
|
||||
.font(body(12.0))
|
||||
.color(p.muted()),
|
||||
)
|
||||
}
|
||||
|
||||
fn game_card(
|
||||
app: &App,
|
||||
p: Paint,
|
||||
k: &Kit,
|
||||
layer: &mut Vec<El>,
|
||||
game: &Summary,
|
||||
index: usize,
|
||||
) -> El {
|
||||
let outcome = game.outcome();
|
||||
let ink = outcome_color(p, outcome);
|
||||
let id = game.recording_id.clone();
|
||||
let champion = game.champion().unwrap_or_else(|| "Unknown champion".into());
|
||||
let duration = game.duration_secs.max(0) as f64;
|
||||
let lp = game.lp_change();
|
||||
let stats = game.stats();
|
||||
|
||||
let mut banner = row()
|
||||
.key("banner")
|
||||
.w_full()
|
||||
.h(26.0)
|
||||
.px(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.fill(ink.alpha(0.16))
|
||||
.child(
|
||||
row()
|
||||
.key("banner-left")
|
||||
.gap(8.0)
|
||||
.center_y()
|
||||
.child(
|
||||
text(outcome.label())
|
||||
.key("outcome")
|
||||
.font(type_::LABEL)
|
||||
.color(ink),
|
||||
)
|
||||
.child(
|
||||
text(game.summoner().unwrap_or_default())
|
||||
.key("summoner")
|
||||
.font(body(11.0))
|
||||
.color(p.muted()),
|
||||
),
|
||||
);
|
||||
if let Some(lp) = &lp {
|
||||
let lp_ink = if lp.delta >= 0 { p.success } else { p.danger };
|
||||
banner = banner.child(
|
||||
text(format!(
|
||||
"{} LP · {}",
|
||||
format::lp_delta(lp.delta),
|
||||
format::rank(&lp.tier, &lp.division)
|
||||
))
|
||||
.key("lp")
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(lp_ink),
|
||||
);
|
||||
}
|
||||
|
||||
let kda = match &stats {
|
||||
Some(s) => format!("{}/{}/{}", s.kills, s.deaths, s.assists),
|
||||
None => "0/0/0".into(),
|
||||
};
|
||||
let ratio = stats.as_ref().map_or("0.0".into(), |s| {
|
||||
format::kda_ratio(s.kills, s.deaths, s.assists)
|
||||
});
|
||||
let mut stats_row = row().key("stats").gap(18.0).center_y();
|
||||
if let Some(s) = &stats {
|
||||
stats_row = stats_row
|
||||
.child(stat(p, &format::cs_per_min(s), "CS/m"))
|
||||
.child(stat(p, &format::gold_per_min(s), "Gold/m"))
|
||||
.child(stat(p, &s.vision_score.to_string(), "Vision"));
|
||||
}
|
||||
|
||||
el().key(format!("game-{index}"))
|
||||
.role("button")
|
||||
.label(format!("{champion}, {}", outcome.label()))
|
||||
.focusable(true)
|
||||
.w_full()
|
||||
.radius(radius::LG)
|
||||
.fill(p.t.card)
|
||||
.border(p.hair, p.t.card_border)
|
||||
.shadow(1.0, 2.0, p.t.shadow)
|
||||
.shadow(8.0, 24.0, p.t.shadow_soft)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(move |app: &mut App| review::open(app, &id))
|
||||
.child(
|
||||
col().key("card").w_full().child(banner).child(
|
||||
row()
|
||||
.key("content")
|
||||
.w_full()
|
||||
.px(space::S3)
|
||||
.py(space::S3)
|
||||
.gap(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.child(
|
||||
row()
|
||||
.key("identity")
|
||||
.gap(space::S3)
|
||||
.center_y()
|
||||
.child(ui::champion_portrait(
|
||||
app,
|
||||
p,
|
||||
game.champion().as_deref(),
|
||||
52.0,
|
||||
))
|
||||
.child(
|
||||
col()
|
||||
.key("identity-labels")
|
||||
.gap(2.0)
|
||||
.child(
|
||||
text(champion)
|
||||
.key("champion")
|
||||
.font(heading(16.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(format!(
|
||||
"{} · {}",
|
||||
game.queue_label(),
|
||||
format::duration(duration)
|
||||
))
|
||||
.key("queue")
|
||||
.font(body(11.5))
|
||||
.color(p.muted()),
|
||||
)
|
||||
.child(
|
||||
text(format::relative_time(game.start_time))
|
||||
.key("when")
|
||||
.font(body(11.0))
|
||||
.color(p.muted()),
|
||||
),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
col()
|
||||
.key("kda")
|
||||
.gap(1.0)
|
||||
.items_end()
|
||||
.child(
|
||||
text(kda)
|
||||
.key("kda-values")
|
||||
.font(heading(15.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(format!("{ratio} KDA"))
|
||||
.key("kda-ratio")
|
||||
.font(body(11.0))
|
||||
.color(p.muted()),
|
||||
),
|
||||
)
|
||||
.child(stats_row)
|
||||
.child(
|
||||
row()
|
||||
.key("actions")
|
||||
.gap(space::S3)
|
||||
.center_y()
|
||||
.child(
|
||||
text("Review →")
|
||||
.key("open")
|
||||
.font(type_::LABEL)
|
||||
.color(p.accent),
|
||||
)
|
||||
.child(card_menu(app, k, layer, p, game, index)),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
fn stat(p: Paint, value: &str, label: &str) -> El {
|
||||
col()
|
||||
.key(format!("stat-{label}"))
|
||||
.gap(0.0)
|
||||
.items_end()
|
||||
.child(
|
||||
text(value)
|
||||
.key("value")
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(text(label).key("label").font(body(10.5)).color(p.muted()))
|
||||
}
|
||||
|
||||
/// The dots at the end of a card: they open the menu of actions a recording offers. The menu
|
||||
/// is drawn over this window, so it stays inside it, and more actions can join `Delete` later.
|
||||
/// The key is the card's position, so rows stay distinct even where ids repeat.
|
||||
fn card_menu(
|
||||
app: &App,
|
||||
k: &Kit,
|
||||
layer: &mut Vec<El>,
|
||||
p: Paint,
|
||||
game: &Summary,
|
||||
index: usize,
|
||||
) -> El {
|
||||
let menu = Menu::new(format!("menu-{index}"))
|
||||
.trigger(ui::menu_button(
|
||||
p,
|
||||
format!("menu-{index}"),
|
||||
&icons::DOTS,
|
||||
"Recording options",
|
||||
move |app: &mut App| app.menu_open = Some(index),
|
||||
))
|
||||
.placement(Placement::BottomEnd)
|
||||
.open(app.menu_open == Some(index))
|
||||
.on_close(|app: &mut App| app.menu_open = None)
|
||||
.item({
|
||||
let id = game.recording_id.clone();
|
||||
MenuItem::new("Delete")
|
||||
.danger(true)
|
||||
.on_select(move |app: &mut App| {
|
||||
app.menu_open = None;
|
||||
app.confirm_delete = Some(id.clone());
|
||||
})
|
||||
});
|
||||
menu.build(k, layer)
|
||||
}
|
||||
|
||||
/// The confirmation the menu's Delete opens: the row leaves the list and its files leave the
|
||||
/// disk. `app::view` draws it over the whole window, title bar included.
|
||||
pub fn delete_dialog(app: &App, p: Paint, layer: &mut Vec<El>) {
|
||||
let panel = col()
|
||||
.key("delete-dialog")
|
||||
.role("dialog")
|
||||
.label("Delete this recording")
|
||||
.w(380.0)
|
||||
.padding(space::S6)
|
||||
.gap(space::S3)
|
||||
.radius(radius::LG)
|
||||
.fill(p.t.card)
|
||||
.border(p.hair, p.t.card_border)
|
||||
.shadow(4.0, 12.0, p.t.shadow)
|
||||
.shadow(24.0, 48.0, p.t.shadow_soft)
|
||||
.modal(true, |app: &mut App| app.confirm_delete = None)
|
||||
.child(
|
||||
text("Are you sure you want to delete this entry?")
|
||||
.key("delete-question")
|
||||
.font(heading(15.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text("The recording and its timeline are removed from disk.")
|
||||
.key("delete-note")
|
||||
.font(body(12.0))
|
||||
.color(p.muted()),
|
||||
)
|
||||
.child(
|
||||
row()
|
||||
.key("delete-actions")
|
||||
.w_full()
|
||||
.gap(space::S2)
|
||||
.justify_end()
|
||||
.child(ui::button(p, "delete-no", "No", false, |app: &mut App| {
|
||||
app.confirm_delete = None;
|
||||
}))
|
||||
.child(ui::button_danger(
|
||||
p,
|
||||
"delete-yes",
|
||||
"Yes",
|
||||
|app: &mut App| {
|
||||
delete_confirmed(app);
|
||||
},
|
||||
)),
|
||||
);
|
||||
|
||||
layer.push(
|
||||
el().key("delete-scrim")
|
||||
.absolute(0.0, 0.0)
|
||||
.w_full()
|
||||
.h_full()
|
||||
.fill(Color::BLACK.alpha(if app.dark { 0.55 } else { 0.28 }))
|
||||
.a11y_hidden(),
|
||||
);
|
||||
layer.push(
|
||||
el().key("delete-layer")
|
||||
.absolute(0.0, 0.0)
|
||||
.w_full()
|
||||
.h_full()
|
||||
.padding(16.0)
|
||||
.center()
|
||||
.child(panel),
|
||||
);
|
||||
}
|
||||
|
||||
/// Yes on the dialog: the files go, the row goes, the dialog closes.
|
||||
fn delete_confirmed(app: &mut App) {
|
||||
let Some(id) = app.confirm_delete.take() else {
|
||||
return;
|
||||
};
|
||||
// A review left open keeps the clip's file in use, and the delete would fail on it.
|
||||
if app.reviewed().is_some_and(|game| game.recording_id == id) {
|
||||
review::leave(app);
|
||||
}
|
||||
let Some(summary) = app.games.iter().find(|g| g.recording_id == id).cloned() else {
|
||||
return;
|
||||
};
|
||||
let video = summary.video_path(&app.video_roots());
|
||||
if let Err(e) = history::delete(&id, video.as_deref()) {
|
||||
app.notify_error(e);
|
||||
return;
|
||||
}
|
||||
app.forget_game(&id);
|
||||
app.notify("Recording deleted");
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! The screens: settings, match history, the clips grid, one open clip, the game review and
|
||||
//! the recording in progress.
|
||||
|
||||
pub mod clip;
|
||||
pub mod clips;
|
||||
pub mod history;
|
||||
pub mod recording;
|
||||
pub mod review;
|
||||
pub mod settings;
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,456 @@
|
||||
//! The daemon's settings model (`record-daemon/src/config/settings.rs`).
|
||||
//!
|
||||
//! Kept field for field, snake_case and all: `updateSettings` parses this with serde and rejects
|
||||
//! anything it does not expect.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::daemon;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Settings {
|
||||
#[serde(default)]
|
||||
pub video: VideoSettings,
|
||||
#[serde(default)]
|
||||
pub output: OutputSettings,
|
||||
#[serde(default)]
|
||||
pub audio: AudioSettings,
|
||||
#[serde(default)]
|
||||
pub daemon: DaemonSettings,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct VideoSettings {
|
||||
#[serde(default)]
|
||||
pub encoder_preset: EncoderPreset,
|
||||
#[serde(default)]
|
||||
pub quality: Quality,
|
||||
#[serde(default = "frame_rate")]
|
||||
pub frame_rate: u32,
|
||||
#[serde(default = "yes")]
|
||||
pub hardware_acceleration: bool,
|
||||
}
|
||||
|
||||
impl Default for VideoSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
encoder_preset: EncoderPreset::default(),
|
||||
quality: Quality::default(),
|
||||
frame_rate: frame_rate(),
|
||||
hardware_acceleration: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(tag = "type", rename_all = "lowercase")]
|
||||
pub enum EncoderPreset {
|
||||
Nvenc {
|
||||
#[serde(default = "nvenc_bitrate")]
|
||||
bitrate: u32,
|
||||
#[serde(default = "nvenc_cq")]
|
||||
cq_level: u32,
|
||||
#[serde(default = "yes")]
|
||||
two_pass: bool,
|
||||
},
|
||||
Amf {
|
||||
#[serde(default = "nvenc_bitrate")]
|
||||
bitrate: u32,
|
||||
#[serde(default)]
|
||||
quality: AmfQuality,
|
||||
},
|
||||
X264 {
|
||||
#[serde(default = "x264_preset")]
|
||||
preset: String,
|
||||
#[serde(default = "x264_bitrate")]
|
||||
bitrate: u32,
|
||||
#[serde(default)]
|
||||
crf: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Default for EncoderPreset {
|
||||
fn default() -> Self {
|
||||
Self::Nvenc {
|
||||
bitrate: nvenc_bitrate(),
|
||||
cq_level: nvenc_cq(),
|
||||
two_pass: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // encoder_id and bitrate are read by the tests
|
||||
impl EncoderPreset {
|
||||
/// The daemon's encoder id for this preset (`GetEncodersResponse::current`).
|
||||
pub fn encoder_id(&self) -> &'static str {
|
||||
match self {
|
||||
EncoderPreset::Nvenc { .. } => "jim_nvenc",
|
||||
EncoderPreset::Amf { .. } => "amd_amf_h264",
|
||||
EncoderPreset::X264 { .. } => "x264",
|
||||
}
|
||||
}
|
||||
|
||||
/// The name a daemon-reported encoder id (`.current`) stands for.
|
||||
pub fn encoder_name(id: &str) -> Option<&'static str> {
|
||||
match id {
|
||||
"jim_nvenc" => Some("NVIDIA NVENC"),
|
||||
"amd_amf_h264" => Some("AMD AMF"),
|
||||
"x264" => Some("x264 (Software)"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
EncoderPreset::Nvenc { .. } => "NVIDIA NVENC",
|
||||
EncoderPreset::Amf { .. } => "AMD AMF",
|
||||
EncoderPreset::X264 { .. } => "x264 (Software)",
|
||||
}
|
||||
}
|
||||
|
||||
/// This preset with the encoder changed, keeping the bitrate where both have one.
|
||||
pub fn with_kind(&self, kind: &str) -> EncoderPreset {
|
||||
let bitrate = match self {
|
||||
EncoderPreset::Nvenc { bitrate, .. }
|
||||
| EncoderPreset::Amf { bitrate, .. }
|
||||
| EncoderPreset::X264 { bitrate, .. } => *bitrate,
|
||||
};
|
||||
match kind {
|
||||
"amf" | "AMD AMF" | "amd_amf_h264" => EncoderPreset::Amf {
|
||||
bitrate,
|
||||
quality: AmfQuality::Balanced,
|
||||
},
|
||||
"x264" | "x264 (Software)" => EncoderPreset::X264 {
|
||||
preset: x264_preset(),
|
||||
bitrate,
|
||||
crf: None,
|
||||
},
|
||||
_ => EncoderPreset::Nvenc {
|
||||
bitrate,
|
||||
cq_level: nvenc_cq(),
|
||||
two_pass: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bitrate(&self) -> u32 {
|
||||
match self {
|
||||
EncoderPreset::Nvenc { bitrate, .. }
|
||||
| EncoderPreset::Amf { bitrate, .. }
|
||||
| EncoderPreset::X264 { bitrate, .. } => *bitrate,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AmfQuality {
|
||||
Speed,
|
||||
#[default]
|
||||
Balanced,
|
||||
Quality,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Quality {
|
||||
Low,
|
||||
Medium,
|
||||
#[default]
|
||||
High,
|
||||
Ultra,
|
||||
}
|
||||
|
||||
impl Quality {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Quality::Low => "Low",
|
||||
Quality::Medium => "Medium",
|
||||
Quality::High => "High",
|
||||
Quality::Ultra => "Ultra",
|
||||
}
|
||||
}
|
||||
|
||||
/// What a quality level records at: the screen's resolution, at this bitrate.
|
||||
pub fn detail(self) -> &'static str {
|
||||
match self {
|
||||
Quality::Low => "Your screen's resolution at 4.5 Mbps",
|
||||
Quality::Medium => "Your screen's resolution at 6 Mbps",
|
||||
Quality::High => "Your screen's resolution at 8 Mbps",
|
||||
Quality::Ultra => "Your screen's resolution at 12 Mbps",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct OutputSettings {
|
||||
#[serde(default = "output_path")]
|
||||
pub path: String,
|
||||
#[serde(default = "naming_pattern")]
|
||||
pub naming_pattern: String,
|
||||
#[serde(default = "container")]
|
||||
pub container: String,
|
||||
}
|
||||
|
||||
impl Default for OutputSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
path: output_path(),
|
||||
naming_pattern: naming_pattern(),
|
||||
container: container(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct DaemonSettings {
|
||||
#[serde(default = "yes")]
|
||||
pub auto_record: bool,
|
||||
#[serde(default = "yes")]
|
||||
pub monitor_client: bool,
|
||||
#[serde(default = "poll_interval")]
|
||||
pub poll_interval_ms: u64,
|
||||
#[serde(default)]
|
||||
pub socket_path: Option<String>,
|
||||
#[serde(default = "log_level")]
|
||||
pub log_level: String,
|
||||
#[serde(default = "yes")]
|
||||
pub save_timeline: bool,
|
||||
}
|
||||
|
||||
impl Default for DaemonSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
auto_record: true,
|
||||
monitor_client: true,
|
||||
poll_interval_ms: poll_interval(),
|
||||
socket_path: None,
|
||||
log_level: log_level(),
|
||||
save_timeline: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct AudioSettings {
|
||||
#[serde(default = "yes")]
|
||||
pub enabled: bool,
|
||||
#[serde(default = "audio_bitrate")]
|
||||
pub bitrate: u32,
|
||||
#[serde(default = "sample_rate")]
|
||||
pub sample_rate: u32,
|
||||
#[serde(default = "channels")]
|
||||
pub channels: u32,
|
||||
#[serde(default = "yes")]
|
||||
pub capture_game: bool,
|
||||
#[serde(default = "volume")]
|
||||
pub game_volume: u32,
|
||||
#[serde(default)]
|
||||
pub capture_mic: bool,
|
||||
#[serde(default)]
|
||||
pub mic_device: Option<String>,
|
||||
#[serde(default = "volume")]
|
||||
pub mic_volume: u32,
|
||||
#[serde(default)]
|
||||
pub capture_apps: Vec<AudioSource>,
|
||||
#[serde(default = "volume")]
|
||||
pub apps_volume: u32,
|
||||
}
|
||||
|
||||
impl Default for AudioSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
bitrate: audio_bitrate(),
|
||||
sample_rate: sample_rate(),
|
||||
channels: channels(),
|
||||
capture_game: true,
|
||||
game_volume: volume(),
|
||||
capture_mic: false,
|
||||
mic_device: None,
|
||||
mic_volume: volume(),
|
||||
capture_apps: Vec::new(),
|
||||
apps_volume: volume(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct AudioSource {
|
||||
#[serde(default)]
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub source_type: AudioSourceType,
|
||||
pub device: String,
|
||||
#[serde(default = "yes")]
|
||||
pub enabled: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub volume: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AudioSourceType {
|
||||
Application,
|
||||
DeviceOutput,
|
||||
DeviceInput,
|
||||
}
|
||||
|
||||
impl AudioSourceType {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
AudioSourceType::Application => "Application",
|
||||
AudioSourceType::DeviceOutput => "Output device",
|
||||
AudioSourceType::DeviceInput => "Input device",
|
||||
}
|
||||
}
|
||||
}
|
||||
// ---------------------------------------------------------------------------
|
||||
// Defaults, matching the daemon
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
fn frame_rate() -> u32 {
|
||||
60
|
||||
}
|
||||
fn nvenc_bitrate() -> u32 {
|
||||
8000
|
||||
}
|
||||
fn nvenc_cq() -> u32 {
|
||||
20
|
||||
}
|
||||
fn x264_preset() -> String {
|
||||
"veryfast".into()
|
||||
}
|
||||
fn x264_bitrate() -> u32 {
|
||||
6000
|
||||
}
|
||||
fn output_path() -> String {
|
||||
daemon::recordings_dir().display().to_string()
|
||||
}
|
||||
fn naming_pattern() -> String {
|
||||
"{date}_{time}_{champion}".into()
|
||||
}
|
||||
fn container() -> String {
|
||||
"mp4".into()
|
||||
}
|
||||
fn poll_interval() -> u64 {
|
||||
1000
|
||||
}
|
||||
fn log_level() -> String {
|
||||
"info".into()
|
||||
}
|
||||
fn audio_bitrate() -> u32 {
|
||||
160
|
||||
}
|
||||
fn sample_rate() -> u32 {
|
||||
48_000
|
||||
}
|
||||
fn channels() -> u32 {
|
||||
2
|
||||
}
|
||||
fn volume() -> u32 {
|
||||
100
|
||||
}
|
||||
|
||||
/// Split the daemon's `{ settings: {...} }` wrapper.
|
||||
///
|
||||
/// Every field of [`Settings`] has a default, so a reply that carries no settings at all
|
||||
/// (`{"success": true}`, the answer to `updateSettings`) would parse into the defaults and
|
||||
/// quietly replace what the user has. The daemon always writes the `video` key, and a reply
|
||||
/// without it is an error.
|
||||
pub fn from_response(data: &serde_json::Value) -> Result<Settings, String> {
|
||||
let inner = data.get("settings").unwrap_or(data);
|
||||
if inner.get("video").is_none() {
|
||||
return Err("the daemon's reply carries no settings".to_string());
|
||||
}
|
||||
serde_json::from_value(inner.clone()).map_err(|e| format!("settings did not parse: {e}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn defaults_serialize_the_way_the_daemon_reads_them() {
|
||||
let value = serde_json::to_value(Settings::default()).unwrap();
|
||||
// The daemon parses these exact keys; a rename here makes updateSettings fail.
|
||||
assert_eq!(value["video"]["encoder_preset"]["type"], "nvenc");
|
||||
assert_eq!(value["video"]["encoder_preset"]["cq_level"], 20);
|
||||
assert_eq!(value["video"]["quality"], "high");
|
||||
assert_eq!(value["video"]["frame_rate"], 60);
|
||||
assert_eq!(value["output"]["container"], "mp4");
|
||||
assert!(value["output"]["path"].is_string());
|
||||
assert_eq!(value["audio"]["game_volume"], 100);
|
||||
assert_eq!(value["daemon"]["poll_interval_ms"], 1000);
|
||||
assert!(value["daemon"]["socket_path"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_round_trip_through_json() {
|
||||
let settings = Settings::default();
|
||||
let text = serde_json::to_string(&settings).unwrap();
|
||||
let back: Settings = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(settings, back);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_response_wrapper_is_peeled_once() {
|
||||
let wrapped = json!({"settings": serde_json::to_value(Settings::default()).unwrap()});
|
||||
assert!(from_response(&wrapped).is_ok());
|
||||
let bare = serde_json::to_value(Settings::default()).unwrap();
|
||||
assert!(from_response(&bare).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reply_without_settings_is_an_error() {
|
||||
let replied = json!({"success": true});
|
||||
assert!(from_response(&replied).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_encoder_keeps_its_bitrate_when_it_changes_kind() {
|
||||
let preset = EncoderPreset::X264 {
|
||||
preset: "medium".into(),
|
||||
bitrate: 9000,
|
||||
crf: None,
|
||||
};
|
||||
let nvenc = preset.with_kind("nvenc");
|
||||
assert_eq!(nvenc.encoder_id(), "jim_nvenc");
|
||||
assert_eq!(nvenc.bitrate(), 9000);
|
||||
assert_eq!(preset.with_kind("amf").encoder_id(), "amd_amf_h264");
|
||||
assert_eq!(
|
||||
preset.with_kind("amd_amf_h264").encoder_id(),
|
||||
"amd_amf_h264"
|
||||
);
|
||||
assert_eq!(preset.with_kind("x264").encoder_id(), "x264");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choosing_an_encoder_by_its_menu_label_works() {
|
||||
let preset = EncoderPreset::default();
|
||||
assert_eq!(preset.with_kind("AMD AMF").encoder_id(), "amd_amf_h264");
|
||||
assert_eq!(preset.with_kind("x264 (Software)").encoder_id(), "x264");
|
||||
assert_eq!(preset.with_kind("NVIDIA NVENC").encoder_id(), "jim_nvenc");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_source_type_names_match_the_daemon() {
|
||||
assert_eq!(
|
||||
serde_json::to_value(AudioSourceType::Application).unwrap(),
|
||||
"application"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(AudioSourceType::DeviceOutput).unwrap(),
|
||||
"deviceoutput"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(AudioSourceType::DeviceInput).unwrap(),
|
||||
"deviceinput"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! The app's palette.
|
||||
//!
|
||||
//! One shell colour scheme: near-black surfaces tinted blue, brass for what the user acts on,
|
||||
//! and mint or coral only for results. Champion art and victory banners are the loudest things
|
||||
//! on screen, so the chrome around them stays quiet.
|
||||
//!
|
||||
//! Every colour is OKLCH, written as lightness, chroma and hue. The two appearances share the
|
||||
//! hues and swap lightness, so a control keeps its identity in light mode.
|
||||
|
||||
use rune::tok::Theme;
|
||||
use rune::{Color, oklch, oklcha};
|
||||
|
||||
/// Hues, one per role. Neutrals take a touch of the shell's blue; text keeps the same cast.
|
||||
const SHELL: f32 = 268.0;
|
||||
const BRASS: f32 = 84.0;
|
||||
const MINT: f32 = 157.0;
|
||||
const CORAL: f32 = 22.0;
|
||||
|
||||
pub struct Palette {
|
||||
/// Surfaces and ink: what rune's widgets read.
|
||||
pub theme: Theme,
|
||||
/// The window chrome: title bar and status bar, a step above or below the page.
|
||||
pub chrome: Color,
|
||||
/// A field's well, sunk into the card it sits in.
|
||||
pub field: Color,
|
||||
/// What the user acts on: primary buttons, sliders, the selected tab.
|
||||
pub accent: Color,
|
||||
/// Ink for text on an accent fill.
|
||||
pub accent_ink: Color,
|
||||
pub success: Color,
|
||||
pub danger: Color,
|
||||
pub warning: Color,
|
||||
}
|
||||
|
||||
pub fn palette(dark: bool) -> Palette {
|
||||
if dark {
|
||||
Palette {
|
||||
theme: Theme {
|
||||
bg: oklch(0.168, 0.012, SHELL),
|
||||
card: oklch(0.212, 0.014, SHELL),
|
||||
card_border: oklcha(1.0, 0.0, 0.0, 0.055),
|
||||
text: oklch(0.962, 0.003, SHELL),
|
||||
text_secondary: oklch(0.734, 0.012, SHELL),
|
||||
separator: oklcha(1.0, 0.0, 0.0, 0.05),
|
||||
control_track: oklcha(1.0, 0.0, 0.0, 0.045),
|
||||
control_off: oklcha(1.0, 0.0, 0.0, 0.09),
|
||||
indicator: oklch(0.44, 0.01, SHELL),
|
||||
knob: oklch(0.985, 0.0, 0.0),
|
||||
hover: oklcha(1.0, 0.0, 0.0, 0.018),
|
||||
press: oklcha(1.0, 0.0, 0.0, 0.035),
|
||||
shadow: oklcha(0.0, 0.0, 0.0, 0.45),
|
||||
shadow_soft: oklcha(0.0, 0.0, 0.0, 0.3),
|
||||
edge: oklcha(0.0, 0.0, 0.0, 0.32),
|
||||
knob_shadow: oklcha(0.0, 0.0, 0.0, 0.32),
|
||||
},
|
||||
chrome: oklch(0.192, 0.013, SHELL),
|
||||
field: oklch(0.178, 0.012, SHELL),
|
||||
accent: oklch(0.818, 0.116, BRASS),
|
||||
accent_ink: oklch(0.245, 0.035, BRASS),
|
||||
success: oklch(0.782, 0.132, MINT),
|
||||
danger: oklch(0.706, 0.152, CORAL),
|
||||
warning: oklch(0.812, 0.115, 72.0),
|
||||
}
|
||||
} else {
|
||||
Palette {
|
||||
theme: Theme {
|
||||
bg: oklch(0.966, 0.004, SHELL),
|
||||
card: oklch(1.0, 0.0, 0.0),
|
||||
card_border: oklcha(0.2, 0.02, SHELL, 0.1),
|
||||
text: oklch(0.235, 0.012, SHELL),
|
||||
text_secondary: oklch(0.515, 0.013, SHELL),
|
||||
separator: oklcha(0.2, 0.02, SHELL, 0.12),
|
||||
control_track: oklcha(0.2, 0.01, SHELL, 0.13),
|
||||
control_off: oklcha(0.2, 0.01, SHELL, 0.22),
|
||||
indicator: oklch(1.0, 0.0, 0.0),
|
||||
knob: oklch(1.0, 0.0, 0.0),
|
||||
hover: oklcha(0.2, 0.01, SHELL, 0.06),
|
||||
press: oklcha(0.2, 0.01, SHELL, 0.11),
|
||||
shadow: oklcha(0.2, 0.02, SHELL, 0.16),
|
||||
shadow_soft: oklcha(0.2, 0.02, SHELL, 0.07),
|
||||
edge: oklcha(0.2, 0.02, SHELL, 0.2),
|
||||
knob_shadow: oklcha(0.2, 0.02, SHELL, 0.3),
|
||||
},
|
||||
chrome: oklch(0.988, 0.003, SHELL),
|
||||
field: oklch(0.955, 0.004, SHELL),
|
||||
accent: oklch(0.535, 0.104, 74.0),
|
||||
accent_ink: oklch(1.0, 0.0, 0.0),
|
||||
success: oklch(0.512, 0.122, MINT),
|
||||
danger: oklch(0.55, 0.165, CORAL),
|
||||
warning: oklch(0.52, 0.112, 68.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Relative luminance of a linear-light colour, as WCAG defines contrast.
|
||||
fn luminance(c: Color) -> f64 {
|
||||
0.2126 * c.r as f64 + 0.7152 * c.g as f64 + 0.0722 * c.b as f64
|
||||
}
|
||||
|
||||
fn contrast(a: Color, b: Color) -> f64 {
|
||||
let (x, y) = (luminance(a), luminance(b));
|
||||
let (hi, lo) = if x > y { (x, y) } else { (y, x) };
|
||||
(hi + 0.05) / (lo + 0.05)
|
||||
}
|
||||
|
||||
/// Every colour that carries text keeps WCAG AA (4.5:1) on the surfaces it is drawn on,
|
||||
/// in both appearances. The palette is tuned by hand, so this is the guard that a nudge
|
||||
/// to one number did not make a label unreadable.
|
||||
#[test]
|
||||
fn ink_reads_on_the_surfaces() {
|
||||
for dark in [true, false] {
|
||||
let p = palette(dark);
|
||||
let mode = if dark { "dark" } else { "light" };
|
||||
for (name, ink) in [
|
||||
("text", p.theme.text),
|
||||
("text_secondary", p.theme.text_secondary),
|
||||
("accent", p.accent),
|
||||
("success", p.success),
|
||||
("danger", p.danger),
|
||||
("warning", p.warning),
|
||||
] {
|
||||
for (surface, bg) in [
|
||||
("bg", p.theme.bg),
|
||||
("card", p.theme.card),
|
||||
("chrome", p.chrome),
|
||||
] {
|
||||
let ratio = contrast(ink, bg);
|
||||
assert!(
|
||||
ratio >= 4.5,
|
||||
"{mode}: {name} on {surface} is {ratio:.2}:1, under 4.5:1"
|
||||
);
|
||||
}
|
||||
}
|
||||
let ratio = contrast(p.accent, p.accent_ink);
|
||||
assert!(
|
||||
ratio >= 4.5,
|
||||
"{mode}: accent_ink on accent is {ratio:.2}:1, under 4.5:1"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A field's well has to be visible inside the card it sits in.
|
||||
#[test]
|
||||
fn the_field_well_stands_out_from_the_card() {
|
||||
for dark in [true, false] {
|
||||
let p = palette(dark);
|
||||
let ratio = contrast(p.field, p.theme.card);
|
||||
assert!(ratio >= 1.04, "{dark}: field vs card is {ratio:.2}:1");
|
||||
}
|
||||
}
|
||||
}
|
||||
+819
@@ -0,0 +1,819 @@
|
||||
//! Shared colours and small controls for the screens.
|
||||
|
||||
use rune::tok::{Theme, motion, radius, space, type_};
|
||||
use rune::{Color, Drag, El, Phase, TextStyle, col, el, row, text};
|
||||
|
||||
use crate::app::App;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Paint {
|
||||
pub t: Theme,
|
||||
pub accent: Color,
|
||||
pub accent_ink: Color,
|
||||
pub success: Color,
|
||||
pub danger: Color,
|
||||
pub warning: Color,
|
||||
pub chrome: Color,
|
||||
pub field: Color,
|
||||
pub hair: f32,
|
||||
pub scale: f32,
|
||||
}
|
||||
|
||||
impl Paint {
|
||||
pub fn new(dark: bool, scale: f32) -> Self {
|
||||
let palette = crate::theme::palette(dark);
|
||||
Self {
|
||||
t: palette.theme,
|
||||
accent: palette.accent,
|
||||
accent_ink: palette.accent_ink,
|
||||
success: palette.success,
|
||||
danger: palette.danger,
|
||||
warning: palette.warning,
|
||||
chrome: palette.chrome,
|
||||
field: palette.field,
|
||||
hair: 1.0 / scale,
|
||||
scale,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn muted(&self) -> Color {
|
||||
self.t.text_secondary
|
||||
}
|
||||
}
|
||||
|
||||
pub fn heading(size: f32) -> TextStyle {
|
||||
TextStyle::new(size, 600.0)
|
||||
}
|
||||
|
||||
pub fn body(size: f32) -> TextStyle {
|
||||
TextStyle::new(size, 400.0)
|
||||
}
|
||||
|
||||
/// A titled card of rows with hairlines between them.
|
||||
pub fn card(p: Paint, title: Option<&str>, rows: Vec<El>) -> El {
|
||||
card_action(p, title, None, rows)
|
||||
}
|
||||
|
||||
/// [`card`] with a control in its header, such as the button that adds to the list below.
|
||||
pub fn card_action(p: Paint, title: Option<&str>, action: Option<El>, rows: Vec<El>) -> El {
|
||||
let count = rows.len();
|
||||
let mut inner = col()
|
||||
.key("card")
|
||||
.padding(space::S1)
|
||||
.fill(p.t.card)
|
||||
.radius(radius::LG)
|
||||
.border(p.hair, p.t.card_border)
|
||||
.shadow(1.0, 2.0, p.t.shadow)
|
||||
.shadow(8.0, 24.0, p.t.shadow_soft);
|
||||
for (i, r) in rows.into_iter().enumerate() {
|
||||
inner = inner.child(r);
|
||||
if i + 1 < count {
|
||||
inner = inner.child(
|
||||
el().key(format!("sep{i}"))
|
||||
.h(p.hair)
|
||||
.ml(space::S3)
|
||||
.mr(space::S3)
|
||||
.fill(p.t.separator)
|
||||
.a11y_hidden(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut section = col().gap(space::S2);
|
||||
if let Some(title) = title {
|
||||
let mut header = row()
|
||||
.key("header")
|
||||
.w_full()
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.child(
|
||||
text(title)
|
||||
.key("header-label")
|
||||
.font(type_::SECTION)
|
||||
.color(p.t.text_secondary)
|
||||
.ml(space::S3),
|
||||
);
|
||||
if let Some(action) = action {
|
||||
header = header.child(action);
|
||||
}
|
||||
section = section.child(header);
|
||||
}
|
||||
section.child(inner)
|
||||
}
|
||||
|
||||
/// The 44-point row every setting sits in: a label on the left, a control on the right.
|
||||
pub fn setting_row(p: Paint, key: &str, label: &str, control: El) -> El {
|
||||
row()
|
||||
.key(key)
|
||||
.h(44.0)
|
||||
.px(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.radius(radius::MD)
|
||||
.label(label)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::BODY)
|
||||
.color(p.t.text)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(control)
|
||||
}
|
||||
|
||||
/// A row with a subtitle under the label.
|
||||
pub fn setting_row_with(p: Paint, key: &str, label: &str, subtitle: &str, control: El) -> El {
|
||||
row()
|
||||
.key(key)
|
||||
.h(52.0)
|
||||
.px(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.radius(radius::MD)
|
||||
.label(label)
|
||||
.child(
|
||||
col()
|
||||
.key("labels")
|
||||
.gap(1.0)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::BODY)
|
||||
.color(p.t.text)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
text(subtitle)
|
||||
.key("subtitle")
|
||||
.font(body(11.5))
|
||||
.color(p.t.text_secondary)
|
||||
.a11y_hidden(),
|
||||
),
|
||||
)
|
||||
.child(control)
|
||||
}
|
||||
|
||||
/// A 38 × 22 switch with a 18-point knob.
|
||||
pub fn switch(p: Paint, key: &str, on: bool) -> El {
|
||||
let (w, h, k) = (38.0, 22.0, 18.0);
|
||||
let inset = (h - k) / 2.0;
|
||||
el().key(key)
|
||||
.role("switch")
|
||||
.size(w, h)
|
||||
.radius(h / 2.0)
|
||||
.fill(if on { p.accent } else { p.t.control_off })
|
||||
.motion(motion::SNAPPY)
|
||||
.child(
|
||||
el().key("knob")
|
||||
.size(k, k)
|
||||
.absolute(if on { w - k - inset } else { inset }, inset)
|
||||
.radius(k / 2.0)
|
||||
.fill(p.t.knob)
|
||||
.shadow(1.0, 3.0, p.t.knob_shadow)
|
||||
.shadow(0.0, 0.5, p.t.edge)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A labelled switch row. The whole row is the target and the keyboard stop.
|
||||
pub fn toggle_row(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
label: &str,
|
||||
on: bool,
|
||||
flip: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
setting_row(
|
||||
p,
|
||||
key,
|
||||
label,
|
||||
switch(p, &format!("{key}-switch"), on).a11y_hidden(),
|
||||
)
|
||||
.role("switch")
|
||||
.checked(on)
|
||||
.focusable(true)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(flip)
|
||||
}
|
||||
|
||||
/// A 0-100 slider with its value spelled out on the right.
|
||||
pub fn slider(
|
||||
p: Paint,
|
||||
key: impl Into<String>,
|
||||
label: &'static str,
|
||||
value: u32,
|
||||
on_change: impl Fn(&mut App, u32) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
slider_width(p, key, label, 180.0, value, on_change)
|
||||
}
|
||||
|
||||
/// [`slider`] at a given width, for the player bar where 180 points is too much.
|
||||
pub fn slider_width(
|
||||
p: Paint,
|
||||
key: impl Into<String>,
|
||||
label: &'static str,
|
||||
width: f32,
|
||||
value: u32,
|
||||
on_change: impl Fn(&mut App, u32) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
let key = key.into();
|
||||
let (w, h, k, bar) = (width, 22.0, 18.0, 4.0);
|
||||
let travel = w - k;
|
||||
let v = (value.min(100) as f32 / 100.0).clamp(0.0, 1.0);
|
||||
let to_value = move |x: f32| (((x - k / 2.0) / travel).clamp(0.0, 1.0) * 100.0).round() as u32;
|
||||
let on_change = std::sync::Arc::new(on_change);
|
||||
let drag_change = on_change.clone();
|
||||
let step_change = on_change;
|
||||
row()
|
||||
.key(format!("{key}-control"))
|
||||
.gap(space::S3)
|
||||
.center_y()
|
||||
.child(
|
||||
el().key(key)
|
||||
.role("slider")
|
||||
.label(label)
|
||||
.range_value(f64::from(value.min(100)), 0.0, 100.0)
|
||||
.range_step(5.0)
|
||||
.a11y_value(format!("{value}%"))
|
||||
.on_step(move |s: &mut App, steps, _| {
|
||||
let next = (i64::from(value) + i64::from(steps) * 5).clamp(0, 100) as u32;
|
||||
step_change(s, next);
|
||||
})
|
||||
.size(w, h)
|
||||
.motion(motion::SNAPPY)
|
||||
.on_drag(move |s: &mut App, d: &mut Drag, tx| match d.phase {
|
||||
Phase::Down => {
|
||||
d.data = v;
|
||||
let knob = k / 2.0 + v * travel;
|
||||
if (d.x - knob).abs() > k / 2.0 + 2.0 {
|
||||
let next = to_value(d.x);
|
||||
drag_change(s, next);
|
||||
}
|
||||
}
|
||||
Phase::Move => {
|
||||
let knob = k / 2.0 + d.data * travel;
|
||||
let grab = if (d.start_x - knob).abs() <= k / 2.0 + 2.0 {
|
||||
d.start_x - knob
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let next = to_value(d.x - grab);
|
||||
drag_change(s, next);
|
||||
tx.instant();
|
||||
}
|
||||
Phase::Up => {}
|
||||
})
|
||||
.child(
|
||||
el().key("track")
|
||||
.size(w, bar)
|
||||
.absolute(0.0, (h - bar) / 2.0)
|
||||
.radius(bar / 2.0)
|
||||
.fill(p.t.control_off)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
el().key("fill")
|
||||
.size(k / 2.0 + v * travel, bar)
|
||||
.absolute(0.0, (h - bar) / 2.0)
|
||||
.radius(bar / 2.0)
|
||||
.fill(p.accent)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
el().key("knob")
|
||||
.size(k, k)
|
||||
.absolute(v * travel, (h - k) / 2.0)
|
||||
.radius(k / 2.0)
|
||||
.fill(p.t.knob)
|
||||
.shadow(1.0, 3.0, p.t.knob_shadow)
|
||||
.shadow(0.0, 0.5, p.t.edge)
|
||||
.a11y_hidden(),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
text(format!("{value}%"))
|
||||
.key("value")
|
||||
.w(40.0)
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(p.t.text_secondary)
|
||||
.align(rune::Align::End)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A one-line text field for a settings row. The text sits at the row's end edge, like every
|
||||
/// other control, so values start and end on one line down the card.
|
||||
pub fn text_field(
|
||||
p: Paint,
|
||||
key: &'static str,
|
||||
label: &str,
|
||||
edit: &rune::TextEdit,
|
||||
to: fn(&mut App) -> &mut rune::TextEdit,
|
||||
) -> El {
|
||||
text_field_width(p, key, label, 220.0, rune::Align::End, edit, to, |app| {
|
||||
app.form.dirty = true;
|
||||
})
|
||||
}
|
||||
|
||||
/// [`text_field`] at a given width and text alignment; a dialog field is wide and starts at its
|
||||
/// left edge, where typing begins.
|
||||
#[allow(clippy::too_many_arguments)] // the columns of a field: size, alignment and what typing does
|
||||
pub fn text_field_width(
|
||||
p: Paint,
|
||||
key: &'static str,
|
||||
label: &str,
|
||||
width: f32,
|
||||
align: rune::Align,
|
||||
edit: &rune::TextEdit,
|
||||
to: fn(&mut App) -> &mut rune::TextEdit,
|
||||
on_input: fn(&mut App),
|
||||
) -> El {
|
||||
let focused = edit.focused;
|
||||
row()
|
||||
.key(key)
|
||||
.h(28.0)
|
||||
.w(width)
|
||||
.px(8.0)
|
||||
.center_y()
|
||||
.radius(radius::MD)
|
||||
.fill(p.field)
|
||||
.border(
|
||||
p.hair,
|
||||
if focused {
|
||||
p.accent.alpha(0.7)
|
||||
} else {
|
||||
p.t.card_border
|
||||
},
|
||||
)
|
||||
.child(
|
||||
rune::text_input(edit, type_::BODY)
|
||||
.key("input")
|
||||
.single_line()
|
||||
.w_full()
|
||||
.label(label)
|
||||
.color(p.t.text)
|
||||
.align(align)
|
||||
.caret(p.t.text, p.accent.alpha(0.3))
|
||||
.on_edit(to)
|
||||
.on_input_change(move |app: &mut App, _| on_input(app)),
|
||||
)
|
||||
}
|
||||
|
||||
/// A pill tab; the selected one fills with the accent.
|
||||
pub fn tab(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
label: &str,
|
||||
selected: bool,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
el().key(key)
|
||||
.role("tab")
|
||||
.label(label)
|
||||
.checked(selected)
|
||||
.focusable(true)
|
||||
.px(18.0)
|
||||
.h(28.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(if selected {
|
||||
p.accent.alpha(0.22)
|
||||
} else {
|
||||
Color::TRANSPARENT
|
||||
})
|
||||
.border(
|
||||
p.hair,
|
||||
if selected {
|
||||
p.accent.alpha(0.32)
|
||||
} else {
|
||||
Color::TRANSPARENT
|
||||
},
|
||||
)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(on_press)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::LABEL)
|
||||
.color(if selected {
|
||||
p.accent
|
||||
} else {
|
||||
p.t.text_secondary
|
||||
})
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A small pill button.
|
||||
pub fn button(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
label: &str,
|
||||
primary: bool,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
button_tx(p, key, label, primary, move |app, _| on_press(app))
|
||||
}
|
||||
|
||||
/// [`button`] whose press gets the frame's [`Tx`], for a control that asks the window for
|
||||
/// something: a native folder dialog, an open URL, a clipboard read.
|
||||
pub fn button_tx(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
label: &str,
|
||||
primary: bool,
|
||||
on_press: impl Fn(&mut App, &mut rune::Tx) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
el().key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.h(28.0)
|
||||
.px(14.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(if primary { p.accent } else { p.t.control_off })
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press_tx(on_press)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::LABEL)
|
||||
.color(if primary { p.accent_ink } else { p.t.text })
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// One transport control: an icon, its accessible label, round like the bar it sits in.
|
||||
pub fn media_button(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
icon: &'static rune::Icon,
|
||||
label: &str,
|
||||
primary: bool,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
let ink = if primary { p.accent_ink } else { p.t.text };
|
||||
el().key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.size(32.0, 32.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(if primary { p.accent } else { p.t.control_off })
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(on_press)
|
||||
.child(rune::icon(icon, 16.0).color(ink).a11y_hidden())
|
||||
}
|
||||
|
||||
/// A small square button holding one glyph, for the corner of a card or a dialog.
|
||||
pub fn icon_button(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
glyph: &str,
|
||||
label: &str,
|
||||
primary: bool,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
el().key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.size(24.0, 24.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(if primary {
|
||||
p.accent.alpha(0.14)
|
||||
} else {
|
||||
Color::TRANSPARENT
|
||||
})
|
||||
.border(
|
||||
p.hair,
|
||||
if primary {
|
||||
p.accent.alpha(0.32)
|
||||
} else {
|
||||
Color::TRANSPARENT
|
||||
},
|
||||
)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(on_press)
|
||||
.child(
|
||||
text(glyph)
|
||||
.key("glyph")
|
||||
.font(body(if primary { 16.0 } else { 15.0 }))
|
||||
.color(if primary { p.accent } else { p.muted() })
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A primary button with nothing to do yet, for a dialog whose fields are still empty.
|
||||
pub fn button_muted(p: Paint, key: &str, label: &str) -> El {
|
||||
el().key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.disabled(true)
|
||||
.h(28.0)
|
||||
.px(14.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(p.accent.alpha(0.28))
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::LABEL)
|
||||
.color(p.accent_ink.alpha(0.55))
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A process's icon as Windows draws it for the executable, with its initial until the icon is
|
||||
/// decoded and for processes whose executable has none.
|
||||
pub fn process_icon(app: &App, p: Paint, process: &str, size: f32) -> El {
|
||||
let radius = (size * 0.22).max(2.0);
|
||||
let initial = process
|
||||
.trim()
|
||||
.chars()
|
||||
.next()
|
||||
.map(|c| c.to_ascii_uppercase().to_string())
|
||||
.unwrap_or_else(|| "?".to_string());
|
||||
let image = app
|
||||
.processes
|
||||
.get(&crate::process::normalize(process))
|
||||
.and_then(|found| found.path.as_deref())
|
||||
.and_then(|path| {
|
||||
app.icons
|
||||
.as_ref()
|
||||
.map(|icons| icons.app_icon_scaled(path, size, p.scale))
|
||||
});
|
||||
let tile = el()
|
||||
.key("process-icon")
|
||||
.size(size, size)
|
||||
.radius(radius)
|
||||
.fill(p.t.control_off)
|
||||
.a11y_hidden();
|
||||
match image {
|
||||
Some(image) => tile.child(
|
||||
el().key("process-image")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.radius(radius)
|
||||
.pixels(image.pixels()),
|
||||
),
|
||||
None => tile.child(
|
||||
text(initial)
|
||||
.key("initial")
|
||||
.font(body(size * 0.52))
|
||||
.color(p.muted())
|
||||
.center(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a process is up: a chip beside its name in the list.
|
||||
pub fn process_state(p: Paint, running: bool, width: f32) -> El {
|
||||
let color = if running { p.success } else { p.muted() };
|
||||
row()
|
||||
.key("process-state")
|
||||
.w(width)
|
||||
.h(20.0)
|
||||
.px(8.0)
|
||||
.gap(6.0)
|
||||
.center_y()
|
||||
.radius(radius::MD)
|
||||
.fill(color.alpha(0.12))
|
||||
.child(
|
||||
el().key("state-dot")
|
||||
.size(6.0, 6.0)
|
||||
.radius(3.0)
|
||||
.fill(color)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
text(if running { "Running" } else { "Not found" })
|
||||
.key("state-label")
|
||||
.font(body(10.5))
|
||||
.color(color),
|
||||
)
|
||||
}
|
||||
|
||||
/// A coloured dot used for status.
|
||||
pub fn dot(color: Color) -> El {
|
||||
el().key("dot")
|
||||
.size(8.0, 8.0)
|
||||
.radius(4.0)
|
||||
.fill(color)
|
||||
.a11y_hidden()
|
||||
}
|
||||
|
||||
/// A square champion portrait at `size` points: the Data Dragon file once it is on disk,
|
||||
/// initials on a colour derived from the name until then (and offline).
|
||||
pub fn champion_portrait(app: &App, p: Paint, champion: Option<&str>, size: f32) -> El {
|
||||
let name = champion.unwrap_or_default();
|
||||
let hue = name
|
||||
.bytes()
|
||||
.fold(2166136261u32, |hash, byte| {
|
||||
hash.wrapping_mul(16777619) ^ byte as u32
|
||||
})
|
||||
.rem_euclid(360) as f32;
|
||||
let (fill, ink) = if name.is_empty() {
|
||||
(p.t.control_off, p.muted())
|
||||
} else {
|
||||
(rune::oklch(0.36, 0.075, hue), rune::oklch(0.94, 0.02, hue))
|
||||
};
|
||||
let radius = (size * 0.14).max(2.0);
|
||||
let tile = el()
|
||||
.key("portrait")
|
||||
.size(size, size)
|
||||
.radius(radius)
|
||||
.fill(fill)
|
||||
.border(p.hair, ink.alpha(0.18))
|
||||
.a11y_hidden();
|
||||
match app
|
||||
.portraits
|
||||
.as_ref()
|
||||
.and_then(|portraits| portraits.image(name, size, p.scale))
|
||||
{
|
||||
Some(image) => tile.child(
|
||||
el().key("portrait-image")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.radius(radius)
|
||||
.pixels(image.pixels()),
|
||||
),
|
||||
None => tile.child(
|
||||
text(initials(name))
|
||||
.font(heading(size * 0.33))
|
||||
.color(ink)
|
||||
.center(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Up to two letters from the champion's name: `Kai'Sa` is KS, `Jinx` is J.
|
||||
fn initials(name: &str) -> String {
|
||||
let letters: Vec<char> = name
|
||||
.split(|c: char| !c.is_alphanumeric())
|
||||
.filter(|word| !word.is_empty())
|
||||
.filter_map(|word| word.chars().next())
|
||||
.take(2)
|
||||
.collect();
|
||||
if letters.is_empty() {
|
||||
"?".into()
|
||||
} else {
|
||||
letters.into_iter().collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A scroll viewport's scroll bar: a thumb in a strip of its own at the viewport's end edge,
|
||||
/// shown whenever the content overflows, and dragged to scroll.
|
||||
///
|
||||
/// The screen lays the thumb where the viewport's strip is (the content leaves it room), so it
|
||||
/// never draws over a card. `follow` takes where the viewport is, `thumb` draws it.
|
||||
pub struct ScrollBar {
|
||||
area: rune::Live<[f32; 4]>,
|
||||
thumb: rune::Live<[f32; 4]>,
|
||||
last: std::rc::Rc<std::cell::Cell<rune::ScrollPos>>,
|
||||
}
|
||||
|
||||
impl Default for ScrollBar {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ScrollBar {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
area: rune::Live::new([0.0; 4]),
|
||||
thumb: rune::Live::new([0.0; 4]),
|
||||
last: std::rc::Rc::new(std::cell::Cell::new(rune::ScrollPos::default())),
|
||||
}
|
||||
}
|
||||
/// Where the viewport is scrolled to, as of the last frame that reported it.
|
||||
///
|
||||
/// A screen can read this to load more rows as the end of a long list comes into view.
|
||||
pub fn position(&self) -> rune::ScrollPos {
|
||||
self.last.get()
|
||||
}
|
||||
|
||||
/// Make this viewport's scrolling move the thumb, and its key one a drag can scroll to.
|
||||
pub fn follow(&self, key: &'static str, viewport: El) -> El {
|
||||
let reported = self.area.clone();
|
||||
let area = self.area.clone();
|
||||
let thumb = self.thumb.clone();
|
||||
let layout_thumb = self.thumb.clone();
|
||||
let last = self.last.clone();
|
||||
let layout_last = self.last.clone();
|
||||
viewport
|
||||
.on_layout_tx(move |_app: &mut App, rect, tx| {
|
||||
reported.set(rect);
|
||||
place(&layout_thumb, rect, layout_last.get());
|
||||
tx.live_only();
|
||||
})
|
||||
.on_scroll_offset(move |at: rune::ScrollPos| {
|
||||
last.set(at);
|
||||
place(&thumb, area.get(), at);
|
||||
})
|
||||
.key(key)
|
||||
}
|
||||
|
||||
/// The thumb, drawn over the window. `key` must differ per bar on one screen.
|
||||
pub fn thumb(&self, p: Paint, key: &'static str, viewport: &'static str) -> El {
|
||||
let last = self.last.clone();
|
||||
let area = self.area.clone();
|
||||
el().key(key)
|
||||
.absolute(0.0, 0.0)
|
||||
.size(10.0, 0.0)
|
||||
.radius(5.0)
|
||||
.fill(p.t.text_secondary.alpha(0.45))
|
||||
.hover(p.t.text_secondary.alpha(0.8))
|
||||
.live_rect(&self.thumb)
|
||||
.a11y_hidden()
|
||||
.on_drag_any(move |d: &mut rune::Drag, tx: &mut rune::Tx| {
|
||||
tx.live_only();
|
||||
let at = last.get();
|
||||
let max = at.max[1];
|
||||
let [_, _, _, area_h] = area.get();
|
||||
let travel = (area_h - d.h).max(1.0);
|
||||
if max <= 0.5 || area_h <= 1.0 {
|
||||
return;
|
||||
}
|
||||
match d.phase {
|
||||
rune::Phase::Down => d.data = at.offset[1],
|
||||
rune::Phase::Move => {
|
||||
let y = (d.data + d.dy * max / travel).clamp(0.0, max);
|
||||
tx.scroll_to(viewport, 0.0, y);
|
||||
}
|
||||
rune::Phase::Up => {}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the thumb where `at` says the viewport is, inside `area`'s window rect.
|
||||
fn place(thumb: &rune::Live<[f32; 4]>, [x, y, w, h]: [f32; 4], at: rune::ScrollPos) {
|
||||
let content = at.viewport[1] + at.max[1];
|
||||
if h <= 1.0 || w <= 1.0 || at.max[1] <= 0.5 || content <= 0.0 {
|
||||
thumb.set([0.0, 0.0, 0.0, 0.0]);
|
||||
return;
|
||||
}
|
||||
let height = (h * at.viewport[1] / content).clamp(28.0, h);
|
||||
let progress = (at.offset[1] / at.max[1]).clamp(0.0, 1.0);
|
||||
thumb.set([x + w - 12.0, y + progress * (h - height), 10.0, height]);
|
||||
}
|
||||
|
||||
/// A small square button holding an icon: the trigger a menu opens from. Its handler says what
|
||||
/// opening means; the menu itself is drawn in the window, so it can never leave it.
|
||||
pub fn menu_button(
|
||||
p: Paint,
|
||||
key: impl Into<String>,
|
||||
icon: &'static rune::Icon,
|
||||
label: &str,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
el().key(key.into())
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.size(24.0, 24.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(on_press)
|
||||
.child(rune::icon(icon, 18.0).color(p.muted()).a11y_hidden())
|
||||
}
|
||||
|
||||
/// A quiet destructive button: danger ink for a confirm whose answer cannot be undone.
|
||||
pub fn button_danger(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
label: &str,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
el().key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.h(28.0)
|
||||
.px(14.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(p.danger.alpha(0.14))
|
||||
.border(p.hair, p.danger.alpha(0.32))
|
||||
.hover(p.danger.alpha(0.22))
|
||||
.press(p.danger.alpha(0.3))
|
||||
.on_press(on_press)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::LABEL)
|
||||
.color(p.danger)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "6e1143dda817360dd3a2a64f9133c6e5dfabd881"
|
||||
},
|
||||
"path_in_vcs": "parley_engine"
|
||||
}
|
||||
+545
@@ -0,0 +1,545 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck"
|
||||
version = "1.25.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
|
||||
dependencies = [
|
||||
"bytemuck_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck_derive"
|
||||
version = "1.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core_maths"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
|
||||
dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81bf886368962a7d8456f136073ed33ed1b0770c690d2063731bb6a776e99f33"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fontique"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbf1df16263783918b7da396077521f92b729ef7c429444dfcf03581f1448b77"
|
||||
dependencies = [
|
||||
"hashbrown",
|
||||
"linebender_resource_handle",
|
||||
"memmap2",
|
||||
"parlance",
|
||||
"read-fonts",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "harfrust"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"bytemuck",
|
||||
"core_maths",
|
||||
"read-fonts",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_collections"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"potential_utf",
|
||||
"utf8_iter",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_core"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"litemap",
|
||||
"serde",
|
||||
"tinystr",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_fallback"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9"
|
||||
dependencies = [
|
||||
"icu_locale_core",
|
||||
"icu_locale_fallback_data",
|
||||
"icu_provider",
|
||||
"potential_utf",
|
||||
"tinystr",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_fallback_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8"
|
||||
|
||||
[[package]]
|
||||
name = "icu_normalizer"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
|
||||
dependencies = [
|
||||
"icu_collections",
|
||||
"icu_normalizer_data",
|
||||
"icu_properties",
|
||||
"icu_provider",
|
||||
"smallvec",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_normalizer_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
|
||||
|
||||
[[package]]
|
||||
name = "icu_properties"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"icu_collections",
|
||||
"icu_locale_core",
|
||||
"icu_properties_data",
|
||||
"icu_provider",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_properties_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
|
||||
|
||||
[[package]]
|
||||
name = "icu_provider"
|
||||
version = "2.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"icu_locale_core",
|
||||
"serde",
|
||||
"stable_deref_trait",
|
||||
"writeable",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_segmenter"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82d07aafccd67af15d02512a6adf5896fbc5ed00f2e99b471d2efa14016db3db"
|
||||
dependencies = [
|
||||
"icu_collections",
|
||||
"icu_locale_fallback",
|
||||
"icu_provider",
|
||||
"icu_segmenter_data",
|
||||
"potential_utf",
|
||||
"smallvec",
|
||||
"utf8_iter",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_segmenter_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.186"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "linebender_resource_handle"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
|
||||
[[package]]
|
||||
name = "litemap"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
|
||||
|
||||
[[package]]
|
||||
name = "memmap2"
|
||||
version = "0.9.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "parlance"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parley_data"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c43b63f808f6cc8f4a3b07de0d62a977bddd2e0bb5c232bd9e93ba8ef92e5e4b"
|
||||
dependencies = [
|
||||
"icu_collections",
|
||||
"icu_properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parley_emoji"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c4482d912d7671a7cd2089794f90ef3bb5f5f8c738230fb0fcd50fa020f0ed3"
|
||||
|
||||
[[package]]
|
||||
name = "parley_engine"
|
||||
version = "0.12.0"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust",
|
||||
"hashbrown",
|
||||
"icu_locale_core",
|
||||
"icu_normalizer",
|
||||
"icu_properties",
|
||||
"icu_segmenter",
|
||||
"linebender_resource_handle",
|
||||
"parlance",
|
||||
"parley_data",
|
||||
"parley_emoji",
|
||||
"skrifa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.41.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"core_maths",
|
||||
"font-types",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.44.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"core_maths",
|
||||
"read-fonts",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.16.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synstructure"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinystr"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"serde_core",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
|
||||
dependencies = [
|
||||
"stable_deref_trait",
|
||||
"yoke-derive",
|
||||
"zerofrom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yoke-derive"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom"
|
||||
version = "0.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
|
||||
dependencies = [
|
||||
"zerofrom-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom-derive"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerovec"
|
||||
version = "0.11.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerovec-derive"
|
||||
version = "0.11.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
Vendored
+162
@@ -0,0 +1,162 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
name = "parley_engine"
|
||||
version = "0.12.0"
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Parley Engine provides low level APIs for implementing text layout."
|
||||
readme = "README.md"
|
||||
keywords = [
|
||||
"text",
|
||||
"layout",
|
||||
]
|
||||
categories = [
|
||||
"gui",
|
||||
"graphics",
|
||||
]
|
||||
license = "Apache-2.0 OR MIT"
|
||||
repository = "https://github.com/linebender/parley"
|
||||
resolver = "2"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
[features]
|
||||
bytemuck = [
|
||||
"fontique/bytemuck",
|
||||
"parlance/bytemuck",
|
||||
]
|
||||
complex-scripts = []
|
||||
line-dictionaries = []
|
||||
default = ["std"]
|
||||
libm = [
|
||||
"fontique/libm",
|
||||
"harfrust/libm",
|
||||
"skrifa/libm",
|
||||
]
|
||||
std = [
|
||||
"fontique/std",
|
||||
"harfrust/std",
|
||||
"parlance/std",
|
||||
"parley_emoji/std",
|
||||
"skrifa/std",
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "parley_engine"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies.fontique]
|
||||
version = "0.12.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.harfrust]
|
||||
version = "0.12.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.hashbrown]
|
||||
version = "0.17.1"
|
||||
features = [
|
||||
"default-hasher",
|
||||
"raw-entry",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[dependencies.icu_locale_core]
|
||||
version = "2.3.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.icu_normalizer]
|
||||
version = "2.3.0"
|
||||
features = ["compiled_data"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.icu_properties]
|
||||
version = "2.3.0"
|
||||
features = ["compiled_data"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.icu_segmenter]
|
||||
version = "2.3.0"
|
||||
features = ["compiled_data"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.linebender_resource_handle]
|
||||
version = "0.1.1"
|
||||
default-features = false
|
||||
|
||||
[dependencies.parlance]
|
||||
version = "0.1.1"
|
||||
default-features = false
|
||||
|
||||
[dependencies.parley_data]
|
||||
version = "0.12.0"
|
||||
features = ["baked"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.parley_emoji]
|
||||
version = "0.12.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.skrifa]
|
||||
version = "0.44.0"
|
||||
default-features = false
|
||||
|
||||
[lints.clippy]
|
||||
allow_attributes_without_reason = "warn"
|
||||
cargo_common_metadata = "warn"
|
||||
cast_possible_truncation = "warn"
|
||||
collection_is_never_read = "warn"
|
||||
dbg_macro = "warn"
|
||||
debug_assert_with_mut_call = "warn"
|
||||
default_trait_access = "warn"
|
||||
doc_markdown = "warn"
|
||||
fn_to_numeric_cast_any = "warn"
|
||||
infinite_loop = "warn"
|
||||
large_stack_arrays = "warn"
|
||||
mismatching_type_param_order = "warn"
|
||||
missing_assert_message = "warn"
|
||||
missing_fields_in_debug = "warn"
|
||||
negative_feature_names = "warn"
|
||||
redundant_feature_names = "warn"
|
||||
same_functions_in_if_condition = "warn"
|
||||
semicolon_if_nothing_returned = "warn"
|
||||
should_panic_without_expect = "warn"
|
||||
todo = "warn"
|
||||
too_many_arguments = "allow"
|
||||
unseparated_literal_suffix = "warn"
|
||||
use_self = "warn"
|
||||
wildcard_dependencies = "warn"
|
||||
|
||||
[lints.rust]
|
||||
elided_lifetimes_in_paths = "warn"
|
||||
keyword_idents_2024 = "forbid"
|
||||
missing_debug_implementations = "warn"
|
||||
missing_docs = "warn"
|
||||
non_ascii_idents = "forbid"
|
||||
non_local_definitions = "forbid"
|
||||
trivial_numeric_casts = "warn"
|
||||
unnameable_types = "warn"
|
||||
unreachable_pub = "warn"
|
||||
unsafe_code = "deny"
|
||||
unsafe_op_in_unsafe_fn = "forbid"
|
||||
unused_import_braces = "warn"
|
||||
unused_lifetimes = "warn"
|
||||
unused_macro_rules = "warn"
|
||||
unused_qualifications = "warn"
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
[package]
|
||||
name = "parley_engine"
|
||||
version.workspace = true
|
||||
description = "Parley Engine provides low level APIs for implementing text layout."
|
||||
keywords = ["text", "layout"]
|
||||
categories = ["gui", "graphics"]
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = ["fontique/std", "harfrust/std", "parlance/std", "parley_emoji/std", "skrifa/std"]
|
||||
libm = ["fontique/libm", "harfrust/libm", "skrifa/libm"]
|
||||
bytemuck = ["fontique/bytemuck", "parlance/bytemuck"]
|
||||
# Enables dictionary-based line and word breaking for complex scripts (CJK, Thai, Khmer, Lao, Myanmar).
|
||||
# When disabled, a lightweight segmenter is used that falls back to character-level breaks for those scripts.
|
||||
complex-scripts = []
|
||||
|
||||
[dependencies]
|
||||
fontique = { workspace = true }
|
||||
parlance = { workspace = true }
|
||||
parley_data = { workspace = true, features = ["baked"] }
|
||||
parley_emoji = { workspace = true }
|
||||
|
||||
harfrust = { workspace = true }
|
||||
hashbrown = { workspace = true }
|
||||
icu_locale_core = { workspace = true }
|
||||
icu_normalizer = { workspace = true, features = ["compiled_data"] }
|
||||
icu_properties = { workspace = true, features = ["compiled_data"] }
|
||||
icu_segmenter = { workspace = true, features = ["compiled_data"] }
|
||||
linebender_resource_handle = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
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
|
||||
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
Copyright 2025 the Parley Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
Vendored
+137
@@ -0,0 +1,137 @@
|
||||
<div align="center">
|
||||
|
||||
# Parley Engine
|
||||
|
||||
**Low level text layout**
|
||||
|
||||
[](https://crates.io/crates/parley_engine)
|
||||
[](https://docs.rs/parley_engine)
|
||||
[](#license)
|
||||
\
|
||||
[](https://xi.zulipchat.com/#narrow/channel/205635-parley)
|
||||
[](https://github.com/linebender/parley/actions)
|
||||
[](https://deps.rs/crate/parley_engine)
|
||||
|
||||
</div>
|
||||
|
||||
<!-- We use cargo-rdme to update the README with the contents of lib.rs.
|
||||
To edit the following section, update it in lib.rs, then run:
|
||||
cargo rdme --workspace-project=parley_engine --heading-base-level=0
|
||||
Full documentation at https://github.com/orium/cargo-rdme -->
|
||||
|
||||
<!-- Intra-doc links used in lib.rs should be evaluated here.
|
||||
See https://linebender.org/blog/doc-include/ for related discussion. -->
|
||||
|
||||
<!-- cargo-rdme start -->
|
||||
|
||||
Parley Engine provides low level APIs for shaping paragraphs of text.
|
||||
|
||||
## Usage
|
||||
|
||||
Use [`Analyzer`], [`Analysis`], [`Shaper`] and [`ShapedText`] to shape a paragraph of text into
|
||||
glyphs. Correct reshaping of lines is in progress; in the meantime you can break text at
|
||||
[`Atom`] or [`ShapedCluster`][crate::shape::ShapedCluster] boundaries.
|
||||
|
||||
Text analysis is performed before shaping, and the same source string must be passed to each
|
||||
stage.
|
||||
|
||||
Higher-level users may prefer using [`parley`][parley], which uses this crate and implements
|
||||
layout and styling.
|
||||
|
||||
```rust
|
||||
let mut analysis = Analysis::default();
|
||||
let mut analyzer = Analyzer::default();
|
||||
let mut shaped_text = ShapedText::default();
|
||||
let mut shaper = Shaper::default();
|
||||
|
||||
let text = "The quick brown ثعلب jumps over the lazy dog.";
|
||||
let char_count = text.chars().count();
|
||||
let char_style_indices = vec![0; char_count];
|
||||
|
||||
analyzer.analyze(text, &AnalysisOptions::default(), &mut analysis);
|
||||
shaper.shape_text(
|
||||
text,
|
||||
&analysis,
|
||||
&char_style_indices,
|
||||
[Item {
|
||||
char_end: char_count.try_into().unwrap(),
|
||||
options: ShapeOptions {
|
||||
font_size: 16.0,
|
||||
language: None,
|
||||
features: &[],
|
||||
variations: &[],
|
||||
},
|
||||
}],
|
||||
select_font, // Selects fonts covering each cluster.
|
||||
&mut shaped_text,
|
||||
);
|
||||
|
||||
for (run_idx, run) in shaped_text.runs().iter().enumerate() {
|
||||
let slice = shaped_text.run_slice(run_idx as u32);
|
||||
// You can, for example, measure grapheme advances for hit-testing or
|
||||
// placing carets.
|
||||
for atom in slice.atoms_start() {
|
||||
for grapheme in atom.graphemes_start() {
|
||||
std::dbg!(grapheme);
|
||||
}
|
||||
}
|
||||
|
||||
// Or get glyphs for rendering (for simplicity, this iterates clusters in
|
||||
// logical order, but for rendering you'd want to reorder runs and clusters
|
||||
// according to their `run.bidi_level`).
|
||||
for cluster in slice.shaped_clusters_range() {
|
||||
for glyph in slice.shaped_cluster_glyphs(cluster) {
|
||||
std::dbg!(glyph);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- `std` (enabled by default): This is currently unused and is provided for forward compatibility.
|
||||
- `bytemuck`: Forwarded to [`parlance`], which then implements traits from `bytemuck` on its
|
||||
types.
|
||||
|
||||
[parley]: https://docs.rs/parley
|
||||
|
||||
<!-- cargo-rdme end -->
|
||||
|
||||
## Minimum supported Rust Version (MSRV)
|
||||
|
||||
This version of Parley Engine has been verified to compile with **Rust 1.88** and later.
|
||||
|
||||
Future versions of Parley Engine might increase the Rust version requirement.
|
||||
It will not be treated as a breaking change and as such can even happen with small patch releases.
|
||||
|
||||
<details>
|
||||
<summary>Click here if compiling fails.</summary>
|
||||
|
||||
As time has passed, some of Parley Engine's dependencies could have released versions with a higher Rust requirement.
|
||||
If you encounter a compilation issue due to a dependency and don't want to upgrade your Rust toolchain, then you could downgrade the dependency.
|
||||
|
||||
```sh
|
||||
# Use the problematic dependency's name and version
|
||||
cargo update -p package_name --precise 0.1.1
|
||||
```
|
||||
</details>
|
||||
|
||||
## Community
|
||||
|
||||
Discussion of Parley Engine development happens in the [Linebender Zulip](https://xi.zulipchat.com/), specifically the [#parley channel](https://xi.zulipchat.com/#narrow/channel/205635-parley).
|
||||
All public content can be read without logging in.
|
||||
|
||||
Contributions are welcome by pull request. The [Rust code of conduct] applies.
|
||||
|
||||
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache 2.0 license, shall be licensed as noted in the [License](#license) section, without any additional terms or conditions.
|
||||
|
||||
## License
|
||||
|
||||
Licensed under either of
|
||||
|
||||
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
|
||||
|
||||
at your option.
|
||||
|
||||
[Rust code of conduct]: https://www.rust-lang.org/policies/code-of-conduct
|
||||
+934
@@ -0,0 +1,934 @@
|
||||
// Copyright 2025 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Text analysis.
|
||||
//!
|
||||
//! Analysis is performed prior to shaping and is independent of fonts, turning a `&str` into
|
||||
//! [`Analysis`].
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use core::ops::Range;
|
||||
|
||||
use icu_locale_core::{LanguageIdentifier, langid};
|
||||
use icu_normalizer::properties::{
|
||||
CanonicalComposition, CanonicalCompositionBorrowed, CanonicalDecomposition,
|
||||
CanonicalDecompositionBorrowed,
|
||||
};
|
||||
use icu_properties::props::{BidiMirroringGlyph, GeneralCategory, GraphemeClusterBreak, Script};
|
||||
use icu_properties::{
|
||||
CodePointMapData, CodePointMapDataBorrowed, PropertyNamesShort, PropertyNamesShortBorrowed,
|
||||
};
|
||||
use icu_segmenter::options::{
|
||||
LineBreakOptions, LineBreakStrictness, LineBreakWordOption, WordBreakInvariantOptions,
|
||||
};
|
||||
use icu_segmenter::{
|
||||
GraphemeClusterSegmenter, GraphemeClusterSegmenterBorrowed, LineSegmenter,
|
||||
LineSegmenterBorrowed, WordSegmenter, WordSegmenterBorrowed,
|
||||
};
|
||||
use parlance::{BaseDirection, BidiLevel, LineBreak, WordBreak};
|
||||
use parley_data::Properties;
|
||||
|
||||
use crate::bidi;
|
||||
use crate::break_overrides::LineBreakContext;
|
||||
use crate::{AnalysisOptions, Analyzer, LineBreakConfig};
|
||||
|
||||
/// The result of [`Analyzer::analyze`].
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Analysis {
|
||||
/// Info for each character.
|
||||
pub(crate) info: Vec<CharInfo>,
|
||||
|
||||
/// Bidi level for each character, parallel to `info`.
|
||||
///
|
||||
/// Empty if the text is all LTR.
|
||||
pub(crate) levels: Vec<BidiLevel>,
|
||||
|
||||
/// The base bidi level of the paragraph of text.
|
||||
pub(crate) paragraph_level: BidiLevel,
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
/// Create a reusable [`Analysis`].
|
||||
///
|
||||
/// Pass this to [`Analyzer::analyze`].
|
||||
#[inline]
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Clear the result while retaining capacity.
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.info.clear();
|
||||
self.levels.clear();
|
||||
self.paragraph_level = BidiLevel::new(0);
|
||||
}
|
||||
|
||||
/// The per-character info in source order.
|
||||
#[inline(always)]
|
||||
pub fn char_info(&self) -> &[CharInfo] {
|
||||
&self.info
|
||||
}
|
||||
|
||||
/// The bidi level for each character, parallel to [`Self::char_info`].
|
||||
///
|
||||
/// Empty when the whole paragraph is left-to-right.
|
||||
#[inline(always)]
|
||||
pub fn bidi_levels(&self) -> &[BidiLevel] {
|
||||
&self.levels
|
||||
}
|
||||
|
||||
/// The base bidi level of the paragraph of text.
|
||||
#[inline(always)]
|
||||
pub fn paragraph_level(&self) -> BidiLevel {
|
||||
self.paragraph_level
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Make `pub(crate)` once `parley_engine` owns shaping.
|
||||
#[doc(hidden)]
|
||||
#[expect(missing_debug_implementations, reason = "Will become private")]
|
||||
pub struct AnalysisDataSources;
|
||||
|
||||
impl AnalysisDataSources {
|
||||
#[expect(clippy::new_without_default, reason = "Will become private")]
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn properties(&self, c: char) -> Properties {
|
||||
Properties::get(c)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn grapheme_segmenter(&self) -> GraphemeClusterSegmenterBorrowed<'_> {
|
||||
const { GraphemeClusterSegmenter::new() }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn word_segmenter(&self) -> WordSegmenterBorrowed<'static> {
|
||||
#[cfg(feature = "complex-scripts")]
|
||||
{
|
||||
WordSegmenter::new_dictionary(WordBreakInvariantOptions::default())
|
||||
}
|
||||
#[cfg(not(feature = "complex-scripts"))]
|
||||
{
|
||||
const { WordSegmenter::new_for_non_complex_scripts(WordBreakInvariantOptions::default()) }
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn line_segmenter(&self, key: SegmenterKey) -> LineSegmenterBorrowed<'static> {
|
||||
// We use Japanese arbitrarily; see `SegmenterKey::ja_zh`.
|
||||
static JA: LanguageIdentifier = langid!("ja");
|
||||
|
||||
let mut opt = LineBreakOptions::default();
|
||||
opt.word_option = Some(key.word_option);
|
||||
opt.strictness = Some(key.strictness);
|
||||
opt.content_locale = key.ja_zh.then_some(&JA);
|
||||
line_segmenter_impl(opt)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn composing_normalizer(&self) -> CanonicalCompositionBorrowed<'_> {
|
||||
const { CanonicalComposition::new() }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn decomposing_normalizer(&self) -> CanonicalDecompositionBorrowed<'_> {
|
||||
const { CanonicalDecomposition::new() }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn script_short_name(&self) -> PropertyNamesShortBorrowed<'static, Script> {
|
||||
PropertyNamesShort::new()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn brackets(&self) -> CodePointMapDataBorrowed<'_, BidiMirroringGlyph> {
|
||||
const { CodePointMapData::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The segmenters an [`Analyzer`] has made, kept for its next texts (Rune:
|
||||
/// vendor/parley_engine.patch). Making one looks up its rule data and, with `complex-scripts`,
|
||||
/// loads the dictionaries; they're `'static` and `Copy`, so a kept one is the same value a new
|
||||
/// one would be.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Segmenters {
|
||||
line: Vec<(SegmenterKey, LineSegmenterBorrowed<'static>)>,
|
||||
word: Option<WordSegmenterBorrowed<'static>>,
|
||||
}
|
||||
|
||||
impl Segmenters {
|
||||
fn line(&mut self, key: SegmenterKey) -> LineSegmenterBorrowed<'static> {
|
||||
if let Some((_, segmenter)) = self.line.iter().find(|(k, _)| *k == key) {
|
||||
return *segmenter;
|
||||
}
|
||||
let segmenter = AnalysisDataSources::new().line_segmenter(key);
|
||||
self.line.push((key, segmenter));
|
||||
segmenter
|
||||
}
|
||||
|
||||
fn word(&mut self) -> WordSegmenterBorrowed<'static> {
|
||||
*self
|
||||
.word
|
||||
.get_or_insert_with(|| AnalysisDataSources::new().word_segmenter())
|
||||
}
|
||||
}
|
||||
|
||||
// `line-dictionaries` (Rune: vendor/parley_engine.patch): the line segmenter's Thai, Lao, Khmer and
|
||||
// Burmese dictionaries without the word segmenter's (Chinese and Japanese words come from the host's
|
||||
// `dictionary` segmenter instead).
|
||||
#[cfg(any(feature = "complex-scripts", feature = "line-dictionaries"))]
|
||||
#[inline(always)]
|
||||
fn line_segmenter_impl(opt: LineBreakOptions<'_>) -> LineSegmenterBorrowed<'static> {
|
||||
LineSegmenter::new_dictionary(opt)
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "complex-scripts", feature = "line-dictionaries")))]
|
||||
#[inline(always)]
|
||||
fn line_segmenter_impl(opt: LineBreakOptions<'_>) -> LineSegmenterBorrowed<'static> {
|
||||
LineSegmenter::new_for_non_complex_scripts(opt)
|
||||
}
|
||||
|
||||
/// The line segmenter configuration for a [`LineBreakConfig`].
|
||||
///
|
||||
/// Configurations which result in the same segmentation map to the same key.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct SegmenterKey {
|
||||
word_option: LineBreakWordOption,
|
||||
strictness: LineBreakStrictness,
|
||||
/// See [`LineBreakConfig::language`]; the only languages which impact segmentation are
|
||||
/// Chinese and Japanese. These impact it in the same way, and only under
|
||||
/// [`LineBreak::Normal`] and [`LineBreak::Loose`], so we only track whether one of them
|
||||
/// applies.
|
||||
ja_zh: bool,
|
||||
}
|
||||
|
||||
impl SegmenterKey {
|
||||
const DEFAULT: Self = Self {
|
||||
word_option: LineBreakWordOption::Normal,
|
||||
strictness: LineBreakStrictness::Strict,
|
||||
ja_zh: false,
|
||||
};
|
||||
|
||||
fn new(config: &LineBreakConfig) -> Self {
|
||||
let strictness = match config.line_break {
|
||||
LineBreak::Strict => LineBreakStrictness::Strict,
|
||||
LineBreak::Normal => LineBreakStrictness::Normal,
|
||||
LineBreak::Loose => LineBreakStrictness::Loose,
|
||||
// We add opportunities per grapheme ourselves.
|
||||
LineBreak::Anywhere => return Self::DEFAULT,
|
||||
};
|
||||
let word_option = match config.word_break {
|
||||
WordBreak::Normal => LineBreakWordOption::Normal,
|
||||
WordBreak::BreakAll => LineBreakWordOption::BreakAll,
|
||||
WordBreak::KeepAll => LineBreakWordOption::KeepAll,
|
||||
};
|
||||
let ja_zh = match strictness {
|
||||
LineBreakStrictness::Normal | LineBreakStrictness::Loose => config
|
||||
.language
|
||||
.is_some_and(|language| matches!(language.language(), "ja" | "zh")),
|
||||
_ => false,
|
||||
};
|
||||
Self {
|
||||
word_option,
|
||||
strictness,
|
||||
ja_zh,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-character analysis info.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CharInfo {
|
||||
/// The Unicode script this character belongs to.
|
||||
pub script: Script,
|
||||
flags: u16,
|
||||
}
|
||||
|
||||
impl CharInfo {
|
||||
const VARIATION_SELECTOR_SHIFT: u16 = 0;
|
||||
const REGION_INDICATOR_SHIFT: u16 = 1;
|
||||
const CONTROL_SHIFT: u16 = 2;
|
||||
const EMOJI_OR_PICTOGRAPH_SHIFT: u16 = 3;
|
||||
const CONTRIBUTES_TO_SHAPING_SHIFT: u16 = 4;
|
||||
const FORCE_NORMALIZE_SHIFT: u16 = 5;
|
||||
const GRAPHEME_START_SHIFT: u16 = 6;
|
||||
const WORD_BOUNDARY_SHIFT: u8 = 7;
|
||||
const SOFT_WRAP_OPPORTUNITY_SHIFT: u16 = 8;
|
||||
const EMOJI_SHIFT: u16 = 9;
|
||||
const EMOJI_PRESENTATION_SHIFT: u16 = 10;
|
||||
const EMOJI_MODIFIER_SHIFT: u16 = 11;
|
||||
const EMOJI_MODIFIER_BASE_SHIFT: u16 = 12;
|
||||
|
||||
const VARIATION_SELECTOR_MASK: u16 = 1 << Self::VARIATION_SELECTOR_SHIFT;
|
||||
const REGION_INDICATOR_MASK: u16 = 1 << Self::REGION_INDICATOR_SHIFT;
|
||||
const CONTROL_MASK: u16 = 1 << Self::CONTROL_SHIFT;
|
||||
const EMOJI_OR_PICTOGRAPH_MASK: u16 = 1 << Self::EMOJI_OR_PICTOGRAPH_SHIFT;
|
||||
const CONTRIBUTES_TO_SHAPING_MASK: u16 = 1 << Self::CONTRIBUTES_TO_SHAPING_SHIFT;
|
||||
const FORCE_NORMALIZE_MASK: u16 = 1 << Self::FORCE_NORMALIZE_SHIFT;
|
||||
const GRAPHEME_START_MASK: u16 = 1 << Self::GRAPHEME_START_SHIFT;
|
||||
const WORD_BOUNDARY_MASK: u16 = 1 << Self::WORD_BOUNDARY_SHIFT;
|
||||
const SOFT_WRAP_OPPORTUNITY_MASK: u16 = 1 << Self::SOFT_WRAP_OPPORTUNITY_SHIFT;
|
||||
const EMOJI_MASK: u16 = 1 << Self::EMOJI_SHIFT;
|
||||
const EMOJI_PRESENTATION_MASK: u16 = 1 << Self::EMOJI_PRESENTATION_SHIFT;
|
||||
const EMOJI_MODIFIER_MASK: u16 = 1 << Self::EMOJI_MODIFIER_SHIFT;
|
||||
const EMOJI_MODIFIER_BASE_MASK: u16 = 1 << Self::EMOJI_MODIFIER_BASE_SHIFT;
|
||||
|
||||
fn new(
|
||||
script: Script,
|
||||
is_variation_selector: bool,
|
||||
is_region_indicator: bool,
|
||||
is_control: bool,
|
||||
is_emoji_or_pictograph: bool,
|
||||
contributes_to_shaping: bool,
|
||||
force_normalize: bool,
|
||||
is_grapheme_start: bool,
|
||||
is_word_boundary: bool,
|
||||
is_soft_wrap_opportunity: bool,
|
||||
is_emoji: bool,
|
||||
is_emoji_presentation: bool,
|
||||
is_emoji_modifier: bool,
|
||||
is_emoji_modifier_base: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
script,
|
||||
flags: (is_variation_selector as u16) << Self::VARIATION_SELECTOR_SHIFT
|
||||
| (is_region_indicator as u16) << Self::REGION_INDICATOR_SHIFT
|
||||
| (is_control as u16) << Self::CONTROL_SHIFT
|
||||
| (is_emoji_or_pictograph as u16) << Self::EMOJI_OR_PICTOGRAPH_SHIFT
|
||||
| (contributes_to_shaping as u16) << Self::CONTRIBUTES_TO_SHAPING_SHIFT
|
||||
| (force_normalize as u16) << Self::FORCE_NORMALIZE_SHIFT
|
||||
| (is_grapheme_start as u16) << Self::GRAPHEME_START_SHIFT
|
||||
| (is_word_boundary as u16) << Self::WORD_BOUNDARY_SHIFT
|
||||
| (is_soft_wrap_opportunity as u16) << Self::SOFT_WRAP_OPPORTUNITY_SHIFT
|
||||
| (is_emoji as u16) << Self::EMOJI_SHIFT
|
||||
| (is_emoji_presentation as u16) << Self::EMOJI_PRESENTATION_SHIFT
|
||||
| (is_emoji_modifier as u16) << Self::EMOJI_MODIFIER_SHIFT
|
||||
| (is_emoji_modifier_base as u16) << Self::EMOJI_MODIFIER_BASE_SHIFT,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this character is a variation selector.
|
||||
#[inline(always)]
|
||||
pub fn is_variation_selector(self) -> bool {
|
||||
self.flags & Self::VARIATION_SELECTOR_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character is a regional indicator symbol.
|
||||
#[inline(always)]
|
||||
pub fn is_region_indicator(self) -> bool {
|
||||
self.flags & Self::REGION_INDICATOR_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character is a control character.
|
||||
#[inline(always)]
|
||||
pub fn is_control(self) -> bool {
|
||||
self.flags & Self::CONTROL_MASK != 0
|
||||
}
|
||||
|
||||
/// Returns whether the character has either of the `Emoji` or`Extended_Pictographic` properties.
|
||||
///
|
||||
/// Parley Engine uses this to determine whether a character might be part of an Emoji, and so whether to do
|
||||
/// more stringent checks.
|
||||
///
|
||||
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
|
||||
#[inline(always)]
|
||||
pub fn is_emoji_or_pictograph(self) -> bool {
|
||||
self.flags & Self::EMOJI_OR_PICTOGRAPH_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character has the `Emoji` property ([UTS #51][]).
|
||||
///
|
||||
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
|
||||
#[inline(always)]
|
||||
pub fn is_emoji(self) -> bool {
|
||||
self.flags & Self::EMOJI_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character has the `Emoji_Presentation` property ([UTS #51][]), i.e. it is
|
||||
/// displayed as an emoji by default.
|
||||
///
|
||||
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
|
||||
#[inline(always)]
|
||||
pub fn is_emoji_presentation(self) -> bool {
|
||||
self.flags & Self::EMOJI_PRESENTATION_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character has the `Emoji_Modifier` property ([UTS #51][]), i.e. it is a
|
||||
/// skin tone modifier.
|
||||
///
|
||||
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
|
||||
#[inline(always)]
|
||||
pub fn is_emoji_modifier(self) -> bool {
|
||||
self.flags & Self::EMOJI_MODIFIER_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character has the `Emoji_Modifier_Base` property ([UTS #51][]), i.e. it can
|
||||
/// be followed by a skin tone modifier.
|
||||
///
|
||||
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
|
||||
#[inline(always)]
|
||||
pub fn is_emoji_modifier_base(self) -> bool {
|
||||
self.flags & Self::EMOJI_MODIFIER_BASE_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character contributes glyphs to shaping (`false` for control characters and
|
||||
/// most format characters).
|
||||
#[inline(always)]
|
||||
pub fn contributes_to_shaping(self) -> bool {
|
||||
self.flags & Self::CONTRIBUTES_TO_SHAPING_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character should be normalized before glyph mapping during shaping.
|
||||
#[inline(always)]
|
||||
pub fn force_normalize(self) -> bool {
|
||||
self.flags & Self::FORCE_NORMALIZE_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character begins a grapheme cluster ([UAX #29 § 3][graphemes]).
|
||||
///
|
||||
/// [graphemes]: https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
|
||||
#[inline(always)]
|
||||
pub fn is_grapheme_start(self) -> bool {
|
||||
self.flags & Self::GRAPHEME_START_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether there is a word boundary before this character ([UAX #29 § 4][words]).
|
||||
///
|
||||
/// [words]: https://www.unicode.org/reports/tr29/#Word_Boundaries
|
||||
#[inline(always)]
|
||||
pub fn is_word_boundary(self) -> bool {
|
||||
self.flags & Self::WORD_BOUNDARY_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether there is a soft wrap opportunity before this character ([UAX #14][line-breaking]).
|
||||
///
|
||||
/// Note mandatory breaks (like `\n`) are encoded as [`Whitespace`](crate::shape::Whitespace).
|
||||
///
|
||||
/// [line-breaking]: https://www.unicode.org/reports/tr14/
|
||||
#[inline(always)]
|
||||
pub fn is_soft_wrap_opportunity(self) -> bool {
|
||||
self.flags & Self::SOFT_WRAP_OPPORTUNITY_MASK != 0
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn analyze_text(
|
||||
analyzer: &mut Analyzer,
|
||||
text: &str,
|
||||
options: &AnalysisOptions<'_>,
|
||||
analysis: &mut Analysis,
|
||||
) {
|
||||
/// Turns the sparse, sorted, non-overlapping `options.line_break` into a contiguous sequence of
|
||||
/// `(range, segmenter key)` segments covering all of `text`.
|
||||
///
|
||||
/// Any region not covered by an override takes the default configuration.
|
||||
struct DenseLineBreaks<'a> {
|
||||
line_break: &'a [(Range<usize>, LineBreakConfig)],
|
||||
/// Index of the next word break to emit.
|
||||
next: usize,
|
||||
/// Start of the next segment to emit.
|
||||
cursor: usize,
|
||||
text_len: usize,
|
||||
}
|
||||
|
||||
impl<'a> DenseLineBreaks<'a> {
|
||||
fn new(line_break: &'a [(Range<usize>, LineBreakConfig)], text_len: usize) -> Self {
|
||||
Self {
|
||||
line_break,
|
||||
next: 0,
|
||||
cursor: 0,
|
||||
text_len,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for DenseLineBreaks<'_> {
|
||||
type Item = (Range<usize>, SegmenterKey);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.cursor >= self.text_len {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Ignore empty ranges.
|
||||
while self
|
||||
.line_break
|
||||
.get(self.next)
|
||||
.is_some_and(|(range, _)| range.is_empty())
|
||||
{
|
||||
self.next += 1;
|
||||
}
|
||||
|
||||
match self.line_break.get(self.next) {
|
||||
// A gap before the next override: fill it with the default up to its start.
|
||||
Some((range, _)) if self.cursor < range.start => {
|
||||
let segment = self.cursor..range.start;
|
||||
self.cursor = range.start;
|
||||
Some((segment, SegmenterKey::DEFAULT))
|
||||
}
|
||||
// At the next override: emit it.
|
||||
Some((range, config)) => {
|
||||
self.cursor = range.end;
|
||||
self.next += 1;
|
||||
Some((range.start..range.end, SegmenterKey::new(config)))
|
||||
}
|
||||
// No overrides remain: fill the default to the end.
|
||||
None => {
|
||||
let segment = self.cursor..self.text_len;
|
||||
self.cursor = self.text_len;
|
||||
Some((segment, SegmenterKey::DEFAULT))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LineBreakSegmentIter<'a, I: Iterator> {
|
||||
text: &'a str,
|
||||
segments: I,
|
||||
char_indices: core::str::CharIndices<'a>,
|
||||
current_char: (usize, char),
|
||||
building_range_start: usize,
|
||||
previous_key: SegmenterKey,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl<'a, I> LineBreakSegmentIter<'a, I>
|
||||
where
|
||||
I: Iterator<Item = (Range<usize>, SegmenterKey)>,
|
||||
{
|
||||
fn new(text: &'a str, segments: I, first_segment: (Range<usize>, SegmenterKey)) -> Self {
|
||||
let mut char_indices = text.char_indices();
|
||||
let current_char_len = char_indices.next().unwrap();
|
||||
|
||||
Self {
|
||||
text,
|
||||
segments,
|
||||
char_indices,
|
||||
current_char: current_char_len,
|
||||
building_range_start: first_segment.0.start,
|
||||
previous_key: first_segment.1,
|
||||
done: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, I> Iterator for LineBreakSegmentIter<'a, I>
|
||||
where
|
||||
I: Iterator<Item = (Range<usize>, SegmenterKey)>,
|
||||
{
|
||||
type Item = (&'a str, SegmenterKey, bool);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.done {
|
||||
return None;
|
||||
}
|
||||
|
||||
for (range, key) in self.segments.by_ref() {
|
||||
assert!(range.start < range.end, "Segments must not be empty");
|
||||
|
||||
let style_start_index = range.start;
|
||||
let mut prev_char_index = self.current_char;
|
||||
|
||||
// Find the character at the style boundary.
|
||||
while self.current_char.0 < style_start_index {
|
||||
prev_char_index = self.current_char;
|
||||
self.current_char = self.char_indices.next().unwrap();
|
||||
}
|
||||
|
||||
let current_key = key;
|
||||
if self.previous_key == current_key {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Produce one substring for each different segmenter key run
|
||||
let prev_size = prev_char_index.1.len_utf8();
|
||||
let size = self.current_char.1.len_utf8();
|
||||
|
||||
let substring = &self.text[self.building_range_start..style_start_index + size];
|
||||
let result_style = self.previous_key;
|
||||
|
||||
self.building_range_start = style_start_index - prev_size;
|
||||
self.previous_key = current_key;
|
||||
|
||||
return Some((substring, result_style, false));
|
||||
}
|
||||
|
||||
// Final segment
|
||||
self.done = true;
|
||||
let last_substring = &self.text[self.building_range_start..self.text.len()];
|
||||
Some((last_substring, self.previous_key, true))
|
||||
}
|
||||
}
|
||||
|
||||
if text.is_empty() {
|
||||
analyzer
|
||||
.bidi
|
||||
.resolve(core::iter::empty(), options.base_direction);
|
||||
analysis.paragraph_level = analyzer.bidi.base_level();
|
||||
return;
|
||||
}
|
||||
|
||||
// Line boundaries (word break naming refers to the line boundary determination config).
|
||||
//
|
||||
// This breaks text into sequences with similar line boundary config (part of style
|
||||
// information). If this config is consistent for all text, we use a fast path through this.
|
||||
let mut segments = DenseLineBreaks::new(options.line_break, text.len());
|
||||
// `text` is non-empty (checked above), so there is always at least one segment.
|
||||
let first_segment = segments.next().unwrap();
|
||||
let contiguous_substrings = LineBreakSegmentIter::new(text, segments, first_segment);
|
||||
|
||||
let mut global_offset = 0;
|
||||
let mut line_boundary_positions: Vec<usize> = Vec::new();
|
||||
|
||||
let data_sources = AnalysisDataSources::new();
|
||||
|
||||
for (substring_index, (substring, segmenter_key, last)) in contiguous_substrings.enumerate() {
|
||||
// Fast path for text with a single segmenter configuration.
|
||||
if substring_index == 0 && last {
|
||||
let mut lb_iter = analyzer
|
||||
.segmenters
|
||||
.line(segmenter_key)
|
||||
.segment_str(substring);
|
||||
|
||||
let _first = lb_iter.next();
|
||||
let second = lb_iter.next();
|
||||
if second.is_none() {
|
||||
continue;
|
||||
}
|
||||
let third = lb_iter.next();
|
||||
if third.is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let iter = [second.unwrap(), third.unwrap()].into_iter().chain(lb_iter);
|
||||
|
||||
line_boundary_positions.extend(iter);
|
||||
// Remove the unnecessary boundary at the end added by ICU4X.
|
||||
line_boundary_positions.pop();
|
||||
break;
|
||||
}
|
||||
|
||||
let line_boundaries_iter = analyzer
|
||||
.segmenters
|
||||
.line(segmenter_key)
|
||||
.segment_str(substring);
|
||||
|
||||
let mut substring_chars = substring.chars();
|
||||
if substring_index != 0 {
|
||||
global_offset -= substring_chars.next().unwrap().len_utf8();
|
||||
}
|
||||
// There will always be at least two characters if we are not taking the fast path for
|
||||
// a single word break style substring.
|
||||
let last_len = substring_chars.next_back().unwrap().len_utf8();
|
||||
|
||||
// Mark line boundaries (overriding word boundaries where present).
|
||||
for (index, pos) in line_boundaries_iter.enumerate() {
|
||||
// icu adds leading and trailing line boundaries, which we don't use.
|
||||
if index == 0 || pos == substring.len() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// For all but the last substring, we ignore line boundaries caused by the last
|
||||
// character, as this character is carried back from the next substring, and will be
|
||||
// accounted for there.
|
||||
if !last && pos == substring.len() - last_len {
|
||||
continue;
|
||||
}
|
||||
line_boundary_positions.push(pos + global_offset);
|
||||
}
|
||||
|
||||
if !last {
|
||||
global_offset += substring.len() - last_len;
|
||||
}
|
||||
}
|
||||
|
||||
// Words, and in Thai, Lao, Khmer and Burmese line breaks, that the host's dictionary finds
|
||||
// (`dictionary`; Rune: vendor/parley_engine.patch).
|
||||
let mut dictionary = crate::dictionary::Words::of(text, |c| data_sources.properties(c));
|
||||
let before = line_boundary_positions.len();
|
||||
line_boundary_positions.extend(dictionary.line_breaks());
|
||||
if line_boundary_positions.len() > before {
|
||||
line_boundary_positions.sort_unstable();
|
||||
line_boundary_positions.dedup();
|
||||
}
|
||||
|
||||
// Collect boundary byte positions compactly
|
||||
let mut wb_iter = analyzer.segmenters.word().segment_str(text).peekable();
|
||||
let mut gb_iter = data_sources
|
||||
.grapheme_segmenter()
|
||||
.segment_str(text)
|
||||
.peekable();
|
||||
|
||||
// Merge boundaries - line takes precedence over word
|
||||
let mut lb_iter = line_boundary_positions.iter().peekable();
|
||||
let mut prev_char = None;
|
||||
let mut prev_prev_char = None;
|
||||
// Whether the preceding character is a mandatory break.
|
||||
let mut prev_is_mandatory_linebreak = false;
|
||||
// Whether the preceding character is a break-space, i.e. a space, tab or ideographic space in
|
||||
// a `break_spaces` range.
|
||||
let mut prev_is_break_space = false;
|
||||
let mut break_spaces_iter = options.break_spaces.iter().peekable();
|
||||
let mut break_anywhere_iter = options
|
||||
.line_break
|
||||
.iter()
|
||||
.filter(|(_, config)| config.line_break == LineBreak::Anywhere)
|
||||
.map(|(range, _)| range)
|
||||
.peekable();
|
||||
let boundary_iter = text.char_indices().map(|(byte_pos, ch)| {
|
||||
// advance any stale word boundary positions
|
||||
while let Some(&w) = wb_iter.peek() {
|
||||
if w < byte_pos {
|
||||
_ = wb_iter.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// advance any stale grapheme boundary positions
|
||||
while let Some(&g) = gb_iter.peek() {
|
||||
if g < byte_pos {
|
||||
_ = gb_iter.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// advance any stale line boundary positions
|
||||
while let Some(&l) = lb_iter.peek() {
|
||||
if *l < byte_pos {
|
||||
_ = lb_iter.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let mut is_word = false;
|
||||
if let Some(&w) = wb_iter.peek()
|
||||
&& w == byte_pos
|
||||
{
|
||||
is_word = true;
|
||||
_ = wb_iter.next();
|
||||
}
|
||||
let mut is_grapheme_start = false;
|
||||
if let Some(&g) = gb_iter.peek()
|
||||
&& g == byte_pos
|
||||
{
|
||||
is_grapheme_start = true;
|
||||
_ = gb_iter.next();
|
||||
}
|
||||
let properties = data_sources.properties(ch);
|
||||
|
||||
// For characters requiring a dictionary for deciding word boundaries, apply
|
||||
// UAX #29 Rule WB999 in case there's no dictionary (because ICU4X does not); inside a run
|
||||
// the host's dictionary segmented, its boundaries decide.
|
||||
if let Some(bound) = dictionary.word_at(byte_pos) {
|
||||
is_word = bound;
|
||||
} else if !is_word
|
||||
&& is_grapheme_start
|
||||
&& properties.needs_dictionary_word_break()
|
||||
&& !has_word_dictionary(properties.script())
|
||||
{
|
||||
is_word = true;
|
||||
}
|
||||
|
||||
let is_icu_line = if let Some(&l) = lb_iter.peek()
|
||||
&& *l == byte_pos
|
||||
{
|
||||
_ = lb_iter.next();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
// CSS Text 4 § 4.3.1 `break-spaces`: a soft wrap opportunity exists after each preserved
|
||||
// space or tab (but never directly before a mandatory break, UAX #14 LB6).
|
||||
while break_spaces_iter
|
||||
.peek()
|
||||
.is_some_and(|range| range.end <= byte_pos)
|
||||
{
|
||||
_ = break_spaces_iter.next();
|
||||
}
|
||||
let after_break_space = prev_is_break_space;
|
||||
prev_is_break_space = break_spaces_iter
|
||||
.peek()
|
||||
.is_some_and(|range| range.contains(&byte_pos))
|
||||
&& matches!(ch, ' ' | '\t' | '\u{3000}');
|
||||
|
||||
while break_anywhere_iter
|
||||
.peek()
|
||||
.is_some_and(|range| range.end <= byte_pos)
|
||||
{
|
||||
_ = break_anywhere_iter.next();
|
||||
}
|
||||
let is_break_anywhere = break_anywhere_iter
|
||||
.peek()
|
||||
.is_some_and(|range| range.contains(&byte_pos));
|
||||
|
||||
let is_mandatory_linebreak = properties.is_mandatory_linebreak();
|
||||
|
||||
// We never have a soft wrap opportunity before a mandatory break (following UAX #14 LB6),
|
||||
// and we never have one right after a mandatory break: the mandatory break is handled
|
||||
// separately.
|
||||
let is_soft_wrap_opportunity = if is_mandatory_linebreak || prev_is_mandatory_linebreak {
|
||||
false
|
||||
} else {
|
||||
let mut opportunity = if is_break_anywhere {
|
||||
// `line-break: anywhere`: an opportunity around every grapheme.
|
||||
prev_char.is_some() && is_grapheme_start
|
||||
} else {
|
||||
is_icu_line || after_break_space
|
||||
};
|
||||
// Consumers can override soft wrap opportunities, except around a mandatory
|
||||
// break.
|
||||
if let (Some(prev), Some(lb_override)) = (prev_char, options.line_break_override) {
|
||||
let forced = lb_override(LineBreakContext {
|
||||
before_before: prev_prev_char,
|
||||
before: prev,
|
||||
after: ch,
|
||||
});
|
||||
if let Some(forced) = forced {
|
||||
opportunity = forced;
|
||||
}
|
||||
}
|
||||
opportunity
|
||||
};
|
||||
|
||||
prev_prev_char = prev_char;
|
||||
prev_char = Some(ch);
|
||||
prev_is_mandatory_linebreak = is_mandatory_linebreak;
|
||||
|
||||
(
|
||||
is_soft_wrap_opportunity,
|
||||
is_word,
|
||||
is_grapheme_start,
|
||||
ch,
|
||||
properties,
|
||||
)
|
||||
});
|
||||
|
||||
let mut needs_bidi_resolution = false;
|
||||
|
||||
analysis.info.reserve(text.len());
|
||||
for (is_soft_wrap_opportunity, is_word, is_grapheme_start, ch, properties) in boundary_iter {
|
||||
let script = properties.script();
|
||||
let grapheme_cluster_break = properties.grapheme_cluster_break();
|
||||
let bidi_class = properties.bidi_class();
|
||||
let general_category = properties.general_category();
|
||||
let is_emoji_or_pictograph = properties.is_emoji_or_pictograph();
|
||||
let is_variation_selector = properties.is_variation_selector();
|
||||
let is_region_indicator = properties.is_region_indicator();
|
||||
|
||||
let force_normalize = {
|
||||
// "Extend" break chars should be normalized first, with two exceptions
|
||||
if matches!(grapheme_cluster_break, GraphemeClusterBreak::Extend) &&
|
||||
ch as u32 != 0x200C && // Is not a Zero Width Non-Joiner &&
|
||||
!is_variation_selector
|
||||
{
|
||||
true
|
||||
} else {
|
||||
// All spacing mark break chars should be normalized first.
|
||||
matches!(grapheme_cluster_break, GraphemeClusterBreak::SpacingMark)
|
||||
}
|
||||
};
|
||||
|
||||
needs_bidi_resolution |= bidi::needs_bidi_resolution(bidi_class);
|
||||
|
||||
analysis.info.push(CharInfo::new(
|
||||
script,
|
||||
is_variation_selector,
|
||||
is_region_indicator,
|
||||
general_category == GeneralCategory::Control,
|
||||
is_emoji_or_pictograph,
|
||||
contributes_to_shaping(general_category, script),
|
||||
force_normalize,
|
||||
is_grapheme_start,
|
||||
is_word,
|
||||
is_soft_wrap_opportunity,
|
||||
properties.is_emoji(),
|
||||
properties.is_emoji_presentation(),
|
||||
properties.is_emoji_modifier(),
|
||||
properties.is_emoji_modifier_base(),
|
||||
));
|
||||
}
|
||||
|
||||
if needs_bidi_resolution || options.base_direction == BaseDirection::Rtl {
|
||||
analyzer.bidi.resolve(
|
||||
text.chars().map(|ch| {
|
||||
let bidi_class = data_sources.properties(ch).bidi_class();
|
||||
// TODO: maybe extend Properties to u64 to fit BidiMirroringGlyph
|
||||
let bracket = data_sources.brackets().get(ch);
|
||||
(ch, (bidi_class, bracket))
|
||||
}),
|
||||
options.base_direction,
|
||||
);
|
||||
core::mem::swap(&mut analysis.levels, &mut analyzer.bidi.levels);
|
||||
analysis.paragraph_level = analyzer.bidi.base_level();
|
||||
}
|
||||
}
|
||||
|
||||
/// All characters contribute to shaping except:
|
||||
/// - Control characters
|
||||
/// - Format characters, unless they use the "Inherited" script
|
||||
#[inline(always)]
|
||||
pub(crate) fn contributes_to_shaping(general_category: GeneralCategory, script: Script) -> bool {
|
||||
if matches!(
|
||||
general_category,
|
||||
GeneralCategory::Control
|
||||
| GeneralCategory::LineSeparator
|
||||
| GeneralCategory::ParagraphSeparator
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
!(general_category == GeneralCategory::Format && script != Script::Inherited)
|
||||
}
|
||||
|
||||
/// Whether ICU4X has a word-segmentation dictionary for this script.
|
||||
///
|
||||
/// If it does not, we need to apply UAX #29 Rule WB999 manually, because ICU4X does not.
|
||||
///
|
||||
/// This is approximate, because ICU4X actually decides based on a table of code point ranges: e.g.,
|
||||
/// some Han characters do not get a dictionary check. That's only a problem if there's a run of
|
||||
/// repeated such characters, which is probably not too likely to be a problem in practice.
|
||||
///
|
||||
/// If ICU4X does implement WB999 in the future, we can stop doing it manually (and this method can
|
||||
/// be removed).
|
||||
#[inline(always)]
|
||||
fn has_word_dictionary(script: Script) -> bool {
|
||||
cfg!(feature = "complex-scripts")
|
||||
&& matches!(
|
||||
script,
|
||||
Script::Han
|
||||
| Script::Hiragana
|
||||
| Script::Thai
|
||||
| Script::Lao
|
||||
| Script::Khmer
|
||||
| Script::Myanmar
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use alloc::vec::Vec;
|
||||
use icu_segmenter::WordSegmenter;
|
||||
use icu_segmenter::options::WordBreakInvariantOptions;
|
||||
|
||||
/// For some characters, determining word boundaries requires a dictionary lookup.
|
||||
///
|
||||
/// Without dictionaries, ICU4X reports such runs as being a single word. But note
|
||||
/// UAX #29 Rule WB999 says that, without a dictionary, there should be word boundaries.
|
||||
///
|
||||
/// We do that patchup ourselves. Once this test starts failing, it's likely ICU4X now follows
|
||||
/// that rule, and we can drop the patchup (the code calling [`super::has_word_dictionary`]).
|
||||
/// Once that's the case, [`parley_data::Properties::needs_dictionary_word_break`] can also be
|
||||
/// dropped.
|
||||
#[test]
|
||||
fn icu4x_word_segmentation_patchup_required() {
|
||||
let segmenter =
|
||||
WordSegmenter::new_for_non_complex_scripts(WordBreakInvariantOptions::default());
|
||||
let breaks: Vec<_> = segmenter.segment_str("中文文本测试").collect();
|
||||
assert_eq!(breaks, &[0, 18]);
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! The analyzer API.
|
||||
|
||||
use core::ops::Range;
|
||||
|
||||
use parlance::{BaseDirection, Language, LineBreak, WordBreak};
|
||||
|
||||
use crate::{bidi::BidiResolver, break_overrides::LineBreakOverrideFn};
|
||||
|
||||
use crate::analysis::{Analysis, analyze_text};
|
||||
|
||||
/// Reusable scratch for [`Analyzer::analyze`].
|
||||
#[derive(Default)]
|
||||
pub struct Analyzer {
|
||||
pub(crate) bidi: BidiResolver,
|
||||
pub(crate) segmenters: crate::analysis::Segmenters,
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for Analyzer {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("Analyzer").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Analyzer {
|
||||
/// Creates a new analyzer.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Analyze `text`, overwriting `analysis`.
|
||||
///
|
||||
/// This reuses the allocations of `analysis`.
|
||||
pub fn analyze(&mut self, text: &str, options: &AnalysisOptions<'_>, analysis: &mut Analysis) {
|
||||
analysis.clear();
|
||||
analyze_text(self, text, options, analysis);
|
||||
}
|
||||
}
|
||||
|
||||
/// Configuration of line break opportunities for a range of text.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub struct LineBreakConfig {
|
||||
/// CSS `word-break`.
|
||||
pub word_break: WordBreak,
|
||||
/// CSS `line-break`.
|
||||
pub line_break: LineBreak,
|
||||
/// The content language.
|
||||
///
|
||||
/// Chinese and Japanese content uses tailored line breaking rules, which for example allow
|
||||
/// breaks before small kana and some punctuation under [`LineBreak::Normal`] and
|
||||
/// [`LineBreak::Loose`].
|
||||
pub language: Option<Language>,
|
||||
}
|
||||
|
||||
/// Options controlling [`Analyzer::analyze`].
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct AnalysisOptions<'a> {
|
||||
/// The paragraph's base direction.
|
||||
///
|
||||
/// Defaults to [`BaseDirection::Auto`], which infers the direction from the text.
|
||||
pub base_direction: BaseDirection,
|
||||
|
||||
/// Line breaking configuration for ranges of the source text.
|
||||
///
|
||||
/// Ranges must be sorted and non-overlapping, and must start and end on character boundaries of
|
||||
/// the text. Empty ranges are ignored. Gaps use [`LineBreakConfig::default`].
|
||||
pub line_break: &'a [(Range<usize>, LineBreakConfig)],
|
||||
|
||||
/// Ranges of the source text in which a soft wrap opportunity follows every space, tab, and
|
||||
/// ideographic space.
|
||||
///
|
||||
/// This implements the additional soft wrap opportunities of
|
||||
/// [CSS's white-space-collapse: break-spaces][css-break-spaces].
|
||||
///
|
||||
/// Outside these ranges, [UAX #14 § 6][uax-14-algorithm] is followed, which defines where soft
|
||||
/// wrap opportunities exist. For example, rules LB7 and LB18 give a sequence of spaces an
|
||||
/// opportunity only at its end. The ranges specified here add an opportunity after every space,
|
||||
/// tab, and ideographic space, except directly before a mandatory break. This overrides the
|
||||
/// "non-tailorable" UAX #14 Rule LB7, and so deviates from Unicode's line breaking algorithm.
|
||||
///
|
||||
/// Ranges must be sorted and non-overlapping, and must start and end on character boundaries
|
||||
/// of the text. Empty ranges are ignored. Gaps apply the default rules.
|
||||
///
|
||||
/// [css-break-spaces]: https://www.w3.org/TR/css-text-4/#valdef-white-space-collapse-break-spaces
|
||||
/// [uax-14-algorithm]: https://unicode.org/reports/tr14/#Algorithm
|
||||
pub break_spaces: &'a [Range<usize>],
|
||||
|
||||
/// The callback which will be called as a first provider of line breaking decisions.
|
||||
///
|
||||
/// See [`LineBreakOverrideFn`] for more details.
|
||||
pub line_break_override: Option<&'a LineBreakOverrideFn>,
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for AnalysisOptions<'_> {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("AnalysisOptions")
|
||||
.field("base_direction", &self.base_direction)
|
||||
.field("line_break", &self.line_break)
|
||||
.field("break_spaces", &self.break_spaces)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use parlance::BidiLevel;
|
||||
|
||||
use super::{AnalysisOptions, Analyzer};
|
||||
use crate::{Analysis, BaseDirection};
|
||||
|
||||
fn analyze(text: &str, base_direction: BaseDirection) -> Analysis {
|
||||
let mut analyzer = Analyzer::new();
|
||||
let mut analysis = Analysis::new();
|
||||
analyzer.analyze(
|
||||
text,
|
||||
&AnalysisOptions {
|
||||
base_direction,
|
||||
..AnalysisOptions::default()
|
||||
},
|
||||
&mut analysis,
|
||||
);
|
||||
analysis
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_rtl_resolves_numeric_and_neutral_text() {
|
||||
let text = "123 / 456";
|
||||
let auto = analyze(text, BaseDirection::Auto);
|
||||
let rtl = analyze(text, BaseDirection::Rtl);
|
||||
|
||||
assert_eq!(auto.paragraph_level(), BidiLevel::new(0));
|
||||
assert!(auto.paragraph_level().is_ltr());
|
||||
assert!(auto.bidi_levels().is_empty());
|
||||
|
||||
assert_eq!(rtl.paragraph_level(), BidiLevel::new(1));
|
||||
assert!(rtl.paragraph_level().is_rtl());
|
||||
assert_eq!(rtl.bidi_levels().len(), text.chars().count());
|
||||
for (ch, level) in text.chars().zip(rtl.bidi_levels()) {
|
||||
if ch.is_ascii_digit() {
|
||||
assert!(level.is_ltr());
|
||||
}
|
||||
}
|
||||
assert!(rtl.bidi_levels().iter().any(|level| level.is_rtl()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_ltr_takes_precedence_over_first_strong_direction() {
|
||||
let text = "مرحبا hello";
|
||||
let auto = analyze(text, BaseDirection::Auto);
|
||||
let ltr = analyze(text, BaseDirection::Ltr);
|
||||
|
||||
assert!(auto.paragraph_level().is_rtl());
|
||||
assert!(ltr.paragraph_level().is_ltr());
|
||||
assert_ne!(auto.bidi_levels(), ltr.bidi_levels());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_rtl_preserves_ltr_run_direction() {
|
||||
let analysis = analyze("hello", BaseDirection::Rtl);
|
||||
|
||||
assert!(analysis.paragraph_level().is_rtl());
|
||||
assert!(analysis.bidi_levels().iter().all(|level| level.is_ltr()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_direction_applies_to_empty_text() {
|
||||
let analysis = analyze("", BaseDirection::Rtl);
|
||||
|
||||
assert!(analysis.paragraph_level().is_rtl());
|
||||
assert!(analysis.bidi_levels().is_empty());
|
||||
}
|
||||
}
|
||||
Vendored
+917
@@ -0,0 +1,917 @@
|
||||
// Copyright 2021 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Unicode bidirectional algorithm.
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use icu_properties::props::{BidiClass, BidiMirroringGlyph, BidiPairedBracketType};
|
||||
use parlance::{BaseDirection, BidiLevel};
|
||||
|
||||
/// Resolver for the Unicode bidirectional algorithm.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct BidiResolver {
|
||||
base_level: BidiLevel,
|
||||
pub(crate) levels: Vec<BidiLevel>,
|
||||
initial_types: Vec<BidiClass>,
|
||||
types: Vec<BidiClass>,
|
||||
brackets: Vec<(usize, char, BidiMirroringGlyph)>,
|
||||
bracket_pairs: Vec<(usize, usize)>,
|
||||
runs: Vec<Run>,
|
||||
indices: Vec<usize>,
|
||||
flags: u16,
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for BidiResolver {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("BidiResolver")
|
||||
.field("base_level", &self.base_level)
|
||||
.field("levels", &self.levels)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl BidiResolver {
|
||||
/// Returns the base level of the text.
|
||||
pub(crate) fn base_level(&self) -> BidiLevel {
|
||||
self.base_level
|
||||
}
|
||||
|
||||
/// Clears the resolver state.
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.initial_types.clear();
|
||||
self.levels.clear();
|
||||
self.types.clear();
|
||||
self.brackets.clear();
|
||||
self.bracket_pairs.clear();
|
||||
self.flags = 0;
|
||||
self.base_level = BidiLevel::new(0);
|
||||
}
|
||||
|
||||
/// Resolves a paragraph with the specified base direction and
|
||||
/// precomputed types.
|
||||
pub(crate) fn resolve(
|
||||
&mut self,
|
||||
chars: impl Iterator<Item = (char, (BidiClass, BidiMirroringGlyph))>,
|
||||
base_direction: BaseDirection,
|
||||
) {
|
||||
self.clear();
|
||||
let mut needs_bidi = false;
|
||||
let mut len = 0;
|
||||
for (i, (ch, (t, bracket))) in chars.enumerate() {
|
||||
self.initial_types.push(t);
|
||||
|
||||
if bracket.paired_bracket_type != BidiPairedBracketType::None {
|
||||
self.brackets.push((i, ch, bracket));
|
||||
}
|
||||
|
||||
needs_bidi = needs_bidi || mask(t) & BIDI_MASK != 0;
|
||||
len += 1;
|
||||
}
|
||||
self.base_level = match base_direction {
|
||||
BaseDirection::Auto => Self::default_level(&self.initial_types),
|
||||
BaseDirection::Ltr => BidiLevel::new(0),
|
||||
BaseDirection::Rtl => BidiLevel::new(1),
|
||||
};
|
||||
if !needs_bidi && self.base_level == BidiLevel::new(0) {
|
||||
self.flags |= 1;
|
||||
self.levels.resize(len, self.base_level);
|
||||
return;
|
||||
}
|
||||
self.types.extend_from_slice(&self.initial_types);
|
||||
self.resolve_levels();
|
||||
self.resolve_runs();
|
||||
//self.dump_sequences();
|
||||
for i in 0..self.runs.len() {
|
||||
if self.runs[i].in_sequence {
|
||||
continue;
|
||||
}
|
||||
self.types.truncate(len);
|
||||
self.indices.clear();
|
||||
let mut cur = i;
|
||||
let level = self.runs[i].level;
|
||||
let sos = self.runs[i].sos;
|
||||
let mut eos;
|
||||
loop {
|
||||
let run = &self.runs[cur];
|
||||
for i in run.start..run.end {
|
||||
let ty = self.types[i];
|
||||
if !is_removed_by_x9(ty) {
|
||||
self.types.push(ty);
|
||||
self.indices.push(i);
|
||||
}
|
||||
}
|
||||
eos = run.eos;
|
||||
cur = match run.next {
|
||||
Some(i) => i,
|
||||
None => break,
|
||||
};
|
||||
}
|
||||
self.resolve_sequence(level.to_u8(), sos, eos, self.indices.len());
|
||||
}
|
||||
for i in 0..len {
|
||||
let t = self.initial_types[i];
|
||||
if t == BidiClass::SegmentSeparator || t == BidiClass::ParagraphSeparator {
|
||||
self.levels[i] = self.base_level;
|
||||
for j in (0..i).rev() {
|
||||
let t = self.initial_types[j];
|
||||
if is_removed_by_x9(t) {
|
||||
continue;
|
||||
} else if t == BidiClass::WhiteSpace
|
||||
|| is_isolate_initiator(t)
|
||||
|| t == BidiClass::PopDirectionalIsolate
|
||||
{
|
||||
self.levels[j] = self.base_level;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if is_removed_by_x9(t) {
|
||||
if i == 0 {
|
||||
self.levels[i] = self.base_level;
|
||||
} else {
|
||||
self.levels[i] = self.levels[i - 1];
|
||||
}
|
||||
//self.levels[i] = 0xFF;
|
||||
}
|
||||
}
|
||||
for i in (0..len).rev() {
|
||||
let t = self.initial_types[i];
|
||||
if is_removed_by_x9(t) {
|
||||
continue;
|
||||
} else if t == BidiClass::WhiteSpace
|
||||
|| is_isolate_initiator(t)
|
||||
|| t == BidiClass::PopDirectionalIsolate
|
||||
{
|
||||
// UAX #9 L1: whitespace, isolate initiators and PDIs that end the paragraph take
|
||||
// the paragraph's level (Rune: vendor/parley_engine.patch).
|
||||
self.levels[i] = self.base_level;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_level(types: &[BidiClass]) -> BidiLevel {
|
||||
let mut isolates = 0;
|
||||
for ty in types {
|
||||
let ty = *ty;
|
||||
match ty {
|
||||
BidiClass::RightToLeftIsolate
|
||||
| BidiClass::LeftToRightIsolate
|
||||
| BidiClass::FirstStrongIsolate => isolates += 1,
|
||||
BidiClass::PopDirectionalIsolate if isolates > 0 => isolates -= 1,
|
||||
BidiClass::LeftToRight | BidiClass::RightToLeft | BidiClass::ArabicLetter
|
||||
if isolates == 0 =>
|
||||
{
|
||||
return if ty == BidiClass::LeftToRight {
|
||||
BidiLevel::new(0)
|
||||
} else {
|
||||
BidiLevel::new(1)
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
BidiLevel::new(0)
|
||||
}
|
||||
|
||||
fn default_level_until_pdi(types: &[BidiClass]) -> u8 {
|
||||
let mut isolates = 0;
|
||||
for ty in types {
|
||||
let ty = *ty;
|
||||
match ty {
|
||||
BidiClass::RightToLeftIsolate
|
||||
| BidiClass::LeftToRightIsolate
|
||||
| BidiClass::FirstStrongIsolate => isolates += 1,
|
||||
BidiClass::PopDirectionalIsolate => {
|
||||
if isolates > 0 {
|
||||
isolates -= 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
BidiClass::LeftToRight | BidiClass::RightToLeft | BidiClass::ArabicLetter
|
||||
if isolates == 0 =>
|
||||
{
|
||||
return if ty == BidiClass::LeftToRight { 0 } else { 1 };
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
fn resolve_levels(&mut self) {
|
||||
let base = self.base_level;
|
||||
let len = self.types.len();
|
||||
self.levels.clear();
|
||||
self.levels.resize(len, BidiLevel::new(0));
|
||||
let mut stack = Stack::new();
|
||||
let mut overflow_isolates = 0;
|
||||
let mut overflow_embedding = 0;
|
||||
let mut valid_isolates = 0;
|
||||
stack.push(base, BidiClass::OtherNeutral, false);
|
||||
for i in 0..len {
|
||||
let t = self.types[i];
|
||||
let tmask = mask(t);
|
||||
if tmask & EXPLICIT_MASK != 0 {
|
||||
let is_isolate = tmask & ISOLATE_MASK != 0;
|
||||
let is_rtl = if t == BidiClass::FirstStrongIsolate && i + 1 < len {
|
||||
Self::default_level_until_pdi(&self.types[i + 1..]) == 1
|
||||
} else {
|
||||
tmask & RTL_MASK != 0
|
||||
};
|
||||
if is_isolate {
|
||||
self.levels[i] = stack.embedding_level();
|
||||
let os = stack.override_status();
|
||||
if os != BidiClass::OtherNeutral {
|
||||
self.types[i] = os;
|
||||
}
|
||||
}
|
||||
let new_level = if is_rtl {
|
||||
stack.embedding_level().next_odd()
|
||||
} else {
|
||||
stack.embedding_level().next_even()
|
||||
};
|
||||
if new_level <= BidiLevel::MAX && overflow_isolates == 0 && overflow_embedding == 0
|
||||
{
|
||||
if is_isolate {
|
||||
valid_isolates += 1;
|
||||
}
|
||||
stack.push(
|
||||
new_level,
|
||||
if t == BidiClass::LeftToRightOverride {
|
||||
BidiClass::LeftToRight
|
||||
} else if t == BidiClass::RightToLeftOverride {
|
||||
BidiClass::RightToLeft
|
||||
} else {
|
||||
BidiClass::OtherNeutral
|
||||
},
|
||||
is_isolate,
|
||||
);
|
||||
} else if is_isolate {
|
||||
overflow_isolates += 1;
|
||||
} else if overflow_isolates == 0 {
|
||||
overflow_embedding += 1;
|
||||
}
|
||||
} else if t == BidiClass::PopDirectionalIsolate {
|
||||
if overflow_isolates > 0 {
|
||||
overflow_isolates -= 1;
|
||||
} else if valid_isolates == 0 {
|
||||
// empty
|
||||
} else {
|
||||
overflow_embedding = 0;
|
||||
while !stack.isolate_status() {
|
||||
stack.pop();
|
||||
}
|
||||
stack.pop();
|
||||
valid_isolates -= 1;
|
||||
}
|
||||
self.levels[i] = stack.embedding_level();
|
||||
if stack.override_status() != BidiClass::OtherNeutral {
|
||||
self.types[i] = stack.override_status();
|
||||
}
|
||||
} else if t == BidiClass::PopDirectionalFormat {
|
||||
self.levels[i] = stack.embedding_level();
|
||||
if overflow_isolates > 0 {
|
||||
// empty
|
||||
} else if overflow_embedding > 0 {
|
||||
overflow_embedding -= 1;
|
||||
} else if !stack.isolate_status() && stack.depth >= 2 {
|
||||
stack.pop();
|
||||
}
|
||||
} else if t == BidiClass::ParagraphSeparator {
|
||||
stack.depth = 1;
|
||||
overflow_isolates = 0;
|
||||
overflow_embedding = 0;
|
||||
valid_isolates = 0;
|
||||
self.levels[i] = base;
|
||||
} else if t != BidiClass::BoundaryNeutral {
|
||||
self.levels[i] = stack.embedding_level();
|
||||
if stack.override_status() != BidiClass::OtherNeutral {
|
||||
self.types[i] = stack.override_status();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_runs(&mut self) {
|
||||
let len = self.types.len();
|
||||
self.runs.clear();
|
||||
let mut start = 0;
|
||||
while start < len {
|
||||
if !is_removed_by_x9(self.types[start]) {
|
||||
break;
|
||||
}
|
||||
start += 1;
|
||||
}
|
||||
if start == len {
|
||||
return;
|
||||
}
|
||||
let mut level = self.levels[start];
|
||||
let mut offset = 0;
|
||||
for i in start + 1..len {
|
||||
if is_removed_by_x9(self.types[i]) {
|
||||
continue;
|
||||
}
|
||||
if self.levels[i] != level {
|
||||
self.runs.push(Run::new(level, offset, i));
|
||||
offset = i;
|
||||
level = self.levels[i];
|
||||
}
|
||||
}
|
||||
if offset < len {
|
||||
self.runs.push(Run::new(level, offset, len));
|
||||
}
|
||||
for run in &mut self.runs {
|
||||
while run.start < run.end {
|
||||
if is_removed_by_x9(self.types[run.start]) {
|
||||
run.start += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
while run.end > run.start {
|
||||
if is_removed_by_x9(self.types[run.end - 1]) {
|
||||
run.end -= 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if run.start == run.end {
|
||||
continue;
|
||||
}
|
||||
if self.types[run.start] == BidiClass::PopDirectionalIsolate {
|
||||
run.starts_with_pdi = true;
|
||||
}
|
||||
let mut prev_level = self.base_level;
|
||||
for i in (0..run.start).rev() {
|
||||
if !is_removed_by_x9(self.types[i]) {
|
||||
prev_level = self.levels[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
run.sos = type_from_level(prev_level.max(run.level));
|
||||
if is_isolate_initiator(self.initial_types[run.end - 1]) {
|
||||
run.ends_with_isolate = true;
|
||||
run.eos = type_from_level(self.base_level.max(run.level));
|
||||
} else {
|
||||
let mut next_level = self.base_level;
|
||||
for i in run.end..len {
|
||||
if !is_removed_by_x9(self.types[i]) {
|
||||
next_level = self.levels[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
run.eos = type_from_level(next_level.max(run.level));
|
||||
}
|
||||
}
|
||||
for i in 0..self.runs.len() {
|
||||
if self.runs[i].ends_with_isolate {
|
||||
let level = self.runs[i].level;
|
||||
for j in i + 1..self.runs.len() {
|
||||
if self.runs[j].starts_with_pdi && self.runs[j].level == level {
|
||||
self.runs[i].next = Some(j);
|
||||
self.runs[j].in_sequence = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::needless_range_loop, reason = "Deferred")]
|
||||
fn resolve_sequence(&mut self, level: u8, sos: BidiClass, eos: BidiClass, len: usize) {
|
||||
if len == 0 {
|
||||
return;
|
||||
}
|
||||
const W1_MASK: u32 = mask(BidiClass::LeftToRightIsolate)
|
||||
| mask(BidiClass::RightToLeftIsolate)
|
||||
| mask(BidiClass::FirstStrongIsolate)
|
||||
| mask(BidiClass::PopDirectionalIsolate);
|
||||
const W2_MASK: u32 = mask(BidiClass::LeftToRight)
|
||||
| mask(BidiClass::RightToLeft)
|
||||
| mask(BidiClass::ArabicLetter);
|
||||
const W4_MASK: u32 = mask(BidiClass::EuropeanSeparator) | mask(BidiClass::CommonSeparator);
|
||||
let mut prev = sos;
|
||||
let mut prev_strong = prev;
|
||||
let types = &mut self.types[self.initial_types.len()..];
|
||||
for i in 0..len {
|
||||
let mut t = types[i];
|
||||
let tmask = mask(t);
|
||||
if t == BidiClass::NonspacingMark {
|
||||
// W1
|
||||
types[i] = prev;
|
||||
} else {
|
||||
if tmask & W1_MASK != 0 {
|
||||
prev = BidiClass::OtherNeutral;
|
||||
continue;
|
||||
}
|
||||
if t == BidiClass::EuropeanNumber {
|
||||
// W2
|
||||
if prev_strong == BidiClass::ArabicLetter {
|
||||
t = BidiClass::ArabicNumber;
|
||||
types[i] = t;
|
||||
}
|
||||
} else if tmask & W2_MASK != 0 {
|
||||
prev_strong = t;
|
||||
// W3
|
||||
if t == BidiClass::ArabicLetter {
|
||||
t = BidiClass::RightToLeft;
|
||||
types[i] = t;
|
||||
}
|
||||
} else if tmask & W4_MASK != 0 && i < (len - 1) {
|
||||
// W4
|
||||
let mut next = types[i + 1];
|
||||
if next == BidiClass::EuropeanNumber && prev_strong == BidiClass::ArabicLetter {
|
||||
next = BidiClass::ArabicNumber;
|
||||
}
|
||||
if prev == BidiClass::EuropeanNumber && next == BidiClass::EuropeanNumber {
|
||||
t = BidiClass::EuropeanNumber;
|
||||
types[i] = t;
|
||||
} else if t == BidiClass::CommonSeparator
|
||||
&& prev == BidiClass::ArabicNumber
|
||||
&& next == BidiClass::ArabicNumber
|
||||
{
|
||||
t = BidiClass::ArabicNumber;
|
||||
types[i] = t;
|
||||
}
|
||||
}
|
||||
prev = t;
|
||||
}
|
||||
}
|
||||
// W5
|
||||
let mut i = 0;
|
||||
while i < len {
|
||||
if types[i] == BidiClass::EuropeanTerminator {
|
||||
let limit = find_limit(types, i, BidiClass::EuropeanTerminator);
|
||||
let mut t = if i == 0 { sos } else { types[i - 1] };
|
||||
if t != BidiClass::EuropeanNumber {
|
||||
t = if limit == len { eos } else { types[limit] };
|
||||
}
|
||||
if t == BidiClass::EuropeanNumber {
|
||||
for j in i..limit {
|
||||
types[j] = BidiClass::EuropeanNumber;
|
||||
}
|
||||
}
|
||||
i = limit;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
// W6, W7
|
||||
const W6_MASK: u32 = mask(BidiClass::EuropeanSeparator)
|
||||
| mask(BidiClass::EuropeanTerminator)
|
||||
| mask(BidiClass::CommonSeparator);
|
||||
prev_strong = sos;
|
||||
for i in 0..len {
|
||||
let t = types[i];
|
||||
if mask(t) & W6_MASK != 0 {
|
||||
// W6
|
||||
types[i] = BidiClass::OtherNeutral;
|
||||
} else if t == BidiClass::EuropeanNumber {
|
||||
// W7
|
||||
if prev_strong == BidiClass::LeftToRight {
|
||||
types[i] = BidiClass::LeftToRight;
|
||||
}
|
||||
} else if t == BidiClass::LeftToRight || t == BidiClass::RightToLeft {
|
||||
prev_strong = t;
|
||||
}
|
||||
}
|
||||
// N0
|
||||
if !self.brackets.is_empty() {
|
||||
let base_brackets = self.bracket_pairs.len();
|
||||
let mut bracket_stack = BracketStack::new();
|
||||
for i in 0..len {
|
||||
if types[i] != BidiClass::OtherNeutral {
|
||||
continue;
|
||||
}
|
||||
let index = self.indices[i];
|
||||
if let Ok(index) = self.brackets.binary_search_by(|x| x.0.cmp(&index)) {
|
||||
let (_, ch, bracket) = self.brackets[index];
|
||||
match bracket.paired_bracket_type {
|
||||
BidiPairedBracketType::Open => {
|
||||
if bracket_stack.depth == MAX_BRACKET_STACK {
|
||||
break;
|
||||
}
|
||||
bracket_stack.push(i, bracket.mirroring_glyph.unwrap());
|
||||
}
|
||||
BidiPairedBracketType::Close => {
|
||||
if let Some(open) = bracket_stack.find_and_pop(ch) {
|
||||
self.bracket_pairs.push((open, i));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.bracket_pairs.len() > base_brackets {
|
||||
let embed_dir = if level & 1 != 0 {
|
||||
BidiClass::RightToLeft
|
||||
} else {
|
||||
BidiClass::LeftToRight
|
||||
};
|
||||
let bracket_pairs = &mut self.bracket_pairs[base_brackets..];
|
||||
bracket_pairs.sort_unstable_by_key(|a| a.0);
|
||||
for pair in bracket_pairs {
|
||||
let mut pair_dir = BidiClass::OtherNeutral;
|
||||
for i in pair.0 + 1..pair.1 {
|
||||
let dir = match types[i] {
|
||||
BidiClass::EuropeanNumber
|
||||
| BidiClass::ArabicNumber
|
||||
| BidiClass::ArabicLetter
|
||||
| BidiClass::RightToLeft => BidiClass::RightToLeft,
|
||||
BidiClass::LeftToRight => BidiClass::LeftToRight,
|
||||
_ => BidiClass::OtherNeutral,
|
||||
};
|
||||
if dir == BidiClass::OtherNeutral {
|
||||
continue;
|
||||
}
|
||||
pair_dir = dir;
|
||||
if dir == embed_dir {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if pair_dir == BidiClass::OtherNeutral {
|
||||
pair.0 = self.indices[pair.0];
|
||||
pair.1 = self.indices[pair.1];
|
||||
continue;
|
||||
}
|
||||
if pair_dir != embed_dir {
|
||||
pair_dir = sos;
|
||||
for i in (0..pair.0).rev() {
|
||||
let dir = match types[i] {
|
||||
BidiClass::EuropeanNumber
|
||||
| BidiClass::ArabicNumber
|
||||
| BidiClass::ArabicLetter
|
||||
| BidiClass::RightToLeft => BidiClass::RightToLeft,
|
||||
BidiClass::LeftToRight => BidiClass::LeftToRight,
|
||||
_ => BidiClass::OtherNeutral,
|
||||
};
|
||||
if dir != BidiClass::OtherNeutral {
|
||||
pair_dir = dir;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if pair_dir == embed_dir || pair_dir == BidiClass::OtherNeutral {
|
||||
pair_dir = embed_dir;
|
||||
}
|
||||
}
|
||||
types[pair.0] = pair_dir;
|
||||
types[pair.1] = pair_dir;
|
||||
for i in pair.0 + 1..pair.1 {
|
||||
let index = self.indices[i];
|
||||
if self.initial_types[index] == BidiClass::NonspacingMark {
|
||||
types[i] = pair_dir;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for i in pair.1 + 1..len {
|
||||
let index = self.indices[i];
|
||||
if self.initial_types[index] == BidiClass::NonspacingMark {
|
||||
types[i] = pair_dir;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
pair.0 = self.indices[pair.0];
|
||||
pair.1 = self.indices[pair.1];
|
||||
}
|
||||
}
|
||||
}
|
||||
// N1, N2
|
||||
const N_MASK: u32 = mask(BidiClass::ParagraphSeparator)
|
||||
| mask(BidiClass::SegmentSeparator)
|
||||
| mask(BidiClass::WhiteSpace)
|
||||
| mask(BidiClass::OtherNeutral)
|
||||
| mask(BidiClass::RightToLeftIsolate)
|
||||
| mask(BidiClass::LeftToRightIsolate)
|
||||
| mask(BidiClass::FirstStrongIsolate)
|
||||
| mask(BidiClass::PopDirectionalIsolate);
|
||||
let mut i = 0;
|
||||
while i < len {
|
||||
let t = types[i];
|
||||
if mask(t) & N_MASK != 0 {
|
||||
let offset = i;
|
||||
let limit = find_limit_by_mask(types, offset, N_MASK);
|
||||
let mut leading;
|
||||
let mut trailing;
|
||||
if offset == 0 {
|
||||
leading = sos;
|
||||
} else {
|
||||
leading = types[offset - 1];
|
||||
if leading == BidiClass::ArabicNumber || leading == BidiClass::EuropeanNumber {
|
||||
leading = BidiClass::RightToLeft;
|
||||
}
|
||||
}
|
||||
if limit == len {
|
||||
trailing = eos;
|
||||
} else {
|
||||
trailing = types[limit];
|
||||
if trailing == BidiClass::ArabicNumber || trailing == BidiClass::EuropeanNumber
|
||||
{
|
||||
trailing = BidiClass::RightToLeft;
|
||||
}
|
||||
}
|
||||
let resolved = if leading == trailing {
|
||||
// N1
|
||||
leading
|
||||
} else {
|
||||
// N2
|
||||
if level & 1 != 0 {
|
||||
BidiClass::RightToLeft
|
||||
} else {
|
||||
BidiClass::LeftToRight
|
||||
}
|
||||
};
|
||||
for j in offset..limit {
|
||||
types[j] = resolved;
|
||||
}
|
||||
i = limit - 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
// Implicit levels
|
||||
if level & 1 == 0 {
|
||||
// I1
|
||||
for i in 0..len {
|
||||
let index = self.indices[i];
|
||||
let t = types[i];
|
||||
if t == BidiClass::RightToLeft {
|
||||
self.levels[index] = BidiLevel::new(level + 1);
|
||||
} else if t != BidiClass::LeftToRight {
|
||||
self.levels[index] = BidiLevel::new(level + 2);
|
||||
} else {
|
||||
self.levels[index] = BidiLevel::new(level);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// I2
|
||||
for i in 0..len {
|
||||
let index = self.indices[i];
|
||||
let t = types[i];
|
||||
if t != BidiClass::RightToLeft {
|
||||
self.levels[index] = BidiLevel::new(level + 1);
|
||||
} else {
|
||||
self.levels[index] = BidiLevel::new(level);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a default bidi type for a level.
|
||||
pub(crate) fn type_from_level(level: BidiLevel) -> BidiClass {
|
||||
if level.is_ltr() {
|
||||
BidiClass::LeftToRight
|
||||
} else {
|
||||
BidiClass::RightToLeft
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes an ordering for a sequence of bidi runs based on levels.
|
||||
pub(crate) fn _reorder<F>(order: &mut [usize], levels: F)
|
||||
where
|
||||
F: Fn(usize) -> u8,
|
||||
{
|
||||
let mut max_level = 0;
|
||||
let mut lowest_odd_level = 255;
|
||||
for (i, o) in order.iter_mut().enumerate() {
|
||||
*o = i;
|
||||
let level = levels(i);
|
||||
if level > max_level {
|
||||
max_level = level;
|
||||
}
|
||||
if level & 1 != 0 && level < lowest_odd_level {
|
||||
lowest_odd_level = level;
|
||||
}
|
||||
}
|
||||
let len = order.len();
|
||||
for level in (lowest_odd_level..=max_level).rev() {
|
||||
let mut i = 0;
|
||||
while i < len {
|
||||
if levels(i) >= level {
|
||||
let mut end = i + 1;
|
||||
while end < len && levels(end) >= level {
|
||||
end += 1;
|
||||
}
|
||||
let mut j = i;
|
||||
let mut k = end - 1;
|
||||
while j < k {
|
||||
order.swap(j, k);
|
||||
j += 1;
|
||||
k -= 1;
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether the character needs bidirectional resolution.
|
||||
#[inline(always)]
|
||||
pub(crate) fn needs_bidi_resolution(bidi_class: BidiClass) -> bool {
|
||||
mask(bidi_class) & BIDI_MASK != 0
|
||||
}
|
||||
|
||||
const OVERRIDE_MASK: u32 = mask(BidiClass::RightToLeftEmbedding)
|
||||
| mask(BidiClass::LeftToRightEmbedding)
|
||||
| mask(BidiClass::RightToLeftOverride)
|
||||
| mask(BidiClass::LeftToRightOverride);
|
||||
const ISOLATE_MASK: u32 = mask(BidiClass::RightToLeftIsolate)
|
||||
| mask(BidiClass::LeftToRightIsolate)
|
||||
| mask(BidiClass::FirstStrongIsolate);
|
||||
const EXPLICIT_MASK: u32 = OVERRIDE_MASK | ISOLATE_MASK;
|
||||
const RTL_MASK: u32 = mask(BidiClass::RightToLeftEmbedding)
|
||||
| mask(BidiClass::RightToLeftOverride)
|
||||
| mask(BidiClass::RightToLeftIsolate);
|
||||
const REMOVED_BY_X9_MASK: u32 =
|
||||
OVERRIDE_MASK | mask(BidiClass::PopDirectionalFormat) | mask(BidiClass::BoundaryNeutral);
|
||||
const BIDI_MASK: u32 = EXPLICIT_MASK
|
||||
| mask(BidiClass::RightToLeft)
|
||||
| mask(BidiClass::ArabicLetter)
|
||||
| mask(BidiClass::ArabicNumber);
|
||||
const _RESET_MASK: u32 =
|
||||
ISOLATE_MASK | mask(BidiClass::PopDirectionalIsolate) | mask(BidiClass::WhiteSpace);
|
||||
|
||||
fn is_isolate_initiator(ty: BidiClass) -> bool {
|
||||
mask(ty) & ISOLATE_MASK != 0
|
||||
}
|
||||
|
||||
pub(crate) fn is_removed_by_x9(ty: BidiClass) -> bool {
|
||||
mask(ty) & REMOVED_BY_X9_MASK != 0
|
||||
}
|
||||
|
||||
pub(crate) fn _is_reset(ty: BidiClass) -> bool {
|
||||
mask(ty) & _RESET_MASK != 0
|
||||
}
|
||||
|
||||
fn find_limit(types: &[BidiClass], offset: usize, ty: BidiClass) -> usize {
|
||||
let mut len = offset;
|
||||
for &t in &types[offset..] {
|
||||
if t != ty {
|
||||
break;
|
||||
}
|
||||
len += 1;
|
||||
}
|
||||
len
|
||||
}
|
||||
|
||||
fn find_limit_by_mask(types: &[BidiClass], offset: usize, mask: u32) -> usize {
|
||||
let mut len = offset;
|
||||
for &t in &types[offset..] {
|
||||
if self::mask(t) & mask == 0 {
|
||||
break;
|
||||
}
|
||||
len += 1;
|
||||
}
|
||||
len
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Run {
|
||||
level: BidiLevel,
|
||||
ends_with_isolate: bool,
|
||||
starts_with_pdi: bool,
|
||||
sos: BidiClass,
|
||||
eos: BidiClass,
|
||||
start: usize,
|
||||
end: usize,
|
||||
in_sequence: bool,
|
||||
next: Option<usize>,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
fn new(level: BidiLevel, start: usize, end: usize) -> Self {
|
||||
Self {
|
||||
level,
|
||||
ends_with_isolate: false,
|
||||
starts_with_pdi: false,
|
||||
sos: BidiClass::OtherNeutral,
|
||||
eos: BidiClass::OtherNeutral,
|
||||
start,
|
||||
end,
|
||||
in_sequence: false,
|
||||
next: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_STACK: usize = BidiLevel::MAX.to_u8() as usize;
|
||||
|
||||
struct Stack {
|
||||
embedding_level: [BidiLevel; MAX_STACK + 1],
|
||||
override_status: [BidiClass; MAX_STACK + 1],
|
||||
isolate_status: [bool; MAX_STACK + 1],
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
impl Stack {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
depth: 0,
|
||||
embedding_level: [BidiLevel::new(0); MAX_STACK + 1],
|
||||
override_status: [BidiClass::OtherNeutral; MAX_STACK + 1],
|
||||
isolate_status: [false; MAX_STACK + 1],
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, level: BidiLevel, override_status: BidiClass, isolate_status: bool) {
|
||||
let d = self.depth;
|
||||
self.embedding_level[d] = level;
|
||||
self.override_status[d] = override_status;
|
||||
self.isolate_status[d] = isolate_status;
|
||||
self.depth += 1;
|
||||
}
|
||||
|
||||
fn pop(&mut self) {
|
||||
if self.depth > 1 {
|
||||
self.depth -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn embedding_level(&self) -> BidiLevel {
|
||||
self.embedding_level[self.depth - 1]
|
||||
}
|
||||
|
||||
fn override_status(&self) -> BidiClass {
|
||||
self.override_status[self.depth - 1]
|
||||
}
|
||||
|
||||
fn isolate_status(&self) -> bool {
|
||||
self.isolate_status[self.depth - 1]
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_BRACKET_STACK: usize = 63;
|
||||
|
||||
struct BracketStack {
|
||||
openers: [(usize, char); MAX_BRACKET_STACK],
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
impl BracketStack {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
openers: [(0, '\0'); MAX_BRACKET_STACK],
|
||||
depth: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, offset: usize, closer: char) {
|
||||
self.openers[self.depth] = (offset, closer);
|
||||
self.depth += 1;
|
||||
}
|
||||
|
||||
fn find_and_pop(&mut self, closer: char) -> Option<usize> {
|
||||
if self.depth == 0 {
|
||||
return None;
|
||||
}
|
||||
for i in (0..self.depth).rev() {
|
||||
let c = self.openers[i].1;
|
||||
if c == closer
|
||||
|| (c == '\u{232A}' && closer == '\u{3009}')
|
||||
|| (c == '\u{3009}' && closer == '\u{232A}')
|
||||
{
|
||||
self.depth = i;
|
||||
return Some(self.openers[i].0);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns a bidi class into a single bit, for cheap set membership testing.
|
||||
const fn mask(t: BidiClass) -> u32 {
|
||||
let bit = match t {
|
||||
BidiClass::LeftToRight => 0,
|
||||
BidiClass::RightToLeft => 1,
|
||||
BidiClass::EuropeanNumber => 2,
|
||||
BidiClass::EuropeanSeparator => 3,
|
||||
BidiClass::EuropeanTerminator => 4,
|
||||
BidiClass::ArabicNumber => 5,
|
||||
BidiClass::CommonSeparator => 6,
|
||||
BidiClass::ParagraphSeparator => 7,
|
||||
BidiClass::SegmentSeparator => 8,
|
||||
BidiClass::WhiteSpace => 9,
|
||||
BidiClass::OtherNeutral => 10,
|
||||
BidiClass::LeftToRightEmbedding => 11,
|
||||
BidiClass::LeftToRightOverride => 12,
|
||||
BidiClass::ArabicLetter => 13,
|
||||
BidiClass::RightToLeftEmbedding => 14,
|
||||
BidiClass::RightToLeftOverride => 15,
|
||||
BidiClass::PopDirectionalFormat => 16,
|
||||
BidiClass::NonspacingMark => 17,
|
||||
BidiClass::BoundaryNeutral => 18,
|
||||
BidiClass::FirstStrongIsolate => 19,
|
||||
BidiClass::LeftToRightIsolate => 20,
|
||||
BidiClass::RightToLeftIsolate => 21,
|
||||
BidiClass::PopDirectionalIsolate => 22,
|
||||
_ => {
|
||||
debug_assert!(false, "unhandled Bidi_Class");
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
1 << bit
|
||||
}
|
||||
+436
@@ -0,0 +1,436 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Overrides for line-break opportunities.
|
||||
|
||||
use core::ops::RangeInclusive;
|
||||
|
||||
/// Context for a potential line break opportunity between two adjacent code points.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct LineBreakContext {
|
||||
/// The code point before the `before` code point, if any.
|
||||
pub before_before: Option<char>,
|
||||
/// The code point before the potential break.
|
||||
pub before: char,
|
||||
/// The code point after the potential break.
|
||||
pub after: char,
|
||||
}
|
||||
|
||||
/// Line break opportunity override.
|
||||
///
|
||||
/// Called for each adjacent pair of Unicode code points in the text, in order, except for pairs
|
||||
/// containing a mandatory break character. The [`LineBreakContext`] describes the potential break.
|
||||
///
|
||||
/// Returning:
|
||||
/// - `Some(true)` : forces a line break opportunity between the pair
|
||||
/// - `Some(false)` : suppresses any opportunity
|
||||
/// - `None` : defers to the default (ICU) behavior
|
||||
///
|
||||
/// Note that pairs with a mandatory break aren't soft wrap opportunities. Mandatory breaks are
|
||||
/// reported as [`Whitespace`][crate::shape::Whitespace].
|
||||
///
|
||||
/// This is typically used to force preferential line breaking decisions when it
|
||||
/// comes to ASCII punctuation like `/`, `-`, etc. For example, to prevent break
|
||||
/// opportunities within "1/2".
|
||||
///
|
||||
/// A separate use case is to match the line breaking behavior of existing systems
|
||||
/// such as web browsers. See [`CHROMIUM_LINE_BREAK_OVERRIDE`] for a ready-made
|
||||
/// override function that mirrors Chromium's behavior.
|
||||
pub type LineBreakOverrideFn = dyn Fn(LineBreakContext) -> Option<bool> + Send + Sync;
|
||||
|
||||
/// A line break override function mirroring Chromium's preferred line breaking behavior.
|
||||
///
|
||||
/// See: <https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/text/character_property_data_generator.cc;l=449-495>
|
||||
///
|
||||
/// # Differences from other browsers
|
||||
///
|
||||
/// ## Compared to Safari
|
||||
///
|
||||
/// Chromium (and this table) differs from Safari in 9 cases:
|
||||
/// - A "-" followed by one of "!|$|)|/|:|;|?|]|}" is suppressed in Chromium, but broken in Safari.
|
||||
///
|
||||
/// ## Compared to Firefox
|
||||
///
|
||||
/// Firefox always defers to the default ICU behavior.
|
||||
pub static CHROMIUM_LINE_BREAK_OVERRIDE: &LineBreakOverrideFn =
|
||||
&(chromium_override as fn(LineBreakContext) -> Option<bool>);
|
||||
|
||||
fn chromium_override(cx: LineBreakContext) -> Option<bool> {
|
||||
let LineBreakContext {
|
||||
before_before,
|
||||
before,
|
||||
after,
|
||||
..
|
||||
} = cx;
|
||||
// CSS "does not fully define where soft wrap opportunities occur".
|
||||
// (https://www.w3.org/TR/css-text-3/#line-breaking)
|
||||
// We find that Chrome always treats the position after a space sequence
|
||||
// as a line break opportunity, despite this not matching UAX-14
|
||||
// (see LB13: https://www.unicode.org/reports/tr14/#LB13; we're not currently
|
||||
// aware of any others).
|
||||
//
|
||||
// See also https://github.com/linebender/parley/pull/485, and https://github.com/linebender/parley/issues/619.
|
||||
//
|
||||
// See `LazyLineBreakIterator::NextBreakablePosition`
|
||||
// <https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/text/text_break_iterator.cc;l=282-303>
|
||||
if before == ' ' && after != ' ' {
|
||||
return Some(true);
|
||||
}
|
||||
// Before consulting 'before' / 'after' pair table, check for the special "-" case.
|
||||
//
|
||||
// Chromium doesn't allow breaking when it looks like the minus sign is for a negative
|
||||
// number like "Subtract -5 from X". But, Chromium does allow breaking when the minus
|
||||
// sign is part of a long URL like "AAAA-2222".
|
||||
//
|
||||
// See <https://github.com/chromium/chromium/blob/c6bee15e8f336c8feabf539d8bbb540c134ec20a/third_party/blink/renderer/platform/text/text_break_iterator.cc#L224-L240>
|
||||
if before == '-' && after.is_ascii_digit() {
|
||||
return Some(before_before.is_some_and(|c| c.is_ascii_alphanumeric()));
|
||||
}
|
||||
CHROMIUM_LINE_BREAK_TABLE.lookup(before, after)
|
||||
}
|
||||
|
||||
/// A static table mirroring Chromium's preferred line breaking behavior for `before` / `after`
|
||||
/// printable ASCII code points.
|
||||
static CHROMIUM_LINE_BREAK_TABLE: AsciiLineBreakTable<5> =
|
||||
AsciiLineBreakTableBuilder::chromium().build::<5>();
|
||||
|
||||
/// A line break override table for ASCII character pairs.
|
||||
///
|
||||
/// See [`LineBreakOverrideFn`] for more details.
|
||||
///
|
||||
/// All table operations are `const`, which means that derived tables don't
|
||||
/// need a runtime construction step.
|
||||
///
|
||||
/// The table is row-deduplicated. Each `before` character maps to
|
||||
/// one of `N` distinct rows, so tables can be kept tiny.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use parley_engine::break_overrides::CHROMIUM_LINE_BREAK_OVERRIDE;
|
||||
/// # use parley_engine::{Analysis, AnalysisOptions, Analyzer};
|
||||
/// # let mut analyzer = Analyzer::new();
|
||||
/// # let mut analysis = Analysis::new();
|
||||
/// let text = "Hello there!";
|
||||
/// let options = AnalysisOptions {
|
||||
/// // Emulate Chromium:
|
||||
/// line_break_override: Some(CHROMIUM_LINE_BREAK_OVERRIDE),
|
||||
/// ..AnalysisOptions::default()
|
||||
/// };
|
||||
/// analyzer.analyze(text, &options, &mut analysis);
|
||||
/// ```
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AsciiLineBreakTable<const N: usize> {
|
||||
/// Maps each `before` character (`0..128`) to a row in `rows`.
|
||||
row_of: [u8; 128],
|
||||
/// The distinct rows.
|
||||
rows: [Row; N],
|
||||
}
|
||||
|
||||
impl<const N: usize> AsciiLineBreakTable<N> {
|
||||
/// Look up the break override for a `(before, after)` pair.
|
||||
///
|
||||
/// Return semantics copied from [`LineBreakOverrideFn`].
|
||||
pub const fn lookup(&self, before: char, after: char) -> Option<bool> {
|
||||
let (b, a) = (before as u32, after as u32);
|
||||
if b >= 128 || a >= 128 {
|
||||
return None;
|
||||
}
|
||||
let row = &self.rows[self.row_of[b as usize] as usize];
|
||||
if row.overridden & (1_u128 << a) == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(row.allow & (1_u128 << a) != 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A single deduplicated row of a [`AsciiLineBreakTable`].
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Row {
|
||||
/// Bits set means the pair has an override.
|
||||
overridden: u128,
|
||||
/// Bits set means a break is allowed.
|
||||
allow: u128,
|
||||
}
|
||||
|
||||
/// A builder for an [`AsciiLineBreakTable`].
|
||||
///
|
||||
/// Construction is `const`. We create a dense `128 x 128` grid of overrides,
|
||||
/// then compress it into a row-deduplicated table via [`AsciiLineBreakTableBuilder::build`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AsciiLineBreakTableBuilder {
|
||||
/// Bit `after` set in row `before` means the pair has an explicit override.
|
||||
overridden: [u128; 128],
|
||||
/// Bit `after` set in row `before` means a break is allowed for that pair.
|
||||
allow: [u128; 128],
|
||||
}
|
||||
|
||||
impl AsciiLineBreakTableBuilder {
|
||||
/// A builder that defers every pair to the default ICU behavior.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
overridden: [0; 128],
|
||||
allow: [0; 128],
|
||||
}
|
||||
}
|
||||
|
||||
/// Override every pair in the cartesian product of the two inclusive ASCII
|
||||
/// ranges.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// All range bounds must be printable ASCII (`<= '\u{7f}'`).
|
||||
pub const fn with_pairs(
|
||||
mut self,
|
||||
before: RangeInclusive<char>,
|
||||
after: RangeInclusive<char>,
|
||||
allow_break: bool,
|
||||
) -> Self {
|
||||
assert!(
|
||||
*before.end() as u32 <= 0x7f && *after.end() as u32 <= 0x7f,
|
||||
"only printable ASCII is supported",
|
||||
);
|
||||
let mut before_pos = *before.start() as u32;
|
||||
while before_pos <= *before.end() as u32 {
|
||||
let mut after_pos = *after.start() as u32;
|
||||
while after_pos <= *after.end() as u32 {
|
||||
let bit = 1_u128 << after_pos;
|
||||
self.overridden[before_pos as usize] |= bit;
|
||||
if allow_break {
|
||||
self.allow[before_pos as usize] |= bit;
|
||||
} else {
|
||||
self.allow[before_pos as usize] &= !bit;
|
||||
}
|
||||
after_pos += 1;
|
||||
}
|
||||
before_pos += 1;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Compress the dense grid into a row-deduplicated [`AsciiLineBreakTable`]
|
||||
/// with at most `N` distinct rows.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `N` does not exactly match the number of distinct rows required.
|
||||
pub const fn build<const N: usize>(&self) -> AsciiLineBreakTable<N> {
|
||||
// Row 0 is reserved as the "defer everything" row.
|
||||
let mut rows = [Row {
|
||||
overridden: 0,
|
||||
allow: 0,
|
||||
}; N];
|
||||
let mut len = 1_usize;
|
||||
let mut row_of = [0_u8; 128];
|
||||
|
||||
let mut b = 0;
|
||||
while b < 128 {
|
||||
let (ov, al) = (self.overridden[b], self.allow[b]);
|
||||
let mut idx = 0;
|
||||
let mut found = usize::MAX;
|
||||
while idx < len {
|
||||
if rows[idx].overridden == ov && rows[idx].allow == al {
|
||||
found = idx;
|
||||
break;
|
||||
}
|
||||
idx += 1;
|
||||
}
|
||||
let r = if found != usize::MAX {
|
||||
found
|
||||
} else {
|
||||
assert!(
|
||||
len < N,
|
||||
"N is too small to contain table. Repeat with a larger N."
|
||||
);
|
||||
rows[len] = Row {
|
||||
overridden: ov,
|
||||
allow: al,
|
||||
};
|
||||
len += 1;
|
||||
len - 1
|
||||
};
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
reason = "TODO: fix this (`N` should be `u8`, or `row_of` should contain `usize`)"
|
||||
)]
|
||||
{
|
||||
row_of[b] = r as u8;
|
||||
}
|
||||
b += 1;
|
||||
}
|
||||
|
||||
assert!(
|
||||
len == N,
|
||||
"N is larger than required. Repeat with a smaller N."
|
||||
);
|
||||
|
||||
AsciiLineBreakTable { row_of, rows }
|
||||
}
|
||||
|
||||
/// See [`CHROMIUM_LINE_BREAK_TABLE`] for more details.
|
||||
const fn chromium() -> Self {
|
||||
// The printable ASCII range `'!'..=0x7F`.
|
||||
const ALL: RangeInclusive<char> = '!'..='\u{7f}';
|
||||
|
||||
Self::new()
|
||||
.with_pairs(ALL, ALL, false)
|
||||
.with_pairs(ALL, '('..='(', true)
|
||||
.with_pairs(ALL, '<'..='<', true)
|
||||
.with_pairs(ALL, '['..='[', true)
|
||||
.with_pairs(ALL, '{'..='{', true)
|
||||
.with_pairs('-'..='-', ALL, true)
|
||||
.with_pairs('?'..='?', ALL, true)
|
||||
.with_pairs('-'..='-', '$'..='$', false)
|
||||
.with_pairs(ALL, '!'..='!', false)
|
||||
.with_pairs('?'..='?', '"'..='"', false)
|
||||
.with_pairs('?'..='?', '\''..='\'', false)
|
||||
.with_pairs(ALL, ')'..=')', false)
|
||||
.with_pairs(ALL, ','..=',', false)
|
||||
.with_pairs(ALL, '.'..='.', false)
|
||||
.with_pairs(ALL, '/'..='/', false)
|
||||
.with_pairs('-'..='-', '0'..='9', false)
|
||||
.with_pairs(ALL, ':'..=':', false)
|
||||
.with_pairs(ALL, ';'..=';', false)
|
||||
.with_pairs(ALL, '?'..='?', false)
|
||||
.with_pairs(ALL, ']'..=']', false)
|
||||
.with_pairs(ALL, '}'..='}', false)
|
||||
.with_pairs('$'..='$', ALL, false)
|
||||
.with_pairs('\''..='\'', ALL, false)
|
||||
.with_pairs('('..='(', ALL, false)
|
||||
.with_pairs('/'..='/', ALL, false)
|
||||
.with_pairs('0'..='9', ALL, false)
|
||||
.with_pairs('<'..='<', ALL, false)
|
||||
.with_pairs('@'..='@', ALL, false)
|
||||
.with_pairs('A'..='Z', ALL, false)
|
||||
.with_pairs('['..='[', ALL, false)
|
||||
.with_pairs('^'..='`', ALL, false)
|
||||
.with_pairs('a'..='z', ALL, false)
|
||||
.with_pairs('{'..='{', ALL, false)
|
||||
.with_pairs('\u{7f}'..='\u{7f}', ALL, false)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AsciiLineBreakTableBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::AsciiLineBreakTableBuilder;
|
||||
use super::CHROMIUM_LINE_BREAK_TABLE;
|
||||
use super::LineBreakContext;
|
||||
use super::chromium_override;
|
||||
|
||||
fn cx(before_before: Option<char>, before: char, after: char) -> LineBreakContext {
|
||||
LineBreakContext {
|
||||
before_before,
|
||||
before,
|
||||
after,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chromium_hyphen_digit_depends_on_preceding_char() {
|
||||
// A break between '-' and a digit is allowed only when the character
|
||||
// preceding the '-' is ASCII alphanumeric.
|
||||
assert_eq!(chromium_override(cx(Some('D'), '-', '1')), Some(true));
|
||||
assert_eq!(chromium_override(cx(Some('4'), '-', '5')), Some(true));
|
||||
// Otherwise the '-' may be a minus sign, so the break is suppressed.
|
||||
assert_eq!(chromium_override(cx(Some(' '), '-', '1')), Some(false));
|
||||
assert_eq!(chromium_override(cx(Some('('), '-', '1')), Some(false));
|
||||
// No preceding character (start of text) behaves like a non-alphanumeric
|
||||
// context, matching Chromium's `last_last_ch == 0`.
|
||||
assert_eq!(chromium_override(cx(None, '-', '1')), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chromium_ignores_uax_14_lb13() {
|
||||
// Blink allows a break after a space run unconditionally.
|
||||
// See comment in non-test code for more details.
|
||||
for after in ['}', ')', ']', '!', '.', ',', '/', ':', ';', '?', 'b', '('] {
|
||||
assert_eq!(
|
||||
chromium_override(cx(None, ' ', after)),
|
||||
Some(true),
|
||||
"expected a break after the space, before {after:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chromium_hyphen_non_digit_defers_to_table() {
|
||||
// '-' followed by a non-digit ignores `before_before` and uses the table.
|
||||
assert_eq!(chromium_override(cx(Some('D'), '-', 'b')), Some(true));
|
||||
assert_eq!(chromium_override(cx(None, '-', 'b')), Some(true));
|
||||
// Non-ASCII after '-' defers to ICU.
|
||||
assert_eq!(chromium_override(cx(Some('D'), '-', 'é')), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chromium_suppresses_ascii_punctuation_breaks() {
|
||||
let t = &CHROMIUM_LINE_BREAK_TABLE;
|
||||
// No break before or after a slash.
|
||||
assert_eq!(t.lookup('a', '/'), Some(false));
|
||||
assert_eq!(t.lookup('/', 'b'), Some(false));
|
||||
// No break around other punctuation.
|
||||
assert_eq!(t.lookup('a', '.'), Some(false));
|
||||
assert_eq!(t.lookup('a', ':'), Some(false));
|
||||
// No break between letters.
|
||||
assert_eq!(t.lookup('a', 'b'), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chromium_allows_some_breaks() {
|
||||
let t = &CHROMIUM_LINE_BREAK_TABLE;
|
||||
// Break allowed before opening punctuation, but only when the preceding
|
||||
// character's row was not later suppressed.
|
||||
assert_eq!(t.lookup(')', '('), Some(true));
|
||||
assert_eq!(t.lookup(')', '<'), Some(true));
|
||||
assert_eq!(t.lookup('a', '('), Some(false));
|
||||
// Break allowed after '-' and '?' except when...
|
||||
assert_eq!(t.lookup('-', 'b'), Some(true));
|
||||
assert_eq!(t.lookup('?', 'b'), Some(true));
|
||||
// ...break not allowed after '-' before a digit, or '?' before a quote.
|
||||
assert_eq!(t.lookup('-', '5'), Some(false));
|
||||
assert_eq!(t.lookup('?', '"'), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_ascii_pairs_defer_to_icu() {
|
||||
let t = &CHROMIUM_LINE_BREAK_TABLE;
|
||||
assert_eq!(t.lookup('a', 'é'), None);
|
||||
assert_eq!(t.lookup('é', 'a'), None);
|
||||
// Space (0x20) is below the printable range, so it defers too.
|
||||
assert_eq!(t.lookup('a', ' '), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_table_defers_to_icu() {
|
||||
let t = AsciiLineBreakTableBuilder::new().build::<1>();
|
||||
assert_eq!(t.lookup('a', '/'), None);
|
||||
assert_eq!(t.lookup('a', '('), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dedup_matches_dense_for_chromium() {
|
||||
let builder = AsciiLineBreakTableBuilder::chromium();
|
||||
for b in 0..128_u32 {
|
||||
for a in 0..128_u32 {
|
||||
let bit = 1_u128 << a;
|
||||
let dense = if builder.overridden[b as usize] & bit == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(builder.allow[b as usize] & bit != 0)
|
||||
};
|
||||
let (before, after) = (char::from_u32(b).unwrap(), char::from_u32(a).unwrap());
|
||||
assert_eq!(
|
||||
CHROMIUM_LINE_BREAK_TABLE.lookup(before, after),
|
||||
dense,
|
||||
"mismatch at (before={b:#04x}, after={a:#04x})",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Word boundaries for the scripts whose words need a dictionary (Thai, Lao, Khmer, Burmese,
|
||||
//! Chinese and Japanese), from outside Parley (Rune: vendor/parley_engine.patch). A build without
|
||||
//! `complex-scripts` links none of ICU's dictionaries; a host that has its own (a browser's
|
||||
//! `Intl.Segmenter`) gives them here. Its boundaries are the words inside each such run and, in
|
||||
//! Thai, Lao, Khmer and Burmese, the run's line break opportunities too, as ICU's dictionary
|
||||
//! line segmenter makes them (UAX #14 breaks class SA at word boundaries).
|
||||
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use icu_properties::props::{GeneralCategory, Script};
|
||||
use parley_data::Properties;
|
||||
|
||||
/// Appends to `out` the word boundaries strictly inside `text`, as ascending byte offsets, for a
|
||||
/// `text` all in one dictionary language: `language` is `th`, `lo`, `km`, `my` or `ja` (Han,
|
||||
/// hiragana and katakana, whose dictionary Chinese and Japanese share).
|
||||
pub type DictionarySegmenter = fn(text: &str, language: &str, out: &mut Vec<usize>);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
static SEGMENTER: std::sync::OnceLock<DictionarySegmenter> = std::sync::OnceLock::new();
|
||||
|
||||
/// Gives Parley the host's dictionary word boundaries, once (a second call changes nothing).
|
||||
/// Without `complex-scripts` and without this, a Thai phrase has no break opportunity and a
|
||||
/// Chinese sentence's words are its characters. Needs `std`.
|
||||
pub fn set_dictionary_segmenter(segmenter: DictionarySegmenter) {
|
||||
#[cfg(feature = "std")]
|
||||
let _ = SEGMENTER.set(segmenter);
|
||||
#[cfg(not(feature = "std"))]
|
||||
let _ = segmenter;
|
||||
}
|
||||
|
||||
fn segmenter() -> Option<DictionarySegmenter> {
|
||||
#[cfg(all(feature = "std", not(feature = "complex-scripts")))]
|
||||
return SEGMENTER.get().copied();
|
||||
#[cfg(not(all(feature = "std", not(feature = "complex-scripts"))))]
|
||||
None
|
||||
}
|
||||
|
||||
/// The dictionary language a character's script asks for, and whether its words are its line
|
||||
/// break opportunities (class SA).
|
||||
fn language(script: Script) -> Option<(&'static str, bool)> {
|
||||
Some(match script {
|
||||
Script::Thai => ("th", true),
|
||||
Script::Lao => ("lo", true),
|
||||
Script::Khmer => ("km", true),
|
||||
Script::Myanmar => ("my", true),
|
||||
Script::Han | Script::Hiragana | Script::Katakana => ("ja", false),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A mark, a joiner or a length mark (ー) carries on the run before it.
|
||||
fn continues(properties: Properties, ch: char) -> bool {
|
||||
matches!(properties.script(), Script::Inherited)
|
||||
|| matches!(
|
||||
properties.general_category(),
|
||||
GeneralCategory::NonspacingMark | GeneralCategory::SpacingMark | GeneralCategory::EnclosingMark
|
||||
)
|
||||
|| matches!(ch, '\u{200C}' | '\u{200D}' | '\u{30FC}')
|
||||
}
|
||||
|
||||
/// The text's dictionary runs and the host's word boundaries inside them.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Words {
|
||||
/// `(start, end, sa)` byte ranges, ascending.
|
||||
runs: Vec<(usize, usize, bool)>,
|
||||
/// Boundaries strictly inside the runs, ascending.
|
||||
bounds: Vec<usize>,
|
||||
run: usize,
|
||||
bound: usize,
|
||||
}
|
||||
|
||||
impl Words {
|
||||
pub(crate) fn of(text: &str, properties: impl Fn(char) -> Properties) -> Self {
|
||||
let Some(segment) = segmenter() else { return Self::default() };
|
||||
let mut words = Self::default();
|
||||
let mut open: Option<(usize, &'static str, bool)> = None;
|
||||
let close = |words: &mut Self, start: usize, end: usize, lang: &'static str, sa: bool| {
|
||||
let run = &text[start..end];
|
||||
// A single character has no boundary inside it.
|
||||
if run.chars().nth(1).is_none() {
|
||||
return;
|
||||
}
|
||||
let mut found = Vec::new();
|
||||
segment(run, lang, &mut found);
|
||||
words.bounds.extend(found.into_iter().filter(|&b| b > 0 && b < run.len() && run.is_char_boundary(b)).map(|b| b + start));
|
||||
words.runs.push((start, end, sa));
|
||||
};
|
||||
for (at, ch) in text.char_indices() {
|
||||
let props = properties(ch);
|
||||
if let Some((start, lang, sa)) = open {
|
||||
if continues(props, ch) || language(props.script()).is_some_and(|(l, _)| l == lang) {
|
||||
continue;
|
||||
}
|
||||
close(&mut words, start, at, lang, sa);
|
||||
}
|
||||
open = language(props.script()).map(|(lang, sa)| (at, lang, sa));
|
||||
}
|
||||
if let Some((start, lang, sa)) = open {
|
||||
close(&mut words, start, text.len(), lang, sa);
|
||||
}
|
||||
words
|
||||
}
|
||||
|
||||
/// The boundaries inside Thai, Lao, Khmer and Burmese runs: their line break opportunities.
|
||||
/// None with `line-dictionaries`, whose line segmenter finds them itself.
|
||||
pub(crate) fn line_breaks(&self) -> impl Iterator<Item = usize> + '_ {
|
||||
let mut run = if cfg!(feature = "line-dictionaries") { self.runs.len() } else { 0 };
|
||||
self.bounds.iter().copied().filter(move |&b| {
|
||||
while self.runs.get(run).is_some_and(|r| r.1 <= b) {
|
||||
run += 1;
|
||||
}
|
||||
self.runs.get(run).is_some_and(|r| r.0 < b && r.2)
|
||||
})
|
||||
}
|
||||
|
||||
/// Inside a run (past its first character), whether `at` is a word boundary; `None` outside
|
||||
/// one, where the rule-based segmenter decides. Asked in ascending order.
|
||||
pub(crate) fn word_at(&mut self, at: usize) -> Option<bool> {
|
||||
while self.runs.get(self.run).is_some_and(|r| r.1 <= at) {
|
||||
self.run += 1;
|
||||
}
|
||||
let run = self.runs.get(self.run)?;
|
||||
if at <= run.0 {
|
||||
return None;
|
||||
}
|
||||
while self.bounds.get(self.bound).is_some_and(|&b| b < at) {
|
||||
self.bound += 1;
|
||||
}
|
||||
Some(self.bounds.get(self.bound) == Some(&at))
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
// Copyright 2025 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
/// Glyph with an offset and advance.
|
||||
#[derive(Copy, Clone, Default, Debug, PartialEq)]
|
||||
#[expect(missing_docs, reason = "Deferred")]
|
||||
pub struct Glyph {
|
||||
pub id: u32,
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub advance: f32,
|
||||
}
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Itemization breaks text into individually-shapeable items.
|
||||
|
||||
use core::{ops::Range, str::CharIndices};
|
||||
|
||||
use icu_properties::props::Script as IcuScript;
|
||||
use parlance::{BidiLevel, Script};
|
||||
|
||||
use crate::{Analysis, CharInfo, ShapeOptions};
|
||||
|
||||
/// A range of text.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TextRange {
|
||||
/// The range of byte offsets.
|
||||
pub byte_range: Range<usize>,
|
||||
|
||||
/// The range of character indices.
|
||||
pub char_range: Range<usize>,
|
||||
}
|
||||
|
||||
/// A span of text inside an [`Item`] with constant script and bidirectional embedding level.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Segment {
|
||||
/// The text range of this item.
|
||||
pub range: TextRange,
|
||||
|
||||
/// The bidi level of characters in this item.
|
||||
pub bidi_level: BidiLevel,
|
||||
|
||||
/// The script of characters in this item.
|
||||
///
|
||||
/// Characters in the source text that do not have a particular script (i.e., they are one of
|
||||
/// [`Script::COMMON`], [`Script::UNKNOWN`] or [`Script::INHERITED`]) get their script from
|
||||
/// surrounding context. Currently, these just inherit the script of the preceding characters.
|
||||
/// Leading characters without a particular script inherit the script of the first character
|
||||
/// *with* a particular script. These heuristics may change in the future. For more, see UAX 24
|
||||
/// (<https://www.unicode.org/reports/tr24/>) Section 5.
|
||||
pub script: Script,
|
||||
}
|
||||
|
||||
/// A span of text shaped with specific [`ShapeOptions`].
|
||||
///
|
||||
/// An [`Item`] represents a sequence of constant [`ShapeOptions`], but cannot always be passed to
|
||||
/// the shaper as a single unit. Within an item, the script or bidirectional text embedding level
|
||||
/// may change, which requires further splitting the item into segments of constant script and bidi
|
||||
/// level (see [`Segment`]).
|
||||
#[derive(Debug)]
|
||||
pub struct Item<'a> {
|
||||
/// The character offset in the source text which this item ends.
|
||||
///
|
||||
/// This must be strictly greater than the previous item's end. For the first item, it must be
|
||||
/// greater than 0.
|
||||
pub char_end: u32,
|
||||
|
||||
/// The options to shape this item with.
|
||||
//
|
||||
// TODO: should users instead be allowed to build `options` at the `Segment` level (i.e.,
|
||||
// through some callback)? The motivation is for users to have access to the segment's `Script`
|
||||
// and be able to set font features based on that. If the entirety of `ShapeOptions` moves
|
||||
// there, it would allow users to set, e.g., a font size per segment, even though it's not
|
||||
// necessarily an item boundary; and note an item then doesn't mean a whole lot anymore. We
|
||||
// could also allow only some options to be per-segment. In any case, we're probably moving
|
||||
// towards a future where items reset grapheme segmentation, but segments do not (note Gecko and
|
||||
// Blink also reset grapheme segmentation when something like font size changes, but not when
|
||||
// the script changes).
|
||||
pub options: ShapeOptions<'a>,
|
||||
// TODO: we probably should allow users to pass in some data (like we allow passing
|
||||
// style_indices elsewhere), which we copy onto `ShapedRun`. That allows users to easily
|
||||
// correlate `ShapedRun`s with some data they themselves hold.
|
||||
//
|
||||
// This is potentially important for better correctness in `parley`: it itemizes based on
|
||||
// `nearly_eq` of shaping-relevant styles like font size, i.e., it should then read that item's
|
||||
// style to know the font size, even though it may be different for the run.
|
||||
// /// Opaque data copied onto every `ShapedRun` produced from this item.
|
||||
// pub user_data: u16,
|
||||
}
|
||||
|
||||
/// Produces the items in a text via [`Self::next`]; created by [`Analysis::itemize`].
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Itemizer<'a> {
|
||||
/// Our underlying iterator over the input text.
|
||||
char_indices: CharIndices<'a>,
|
||||
/// The per-char info, parallel to [`Self::char_indices`].
|
||||
char_info: &'a [CharInfo],
|
||||
/// The per-char bidi level, parallel to [`Self::char_indices`].
|
||||
bidi_levels: &'a [BidiLevel],
|
||||
|
||||
/// The paragraph's base bidi level.
|
||||
///
|
||||
/// If [`Self::bidi_levels`] is empty as a special case, this is the bidi level of each
|
||||
/// character.
|
||||
paragraph_bidi_level: BidiLevel,
|
||||
|
||||
/// The running character offset of the last-processed item.
|
||||
current_char_offset: usize,
|
||||
/// The running script of the last-processed item.
|
||||
current_script: IcuScript,
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
/// Divide the `text` into individually-shapeable segments.
|
||||
///
|
||||
/// The `text` passed in must be the same as used for producing the `self` analysis.
|
||||
///
|
||||
/// The text is divided into items produced by a predicate passed to [`Itemizer::next`] and
|
||||
/// further divided into segments of constant bidi level and script.
|
||||
///
|
||||
/// Characters that don't have a particular script have their script resolved based on
|
||||
/// surrounding context (see [`Segment::script`]).
|
||||
pub(crate) fn itemize<'a>(&'a self, text: &'a str) -> Itemizer<'a> {
|
||||
let first_real_script = self
|
||||
.char_info()
|
||||
.iter()
|
||||
.map(|x| x.script)
|
||||
.find(|&script| real_script(script))
|
||||
.unwrap_or(IcuScript::Latin);
|
||||
|
||||
Itemizer {
|
||||
char_indices: text.char_indices(),
|
||||
char_info: self.char_info(),
|
||||
bidi_levels: self.bidi_levels(),
|
||||
paragraph_bidi_level: self.paragraph_level(),
|
||||
|
||||
current_char_offset: 0,
|
||||
current_script: first_real_script,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Itemizer<'_> {
|
||||
/// Produce the next segment, if any.
|
||||
///
|
||||
/// For consecutive characters where the bidi level and script are unchanging, the `split_after`
|
||||
/// predicate is called with the growing item range, and can be used to split on additional
|
||||
/// properties like shaping-relevant style changes (e.g., font size) or properties like
|
||||
/// language.
|
||||
///
|
||||
/// The predicate is given a range encoding the current item and considers whether to split
|
||||
/// after that item based on the next character. Iff the predicate returns `true`, the text is
|
||||
/// split after that item; i.e., given a range of `start..end`, the predicate controls whether
|
||||
/// that item is now finished, or whether it is extended to include the character at `end` (at
|
||||
/// which point the item spans `start..end+1`).
|
||||
//
|
||||
// TODO: currently the items from `split_after` have the same effect as a change in bidi or
|
||||
// script. This is not how browsers handle things. In particular, `split_after` should reset
|
||||
// grapheme segmentation, whereas bidi and script should produce separately-shaped segments.
|
||||
#[inline]
|
||||
pub(crate) fn next(
|
||||
&mut self,
|
||||
mut split_after: impl FnMut(TextRange) -> bool,
|
||||
) -> Option<Segment> {
|
||||
if self.char_info.is_empty() {
|
||||
// We're already finished.
|
||||
debug_assert!(
|
||||
self.char_indices.next().is_none() && self.bidi_levels.is_empty(),
|
||||
"`char_info`, `bidi_levels`, and `char_indices` should now all be empty \
|
||||
(though note `bidi_levels` may already have been empty as a special-case)"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut item_bidi_level = BidiLevel::new(0); // Initialized in the loop.
|
||||
|
||||
let start_byte_offset = self.char_indices.offset();
|
||||
let mut item_char_len = 0;
|
||||
loop {
|
||||
let byte_offset = self.char_indices.offset();
|
||||
|
||||
let bidi_level = if self.bidi_levels.is_empty() {
|
||||
self.paragraph_bidi_level
|
||||
} else {
|
||||
self.bidi_levels[0]
|
||||
};
|
||||
let mut script = self.char_info[0].script;
|
||||
|
||||
if !real_script(script) {
|
||||
// This is a very simple heuristic, where if a character does not have a "real
|
||||
// script," it inherits the script of the preceding character. UAX 24 paragraph
|
||||
// 5.1 says this "works well in many cases", but also suggests performing, e.g.,
|
||||
// bracket matching (for example, the parentheses in `hello (αβγ)` should ideally
|
||||
// both be marked as being `Latin`). At that point, `Itemizer` would probably like
|
||||
// to have reusable scratch for the bracket stack.
|
||||
script = self.current_script;
|
||||
}
|
||||
|
||||
// First iteration of the loop, initialize item properties.
|
||||
if item_char_len == 0 {
|
||||
item_bidi_level = bidi_level;
|
||||
self.current_script = script;
|
||||
}
|
||||
|
||||
if bidi_level != item_bidi_level || script != self.current_script {
|
||||
break;
|
||||
}
|
||||
|
||||
if item_char_len > 0
|
||||
&& split_after(TextRange {
|
||||
byte_range: start_byte_offset..byte_offset,
|
||||
char_range: self.current_char_offset..self.current_char_offset + item_char_len,
|
||||
})
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
self.char_indices.next().expect("The passed in `text` was not of the same length as the text used to generate `Analysis`");
|
||||
self.char_info = &self.char_info[1..];
|
||||
if !self.bidi_levels.is_empty() {
|
||||
self.bidi_levels = &self.bidi_levels[1..];
|
||||
}
|
||||
|
||||
item_char_len += 1;
|
||||
|
||||
if self.char_info.is_empty() {
|
||||
// The text is now empty, so we're finished.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let start_char_offset = self.current_char_offset;
|
||||
self.current_char_offset += item_char_len;
|
||||
|
||||
Some(Segment {
|
||||
range: TextRange {
|
||||
byte_range: start_byte_offset..self.char_indices.offset(),
|
||||
char_range: start_char_offset..self.current_char_offset,
|
||||
},
|
||||
script: icu_script_to_parlance_script(self.current_script),
|
||||
bidi_level: item_bidi_level,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn real_script(script: IcuScript) -> bool {
|
||||
script != IcuScript::Common && script != IcuScript::Unknown && script != IcuScript::Inherited
|
||||
}
|
||||
|
||||
/// Convert an ICU script into a [`Script`].
|
||||
#[inline]
|
||||
fn icu_script_to_parlance_script(script: IcuScript) -> Script {
|
||||
static SHORT_NAMES: icu_properties::PropertyNamesShortBorrowed<'static, IcuScript> =
|
||||
icu_properties::PropertyNamesShort::new();
|
||||
|
||||
SHORT_NAMES
|
||||
.get(script)
|
||||
.and_then(|name| Script::parse(name).ok())
|
||||
.unwrap_or(Script::UNKNOWN)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use alloc::vec::Vec;
|
||||
use parlance::Script;
|
||||
|
||||
use crate::{Analysis, AnalysisOptions, Analyzer};
|
||||
|
||||
use super::Segment;
|
||||
|
||||
const LATN: Script = Script::from_bytes(*b"Latn");
|
||||
const GREK: Script = Script::from_bytes(*b"Grek");
|
||||
const ARAB: Script = Script::from_bytes(*b"Arab");
|
||||
|
||||
fn analyze(text: &str) -> Analysis {
|
||||
let mut analyzer = Analyzer::new();
|
||||
let mut analysis = Analysis::new();
|
||||
let options = AnalysisOptions::default();
|
||||
analyzer.analyze(text, &options, &mut analysis);
|
||||
analysis
|
||||
}
|
||||
|
||||
fn items(text: &str) -> Vec<Segment> {
|
||||
let analysis = analyze(text);
|
||||
let mut itemizer = analysis.itemize(text);
|
||||
core::iter::from_fn(|| itemizer.next(|_| false)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty() {
|
||||
assert!(items("").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_direction() {
|
||||
let text = "hello مرحبا";
|
||||
let items = items(text);
|
||||
assert!(items.len() >= 2);
|
||||
assert_eq!(items[0].script, LATN);
|
||||
assert!(items[0].bidi_level.is_ltr());
|
||||
assert!(
|
||||
items
|
||||
.iter()
|
||||
.any(|item| item.script == ARAB && item.bidi_level.is_rtl())
|
||||
);
|
||||
|
||||
// Items tile the text contiguously.
|
||||
let mut cursor = 0;
|
||||
for item in &items {
|
||||
assert_eq!(item.range.byte_range.start, cursor);
|
||||
cursor = item.range.byte_range.end;
|
||||
}
|
||||
assert_eq!(cursor, text.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predicate() {
|
||||
let text = "abcdef";
|
||||
let analysis = analyze(text);
|
||||
let mut itemizer = analysis.itemize(text);
|
||||
let items: Vec<_> =
|
||||
core::iter::from_fn(|| itemizer.next(|range| range.char_range.end == 3)).collect();
|
||||
assert_eq!(items.len(), 2);
|
||||
assert_eq!(items[0].range.byte_range, 0..3);
|
||||
assert_eq!(items[0].range.char_range, 0..3);
|
||||
assert_eq!(items[1].range.byte_range, 3..6);
|
||||
assert_eq!(items[1].range.char_range, 3..6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neutral_backward() {
|
||||
// Latin, a space (`Common`), then Greek.
|
||||
let text = "abc αβγ";
|
||||
let items = items(text);
|
||||
assert_eq!(items.len(), 2);
|
||||
// The space attaches to the Latin run.
|
||||
assert_eq!(&text[items[0].range.byte_range.clone()], "abc ");
|
||||
assert_eq!(items[0].script, LATN);
|
||||
assert_eq!(&text[items[1].range.byte_range.clone()], "αβγ");
|
||||
assert_eq!(items[1].script, GREK);
|
||||
}
|
||||
}
|
||||
Vendored
+130
@@ -0,0 +1,130 @@
|
||||
// Copyright 2025 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Parley Engine provides low level APIs for shaping paragraphs of text.
|
||||
//!
|
||||
//! ## Usage
|
||||
//!
|
||||
//! Use [`Analyzer`], [`Analysis`], [`Shaper`] and [`ShapedText`] to shape a paragraph of text into
|
||||
//! glyphs. Correct reshaping of lines is in progress; in the meantime you can break text at
|
||||
//! [`Atom`] or [`ShapedCluster`][crate::shape::ShapedCluster] boundaries.
|
||||
//!
|
||||
//! Text analysis is performed before shaping, and the same source string must be passed to each
|
||||
//! stage.
|
||||
//!
|
||||
//! Higher-level users may prefer using [`parley`][parley], which uses this crate and implements
|
||||
//! layout and styling.
|
||||
//!
|
||||
//! ```rust,no_run
|
||||
//! # // We only compile this doctest because we don't have a font available.
|
||||
//! # use parley_engine::{Analysis, AnalysisOptions, Analyzer, FontInstanceRef, FontSelector, ShapedText, ShapeOptions, Shaper};
|
||||
//! # use parley_engine::shape::CharCluster;
|
||||
//! # use parley_engine::itemize::{Item, Segment};
|
||||
//! #
|
||||
//! # struct NoFont;
|
||||
//! # impl FontSelector for NoFont {
|
||||
//! # fn select_font(
|
||||
//! # &mut self,
|
||||
//! # _segment: &Segment,
|
||||
//! # _options: &ShapeOptions<'_>,
|
||||
//! # _cluster: &mut CharCluster,
|
||||
//! # ) -> Option<FontInstanceRef<'_>> {
|
||||
//! # unimplemented!()
|
||||
//! # }
|
||||
//! # }
|
||||
//! #
|
||||
//! # let select_font = NoFont;
|
||||
//! let mut analysis = Analysis::default();
|
||||
//! let mut analyzer = Analyzer::default();
|
||||
//! let mut shaped_text = ShapedText::default();
|
||||
//! let mut shaper = Shaper::default();
|
||||
//!
|
||||
//! let text = "The quick brown ثعلب jumps over the lazy dog.";
|
||||
//! let char_count = text.chars().count();
|
||||
//! let char_style_indices = vec![0; char_count];
|
||||
//!
|
||||
//! analyzer.analyze(text, &AnalysisOptions::default(), &mut analysis);
|
||||
//! shaper.shape_text(
|
||||
//! text,
|
||||
//! &analysis,
|
||||
//! &char_style_indices,
|
||||
//! [Item {
|
||||
//! char_end: char_count.try_into().unwrap(),
|
||||
//! options: ShapeOptions {
|
||||
//! font_size: 16.0,
|
||||
//! language: None,
|
||||
//! features: &[],
|
||||
//! variations: &[],
|
||||
//! },
|
||||
//! }],
|
||||
//! select_font, // Selects fonts covering each cluster.
|
||||
//! &mut shaped_text,
|
||||
//! );
|
||||
//!
|
||||
//! for (run_idx, run) in shaped_text.runs().iter().enumerate() {
|
||||
//! let slice = shaped_text.run_slice(run_idx as u32);
|
||||
//! // You can, for example, measure grapheme advances for hit-testing or
|
||||
//! // placing carets.
|
||||
//! for atom in slice.atoms_start() {
|
||||
//! for grapheme in atom.graphemes_start() {
|
||||
//! std::dbg!(grapheme);
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! // Or get glyphs for rendering (for simplicity, this iterates clusters in
|
||||
//! // logical order, but for rendering you'd want to reorder runs and clusters
|
||||
//! // according to their `run.bidi_level`).
|
||||
//! for cluster in slice.shaped_clusters_range() {
|
||||
//! for glyph in slice.shaped_cluster_glyphs(cluster) {
|
||||
//! std::dbg!(glyph);
|
||||
//! }
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! ## Features
|
||||
//!
|
||||
//! - `std` (enabled by default): This is currently unused and is provided for forward compatibility.
|
||||
//! - `bytemuck`: Forwarded to [`parlance`], which then implements traits from `bytemuck` on its
|
||||
//! types.
|
||||
//!
|
||||
//! [parley]: https://docs.rs/parley
|
||||
|
||||
// LINEBENDER LINT SET - lib.rs - v3
|
||||
// See https://linebender.org/wiki/canonical-lints/
|
||||
// These lints shouldn't apply to examples or tests.
|
||||
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
|
||||
// These lints shouldn't apply to examples.
|
||||
#![warn(clippy::print_stdout, clippy::print_stderr)]
|
||||
// Targeting e.g. 32-bit means structs containing usize can give false positives for 64-bit.
|
||||
#![cfg_attr(target_pointer_width = "64", warn(clippy::trivially_copy_pass_by_ref))]
|
||||
// END LINEBENDER LINT SET
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
// Vendored: the upstream crate has an unreachable expression rustc warns about; keep the build log quiet.
|
||||
#![allow(unreachable_code)]
|
||||
#![no_std]
|
||||
#[cfg(feature = "std")]
|
||||
extern crate std;
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
mod analysis;
|
||||
mod analyzer;
|
||||
mod bidi;
|
||||
pub mod break_overrides;
|
||||
pub mod dictionary;
|
||||
pub mod platform;
|
||||
mod glyph;
|
||||
pub mod itemize;
|
||||
mod lru_cache;
|
||||
pub mod shape;
|
||||
|
||||
pub use linebender_resource_handle::FontData;
|
||||
pub use parlance::{BaseDirection, NormalizedCoord};
|
||||
|
||||
pub use analysis::{Analysis, AnalysisDataSources, CharInfo};
|
||||
pub use analyzer::{AnalysisOptions, Analyzer, LineBreakConfig};
|
||||
pub use glyph::Glyph;
|
||||
pub use shape::atom::{Atom, Atoms, Grapheme, Graphemes, ShapedClusterGlyphs, ShapedSlice};
|
||||
pub use shape::shaped_text::{FontMetrics, ShapedRun, ShapedText};
|
||||
pub use shape::shaper::{FontInstance, FontInstanceRef, FontSelector, ShapeOptions, Shaper};
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
// Copyright 2025 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use hashbrown::Equivalent;
|
||||
|
||||
/// An entry in the cache.
|
||||
pub(crate) struct Entry<ID, T> {
|
||||
pub epoch: u64,
|
||||
pub id: ID,
|
||||
pub data: T,
|
||||
}
|
||||
|
||||
/// A least-recently-used cache. This cache uses a linear scan of its entries
|
||||
/// to find a given entry - it is optimised for a low number of entries. Preferably
|
||||
/// keep `max_entries` low - in the order of tens.
|
||||
pub(crate) struct LruCache<ID, T> {
|
||||
entries: Vec<Entry<ID, T>>,
|
||||
epoch: u64,
|
||||
max_entries: usize,
|
||||
}
|
||||
|
||||
impl<ID, T> LruCache<ID, T> {
|
||||
pub(crate) fn new(max_entries: usize) -> Self {
|
||||
Self {
|
||||
entries: Vec::default(),
|
||||
epoch: 0,
|
||||
max_entries,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a reference to the entry with the given ID. If the entry is not
|
||||
/// found, it is created and returned using `make_data`.
|
||||
///
|
||||
/// The lookup key must be `Equivalent` to ID for lookups and convertible `Into<ID>`
|
||||
/// for creating new entries.
|
||||
pub(crate) fn entry<K>(&mut self, id: K, make_data: impl FnOnce() -> T) -> &T
|
||||
where
|
||||
K: Equivalent<ID> + Into<ID>,
|
||||
{
|
||||
let index = self.find_entry(id, make_data);
|
||||
self.epoch += 1;
|
||||
let entry = &mut self.entries[index];
|
||||
entry.epoch = self.epoch;
|
||||
&entry.data
|
||||
}
|
||||
|
||||
fn find_entry<K>(&mut self, id: K, make_data: impl FnOnce() -> T) -> usize
|
||||
where
|
||||
K: Equivalent<ID> + Into<ID>,
|
||||
{
|
||||
let epoch = self.epoch;
|
||||
let mut lowest_serial = epoch;
|
||||
let mut lowest_index = 0;
|
||||
for (i, entry) in self.entries.iter().enumerate() {
|
||||
if id.equivalent(&entry.id) {
|
||||
return i;
|
||||
}
|
||||
if entry.epoch < lowest_serial {
|
||||
lowest_serial = entry.epoch;
|
||||
lowest_index = i;
|
||||
}
|
||||
}
|
||||
if self.entries.len() < self.max_entries {
|
||||
lowest_index = self.entries.len();
|
||||
self.entries.push(Entry {
|
||||
epoch,
|
||||
id: id.into(),
|
||||
data: make_data(),
|
||||
});
|
||||
} else {
|
||||
let entry = &mut self.entries[lowest_index];
|
||||
entry.epoch = epoch;
|
||||
entry.id = id.into();
|
||||
entry.data = make_data();
|
||||
}
|
||||
lowest_index
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use alloc::string::{String, ToString};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct TestId(String);
|
||||
struct TestLookupKey<'a>(&'a str);
|
||||
|
||||
impl<'a> Equivalent<TestId> for TestLookupKey<'a> {
|
||||
fn equivalent(&self, key: &TestId) -> bool {
|
||||
self.0 == key.0.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<TestLookupKey<'a>> for TestId {
|
||||
fn from(key: TestLookupKey<'a>) -> Self {
|
||||
Self(key.0.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl Equivalent<Self> for TestId {
|
||||
fn equivalent(&self, key: &Self) -> bool {
|
||||
self.0 == key.0
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_retrieve_existing_entry() {
|
||||
let mut cache = LruCache::new(3);
|
||||
|
||||
// Insert an entry
|
||||
let value1 = cache.entry(TestLookupKey("key1"), || 42);
|
||||
assert_eq!(*value1, 42);
|
||||
|
||||
// Retrieve the same entry - make_data should not be called
|
||||
let value2 = cache.entry(TestLookupKey("key1"), || {
|
||||
panic!("Should not create new data")
|
||||
});
|
||||
assert_eq!(*value2, 42);
|
||||
assert_eq!(cache.entries.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multiple_entries() {
|
||||
let mut cache = LruCache::new(3);
|
||||
|
||||
let value1 = cache.entry(TestLookupKey("key1"), || 1);
|
||||
assert_eq!(*value1, 1);
|
||||
|
||||
let value2 = cache.entry(TestLookupKey("key2"), || 2);
|
||||
assert_eq!(*value2, 2);
|
||||
|
||||
let value3 = cache.entry(TestLookupKey("key3"), || 3);
|
||||
assert_eq!(*value3, 3);
|
||||
|
||||
assert_eq!(cache.entries.len(), 3);
|
||||
assert_eq!(cache.epoch, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lru_eviction() {
|
||||
let mut cache = LruCache::new(3);
|
||||
|
||||
// Add three entries
|
||||
cache.entry(TestLookupKey("key1"), || 1);
|
||||
cache.entry(TestLookupKey("key2"), || 2);
|
||||
cache.entry(TestLookupKey("key3"), || 3);
|
||||
|
||||
// Access key1 to update its epoch
|
||||
cache.entry(TestLookupKey("key1"), || panic!("Should not create"));
|
||||
|
||||
// Add key4 - should evict key2 (oldest untouched)
|
||||
cache.entry(TestLookupKey("key4"), || 4);
|
||||
|
||||
// Verify key1 is still present
|
||||
let value1 = cache.entry(TestLookupKey("key1"), || {
|
||||
panic!("key1 should still be present")
|
||||
});
|
||||
assert_eq!(*value1, 1);
|
||||
|
||||
// Verify key2 was evicted
|
||||
let mut was_created = false;
|
||||
cache.entry(TestLookupKey("key2"), || {
|
||||
was_created = true;
|
||||
20
|
||||
});
|
||||
assert!(was_created, "key2 should have been evicted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lru_eviction_after_multiple_hits() {
|
||||
let mut cache = LruCache::new(3);
|
||||
|
||||
cache.entry(TestLookupKey("key1"), || 1);
|
||||
cache.entry(TestLookupKey("key2"), || 2);
|
||||
cache.entry(TestLookupKey("key3"), || 3);
|
||||
|
||||
// Hit all three in order: key3 first (making it LRU among hits),
|
||||
// then key1, then key2 (most recently used).
|
||||
cache.entry(TestLookupKey("key3"), || panic!("Should not create"));
|
||||
cache.entry(TestLookupKey("key1"), || panic!("Should not create"));
|
||||
cache.entry(TestLookupKey("key2"), || panic!("Should not create"));
|
||||
|
||||
// Insert key4 — should evict key3 (least recently accessed)
|
||||
cache.entry(TestLookupKey("key4"), || 4);
|
||||
|
||||
// key1 and key2 should still be present with original values
|
||||
// (check these first since verifying key3 eviction will trigger another eviction)
|
||||
let v1 = cache.entry(TestLookupKey("key1"), || {
|
||||
panic!("key1 should still be present")
|
||||
});
|
||||
assert_eq!(*v1, 1);
|
||||
|
||||
let v2 = cache.entry(TestLookupKey("key2"), || {
|
||||
panic!("key2 should still be present")
|
||||
});
|
||||
assert_eq!(*v2, 2);
|
||||
|
||||
// key3 should have been evicted
|
||||
let mut key3_recreated = false;
|
||||
cache.entry(TestLookupKey("key3"), || {
|
||||
key3_recreated = true;
|
||||
30
|
||||
});
|
||||
assert!(key3_recreated, "key3 should have been evicted as the LRU");
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! A face of last resort that the platform draws (Rune: vendor/parley_engine.patch). A host that
|
||||
//! can shape and draw text itself (a browser's canvas, with the system's fonts, shaping and
|
||||
//! colour emoji) registers a font that covers every character and gives its runs a shaper here.
|
||||
//! A run in that font isn't shaped by HarfRust: the host gives one glyph per grapheme, its
|
||||
//! advance measured as the platform lays the run out, and the glyph ids are the host's own, for
|
||||
//! it to draw them.
|
||||
|
||||
use alloc::vec::Vec;
|
||||
|
||||
/// A run in the platform's face, for its shaper.
|
||||
#[derive(Debug)]
|
||||
pub struct PlatformText<'a> {
|
||||
/// The run's text.
|
||||
pub text: &'a str,
|
||||
/// Byte offsets into `text` where each grapheme starts, ascending, the first 0.
|
||||
pub graphemes: &'a [u32],
|
||||
/// Byte offsets where each unit the platform draws whole starts (at grapheme starts, between
|
||||
/// break opportunities), ascending, the first 0. A line never breaks inside one.
|
||||
pub units: &'a [u32],
|
||||
/// The font size, in the layout's units.
|
||||
pub size: f32,
|
||||
/// The weight asked for (`wght`, 100 to 900).
|
||||
pub weight: f32,
|
||||
/// Italic asked for.
|
||||
pub italic: bool,
|
||||
/// The run is right to left.
|
||||
pub rtl: bool,
|
||||
/// The run's language tag, if it has one.
|
||||
pub language: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// One glyph per grapheme of a [`PlatformText`], in logical order.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct PlatformGlyph {
|
||||
/// The host's id for what this glyph draws.
|
||||
pub id: u32,
|
||||
/// The grapheme's advance, in the layout's units.
|
||||
pub advance: f32,
|
||||
/// How far right of its pen the glyph draws, in the layout's units.
|
||||
pub x_offset: f32,
|
||||
}
|
||||
|
||||
/// Fills `out` with one glyph per grapheme of the run, in logical order.
|
||||
pub type PlatformShaper = fn(run: &PlatformText<'_>, out: &mut Vec<PlatformGlyph>);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
static PLATFORM: std::sync::OnceLock<(u64, PlatformShaper)> = std::sync::OnceLock::new();
|
||||
|
||||
/// Makes the font whose data has id `font` (`Blob::id`) the platform's face, shaped by `shaper`,
|
||||
/// once (a second call changes nothing). Needs `std`.
|
||||
pub fn set_platform_face(font: u64, shaper: PlatformShaper) {
|
||||
#[cfg(feature = "std")]
|
||||
let _ = PLATFORM.set((font, shaper));
|
||||
#[cfg(not(feature = "std"))]
|
||||
let _ = (font, shaper);
|
||||
}
|
||||
|
||||
/// The shaper for the font with data id `font`, if it's the platform's face.
|
||||
pub(crate) fn shaper(font: u64) -> Option<PlatformShaper> {
|
||||
#[cfg(feature = "std")]
|
||||
return PLATFORM.get().filter(|(id, _)| *id == font).map(|(_, shaper)| *shaper);
|
||||
#[cfg(not(feature = "std"))]
|
||||
{
|
||||
let _ = font;
|
||||
None
|
||||
}
|
||||
}
|
||||
+1008
File diff suppressed because it is too large.
Load diff
+215
@@ -0,0 +1,215 @@
|
||||
// Copyright 2025 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
use alloc::boxed::Box;
|
||||
use hashbrown::Equivalent;
|
||||
use parlance::FontVariation;
|
||||
|
||||
#[derive(PartialEq, Copy, Clone)]
|
||||
pub(crate) struct ShapeDataKey {
|
||||
/// The font collection's blob ID.
|
||||
font_blob_id: u64,
|
||||
/// The font's index in the font collection.
|
||||
font_index: u32,
|
||||
}
|
||||
|
||||
impl ShapeDataKey {
|
||||
pub(crate) const fn new(font_blob_id: u64, font_index: u32) -> Self {
|
||||
Self {
|
||||
font_blob_id,
|
||||
font_index,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Equivalent<Self> for ShapeDataKey {
|
||||
#[inline(always)]
|
||||
fn equivalent(&self, key: &Self) -> bool {
|
||||
self == key
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Self> for ShapeDataKey {
|
||||
#[inline(always)]
|
||||
fn from(key: &Self) -> Self {
|
||||
*key
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ShapeInstanceId {
|
||||
/// The font collection's blob ID.
|
||||
font_blob_id: u64,
|
||||
/// The font's index in the font collection.
|
||||
font_index: u32,
|
||||
synthesis: fontique::Synthesis,
|
||||
variations: Option<Box<[FontVariation]>>,
|
||||
}
|
||||
|
||||
pub(crate) struct ShapeInstanceKey<'a> {
|
||||
/// The font collection's blob ID.
|
||||
font_blob_id: u64,
|
||||
/// The font's index in the font collection.
|
||||
font_index: u32,
|
||||
synthesis: &'a fontique::Synthesis,
|
||||
variations: Option<&'a [FontVariation]>,
|
||||
}
|
||||
|
||||
impl<'a> ShapeInstanceKey<'a> {
|
||||
pub(crate) const fn new(
|
||||
font_blob_id: u64,
|
||||
font_index: u32,
|
||||
synthesis: &'a fontique::Synthesis,
|
||||
variations: Option<&'a [FontVariation]>,
|
||||
) -> Self {
|
||||
Self {
|
||||
font_blob_id,
|
||||
font_index,
|
||||
synthesis,
|
||||
variations,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Equivalent<ShapeInstanceId> for ShapeInstanceKey<'a> {
|
||||
#[inline(always)]
|
||||
fn equivalent(&self, key: &ShapeInstanceId) -> bool {
|
||||
self.font_blob_id == key.font_blob_id
|
||||
&& self.font_index == key.font_index
|
||||
&& *self.synthesis == key.synthesis
|
||||
&& self.variations == key.variations.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<ShapeInstanceKey<'a>> for ShapeInstanceId {
|
||||
#[inline(always)]
|
||||
fn from(key: ShapeInstanceKey<'a>) -> Self {
|
||||
Self {
|
||||
font_blob_id: key.font_blob_id,
|
||||
font_index: key.font_index,
|
||||
synthesis: *key.synthesis,
|
||||
variations: key.variations.map(|v| v.to_vec().into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shaped run's font metrics: its font instance at a size (Rune: vendor/parley_engine.patch).
|
||||
pub(crate) struct RunMetricsId {
|
||||
instance: ShapeInstanceId,
|
||||
font_size: u32,
|
||||
}
|
||||
|
||||
pub(crate) struct RunMetricsKey<'a> {
|
||||
instance: ShapeInstanceKey<'a>,
|
||||
font_size: f32,
|
||||
}
|
||||
|
||||
impl<'a> RunMetricsKey<'a> {
|
||||
pub(crate) const fn new(instance: ShapeInstanceKey<'a>, font_size: f32) -> Self {
|
||||
Self {
|
||||
instance,
|
||||
font_size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Equivalent<RunMetricsId> for RunMetricsKey<'a> {
|
||||
#[inline(always)]
|
||||
fn equivalent(&self, key: &RunMetricsId) -> bool {
|
||||
self.font_size.to_bits() == key.font_size && self.instance.equivalent(&key.instance)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<RunMetricsKey<'a>> for RunMetricsId {
|
||||
#[inline(always)]
|
||||
fn from(key: RunMetricsKey<'a>) -> Self {
|
||||
Self {
|
||||
instance: key.instance.into(),
|
||||
font_size: key.font_size.to_bits(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ShapePlanId {
|
||||
/// The font collection's blob ID.
|
||||
font_blob_id: u64,
|
||||
/// The font's index in the font collection.
|
||||
font_index: u32,
|
||||
synthesis: fontique::Synthesis,
|
||||
direction: harfrust::Direction,
|
||||
script: harfrust::Script,
|
||||
language: Option<harfrust::Language>,
|
||||
features: Box<[harfrust::Feature]>,
|
||||
variations: Option<Box<[FontVariation]>>,
|
||||
}
|
||||
|
||||
pub(crate) struct ShapePlanKey<'a> {
|
||||
/// The font collection's blob ID.
|
||||
font_blob_id: u64,
|
||||
/// The font's index in the font collection.
|
||||
font_index: u32,
|
||||
synthesis: &'a fontique::Synthesis,
|
||||
direction: harfrust::Direction,
|
||||
script: harfrust::Script,
|
||||
language: Option<harfrust::Language>,
|
||||
features: &'a [harfrust::Feature],
|
||||
variations: Option<&'a [FontVariation]>,
|
||||
}
|
||||
|
||||
impl<'a> ShapePlanKey<'a> {
|
||||
pub(crate) const fn new(
|
||||
font_blob_id: u64,
|
||||
font_index: u32,
|
||||
synthesis: &'a fontique::Synthesis,
|
||||
direction: harfrust::Direction,
|
||||
script: harfrust::Script,
|
||||
language: Option<harfrust::Language>,
|
||||
features: &'a [harfrust::Feature],
|
||||
variations: Option<&'a [FontVariation]>,
|
||||
) -> Self {
|
||||
Self {
|
||||
font_blob_id,
|
||||
font_index,
|
||||
synthesis,
|
||||
direction,
|
||||
script,
|
||||
language,
|
||||
features,
|
||||
variations,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Equivalent<ShapePlanId> for ShapePlanKey<'a> {
|
||||
#[inline(always)]
|
||||
fn equivalent(&self, key: &ShapePlanId) -> bool {
|
||||
self.font_blob_id == key.font_blob_id
|
||||
&& self.font_index == key.font_index
|
||||
&& *self.synthesis == key.synthesis
|
||||
&& self.direction == key.direction
|
||||
&& self.script == key.script
|
||||
&& self.language == key.language
|
||||
&& self.features.len() == key.features.len()
|
||||
&& self.variations == key.variations.as_deref()
|
||||
&& self
|
||||
.features
|
||||
.iter()
|
||||
.zip(key.features.iter())
|
||||
.all(|(a, b)| a == b)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<ShapePlanKey<'a>> for ShapePlanId {
|
||||
#[inline(always)]
|
||||
fn from(key: ShapePlanKey<'a>) -> Self {
|
||||
Self {
|
||||
font_blob_id: key.font_blob_id,
|
||||
font_index: key.font_index,
|
||||
synthesis: *key.synthesis,
|
||||
direction: key.direction,
|
||||
script: key.script,
|
||||
language: key.language,
|
||||
features: key.features.to_vec().into(),
|
||||
variations: key.variations.map(|v| v.to_vec().into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
+638
@@ -0,0 +1,638 @@
|
||||
// Copyright 2025 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
#![expect(missing_docs, reason = "Deferred")]
|
||||
#![expect(missing_debug_implementations, reason = "Deferred")]
|
||||
|
||||
use core::cmp::Ordering;
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use icu_normalizer::properties::Decomposed;
|
||||
use parley_emoji::{EmojiDFA, EmojiPresentationStyle, EmojiSegmentationCategory};
|
||||
|
||||
use crate::{CharInfo, analysis::AnalysisDataSources};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CharCluster {
|
||||
chars: Vec<Char>,
|
||||
map_len: u8,
|
||||
start: u32,
|
||||
end: u32,
|
||||
force_normalize: bool,
|
||||
comp: Form,
|
||||
decomp: Form,
|
||||
emoji_presentation_style: EmojiPresentationStyle,
|
||||
}
|
||||
|
||||
impl CharCluster {
|
||||
#[inline]
|
||||
pub fn range(&self) -> SourceRange {
|
||||
SourceRange {
|
||||
start: self.start,
|
||||
end: self.end,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn chars(&self) -> &[Char] {
|
||||
&self.chars
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_emoji(&self) -> bool {
|
||||
self.emoji_presentation_style.is_emoji()
|
||||
}
|
||||
}
|
||||
|
||||
/// Source range of a cluster in code units.
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct SourceRange {
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default)]
|
||||
pub struct Char {
|
||||
/// The character.
|
||||
pub ch: char,
|
||||
/// Whether the character
|
||||
pub is_control_character: bool,
|
||||
/// True if the character should be considered when mapping glyphs.
|
||||
pub contributes_to_shaping: bool,
|
||||
/// Indexes into the list of styles for the containing text run, to find the style applicable
|
||||
/// to this character.
|
||||
pub style_index: u16,
|
||||
}
|
||||
|
||||
/// Whitespace class of a character.
|
||||
///
|
||||
/// All white space characters as defined
|
||||
/// [by Unicode](https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt) map to a variant of
|
||||
/// this enum. The variants are based on the various sets of white space as in
|
||||
/// [CSS Text 4][css-text-4].
|
||||
///
|
||||
/// A character maps to [`Whitespace::None`] if and only if that character's [`char::is_whitespace`]
|
||||
/// is `false`.
|
||||
///
|
||||
/// [css-text-4]: https://www.w3.org/TR/css-text-4/
|
||||
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug)]
|
||||
#[repr(u8)]
|
||||
pub enum Whitespace {
|
||||
/// Not white space.
|
||||
None = 0,
|
||||
|
||||
/// Standard space.
|
||||
Space = 1,
|
||||
|
||||
/// Non-breaking space (U+00A0).
|
||||
NoBreakSpace = 2,
|
||||
|
||||
/// Ideographic space (U+3000).
|
||||
///
|
||||
/// Note CSS Text 4 doesn't treat this space any differently from [`Self::OtherSpaceSeparator`],
|
||||
/// but some applications do.
|
||||
IdeographicSpace = 3,
|
||||
|
||||
/// The Unicode "space separators" (category `Zs`), except for the standard space, non-breaking
|
||||
/// space and ideographic space.
|
||||
///
|
||||
/// Applications may want to treat those three space separators differently from the general
|
||||
/// class of space separators.
|
||||
OtherSpaceSeparator = 4,
|
||||
|
||||
/// Horizontal tab.
|
||||
Tab = 5,
|
||||
|
||||
/// Newline (CR, LF, CRLF, LS, or PS).
|
||||
Newline = 6,
|
||||
|
||||
/// Vertical tab, form feed and next line.
|
||||
///
|
||||
/// These are Unicode `White_Space`, but CSS Text 4 § 4 says to treat them as visible glyphs.
|
||||
///
|
||||
/// Note [`Self::Tab`] and some of [`Self::Newline`] are also in the Unicode `Cc` category.
|
||||
/// There are also `Cc` characters that aren't `White_Space` (those would be
|
||||
/// [`Whitespace::None`]).
|
||||
ControlWhitespace = 7,
|
||||
// NOTE: if you grow these variants more than eight, ensure you also update the encoding in
|
||||
// `GraphemeFlags`.
|
||||
}
|
||||
|
||||
impl Whitespace {
|
||||
#[inline]
|
||||
pub(crate) const fn from_char(c: char) -> Self {
|
||||
// See https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt.
|
||||
match c {
|
||||
' ' => Self::Space,
|
||||
'\u{00A0}' => Self::NoBreakSpace,
|
||||
'\u{3000}' => Self::IdeographicSpace,
|
||||
// Ogham space mark, en quad through hair space, narrow no-break space, medium
|
||||
// mathematical space.
|
||||
'\u{1680}' | '\u{2000}'..='\u{200A}' | '\u{202F}' | '\u{205F}' => {
|
||||
Self::OtherSpaceSeparator
|
||||
}
|
||||
'\t' => Self::Tab,
|
||||
// Newline, carriage return, line separator, paragraph separator.
|
||||
'\n' | '\r' | '\u{2028}' | '\u{2029}' => Self::Newline,
|
||||
// Vertical tab, form feed, next line. These are `White_Space` that CSS says to render
|
||||
// as control characters.
|
||||
'\u{000b}' | '\u{000c}' | '\u{0085}' => Self::ControlWhitespace,
|
||||
_ => Self::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true for space or no break space.
|
||||
#[inline]
|
||||
pub fn is_space_or_nbsp(self) -> bool {
|
||||
matches!(self, Self::Space | Self::NoBreakSpace)
|
||||
}
|
||||
}
|
||||
|
||||
/// A font's coverage of a character cluster.
|
||||
///
|
||||
/// This is the fraction `covered / total` of characters covered by a font. Coverages are ordered by
|
||||
/// the value of the fraction (with `0 / 0` considered to be completely covered). Use, e.g.,
|
||||
/// [`Self::cmp`] to compare coverages.
|
||||
///
|
||||
/// In the unlikely event there are more characters than this in the character cluster, the counts
|
||||
/// are saturated to [`u8::MAX`].
|
||||
#[derive(Copy, Clone, Eq, Debug)]
|
||||
pub struct Coverage {
|
||||
/// The number of characters covered by the font.
|
||||
pub covered: u8,
|
||||
|
||||
/// The number of characters counting towards coverage.
|
||||
pub total: u8,
|
||||
}
|
||||
|
||||
impl Coverage {
|
||||
/// Zero coverage.
|
||||
///
|
||||
/// Useful, for example, as a starting "best coverage," in case you're searching for a
|
||||
/// best-covering font.
|
||||
pub const NONE: Self = Self {
|
||||
covered: 0,
|
||||
total: u8::MAX,
|
||||
};
|
||||
|
||||
/// Complete coverage, meaning all characters contributing to shaping are covered.
|
||||
///
|
||||
/// A coverage compares equal to `COMPLETE` exactly when it is complete, see also
|
||||
/// [`Self::is_complete`].
|
||||
pub const COMPLETE: Self = Self {
|
||||
covered: u8::MAX,
|
||||
total: u8::MAX,
|
||||
};
|
||||
|
||||
/// Returns `true` iff all characters are covered.
|
||||
#[inline(always)]
|
||||
#[must_use]
|
||||
pub fn is_complete(self) -> bool {
|
||||
self.covered >= self.total
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Coverage {
|
||||
#[inline]
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.cmp(other) == Ordering::Equal
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Coverage {
|
||||
#[inline]
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Coverage {
|
||||
/// Coverages are ordered by the value of the fraction `covered / total`.
|
||||
#[inline]
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
// We check `is_complete` explicitly, such that fractions of `x / 0`, which are considered
|
||||
// complete, are ordered identically to other complete fractions. Cases other than those
|
||||
// with a denominator of 0 would have already been correctly ordered by value through the
|
||||
// cross-multiplication in the `(false, false)` arm, but note we now order all complete
|
||||
// fractions as `Ordering::Equal`.
|
||||
match (self.is_complete(), other.is_complete()) {
|
||||
(true, true) => Ordering::Equal,
|
||||
(true, false) => Ordering::Greater,
|
||||
(false, true) => Ordering::Less,
|
||||
(false, false) => (u16::from(self.covered) * u16::from(other.total))
|
||||
.cmp(&(u16::from(other.covered) * u16::from(self.total))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CharCluster {
|
||||
#[inline]
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.chars.clear();
|
||||
self.map_len = 0;
|
||||
self.start = 0;
|
||||
self.end = 0;
|
||||
self.force_normalize = false;
|
||||
self.comp.clear();
|
||||
self.decomp.clear();
|
||||
self.emoji_presentation_style = EmojiPresentationStyle::Default;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn len(&self) -> usize {
|
||||
self.chars.len()
|
||||
}
|
||||
|
||||
/// Returns the primary style index for the cluster.
|
||||
#[inline(always)]
|
||||
pub fn style_index(&self) -> u16 {
|
||||
self.chars[0].style_index
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn contributes_to_shaping(ch: char, analysis_data_sources: &AnalysisDataSources) -> bool {
|
||||
let props = analysis_data_sources.properties(ch);
|
||||
crate::analysis::contributes_to_shaping(props.general_category(), props.script())
|
||||
}
|
||||
|
||||
fn decomposed(&mut self, analysis_data_sources: &AnalysisDataSources) -> Option<&[Char]> {
|
||||
match self.decomp.state {
|
||||
FormState::Invalid => None,
|
||||
FormState::None => {
|
||||
self.decomp.state = FormState::Invalid;
|
||||
|
||||
// Only attempt pairwise normalization (1 <-> 2 characters)
|
||||
if self.chars.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let decomposer = analysis_data_sources.decomposing_normalizer();
|
||||
let decomp = decomposer.decompose(self.chars[0].ch);
|
||||
match decomp {
|
||||
Decomposed::Default | Decomposed::Singleton(_) => {
|
||||
return None;
|
||||
}
|
||||
Decomposed::Expansion(a, b) => {
|
||||
let mut copy = self.chars[0];
|
||||
copy.ch = a;
|
||||
copy.contributes_to_shaping =
|
||||
Self::contributes_to_shaping(a, analysis_data_sources);
|
||||
self.decomp.chars[0] = copy;
|
||||
|
||||
copy.ch = b;
|
||||
copy.contributes_to_shaping =
|
||||
Self::contributes_to_shaping(b, analysis_data_sources);
|
||||
self.decomp.chars[1] = copy;
|
||||
|
||||
self.decomp.len = 2;
|
||||
}
|
||||
}
|
||||
|
||||
self.decomp.state = FormState::Valid;
|
||||
self.decomp.setup();
|
||||
Some(self.decomp.chars())
|
||||
}
|
||||
FormState::Valid => Some(self.decomp.chars()),
|
||||
}
|
||||
}
|
||||
|
||||
fn composed(&mut self, analysis_data_sources: &AnalysisDataSources) -> Option<&[Char]> {
|
||||
match self.comp.state {
|
||||
FormState::Invalid => None,
|
||||
FormState::None => {
|
||||
self.comp.state = FormState::Invalid;
|
||||
|
||||
// Only attempt pairwise normalization (1 <-> 2 characters)
|
||||
if self.chars.len() != 2 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let composer = analysis_data_sources.composing_normalizer();
|
||||
let ch = composer.compose(self.chars[0].ch, self.chars[1].ch)?;
|
||||
|
||||
let mut copy = self.chars[0];
|
||||
copy.ch = ch;
|
||||
copy.contributes_to_shaping =
|
||||
Self::contributes_to_shaping(ch, analysis_data_sources);
|
||||
self.comp.chars[0] = copy;
|
||||
self.comp.len = 1;
|
||||
|
||||
self.comp.state = FormState::Valid;
|
||||
self.comp.setup();
|
||||
Some(self.comp.chars())
|
||||
}
|
||||
FormState::Valid => Some(self.comp.chars()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculate a candidate font's coverage of this character cluster.
|
||||
///
|
||||
/// The callback `covers` should return whether the character is covered by the font under
|
||||
/// consideration. The coverage returned is the best coverage of the character cluster's
|
||||
/// characters, or the characters of its normalized forms (see
|
||||
/// <https://www.unicode.org/reports/tr15/>).
|
||||
///
|
||||
/// Coverages are ordered by how much of the cluster they cover, see [`Coverage`]. Note
|
||||
/// [`Coverage::total`] may be different from the count of [`Self::chars`], and may also differ
|
||||
/// between subsequent calls due to returning the best coverage of either the original
|
||||
/// characters or one of the normalized forms.
|
||||
pub fn calculate_coverage(
|
||||
&mut self,
|
||||
covers: impl Fn(char) -> bool,
|
||||
analysis_data_sources: &AnalysisDataSources,
|
||||
) -> Coverage {
|
||||
let len = self.len();
|
||||
let mut best_coverage = Mapper {
|
||||
chars: &self.chars[..len],
|
||||
map_len: self.map_len,
|
||||
}
|
||||
.coverage(&covers);
|
||||
if best_coverage.is_complete() {
|
||||
return best_coverage;
|
||||
}
|
||||
if self.force_normalize && self.composed(analysis_data_sources).is_some() {
|
||||
let coverage = self.comp.coverage(&covers);
|
||||
if coverage > best_coverage {
|
||||
best_coverage = coverage;
|
||||
if coverage.is_complete() {
|
||||
return best_coverage;
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.decomposed(analysis_data_sources).is_some() {
|
||||
let coverage = self.decomp.coverage(&covers);
|
||||
if coverage > best_coverage {
|
||||
best_coverage = coverage;
|
||||
if coverage.is_complete() {
|
||||
return best_coverage;
|
||||
}
|
||||
}
|
||||
if !self.force_normalize && self.composed(analysis_data_sources).is_some() {
|
||||
let coverage = self.comp.coverage(&covers);
|
||||
if coverage > best_coverage {
|
||||
best_coverage = coverage;
|
||||
if coverage.is_complete() {
|
||||
return best_coverage;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
best_coverage
|
||||
}
|
||||
|
||||
/// Rebuilds `self` in-place using the existing allocation for the given grapheme.
|
||||
///
|
||||
/// `chars` must yield the grapheme's characters with associated analysis info, and style index.
|
||||
///
|
||||
/// `code_unit_offset_in_string` must be the byte offset of the grapheme's first character in the
|
||||
/// source string. When this method returns, its value is the byte offset just past the end of
|
||||
/// the grapheme in the source string.
|
||||
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
|
||||
#[inline]
|
||||
pub(crate) fn fill(
|
||||
&mut self,
|
||||
chars: impl Iterator<Item = (char, CharInfo, u16)>,
|
||||
code_unit_offset_in_string: &mut usize,
|
||||
) {
|
||||
// Reset cluster but keep allocation
|
||||
self.clear();
|
||||
|
||||
let mut force_normalize = false;
|
||||
let mut is_emoji = false;
|
||||
let mut map_len: u8 = 0;
|
||||
let mut emoji_dfa = EmojiDFA::new();
|
||||
let mut leading_is_emoji_presentation = false;
|
||||
let start = *code_unit_offset_in_string as u32;
|
||||
|
||||
for (i, (ch, info, style_index)) in chars.enumerate() {
|
||||
*code_unit_offset_in_string += ch.len_utf8();
|
||||
force_normalize |= info.force_normalize();
|
||||
|
||||
is_emoji |= info.is_emoji_or_pictograph();
|
||||
|
||||
let mut is_emoji_presentation_selector = false;
|
||||
|
||||
if is_emoji {
|
||||
if i == 0 {
|
||||
leading_is_emoji_presentation = info.is_emoji_presentation();
|
||||
}
|
||||
|
||||
let category = EmojiSegmentationCategory::from_codepoint(
|
||||
ch as u32,
|
||||
info.is_emoji(),
|
||||
info.is_emoji_presentation(),
|
||||
info.is_emoji_modifier(),
|
||||
info.is_emoji_modifier_base(),
|
||||
info.is_region_indicator(),
|
||||
);
|
||||
|
||||
is_emoji_presentation_selector = category.is_presentation_selector();
|
||||
|
||||
emoji_dfa.step_record(category);
|
||||
}
|
||||
|
||||
// Variation selectors don't impact font coverage, and are default ignorable.
|
||||
// TODO: Is there a default ignorable flag we should be using instead?
|
||||
let contributes_to_shaping =
|
||||
info.contributes_to_shaping() && !is_emoji_presentation_selector;
|
||||
if contributes_to_shaping {
|
||||
map_len = map_len.saturating_add(1);
|
||||
}
|
||||
|
||||
self.chars.push(Char {
|
||||
ch,
|
||||
contributes_to_shaping,
|
||||
style_index,
|
||||
is_control_character: info.is_control(),
|
||||
});
|
||||
}
|
||||
|
||||
// Finalize cluster metadata
|
||||
let end = *code_unit_offset_in_string as u32;
|
||||
self.map_len = map_len;
|
||||
self.start = start;
|
||||
self.end = end;
|
||||
self.force_normalize = force_normalize;
|
||||
|
||||
if is_emoji {
|
||||
self.emoji_presentation_style =
|
||||
emoji_dfa.presentation_style(leading_is_emoji_presentation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
enum FormState {
|
||||
None,
|
||||
Valid,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Form {
|
||||
chars: [Char; 2],
|
||||
len: u8,
|
||||
map_len: u8,
|
||||
state: FormState,
|
||||
}
|
||||
|
||||
impl Default for Form {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Form {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
chars: [Char::default(), Char::default()],
|
||||
len: 0,
|
||||
map_len: 0,
|
||||
state: FormState::None,
|
||||
}
|
||||
}
|
||||
|
||||
fn clear(&mut self) {
|
||||
self.chars = [Char::default(), Char::default()];
|
||||
self.len = 0;
|
||||
self.map_len = 0;
|
||||
self.state = FormState::None;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn chars(&self) -> &[Char] {
|
||||
&self.chars[..self.len as usize]
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
|
||||
fn setup(&mut self) {
|
||||
self.map_len = self
|
||||
.chars()
|
||||
.iter()
|
||||
.filter(|c| !c.is_control_character)
|
||||
.count() as u8;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn coverage(&self, covers: &impl Fn(char) -> bool) -> Coverage {
|
||||
Mapper {
|
||||
chars: &self.chars[..self.len as usize],
|
||||
map_len: self.map_len,
|
||||
}
|
||||
.coverage(covers)
|
||||
}
|
||||
}
|
||||
|
||||
struct Mapper<'a> {
|
||||
chars: &'a [Char],
|
||||
map_len: u8,
|
||||
}
|
||||
|
||||
impl<'a> Mapper<'a> {
|
||||
/// Returns the coverage of characters contributing to shaping.
|
||||
fn coverage(&self, covers: &impl Fn(char) -> bool) -> Coverage {
|
||||
let mut mapped: u8 = 0;
|
||||
for c in self.chars.iter() {
|
||||
if c.contributes_to_shaping && covers(c.ch) {
|
||||
mapped = mapped.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
// If this assert is hit, some bookkeeping is wrong somewhere, but the returned coverage is
|
||||
// then simply considered to be complete.
|
||||
debug_assert!(
|
||||
mapped <= self.map_len,
|
||||
"Counted more covered characters than the number of characters we consider to be contributing."
|
||||
);
|
||||
|
||||
Coverage {
|
||||
covered: mapped,
|
||||
total: self.map_len,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::shape::Whitespace;
|
||||
|
||||
use super::Coverage;
|
||||
|
||||
#[test]
|
||||
fn ordering() {
|
||||
assert!(Coverage::NONE < Coverage::COMPLETE);
|
||||
|
||||
assert_eq!(
|
||||
Coverage {
|
||||
covered: 0,
|
||||
total: 0,
|
||||
},
|
||||
Coverage::COMPLETE
|
||||
);
|
||||
assert_eq!(
|
||||
Coverage {
|
||||
covered: 5,
|
||||
total: 5,
|
||||
},
|
||||
Coverage::COMPLETE
|
||||
);
|
||||
assert_eq!(
|
||||
Coverage {
|
||||
// `covered` is greater than `total`, which shouldn't be produced by us, but is
|
||||
// possible because `Coverage`'s fields are `pub`.
|
||||
covered: 3,
|
||||
total: 2,
|
||||
},
|
||||
Coverage::COMPLETE
|
||||
);
|
||||
assert_eq!(
|
||||
Coverage {
|
||||
covered: 255,
|
||||
total: 255,
|
||||
},
|
||||
Coverage::COMPLETE
|
||||
);
|
||||
|
||||
assert!(
|
||||
Coverage {
|
||||
covered: 4,
|
||||
total: 5,
|
||||
} > Coverage::NONE
|
||||
);
|
||||
assert!(
|
||||
Coverage {
|
||||
covered: 4,
|
||||
total: 5,
|
||||
} < Coverage::COMPLETE
|
||||
);
|
||||
|
||||
assert!(
|
||||
Coverage {
|
||||
covered: 254,
|
||||
total: 255,
|
||||
} > Coverage::NONE
|
||||
);
|
||||
assert!(
|
||||
Coverage {
|
||||
covered: 254,
|
||||
total: 255,
|
||||
} < Coverage::COMPLETE
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitespace() {
|
||||
// Test all code points from `NUL` up to the last `White_Space` character as defined in
|
||||
// https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt.
|
||||
for c in '\u{0000}'..='\u{3000}' {
|
||||
let ws = Whitespace::from_char(c);
|
||||
assert!(
|
||||
c.is_whitespace() && ws != Whitespace::None
|
||||
|| !c.is_whitespace() && ws == Whitespace::None,
|
||||
"`Whitespace` should encode exactly all of Unicode's `White_Space` characters."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+393
@@ -0,0 +1,393 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
#![expect(missing_docs, reason = "Deferred")]
|
||||
|
||||
use core::ops::Range;
|
||||
|
||||
use crate::shape::Whitespace;
|
||||
|
||||
/// Data for a single character of the source text.
|
||||
///
|
||||
/// This is a character in the Unicode scalar value sense, i.e., it corresponds to a single `char`
|
||||
/// of the source text.
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub struct Character {
|
||||
pub text_byte_start: u32,
|
||||
/// Style index for this character.
|
||||
pub style_index: u16,
|
||||
/// The whitespace class of this character.
|
||||
pub whitespace: Whitespace,
|
||||
/// Properties of this character.
|
||||
pub flags: CharacterFlags,
|
||||
/// Whether this character begins a grapheme cluster.
|
||||
pub grapheme_start: bool,
|
||||
}
|
||||
|
||||
impl Character {
|
||||
/// The byte range of this character in the source text.
|
||||
#[inline(always)]
|
||||
pub fn text_byte_range(&self) -> Range<usize> {
|
||||
self.text_byte_start as usize..self.text_byte_start as usize + self.flags.len_utf8()
|
||||
}
|
||||
|
||||
/// Returns if this character is any whitespace.
|
||||
#[inline(always)]
|
||||
pub fn is_whitespace(self) -> bool {
|
||||
self.whitespace != Whitespace::None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct ShapedClusterFlags(u16);
|
||||
|
||||
impl ShapedClusterFlags {
|
||||
const GLYPH_LEN_MASK: u16 = 0x00FF;
|
||||
const INLINE_GLYPH: u16 = 1 << 8;
|
||||
const GRAPHEME_START: u16 = 1 << 9;
|
||||
const SAFE_TO_BREAK_BEFORE: u16 = 1 << 10;
|
||||
/// Whether a soft wrap opportunity exists before the cluster's first character.
|
||||
const SOFT_WRAP_BEFORE: u16 = 1 << 11;
|
||||
/// [`Whitespace`] class of the cluster's first character (3 bits).
|
||||
const WHITESPACE_SHIFT: u16 = 12;
|
||||
const WHITESPACE_MASK: u16 = 0b111 << Self::WHITESPACE_SHIFT;
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) const fn new(glyph_len: u8) -> Self {
|
||||
Self(glyph_len as u16)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) const fn with_inline_glyph(mut self, set: bool) -> Self {
|
||||
self.0 = self.0 & !Self::INLINE_GLYPH | if set { Self::INLINE_GLYPH } else { 0 };
|
||||
self
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) const fn with_grapheme_start(mut self, set: bool) -> Self {
|
||||
self.0 = self.0 & !Self::GRAPHEME_START | if set { Self::GRAPHEME_START } else { 0 };
|
||||
self
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) const fn with_safe_to_break_before(mut self, set: bool) -> Self {
|
||||
self.0 =
|
||||
self.0 & !Self::SAFE_TO_BREAK_BEFORE | if set { Self::SAFE_TO_BREAK_BEFORE } else { 0 };
|
||||
self
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) const fn with_first_char(
|
||||
mut self,
|
||||
soft_wrap_opportunity: bool,
|
||||
whitespace: Whitespace,
|
||||
) -> Self {
|
||||
self.0 = self.0 & !(Self::SOFT_WRAP_BEFORE | Self::WHITESPACE_MASK)
|
||||
| if soft_wrap_opportunity {
|
||||
Self::SOFT_WRAP_BEFORE
|
||||
} else {
|
||||
0
|
||||
}
|
||||
| ((whitespace as u16) << Self::WHITESPACE_SHIFT);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn is_soft_wrap_opportunity_before(self) -> bool {
|
||||
self.0 & Self::SOFT_WRAP_BEFORE != 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn whitespace(self) -> Whitespace {
|
||||
match (self.0 & Self::WHITESPACE_MASK) >> Self::WHITESPACE_SHIFT {
|
||||
1 => Whitespace::Space,
|
||||
2 => Whitespace::NoBreakSpace,
|
||||
3 => Whitespace::IdeographicSpace,
|
||||
4 => Whitespace::OtherSpaceSeparator,
|
||||
5 => Whitespace::Tab,
|
||||
6 => Whitespace::Newline,
|
||||
7 => Whitespace::ControlWhitespace,
|
||||
_ => Whitespace::None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn glyph_len(self) -> u8 {
|
||||
(self.0 & Self::GLYPH_LEN_MASK) as u8
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn has_inline_glyph(self) -> bool {
|
||||
self.0 & Self::INLINE_GLYPH != 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn is_grapheme_start(self) -> bool {
|
||||
self.0 & Self::GRAPHEME_START != 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn is_safe_to_break_before(self) -> bool {
|
||||
self.0 & Self::SAFE_TO_BREAK_BEFORE != 0
|
||||
}
|
||||
}
|
||||
|
||||
/// A span of characters and the glyphs they shaped into.
|
||||
///
|
||||
/// Shaping may reorder, compose, decompose, etc.; there is no finer-grained correspondence between
|
||||
/// characters and glyphs. For example, a base letter with a combining mark may shape into a single
|
||||
/// glyph, a single character may shape into multiple glyphs, and a ligature may combine multiple
|
||||
/// characters into shared glyphs.
|
||||
///
|
||||
/// Shaped cluster boundaries are not necessarily [`Grapheme`][crate::Grapheme] boundaries. The
|
||||
/// shared boundaries are encoded by [`Atom`][crate::Atom]s.
|
||||
///
|
||||
/// For more information about clusters, see [HarfBuzz's documentation][harfbuzz].
|
||||
///
|
||||
/// [harfbuzz]: https://harfbuzz.github.io/working-with-harfbuzz-clusters.html
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub struct ShapedCluster {
|
||||
/// The characters of this cluster, as a range into
|
||||
/// [`ShapedText::characters`](crate::ShapedText::characters).
|
||||
//
|
||||
// TODO: this currently stores the full range, but perhaps we could store only the start index.
|
||||
// See <https://github.com/linebender/parley/pull/715#discussion_r3693794119>.
|
||||
pub(crate) chars_range: (u32, u32),
|
||||
|
||||
/// Style index for this cluster.
|
||||
pub style_index: u16,
|
||||
|
||||
/// The index into the glyph array where this cluster's glyphs start.
|
||||
///
|
||||
/// If [`Self::has_inline_glyph`] is `true`, this is a glyph identifier instead. For more, see
|
||||
/// the documentation on that method.
|
||||
pub glyph_offset: u32,
|
||||
|
||||
// /// Number of glyphs in this cluster (0xFF = single glyph stored inline)
|
||||
// pub glyph_len: u8,
|
||||
pub(crate) flags: ShapedClusterFlags,
|
||||
|
||||
/// Advance width for this cluster
|
||||
pub advance: f32,
|
||||
}
|
||||
|
||||
impl ShapedCluster {
|
||||
/// The characters of this cluster, as a range into [`ShapedText::characters`](crate::ShapedText::characters).
|
||||
///
|
||||
/// This is also the range of character positions in the source text (in the Unicode scalar
|
||||
/// value sense).
|
||||
#[inline(always)]
|
||||
pub fn chars_range(&self) -> Range<u32> {
|
||||
self.chars_range.0..self.chars_range.1
|
||||
}
|
||||
|
||||
/// The number of glyphs of this cluster.
|
||||
#[inline(always)]
|
||||
pub fn glyph_len(self) -> u8 {
|
||||
if self.has_inline_glyph() {
|
||||
1
|
||||
} else {
|
||||
self.flags.glyph_len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this cluster's glyph is stored inline in [`Self::glyph_offset`].
|
||||
///
|
||||
/// This is only possible if [`Self::glyph_len`] is one, and the glyph has no offset.
|
||||
/// [`Self::glyph_offset`] then encodes the glyph identifier rather than an index into the glyph
|
||||
/// array. The glyph's advance then is this cluster's advance.
|
||||
#[inline(always)]
|
||||
pub fn has_inline_glyph(self) -> bool {
|
||||
self.flags.has_inline_glyph()
|
||||
}
|
||||
|
||||
/// Whether this shaped cluster's logical start also starts a grapheme.
|
||||
#[inline(always)]
|
||||
pub fn is_grapheme_start(self) -> bool {
|
||||
self.flags.is_grapheme_start()
|
||||
}
|
||||
|
||||
/// Whether breaking logically before this shaped cluster requires reshaping.
|
||||
///
|
||||
/// Note that if this shaped cluster does not start a grapheme (see
|
||||
/// [`Self::is_grapheme_start`]), you have to reshape regardless of this value.
|
||||
#[inline(always)]
|
||||
pub fn is_safe_to_break_before(self) -> bool {
|
||||
self.flags.is_safe_to_break_before()
|
||||
}
|
||||
|
||||
/// Whether a soft wrap opportunity exists before this cluster's first character.
|
||||
///
|
||||
/// This is [`Character::flags`]' soft-wrap bit of the first character of [`Self::chars_range`],
|
||||
/// cached here so that measuring text does not need to touch the character array.
|
||||
#[inline(always)]
|
||||
pub fn is_soft_wrap_opportunity_before(self) -> bool {
|
||||
self.flags.is_soft_wrap_opportunity_before()
|
||||
}
|
||||
|
||||
/// The [`Whitespace`] class of this cluster's first character.
|
||||
///
|
||||
/// See [`Self::is_soft_wrap_opportunity_before`].
|
||||
#[inline(always)]
|
||||
pub fn whitespace(self) -> Whitespace {
|
||||
self.flags.whitespace()
|
||||
}
|
||||
|
||||
/// The number of characters in this cluster.
|
||||
#[inline(always)]
|
||||
pub fn char_len(self) -> u32 {
|
||||
self.chars_range.1 - self.chars_range.0
|
||||
}
|
||||
|
||||
/// The number of graphemes this cluster overlaps.
|
||||
pub(crate) fn graphemes_overlapped(&self, characters: &[Character]) -> u32 {
|
||||
let start = self.chars_range().start as usize + 1;
|
||||
let end = self.chars_range().end as usize;
|
||||
let mut graphemes = 1;
|
||||
for character in &characters[start..end] {
|
||||
graphemes += u32::from(character.grapheme_start);
|
||||
}
|
||||
graphemes
|
||||
}
|
||||
}
|
||||
|
||||
/// Properties of a [`Character`].
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CharacterFlags(u8);
|
||||
|
||||
impl CharacterFlags {
|
||||
/// Bits 0..2: the UTF-8 length of the source character minus one.
|
||||
///
|
||||
/// (Note the UTF-8 length of any character is between 1 and 4 inclusive.)
|
||||
const LEN_UTF8_MASK: u8 = 0b11;
|
||||
/// Whether the source character is an emoji.
|
||||
const EMOJI: u8 = 1 << 2;
|
||||
/// Whether there is a word boundary before the character.
|
||||
const WORD_BOUNDARY: u8 = 1 << 3;
|
||||
/// Whether there is a soft wrap opportunity before the character.
|
||||
const SOFT_WRAP_OPPORTUNITY: u8 = 1 << 4;
|
||||
|
||||
#[inline(always)]
|
||||
pub fn new(source_char: char, is_word_boundary: bool, is_soft_wrap_opportunity: bool) -> Self {
|
||||
// TODO: Defer to ICU4X properties (see: https://docs.rs/icu/latest/icu/properties/props/struct.Emoji.html).
|
||||
let is_emoji = matches!(source_char as u32, 0x1F600..=0x1F64F | 0x1F300..=0x1F5FF | 0x1F680..=0x1F6FF | 0x2600..=0x26FF | 0x2700..=0x27BF);
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
reason = "`len_utf8` is between 1 and 4 inclusive"
|
||||
)]
|
||||
let len_utf8 = source_char.len_utf8() as u8;
|
||||
Self(
|
||||
(len_utf8 - 1)
|
||||
| if is_emoji { Self::EMOJI } else { 0 }
|
||||
| if is_word_boundary {
|
||||
Self::WORD_BOUNDARY
|
||||
} else {
|
||||
0
|
||||
}
|
||||
| if is_soft_wrap_opportunity {
|
||||
Self::SOFT_WRAP_OPPORTUNITY
|
||||
} else {
|
||||
0
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether there is a soft wrap opportunity before this character ([UAX #14][line-breaking]).
|
||||
///
|
||||
/// Note mandatory breaks (like `\n`) are encoded as [`Whitespace`].
|
||||
///
|
||||
/// [line-breaking]: https://www.unicode.org/reports/tr14/
|
||||
#[inline(always)]
|
||||
pub fn is_soft_wrap_opportunity(self) -> bool {
|
||||
self.0 & Self::SOFT_WRAP_OPPORTUNITY != 0
|
||||
}
|
||||
|
||||
/// Returns if there is a word boundary before the character.
|
||||
#[inline(always)]
|
||||
pub fn is_word_boundary(self) -> bool {
|
||||
self.0 & Self::WORD_BOUNDARY != 0
|
||||
}
|
||||
|
||||
/// Returns if the character is an emoji.
|
||||
#[inline(always)]
|
||||
pub fn is_emoji(self) -> bool {
|
||||
self.0 & Self::EMOJI != 0
|
||||
}
|
||||
|
||||
/// Returns the number of bytes the source character would need if encoded in UTF-8.
|
||||
///
|
||||
/// That number of bytes is always between 1 and 4, inclusive.
|
||||
#[inline(always)]
|
||||
pub fn len_utf8(self) -> usize {
|
||||
(self.0 & Self::LEN_UTF8_MASK) as usize + 1
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn character_flags() {
|
||||
for (ch, len, emoji) in [
|
||||
('a', 1, false),
|
||||
(' ', 1, false),
|
||||
('\t', 1, false),
|
||||
('\r', 1, false),
|
||||
('\n', 1, false),
|
||||
('\u{00e9}', 2, false),
|
||||
('\u{2028}', 3, false),
|
||||
('\u{2600}', 3, true),
|
||||
('\u{1F600}', 4, true),
|
||||
] {
|
||||
for (is_word_boundary, is_soft_wrap_opportunity) in
|
||||
[(false, false), (true, false), (false, true), (true, true)]
|
||||
{
|
||||
let flags = CharacterFlags::new(ch, is_word_boundary, is_soft_wrap_opportunity);
|
||||
assert_eq!(flags.len_utf8(), len, "{ch:?}");
|
||||
assert_eq!(flags.is_emoji(), emoji, "{ch:?}");
|
||||
assert_eq!(flags.is_word_boundary(), is_word_boundary, "{ch:?}");
|
||||
assert_eq!(
|
||||
flags.is_soft_wrap_opportunity(),
|
||||
is_soft_wrap_opportunity,
|
||||
"{ch:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let character = Character {
|
||||
text_byte_start: 3,
|
||||
style_index: 7,
|
||||
whitespace: Whitespace::from_char(ch),
|
||||
flags: CharacterFlags::new(ch, false, false),
|
||||
grapheme_start: true,
|
||||
};
|
||||
assert_eq!(character.text_byte_range(), 3..3 + len, "{ch:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_char_flags_round_trip() {
|
||||
let soft_wraps = [false, true];
|
||||
let whitespaces = [
|
||||
Whitespace::None,
|
||||
Whitespace::Space,
|
||||
Whitespace::NoBreakSpace,
|
||||
Whitespace::IdeographicSpace,
|
||||
Whitespace::OtherSpaceSeparator,
|
||||
Whitespace::Tab,
|
||||
Whitespace::Newline,
|
||||
Whitespace::ControlWhitespace,
|
||||
];
|
||||
for soft_wrap in soft_wraps {
|
||||
for whitespace in whitespaces {
|
||||
let flags = ShapedClusterFlags::new(3)
|
||||
.with_grapheme_start(true)
|
||||
.with_first_char(soft_wrap, whitespace);
|
||||
assert_eq!(flags.is_soft_wrap_opportunity_before(), soft_wrap);
|
||||
assert_eq!(flags.whitespace(), whitespace);
|
||||
assert_eq!(flags.glyph_len(), 3);
|
||||
assert!(flags.is_grapheme_start());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Text shaping utilities.
|
||||
|
||||
pub(crate) mod atom;
|
||||
mod cache;
|
||||
mod cluster;
|
||||
mod data;
|
||||
pub(crate) mod shaped_text;
|
||||
pub(crate) mod shaper;
|
||||
|
||||
pub use cluster::{Char, CharCluster, Coverage, SourceRange, Whitespace};
|
||||
pub use data::{Character, CharacterFlags, ShapedCluster};
|
||||
|
||||
pub(crate) use data::ShapedClusterFlags;
|
||||
+859
@@ -0,0 +1,859 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Data structures to store the result of shaping.
|
||||
|
||||
use core::ops::Range;
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use parlance::{BidiLevel, NormalizedCoord};
|
||||
use skrifa::MetadataProvider;
|
||||
|
||||
use crate::{
|
||||
CharInfo, FontInstance, Glyph,
|
||||
itemize::{Segment, TextRange},
|
||||
};
|
||||
|
||||
use super::{
|
||||
Character, CharacterFlags, ShapedCluster, ShapedClusterFlags, Whitespace, atom::ShapedSlice,
|
||||
shaper::ShapeOptions,
|
||||
};
|
||||
|
||||
/// Metrics that apply to the glyphs of a font.
|
||||
///
|
||||
/// These metrics are scaled by the font size.
|
||||
///
|
||||
/// The `underline_*` and `strikethrough_*` fields are derived if not set by the font.
|
||||
///
|
||||
// TODO: Perhaps it'd be nicer if we exposed unscaled metrics (design units) instead. This currently
|
||||
// just follows what `parley` used to do in its `RunMetrics`. If we go unscaled, we should then
|
||||
// either also store units per em, or em-normalize the values like CSS does.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FontMetrics {
|
||||
/// Distance from the baseline to the top of the alignment box.
|
||||
pub ascent: f32,
|
||||
/// Distance from the baseline to the bottom of the alignment box.
|
||||
pub descent: f32,
|
||||
/// Recommended additional spacing between lines.
|
||||
pub leading: f32,
|
||||
/// Offset of the top of underline decoration from the baseline.
|
||||
pub underline_offset: f32,
|
||||
/// Thickness of the underline decoration.
|
||||
pub underline_size: f32,
|
||||
/// Offset of the top of strikethrough decoration from the baseline.
|
||||
pub strikethrough_offset: f32,
|
||||
/// Thickness of the strikethrough decoration.
|
||||
pub strikethrough_size: f32,
|
||||
/// Distance from the baseline to the top of a typical English capital.
|
||||
pub cap_height: Option<f32>,
|
||||
/// Distance from the baseline to the top of the lowercase "x" or
|
||||
/// similar character.
|
||||
pub x_height: Option<f32>,
|
||||
}
|
||||
|
||||
impl FontMetrics {
|
||||
/// Metrics to use when no font is available at all.
|
||||
///
|
||||
/// These roughly match common Latin fonts, so that a layout without fonts still has plausible
|
||||
/// line heights.
|
||||
pub const fn fallback(font_size: f32) -> Self {
|
||||
Self {
|
||||
ascent: font_size * 0.8,
|
||||
descent: font_size * 0.2,
|
||||
leading: 0.,
|
||||
underline_offset: 0.,
|
||||
underline_size: 0.,
|
||||
strikethrough_offset: 0.,
|
||||
strikethrough_size: 0.,
|
||||
cap_height: None,
|
||||
x_height: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute the metrics of `font` at `font_size`, positioned at the variable font location
|
||||
/// given by the `synthesis` and `variations` axis settings.
|
||||
///
|
||||
/// Returns `None` if the font data cannot be parsed.
|
||||
pub fn from_font_instance(
|
||||
font: &FontInstance,
|
||||
font_size: f32,
|
||||
variations: &[parlance::FontVariation],
|
||||
) -> Option<Self> {
|
||||
// A style's metrics depend on its font instance, size and variations alone; a style
|
||||
// table asks for the same few again in every layout (Rune: vendor/parley_engine.patch).
|
||||
#[cfg(feature = "std")]
|
||||
{
|
||||
type Memo = Vec<(u64, u32, fontique::Synthesis, u32, Vec<parlance::FontVariation>, Option<FontMetrics>)>;
|
||||
std::thread_local! {
|
||||
static MEMO: core::cell::RefCell<Memo> = const { core::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
let (id, index, size) = (font.font.data.id(), font.font.index, font_size.to_bits());
|
||||
let found = MEMO.with_borrow(|memo| {
|
||||
memo.iter()
|
||||
.find(|m| m.0 == id && m.1 == index && m.2 == font.synthesis && m.3 == size && m.4 == variations)
|
||||
.map(|m| m.5)
|
||||
});
|
||||
if let Some(metrics) = found {
|
||||
return metrics;
|
||||
}
|
||||
let metrics = Self::compute_from_font_instance(font, font_size, variations);
|
||||
MEMO.with_borrow_mut(|memo| {
|
||||
if memo.len() >= 64 {
|
||||
memo.remove(0);
|
||||
}
|
||||
memo.push((id, index, font.synthesis, size, variations.to_vec(), metrics));
|
||||
});
|
||||
return metrics;
|
||||
}
|
||||
Self::compute_from_font_instance(font, font_size, variations)
|
||||
}
|
||||
|
||||
fn compute_from_font_instance(
|
||||
font: &FontInstance,
|
||||
font_size: f32,
|
||||
variations: &[parlance::FontVariation],
|
||||
) -> Option<Self> {
|
||||
let font_ref =
|
||||
skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).ok()?;
|
||||
let location = font_ref.axes().location(
|
||||
font.synthesis
|
||||
.variation_settings()
|
||||
.iter()
|
||||
.map(|(tag, value)| (skrifa::Tag::new(&tag.to_be_bytes()), *value))
|
||||
.chain(
|
||||
variations
|
||||
.iter()
|
||||
.map(|v| (skrifa::Tag::new(&v.tag.to_bytes()), v.value)),
|
||||
),
|
||||
);
|
||||
Some(Self::from_skrifa_metrics(
|
||||
&skrifa::metrics::Metrics::new(
|
||||
&font_ref,
|
||||
skrifa::prelude::Size::new(font_size),
|
||||
&location,
|
||||
),
|
||||
font_size,
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn from_skrifa_metrics(metrics: &skrifa::metrics::Metrics, font_size: f32) -> Self {
|
||||
// Default values from HarfBuzz: https://github.com/harfbuzz/harfbuzz/blob/12ee77ee00514c442bcd28f9aa9d56b708c37382/src/hb-ot-metrics.cc#L355-L372
|
||||
let fallback_decoration_size = font_size / 18.0;
|
||||
|
||||
let (underline_offset, underline_size) = if let Some(underline) = metrics.underline {
|
||||
(underline.offset, underline.thickness)
|
||||
} else {
|
||||
(-fallback_decoration_size, fallback_decoration_size)
|
||||
};
|
||||
let (strikethrough_offset, strikethrough_size) = if let Some(strikeout) = metrics.strikeout
|
||||
{
|
||||
(strikeout.offset, strikeout.thickness)
|
||||
} else {
|
||||
(metrics.ascent / 2.0, fallback_decoration_size)
|
||||
};
|
||||
|
||||
Self {
|
||||
ascent: metrics.ascent,
|
||||
descent: -metrics.descent,
|
||||
leading: metrics.leading,
|
||||
underline_offset,
|
||||
underline_size,
|
||||
strikethrough_offset,
|
||||
strikethrough_size,
|
||||
x_height: metrics.x_height,
|
||||
cap_height: metrics.cap_height,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of shaping.
|
||||
///
|
||||
/// After [analyzing][crate::Analysis] your text, [shape the text][crate::Shaper::shape_text],
|
||||
/// writing the result into this [`ShapedText`]. This then holds your shaped paragraph of text.
|
||||
///
|
||||
/// This shaped text holds spans of the source text's characters that were shaped into
|
||||
/// [`ShapedCluster`]s. Note that the boundaries of shaped clusters and graphemes need not coincide;
|
||||
/// see [`ShapedCluster`]s documentation for more information.
|
||||
///
|
||||
/// Use [`Self::run_slice`] to get a run's [`ShapedSlice`]. From there, you can interact with slices
|
||||
/// of shaped text, such as walking [atoms](crate::Atom) (e.g., [`ShapedSlice::atoms_start`]) and
|
||||
/// [graphemes](crate::Grapheme) (e.g., [`ShapedSlice::graphemes_start`]).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ShapedText {
|
||||
runs: Vec<ShapedRun>,
|
||||
characters: Vec<Character>,
|
||||
shaped_clusters: Vec<ShapedCluster>,
|
||||
glyphs: Vec<Glyph>,
|
||||
fonts: Vec<FontInstance>,
|
||||
normalized_coords: Vec<NormalizedCoord>,
|
||||
}
|
||||
|
||||
impl ShapedText {
|
||||
/// Create a reusable [`ShapedText`].
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Reserve capacity for at least `additional_chars` more characters.
|
||||
///
|
||||
/// This speculatively reserves capacity for `additional_chars` more clusters and glyphs.
|
||||
#[inline]
|
||||
pub(crate) fn reserve(&mut self, additional_chars: usize) {
|
||||
self.characters.reserve(additional_chars);
|
||||
self.shaped_clusters.reserve(additional_chars);
|
||||
self.glyphs.reserve(additional_chars);
|
||||
}
|
||||
|
||||
/// Clear the result while retaining capacity.
|
||||
#[inline]
|
||||
pub fn clear(&mut self) {
|
||||
self.runs.clear();
|
||||
self.characters.clear();
|
||||
self.shaped_clusters.clear();
|
||||
self.glyphs.clear();
|
||||
self.fonts.clear();
|
||||
self.normalized_coords.clear();
|
||||
}
|
||||
|
||||
/// Get a [`ShapedSlice`] of the run at `run_index`.
|
||||
pub fn run_slice(&self, run_index: u32) -> ShapedSlice<'_> {
|
||||
let run = &self.runs[run_index as usize];
|
||||
ShapedSlice {
|
||||
characters: &self.characters,
|
||||
|
||||
shaped_clusters: &self.shaped_clusters,
|
||||
glyphs: &self.glyphs,
|
||||
|
||||
clusters: (
|
||||
run.shaped_clusters_range.start,
|
||||
run.shaped_clusters_range.end,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The shaped runs.
|
||||
///
|
||||
/// Each run contains glyphs that can be rendered with a single font.
|
||||
#[inline(always)]
|
||||
pub fn runs(&self) -> &[ShapedRun] {
|
||||
&self.runs
|
||||
}
|
||||
|
||||
/// Escape hatch for `parley` tests that remap style indices to check whether layouts are
|
||||
/// otherwise identical. This is not for public consumption!
|
||||
#[doc(hidden)]
|
||||
#[inline(always)]
|
||||
pub fn remap_styles(&mut self, remap: &[u16]) {
|
||||
for character in self.characters.iter_mut() {
|
||||
character.style_index = remap[character.style_index as usize];
|
||||
}
|
||||
for shaped_cluster in self.shaped_clusters.iter_mut() {
|
||||
shaped_cluster.style_index = remap[shaped_cluster.style_index as usize];
|
||||
}
|
||||
}
|
||||
|
||||
/// The character data of the text, in logical order.
|
||||
///
|
||||
/// [`ShapedRun::characters_range`] indexes into this. The nth [`Character`] corresponds exactly
|
||||
/// to the nth character of the source text (in the Unicode scalar value sense). This contains
|
||||
/// every character of the source text unless shaping was aborted due to
|
||||
/// [`FontSelector::select_font`][crate::FontSelector::select_font] failing to return a font.
|
||||
#[inline(always)]
|
||||
pub fn characters(&self) -> &[Character] {
|
||||
&self.characters
|
||||
}
|
||||
|
||||
/// The shaped clusters.
|
||||
///
|
||||
/// [`ShapedRun::shaped_clusters_range`] indexes into this.
|
||||
#[inline(always)]
|
||||
pub fn shaped_clusters(&self) -> &[ShapedCluster] {
|
||||
&self.shaped_clusters
|
||||
}
|
||||
|
||||
/// The shaped glyphs.
|
||||
///
|
||||
/// [`ShapedRun::glyphs_range`] indexes into this.
|
||||
#[inline(always)]
|
||||
pub fn glyphs(&self) -> &[Glyph] {
|
||||
&self.glyphs
|
||||
}
|
||||
|
||||
/// The fonts.
|
||||
///
|
||||
/// [`ShapedRun::font_index`] indexes into this.
|
||||
#[inline(always)]
|
||||
pub fn fonts(&self) -> &[FontInstance] {
|
||||
&self.fonts
|
||||
}
|
||||
|
||||
/// The normalized font coordinates used by runs in this shaped text.
|
||||
///
|
||||
/// [`ShapedRun::normalized_coords_range`] splits this into per-run slices.
|
||||
#[inline(always)]
|
||||
pub fn normalized_coords(&self) -> &[NormalizedCoord] {
|
||||
&self.normalized_coords
|
||||
}
|
||||
|
||||
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
|
||||
pub(crate) fn push_run(
|
||||
&mut self,
|
||||
text: &str,
|
||||
range: TextRange,
|
||||
segment: &Segment,
|
||||
options: &ShapeOptions<'_>,
|
||||
char_info: &[CharInfo],
|
||||
char_style_indices: &[u16],
|
||||
font: &FontInstance,
|
||||
glyph_infos: &[harfrust::GlyphInfo],
|
||||
glyph_positions: &[harfrust::GlyphPosition],
|
||||
normalized_coords: &[harfrust::NormalizedCoord],
|
||||
(font_metrics, units_per_em): (FontMetrics, f32),
|
||||
) {
|
||||
debug_assert_eq!(
|
||||
range.char_range.len(),
|
||||
text[range.byte_range.clone()].chars().count(),
|
||||
"The claimed character range and the text's covered byte range should agree"
|
||||
);
|
||||
|
||||
let normalized_coords_range = {
|
||||
let start = self.normalized_coords.len();
|
||||
self.normalized_coords.extend(
|
||||
normalized_coords
|
||||
.iter()
|
||||
.map(|c| NormalizedCoord::from_bits(c.to_bits())),
|
||||
);
|
||||
start..self.normalized_coords.len()
|
||||
};
|
||||
|
||||
let font_index = self
|
||||
.fonts
|
||||
.iter()
|
||||
.position(|f| f == font)
|
||||
.unwrap_or_else(|| {
|
||||
let index = self.fonts.len();
|
||||
self.fonts.push(font.clone());
|
||||
index
|
||||
});
|
||||
|
||||
// `HarfRust` returns glyphs in visual order, so we need to process them as such while
|
||||
// maintaining logical ordering of clusters.
|
||||
|
||||
let scale_factor = options.font_size / units_per_em;
|
||||
let shaped_clusters_start = self.shaped_clusters.len();
|
||||
|
||||
// Push all characters.
|
||||
let characters_start = self.characters.len();
|
||||
for (((byte_offset, ch), info), style_index) in text[range.byte_range.clone()]
|
||||
.char_indices()
|
||||
.zip(&char_info[range.char_range.clone()])
|
||||
.zip(&char_style_indices[range.char_range.clone()])
|
||||
{
|
||||
self.characters.push(Character {
|
||||
text_byte_start: (range.byte_range.start + byte_offset) as u32,
|
||||
style_index: *style_index,
|
||||
whitespace: Whitespace::from_char(ch),
|
||||
flags: CharacterFlags::new(
|
||||
ch,
|
||||
info.is_word_boundary(),
|
||||
info.is_soft_wrap_opportunity(),
|
||||
),
|
||||
grapheme_start: info.is_grapheme_start(),
|
||||
});
|
||||
}
|
||||
// TODO: we force a grapheme break at the start of the run, as itemization could have split
|
||||
// a grapheme into two. Ideally, grapheme segmentation should be performed after
|
||||
// itemization, at which case this will always be true.
|
||||
self.characters[characters_start].grapheme_start = true;
|
||||
|
||||
let glyphs_start = self.glyphs.len();
|
||||
if segment.bidi_level.is_ltr() {
|
||||
process_shaped_clusters(
|
||||
&mut self.shaped_clusters,
|
||||
&mut self.glyphs,
|
||||
scale_factor,
|
||||
glyph_infos.iter(),
|
||||
glyph_positions.iter(),
|
||||
&self.characters,
|
||||
characters_start,
|
||||
);
|
||||
} else {
|
||||
process_shaped_clusters(
|
||||
&mut self.shaped_clusters,
|
||||
&mut self.glyphs,
|
||||
scale_factor,
|
||||
glyph_infos.iter().rev(),
|
||||
glyph_positions.iter().rev(),
|
||||
&self.characters,
|
||||
characters_start,
|
||||
);
|
||||
// Reverse each cluster's glyphs, such that they are in paint order.
|
||||
//
|
||||
// TODO: could this become a single `reverse` over the range?
|
||||
for cluster in &self.shaped_clusters[shaped_clusters_start..] {
|
||||
if !cluster.has_inline_glyph() && cluster.glyph_len() > 1 {
|
||||
let start = cluster.glyph_offset as usize;
|
||||
self.glyphs[start..start + cluster.glyph_len() as usize].reverse();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let shaped_clusters_range = shaped_clusters_start as u32..self.shaped_clusters.len() as u32;
|
||||
let run_advance = self.shaped_clusters[shaped_clusters_start..]
|
||||
.iter()
|
||||
.map(|cluster| cluster.advance)
|
||||
.sum();
|
||||
|
||||
self.runs.push(ShapedRun {
|
||||
range,
|
||||
font_size: options.font_size,
|
||||
font_index,
|
||||
characters_range: characters_start as u32..self.characters.len() as u32,
|
||||
shaped_clusters_range,
|
||||
glyphs_range: glyphs_start..self.glyphs.len(),
|
||||
normalized_coords_range,
|
||||
bidi_level: segment.bidi_level,
|
||||
advance: run_advance,
|
||||
font_metrics,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// One shaped run, belonging to a [`ShapedText`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ShapedRun {
|
||||
/// The range of text this run corresponds to.
|
||||
pub range: TextRange,
|
||||
/// Font size.
|
||||
pub font_size: f32,
|
||||
/// This run's font, as an index into [`ShapedText::fonts`].
|
||||
//
|
||||
// Note: We carry the font index instead of having `ShapedRun` carry `Arc<FontInstance>`,
|
||||
// meaning `ShapedRun` could become `Copy` once we have access to `core::range::Range`.
|
||||
pub font_index: usize,
|
||||
/// This run's characters, as a range into [`ShapedText::characters`].
|
||||
pub characters_range: Range<u32>,
|
||||
/// This run's shaped clusters, as a range into [`ShapedText::shaped_clusters`].
|
||||
pub shaped_clusters_range: Range<u32>,
|
||||
/// This run's glyphs, as a range into [`ShapedText::glyphs`].
|
||||
pub glyphs_range: Range<usize>,
|
||||
/// The normalized variation coords of this run, as a range into [`ShapedText::normalized_coords`].
|
||||
pub normalized_coords_range: Range<usize>,
|
||||
/// The bidi level of the run.
|
||||
pub bidi_level: BidiLevel,
|
||||
/// Total advance of the run.
|
||||
pub advance: f32,
|
||||
/// The font metrics of this run.
|
||||
pub font_metrics: FontMetrics,
|
||||
}
|
||||
|
||||
/// Processes shaped glyphs from `HarfRust` and converts them into `ShapedCluster` and `Glyph`.
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// ## Output Parameters (mutated by this function):
|
||||
/// * `shaped_clusters` - Vector where new `ShapedCluster` entries will be pushed.
|
||||
/// * `glyphs` - Vector where new `Glyph` entries will be pushed. Note: single-glyph clusters
|
||||
/// with zero offsets are inlined directly into `ShapedCluster`.
|
||||
///
|
||||
/// ## Input Parameters:
|
||||
/// * `scale_factor` - Scaling factor used to convert font units to the target size.
|
||||
/// * `glyph_infos` - `HarfRust` glyph information in logical order (i.e., reversed for RTL runs).
|
||||
/// * `glyph_positions` - `HarfRust` glyph positioning data in logical order (i.e., reversed for RTL
|
||||
/// runs).
|
||||
/// * `characters` must contain the shaped characters whose clusters we're now processing, starting at
|
||||
/// index `characters_start`.
|
||||
/// * `characters_start` - See `characters`.
|
||||
fn process_shaped_clusters<'a>(
|
||||
shaped_clusters: &mut Vec<ShapedCluster>,
|
||||
glyphs: &mut Vec<Glyph>,
|
||||
scale_factor: f32,
|
||||
glyph_infos: impl Iterator<Item = &'a harfrust::GlyphInfo>,
|
||||
glyph_positions: impl Iterator<Item = &'a harfrust::GlyphPosition>,
|
||||
characters: &[Character],
|
||||
characters_start: usize,
|
||||
) {
|
||||
struct Cluster {
|
||||
id: u32,
|
||||
characters_start: usize,
|
||||
glyphs_start: usize,
|
||||
glyphs: u32,
|
||||
inline_glyph: Option<Glyph>,
|
||||
advance: f32,
|
||||
}
|
||||
|
||||
/// Flush `cluster`, whose characters end at `char_end`, onto `shaped_clusters`.
|
||||
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
|
||||
fn flush(
|
||||
cluster: &mut Cluster,
|
||||
char_end: usize,
|
||||
characters: &[Character],
|
||||
shaped_clusters: &mut Vec<ShapedCluster>,
|
||||
) {
|
||||
let first_character = &characters[cluster.characters_start];
|
||||
let is_newline = first_character.whitespace == Whitespace::Newline;
|
||||
let (glyph_offset, glyph_len, inline_glyph, advance) = if is_newline {
|
||||
// Elide glyphs of newlines.
|
||||
(cluster.glyphs_start as u32, 0, false, 0.)
|
||||
} else if let Some(inline_glyph) = cluster.inline_glyph.take() {
|
||||
(inline_glyph.id, 1, true, cluster.advance)
|
||||
} else {
|
||||
(
|
||||
cluster.glyphs_start as u32,
|
||||
cluster.glyphs as u8,
|
||||
false,
|
||||
cluster.advance,
|
||||
)
|
||||
};
|
||||
|
||||
shaped_clusters.push(ShapedCluster {
|
||||
chars_range: (cluster.characters_start as u32, char_end as u32),
|
||||
style_index: first_character.style_index,
|
||||
flags: ShapedClusterFlags::new(glyph_len)
|
||||
.with_grapheme_start(first_character.grapheme_start)
|
||||
// TODO: fill with actual shaping data (`parley` currently just ignores this)
|
||||
.with_safe_to_break_before(false)
|
||||
.with_inline_glyph(inline_glyph)
|
||||
.with_first_char(
|
||||
first_character.flags.is_soft_wrap_opportunity(),
|
||||
first_character.whitespace,
|
||||
),
|
||||
glyph_offset,
|
||||
advance,
|
||||
});
|
||||
}
|
||||
|
||||
let mut cluster = Cluster {
|
||||
id: 0,
|
||||
characters_start,
|
||||
glyphs_start: glyphs.len(),
|
||||
glyphs: 0,
|
||||
inline_glyph: None,
|
||||
advance: 0.,
|
||||
};
|
||||
|
||||
for (glyph_info, glyph_pos) in glyph_infos.zip(glyph_positions) {
|
||||
if glyph_info.cluster != cluster.id {
|
||||
let char_end = characters_start + glyph_info.cluster as usize;
|
||||
flush(&mut cluster, char_end, characters, shaped_clusters);
|
||||
|
||||
cluster = Cluster {
|
||||
id: glyph_info.cluster,
|
||||
characters_start: char_end,
|
||||
glyphs_start: glyphs.len(),
|
||||
glyphs: 0,
|
||||
inline_glyph: None,
|
||||
advance: 0.,
|
||||
};
|
||||
}
|
||||
|
||||
let glyph = Glyph {
|
||||
id: glyph_info.glyph_id,
|
||||
x: (glyph_pos.x_offset as f32) * scale_factor,
|
||||
// Convert from font space (Y-up) to layout space (Y-down)
|
||||
y: -(glyph_pos.y_offset as f32) * scale_factor,
|
||||
advance: (glyph_pos.x_advance as f32) * scale_factor,
|
||||
};
|
||||
if cluster.glyphs == 0 && glyph.x == 0. && glyph.y == 0. {
|
||||
// Defer this potential zero-offset, single glyph cluster
|
||||
cluster.inline_glyph = Some(glyph);
|
||||
} else {
|
||||
if let Some(pending_glyph) = cluster.inline_glyph.take() {
|
||||
glyphs.push(pending_glyph);
|
||||
}
|
||||
glyphs.push(glyph);
|
||||
}
|
||||
cluster.advance += glyph.advance;
|
||||
cluster.glyphs += 1;
|
||||
}
|
||||
|
||||
// Flush the final cluster.
|
||||
flush(&mut cluster, characters.len(), characters, shaped_clusters);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use alloc::{sync::Arc, vec, vec::Vec};
|
||||
|
||||
use fontique::Synthesis;
|
||||
use linebender_resource_handle::{Blob, FontData};
|
||||
|
||||
use crate::{
|
||||
Analysis, AnalysisOptions, Analyzer, FontInstance, FontInstanceRef, FontSelector,
|
||||
ShapeOptions, Shaper,
|
||||
itemize::{Item, Segment},
|
||||
shape::CharCluster,
|
||||
};
|
||||
|
||||
use super::ShapedText;
|
||||
|
||||
const ROBOTO: &[u8] =
|
||||
include_bytes!("../../../parley_dev/assets/fonts/roboto_fonts/Roboto-Regular.ttf");
|
||||
const NOTO_KUFI_ARABIC: &[u8] =
|
||||
include_bytes!("../../../parley_dev/assets/fonts/noto_fonts/NotoKufiArabic-Regular.otf");
|
||||
const NOTO_COLOR_EMOJI: &[u8] = include_bytes!(
|
||||
"../../../parley_dev/assets/fonts/noto_color_emoji/NotoColorEmoji-Subset.ttf"
|
||||
);
|
||||
|
||||
/// A [`FontSelector`] shaping everything with a single font.
|
||||
struct SingleFont(FontInstance);
|
||||
|
||||
impl FontSelector for SingleFont {
|
||||
fn select_font(
|
||||
&mut self,
|
||||
_item: &Segment,
|
||||
_options: &ShapeOptions<'_>,
|
||||
_cluster: &mut CharCluster,
|
||||
) -> Option<FontInstanceRef<'_>> {
|
||||
Some(self.0.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`FontSelector`] shaping clusters starting with a particular character with one font, and
|
||||
/// all other clusters with another, to split the text into runs at that character.
|
||||
struct FontForChar {
|
||||
ch: char,
|
||||
font: FontInstance,
|
||||
other_font: FontInstance,
|
||||
}
|
||||
|
||||
impl FontSelector for FontForChar {
|
||||
fn select_font(
|
||||
&mut self,
|
||||
_segment: &Segment,
|
||||
_options: &ShapeOptions<'_>,
|
||||
cluster: &mut CharCluster,
|
||||
) -> Option<FontInstanceRef<'_>> {
|
||||
if cluster.chars()[0].ch == self.ch {
|
||||
Some(self.font.as_ref())
|
||||
} else {
|
||||
Some(self.other_font.as_ref())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn analyze(text: &str) -> Analysis {
|
||||
let mut analysis = Analysis::new();
|
||||
Analyzer::new().analyze(
|
||||
text,
|
||||
&AnalysisOptions {
|
||||
line_break: &[],
|
||||
line_break_override: None,
|
||||
..AnalysisOptions::default()
|
||||
},
|
||||
&mut analysis,
|
||||
);
|
||||
analysis
|
||||
}
|
||||
|
||||
fn font_instance(font_data: &'static [u8]) -> FontInstance {
|
||||
FontInstance {
|
||||
font: FontData::new(Blob::new(Arc::new(font_data)), 0),
|
||||
synthesis: Synthesis::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn shape_with_font(text: &str, font_data: &'static [u8]) -> ShapedText {
|
||||
shape_with_font_selector(text, SingleFont(font_instance(font_data)))
|
||||
}
|
||||
|
||||
fn shape_with_font_selector(text: &str, select_font: impl FontSelector) -> ShapedText {
|
||||
let analysis = analyze(text);
|
||||
let mut shaper = Shaper::default();
|
||||
let mut shaped = ShapedText::new();
|
||||
|
||||
let char_style_indices = vec![0; text.chars().count()];
|
||||
let items = [Item {
|
||||
char_end: text.chars().count().try_into().unwrap(),
|
||||
options: ShapeOptions {
|
||||
font_size: 32.0,
|
||||
language: None,
|
||||
features: &[],
|
||||
variations: &[],
|
||||
},
|
||||
}];
|
||||
shaper.shape_text(
|
||||
text,
|
||||
&analysis,
|
||||
&char_style_indices,
|
||||
items,
|
||||
select_font,
|
||||
&mut shaped,
|
||||
);
|
||||
shaped
|
||||
}
|
||||
|
||||
/// A run can shape into no glyphs at all: `HarfRust` normally shapes `default-ignorable`
|
||||
/// characters (like a soft-hyphen) into a space glyph with zero advance, but if the space glyph
|
||||
/// is not available, it just deletes the character.
|
||||
///
|
||||
/// This checks whether we handle that.
|
||||
#[test]
|
||||
fn run_without_glyphs_is_kept() {
|
||||
// The soft hyphen is `default-ignorable`, and is a grapheme of its own, so font selection
|
||||
// gives it a run of its own.
|
||||
let shaped = shape_with_font_selector(
|
||||
"a\u{00AD}b",
|
||||
FontForChar {
|
||||
ch: '\u{00AD}',
|
||||
// Our Noto Color Emoji subset has no space character.
|
||||
font: font_instance(NOTO_COLOR_EMOJI),
|
||||
other_font: font_instance(ROBOTO),
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
shaped.characters().iter().count(),
|
||||
3,
|
||||
"the characters of a run without glyphs are shaped"
|
||||
);
|
||||
let [a, soft_hyphen, b] = shaped.runs() else {
|
||||
panic!("expected three runs, got {}", shaped.runs().len());
|
||||
};
|
||||
assert_eq!(a.characters_range, 0..1);
|
||||
assert_eq!(soft_hyphen.characters_range, 1..2);
|
||||
assert_eq!(b.characters_range, 2..3);
|
||||
|
||||
assert!(soft_hyphen.glyphs_range.is_empty());
|
||||
assert_eq!(soft_hyphen.advance, 0.);
|
||||
|
||||
// The soft-hyphen's run should have a single cluster, and it must be without glyphs.
|
||||
let clusters = shaped.run_slice(1).shaped_clusters();
|
||||
assert_eq!(clusters.len(), 1);
|
||||
assert_eq!(clusters[0].glyph_len(), 0);
|
||||
assert_eq!(clusters[0].chars_range(), 1..2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_cluster_run_advance_matches_its_cluster() {
|
||||
let shaped = shape_with_font("A", ROBOTO);
|
||||
let run = &shaped.runs()[0];
|
||||
let cluster = &shaped.shaped_clusters()[run.shaped_clusters_range.start as usize];
|
||||
|
||||
assert!(cluster.advance > 0.0);
|
||||
assert_eq!(run.advance, cluster.advance);
|
||||
}
|
||||
|
||||
/// [U+0600 U+0623 U+064F] is a single grapheme in text-wide segmentation, but U+0600 has
|
||||
/// bidi class AN while the following characters resolve to a different bidi level, so
|
||||
/// itemization splits the grapheme into the items [U+0600] [U+0623 U+064F]. The item
|
||||
/// boundary forces a grapheme start on U+0623.
|
||||
#[test]
|
||||
fn one_grapheme_split_across_items() {
|
||||
let shaped = shape_with_font("\u{0600}\u{0623}\u{064F}", NOTO_KUFI_ARABIC);
|
||||
|
||||
let grapheme_starts: Vec<bool> =
|
||||
shaped.characters.iter().map(|c| c.grapheme_start).collect();
|
||||
assert_eq!(grapheme_starts, [true, true, false]);
|
||||
|
||||
let clusters: Vec<(u32, u32, bool)> = shaped
|
||||
.shaped_clusters
|
||||
.iter()
|
||||
.map(|c| {
|
||||
(
|
||||
c.chars_range().start,
|
||||
c.chars_range().end,
|
||||
c.is_grapheme_start(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(clusters, [(0, 1, true), (1, 3, true)]);
|
||||
}
|
||||
|
||||
/// "ffi" is three graphemes but shapes into one cluster.
|
||||
#[test]
|
||||
fn three_graphemes_one_cluster() {
|
||||
let shaped = shape_with_font("ffi", ROBOTO);
|
||||
|
||||
let grapheme_starts: Vec<bool> =
|
||||
shaped.characters.iter().map(|c| c.grapheme_start).collect();
|
||||
assert_eq!(grapheme_starts, [true, true, true]);
|
||||
|
||||
let clusters: Vec<(u32, u32, bool)> = shaped
|
||||
.shaped_clusters
|
||||
.iter()
|
||||
.map(|c| {
|
||||
(
|
||||
c.chars_range().start,
|
||||
c.chars_range().end,
|
||||
c.is_grapheme_start(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(clusters, [(0, 3, true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newlines_removed() {
|
||||
for newline in ["\n", "\r", "\u{2028}", "\u{2029}"] {
|
||||
let shaped = shape_with_font(&alloc::format!("a{newline}b"), ROBOTO);
|
||||
|
||||
let index = shaped
|
||||
.shaped_clusters
|
||||
.iter()
|
||||
.position(|cluster| cluster.chars_range().start == 1)
|
||||
.unwrap();
|
||||
let newline_cluster = &shaped.shaped_clusters[index];
|
||||
assert_eq!(newline_cluster.glyph_len(), 0, "newline glyphs are removed");
|
||||
assert_eq!(newline_cluster.advance, 0., "newline advance is set to 0");
|
||||
}
|
||||
}
|
||||
|
||||
/// An itemization boundary forces a cluster break in shaping, and must force a grapheme start.
|
||||
#[test]
|
||||
fn item_boundaries_force_grapheme_start() {
|
||||
// Two regional indicators forming a single flag grapheme...
|
||||
let text = "\u{1F1E6}\u{1F1E7}";
|
||||
let char_style_indices = vec![0; text.chars().count()];
|
||||
let analysis = analyze(text);
|
||||
assert_eq!(
|
||||
analysis
|
||||
.char_info()
|
||||
.iter()
|
||||
.map(|info| info.is_grapheme_start())
|
||||
.collect::<Vec<_>>(),
|
||||
[true, false]
|
||||
);
|
||||
|
||||
let font = font_instance(ROBOTO);
|
||||
let mut shaper = Shaper::default();
|
||||
let mut shaped = ShapedText::new();
|
||||
|
||||
// ...split over two items.
|
||||
let items = [
|
||||
Item {
|
||||
char_end: 1,
|
||||
options: ShapeOptions {
|
||||
font_size: 32.0,
|
||||
language: None,
|
||||
features: &[],
|
||||
variations: &[],
|
||||
},
|
||||
},
|
||||
Item {
|
||||
char_end: text.chars().count().try_into().unwrap(),
|
||||
options: ShapeOptions {
|
||||
font_size: 32.0,
|
||||
language: None,
|
||||
features: &[],
|
||||
variations: &[],
|
||||
},
|
||||
},
|
||||
];
|
||||
shaper.shape_text(
|
||||
text,
|
||||
&analysis,
|
||||
&char_style_indices,
|
||||
items,
|
||||
SingleFont(font),
|
||||
&mut shaped,
|
||||
);
|
||||
|
||||
let grapheme_starts: Vec<bool> =
|
||||
shaped.characters.iter().map(|c| c.grapheme_start).collect();
|
||||
assert_eq!(grapheme_starts, [true, true]);
|
||||
|
||||
// But note that, had we had three regional indicator symbols, like `[R0 R1 R2]` itemized as
|
||||
// `[R0] [R1 R2]`, the last pair should form a single grapheme. We don't do that currently.
|
||||
}
|
||||
}
|
||||
+605
@@ -0,0 +1,605 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Shaping of text.
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use core::mem;
|
||||
use harfrust::ShapeOptions as HarfShapeOptions;
|
||||
use linebender_resource_handle::{Blob, FontData};
|
||||
use parlance::{FontFeature, FontVariation, Language};
|
||||
|
||||
use crate::shape::shaped_text::FontMetrics;
|
||||
use crate::{
|
||||
Analysis, CharInfo, ShapedText,
|
||||
itemize::{Item, Segment, TextRange},
|
||||
lru_cache::LruCache,
|
||||
shape::{CharCluster, cache},
|
||||
};
|
||||
|
||||
/// Shaping options for one item.
|
||||
///
|
||||
/// These are styling options relevant for shaping. They're styling, in that they're not derived
|
||||
/// from the underlying text. When you [shape the text][`Shaper::shape_text`], you should split the
|
||||
/// text into [`Item`]s at the points where these options change.
|
||||
#[derive(Debug)]
|
||||
pub struct ShapeOptions<'a> {
|
||||
/// The font size to shape the item with.
|
||||
pub font_size: f32,
|
||||
/// The language to shape the item with.
|
||||
pub language: Option<Language>,
|
||||
/// The font features to shape the item with.
|
||||
///
|
||||
/// If there are font features with duplicate [tags][`FontFeature::tag`], later values override
|
||||
/// earlier values.
|
||||
pub features: &'a [FontFeature],
|
||||
/// The font variations that are constant over an item.
|
||||
pub variations: &'a [FontVariation],
|
||||
}
|
||||
|
||||
/// The font instance to shape an item with.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FontInstance {
|
||||
/// The font.
|
||||
pub font: FontData,
|
||||
/// Font synthesis suggestions.
|
||||
// TODO: Synthesis carries more than we need, and ties us to `fontique`. We can likely change
|
||||
// this to opaque user data.
|
||||
pub synthesis: fontique::Synthesis,
|
||||
}
|
||||
|
||||
impl FontInstance {
|
||||
/// Borrow this font instance.
|
||||
#[inline]
|
||||
pub fn as_ref(&self) -> FontInstanceRef<'_> {
|
||||
FontInstanceRef {
|
||||
data: &self.font.data,
|
||||
index: self.font.index,
|
||||
synthesis: &self.synthesis,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A borrowed [`FontInstance`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FontInstanceRef<'a> {
|
||||
/// Blob containing the content of the font file.
|
||||
pub data: &'a Blob<u8>,
|
||||
/// Index of the font in a collection, or 0 for a single font.
|
||||
pub index: u32,
|
||||
/// Font synthesis suggestions.
|
||||
pub synthesis: &'a fontique::Synthesis,
|
||||
}
|
||||
|
||||
impl From<FontInstanceRef<'_>> for FontInstance {
|
||||
#[inline]
|
||||
fn from(font: FontInstanceRef<'_>) -> Self {
|
||||
Self {
|
||||
font: FontData {
|
||||
data: font.data.clone(),
|
||||
index: font.index,
|
||||
},
|
||||
synthesis: *font.synthesis,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reusable scratch to shape text using [`Self::shape_text`].
|
||||
pub struct Shaper {
|
||||
shape_data_cache: LruCache<cache::ShapeDataKey, harfrust::ShaperData>,
|
||||
shape_instance_cache: LruCache<cache::ShapeInstanceId, harfrust::ShaperInstance>,
|
||||
shape_plan_cache: LruCache<cache::ShapePlanId, harfrust::ShapePlan>,
|
||||
/// Each run's font metrics and units per em (Rune: vendor/parley_engine.patch).
|
||||
run_metrics_cache: LruCache<cache::RunMetricsId, (FontMetrics, f32)>,
|
||||
unicode_buffer: Option<harfrust::UnicodeBuffer>,
|
||||
features: Vec<harfrust::Feature>,
|
||||
char_cluster: CharCluster,
|
||||
}
|
||||
|
||||
impl Default for Shaper {
|
||||
fn default() -> Self {
|
||||
const MAX_ENTRIES: usize = 16;
|
||||
Self {
|
||||
shape_data_cache: LruCache::new(MAX_ENTRIES),
|
||||
shape_instance_cache: LruCache::new(MAX_ENTRIES),
|
||||
shape_plan_cache: LruCache::new(MAX_ENTRIES),
|
||||
run_metrics_cache: LruCache::new(MAX_ENTRIES),
|
||||
unicode_buffer: Some(harfrust::UnicodeBuffer::new()),
|
||||
features: Vec::new(),
|
||||
char_cluster: CharCluster::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for Shaper {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("Shaper").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Shaper {
|
||||
/// Shape text into glyphs, overwriting `shaped_text`.
|
||||
///
|
||||
/// The `text` passed in must be the same as used for producing `analysis`.
|
||||
///
|
||||
/// This uses the items returned by `items`, and further itemizes the text into
|
||||
/// individually-shapeable segments of constant bidi level and script. `items` should be used to
|
||||
/// split on properties like shaping-relevant style changes (e.g., font size) or properties like
|
||||
/// language.
|
||||
///
|
||||
/// `char_style_indices` holds per-character style indices; these are copied onto
|
||||
/// [`Character`][super::Character`] and [`ShapedCluster`][super::ShapedCluster]. A shaped
|
||||
/// cluster's style index is that of its logically first constituent character.
|
||||
///
|
||||
/// Characters that don't have a particular script have their script resolved based on
|
||||
/// surrounding context (see [`Segment::script`]).
|
||||
///
|
||||
/// Each segment is then broken into runs of maximal sequences of character clusters for which
|
||||
/// `select_font` returns the same font.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `items` does not cover the entire source text, or the font returned by
|
||||
/// `select_font` is malformed.
|
||||
pub fn shape_text<'options>(
|
||||
&mut self,
|
||||
text: &str,
|
||||
analysis: &Analysis,
|
||||
// TODO: rename to something like `user_data` (s.t. we don't assume it's a style per se).
|
||||
char_style_indices: &[u16],
|
||||
items: impl IntoIterator<Item = Item<'options>>,
|
||||
mut select_font: impl FontSelector,
|
||||
shaped_text: &mut ShapedText,
|
||||
) {
|
||||
shaped_text.clear();
|
||||
shaped_text.reserve(text.len());
|
||||
|
||||
let char_count = analysis.char_info().len();
|
||||
debug_assert_eq!(
|
||||
char_style_indices.len(),
|
||||
char_count,
|
||||
"The number of character style indices must be equal to the character count"
|
||||
);
|
||||
|
||||
let mut previous_item_end = 0;
|
||||
let mut itemizer = analysis.itemize(text);
|
||||
|
||||
for item in items {
|
||||
assert!(
|
||||
item.char_end > previous_item_end,
|
||||
"item ends must be strictly increasing"
|
||||
);
|
||||
assert!(
|
||||
item.char_end as usize <= char_count,
|
||||
"items must not span past the text"
|
||||
);
|
||||
|
||||
loop {
|
||||
let segment = itemizer
|
||||
.next(
|
||||
#[inline(always)]
|
||||
|text_range| text_range.char_range.end == item.char_end as usize,
|
||||
)
|
||||
.expect("A segment must be yielded, given items tile the full text exactly");
|
||||
|
||||
if shape_segment(
|
||||
self,
|
||||
text,
|
||||
&segment,
|
||||
&item.options,
|
||||
&mut select_font,
|
||||
analysis.char_info(),
|
||||
char_style_indices,
|
||||
shaped_text,
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
// Abort on error. This happens iff `FontSelector::select_font` failed to return a
|
||||
// font. By aborting we ensure `ShapedText` covers the source text contiguously (as
|
||||
// we need a font to construct `ShapedRun`).
|
||||
return;
|
||||
};
|
||||
|
||||
debug_assert!(
|
||||
segment.range.char_range.end <= item.char_end as usize,
|
||||
"Segments must not span past the item."
|
||||
);
|
||||
if segment.range.char_range.end == item.char_end as usize {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
previous_item_end = item.char_end;
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
previous_item_end as usize, char_count,
|
||||
"`items` does not cover the entire source text"
|
||||
);
|
||||
debug_assert_eq!(
|
||||
shaped_text.characters().len(),
|
||||
char_count,
|
||||
"All characters must have been processed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shape one segment.
|
||||
///
|
||||
/// Returns `Err(())` if shaping should be aborted, which happens iff [`FontSelector::select_font`]
|
||||
/// returned `None`.
|
||||
fn shape_segment(
|
||||
scx: &mut Shaper,
|
||||
text: &str,
|
||||
segment: &Segment,
|
||||
options: &ShapeOptions<'_>,
|
||||
select_font: &mut impl FontSelector,
|
||||
char_info: &[CharInfo],
|
||||
char_style_indices: &[u16],
|
||||
shaped_text: &mut ShapedText,
|
||||
) -> Result<(), ()> {
|
||||
select_font.begin_segment(segment, options);
|
||||
|
||||
let text_range = &segment.range.byte_range;
|
||||
let char_range = &segment.range.char_range;
|
||||
|
||||
let segment_text = &text[text_range.clone()];
|
||||
|
||||
// Only process current segment
|
||||
let segment_char_info = &char_info[char_range.start..char_range.end];
|
||||
let segment_char_style_indices = &char_style_indices[char_range.start..char_range.end];
|
||||
|
||||
if segment_text.is_empty() {
|
||||
return Ok(()); // No clusters
|
||||
}
|
||||
|
||||
let char_cluster = &mut scx.char_cluster;
|
||||
|
||||
// Shaping inputs that are constant over the segment.
|
||||
let direction = if segment.bidi_level.is_rtl() {
|
||||
harfrust::Direction::RightToLeft
|
||||
} else {
|
||||
harfrust::Direction::LeftToRight
|
||||
};
|
||||
let hb_script = script_to_harfrust(segment.script);
|
||||
let language = options
|
||||
.language
|
||||
.as_ref()
|
||||
.and_then(|lang| lang.as_str().parse::<harfrust::Language>().ok());
|
||||
scx.features.clear();
|
||||
scx.features.extend(options.features.iter().map(|feature| {
|
||||
harfrust::Feature::new(
|
||||
harfrust::Tag::new(&feature.tag.to_bytes()),
|
||||
feature.value as u32,
|
||||
..,
|
||||
)
|
||||
}));
|
||||
|
||||
// Shape a run of the segment with a single font, appending it to `shaped_text`.
|
||||
let mut shape_run = |font: &FontInstance, range: TextRange| {
|
||||
// The platform's face: its host measures the run and draws it (`platform`).
|
||||
if let Some(platform) = crate::platform::shaper(font.font.data.id()) {
|
||||
shape_platform_run(platform, text, range, segment, options, char_info, char_style_indices, font, shaped_text);
|
||||
return;
|
||||
}
|
||||
// TODO: How do we want to handle errors like this?
|
||||
let font_ref =
|
||||
harfrust::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap();
|
||||
|
||||
// Create harfrust shaper
|
||||
let shaper_data = scx.shape_data_cache.entry(
|
||||
cache::ShapeDataKey::new(font.font.data.id(), font.font.index),
|
||||
|| harfrust::ShaperData::new(&font_ref),
|
||||
);
|
||||
let instance = scx.shape_instance_cache.entry(
|
||||
cache::ShapeInstanceKey::new(
|
||||
font.font.data.id(),
|
||||
font.font.index,
|
||||
&font.synthesis,
|
||||
Some(options.variations),
|
||||
),
|
||||
|| {
|
||||
harfrust::ShaperInstance::from_variations(
|
||||
&font_ref,
|
||||
variations_iter(&font.synthesis, options.variations),
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
let harf_shaper = shaper_data
|
||||
.shaper(&font_ref)
|
||||
.instance(Some(instance))
|
||||
.build();
|
||||
let shaper_plan = scx.shape_plan_cache.entry(
|
||||
cache::ShapePlanKey::new(
|
||||
font.font.data.id(),
|
||||
font.font.index,
|
||||
&font.synthesis,
|
||||
direction,
|
||||
hb_script,
|
||||
language.clone(),
|
||||
&scx.features,
|
||||
Some(options.variations),
|
||||
),
|
||||
|| {
|
||||
harfrust::ShapePlan::new(
|
||||
&harf_shaper,
|
||||
direction,
|
||||
Some(hb_script),
|
||||
language.as_ref(),
|
||||
&scx.features,
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
// Prepare harfrust buffer
|
||||
let mut buffer = mem::take(&mut scx.unicode_buffer).unwrap();
|
||||
buffer.clear();
|
||||
buffer.set_cluster_level(harfrust::BufferClusterLevel::MonotoneCharacters);
|
||||
|
||||
// Use the entire run text including newlines.
|
||||
let run_text = &text[range.byte_range.clone()];
|
||||
buffer.reserve(run_text.len());
|
||||
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
|
||||
for (i, ch) in run_text.chars().enumerate() {
|
||||
// Ensure that each cluster's index matches the index into `infos`. This is required
|
||||
// for efficient cluster lookup within `data.rs`.
|
||||
//
|
||||
// In other words, instead of using `buffer.push_str`, which iterates `run_text`
|
||||
// with `char_indices`, push each char individually via `.chars` with a cluster index
|
||||
// that matches its `infos` counterpart. This allows us to lookup `infos` via cluster
|
||||
// index in `data.rs`.
|
||||
buffer.add(ch, i as u32);
|
||||
}
|
||||
|
||||
buffer.set_pre_context(&text[..range.byte_range.start]);
|
||||
buffer.set_post_context(&text[range.byte_range.end..]);
|
||||
buffer.set_direction(direction);
|
||||
buffer.set_script(hb_script);
|
||||
|
||||
if let Some(lang) = &language {
|
||||
buffer.set_language(lang.clone());
|
||||
}
|
||||
|
||||
let glyph_buffer = harf_shaper.shape(
|
||||
buffer,
|
||||
HarfShapeOptions::new()
|
||||
.plan(Some(shaper_plan))
|
||||
.features(&scx.features)
|
||||
.point_size(Some(options.font_size)),
|
||||
);
|
||||
|
||||
// A run's metrics depend on its font instance and size alone: made once for each.
|
||||
let metrics = *scx.run_metrics_cache.entry(
|
||||
cache::RunMetricsKey::new(
|
||||
cache::ShapeInstanceKey::new(
|
||||
font.font.data.id(),
|
||||
font.font.index,
|
||||
&font.synthesis,
|
||||
Some(options.variations),
|
||||
),
|
||||
options.font_size,
|
||||
),
|
||||
|| {
|
||||
let font_ref =
|
||||
skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap();
|
||||
let metrics = skrifa::metrics::Metrics::new(
|
||||
&font_ref,
|
||||
skrifa::prelude::Size::new(options.font_size),
|
||||
harf_shaper.coords(),
|
||||
);
|
||||
(
|
||||
FontMetrics::from_skrifa_metrics(&metrics, options.font_size),
|
||||
metrics.units_per_em as f32,
|
||||
)
|
||||
},
|
||||
);
|
||||
shaped_text.push_run(
|
||||
text,
|
||||
range,
|
||||
segment,
|
||||
options,
|
||||
char_info,
|
||||
char_style_indices,
|
||||
font,
|
||||
glyph_buffer.glyph_infos(),
|
||||
glyph_buffer.glyph_positions(),
|
||||
harf_shaper.coords(),
|
||||
metrics,
|
||||
);
|
||||
|
||||
// Replace buffer to reuse allocation in the next run.
|
||||
scx.unicode_buffer = Some(glyph_buffer.clear());
|
||||
};
|
||||
|
||||
// This is the run being accumulated, i.e., consecutive graphemes for which `select_font`
|
||||
// returns the same font.
|
||||
let mut run: Option<(FontInstance, TextRange)> = None;
|
||||
|
||||
// The segment's characters with their analysis data and style indices.
|
||||
let mut chars = segment_text
|
||||
.chars()
|
||||
.zip(segment_char_info)
|
||||
.zip(segment_char_style_indices)
|
||||
.map(|((ch, &info), &style_index)| (ch, info, style_index));
|
||||
|
||||
// The lengths of the segment's graphemes in characters.
|
||||
let grapheme_lengths = segment_char_info
|
||||
.chunk_by(|_, info| !info.is_grapheme_start())
|
||||
.map(<[_]>::len);
|
||||
|
||||
// The end of the previous grapheme.
|
||||
let mut byte_end = text_range.start;
|
||||
let mut char_end = char_range.start;
|
||||
|
||||
for grapheme_length in grapheme_lengths {
|
||||
let (byte_start, char_start) = (byte_end, char_end);
|
||||
char_cluster.fill(chars.by_ref().take(grapheme_length), &mut byte_end);
|
||||
char_end += grapheme_length;
|
||||
let grapheme = TextRange {
|
||||
byte_range: byte_start..byte_end,
|
||||
char_range: char_start..char_end,
|
||||
};
|
||||
|
||||
let font = select_font
|
||||
.select_font(segment, options, char_cluster)
|
||||
.ok_or(())?;
|
||||
|
||||
if let Some((run_font, run_range)) = &mut run
|
||||
&& run_font.as_ref() == font
|
||||
{
|
||||
run_range.byte_range.end = byte_end;
|
||||
run_range.char_range.end = char_end;
|
||||
} else {
|
||||
if let Some((run_font, run_range)) = run.take() {
|
||||
// The font changed: shape the previous run.
|
||||
shape_run(&run_font, run_range);
|
||||
}
|
||||
run = Some((font.into(), grapheme));
|
||||
}
|
||||
}
|
||||
if let Some((run_font, run_range)) = run {
|
||||
shape_run(&run_font, run_range);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn variations_iter<'a>(
|
||||
synthesis: &'a fontique::Synthesis,
|
||||
item: &'a [FontVariation],
|
||||
) -> impl Iterator<Item = harfrust::Variation> + 'a {
|
||||
synthesis
|
||||
.variation_settings()
|
||||
.iter()
|
||||
.map(|(tag, value)| harfrust::Variation {
|
||||
tag: *tag,
|
||||
value: *value,
|
||||
})
|
||||
.chain(item.iter().map(|variation| harfrust::Variation {
|
||||
tag: harfrust::Tag::new(&variation.tag.to_bytes()),
|
||||
value: variation.value,
|
||||
}))
|
||||
}
|
||||
|
||||
/// A run in the platform's face (`platform`), appended to `shaped_text`: its host gives a glyph
|
||||
/// per grapheme, with units it draws whole between the run's break opportunities.
|
||||
#[expect(clippy::too_many_arguments, reason = "the shape_run closure's inputs")]
|
||||
fn shape_platform_run(
|
||||
shaper: crate::platform::PlatformShaper,
|
||||
text: &str,
|
||||
range: TextRange,
|
||||
segment: &Segment,
|
||||
options: &ShapeOptions<'_>,
|
||||
char_info: &[CharInfo],
|
||||
char_style_indices: &[u16],
|
||||
font: &FontInstance,
|
||||
shaped_text: &mut ShapedText,
|
||||
) {
|
||||
let run_text = &text[range.byte_range.clone()];
|
||||
let (mut graphemes, mut units, mut clusters) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let mut after_newline = false;
|
||||
for (i, ((at, ch), info)) in run_text.char_indices().zip(&char_info[range.char_range.clone()]).enumerate() {
|
||||
let newline = matches!(ch, '\n' | '\r' | '\u{0B}' | '\u{0C}' | '\u{85}' | '\u{2028}' | '\u{2029}');
|
||||
let grapheme = i == 0 || info.is_grapheme_start() || newline || after_newline;
|
||||
if grapheme {
|
||||
#[expect(clippy::cast_possible_truncation, reason = "a run is under 4 GiB")]
|
||||
{
|
||||
if i == 0 || info.is_soft_wrap_opportunity() || newline || after_newline {
|
||||
units.push(at as u32);
|
||||
}
|
||||
graphemes.push(at as u32);
|
||||
clusters.push(i as u32);
|
||||
}
|
||||
}
|
||||
after_newline = newline;
|
||||
}
|
||||
let wght = harfrust::Tag::new(b"wght");
|
||||
let weight = variations_iter(&font.synthesis, options.variations)
|
||||
.filter(|v| v.tag == wght)
|
||||
.last()
|
||||
.map_or(if font.synthesis.embolden() { 700. } else { 400. }, |v| v.value);
|
||||
let rtl = segment.bidi_level.is_rtl();
|
||||
let mut glyphs = Vec::with_capacity(graphemes.len());
|
||||
shaper(
|
||||
&crate::platform::PlatformText {
|
||||
text: run_text,
|
||||
graphemes: &graphemes,
|
||||
units: &units,
|
||||
size: options.font_size,
|
||||
weight,
|
||||
italic: font.synthesis.skew().is_some(),
|
||||
rtl,
|
||||
language: options.language.as_ref().map(|l| l.as_str()),
|
||||
},
|
||||
&mut glyphs,
|
||||
);
|
||||
glyphs.resize(graphemes.len(), crate::platform::PlatformGlyph::default());
|
||||
let font_ref = skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap();
|
||||
let metrics = skrifa::metrics::Metrics::new(
|
||||
&font_ref,
|
||||
skrifa::prelude::Size::new(options.font_size),
|
||||
skrifa::instance::LocationRef::default(),
|
||||
);
|
||||
let upem = metrics.units_per_em as f32;
|
||||
let units_of = |px: f32| (px * upem / options.font_size.max(1e-3)).round() as i32;
|
||||
let mut infos: Vec<harfrust::GlyphInfo> = Vec::with_capacity(glyphs.len());
|
||||
let mut positions: Vec<harfrust::GlyphPosition> = Vec::with_capacity(glyphs.len());
|
||||
for (glyph, &cluster) in glyphs.iter().zip(&clusters) {
|
||||
let mut info = harfrust::GlyphInfo::default();
|
||||
info.glyph_id = glyph.id;
|
||||
info.cluster = cluster;
|
||||
infos.push(info);
|
||||
let mut position = harfrust::GlyphPosition::default();
|
||||
position.x_advance = units_of(glyph.advance);
|
||||
position.x_offset = units_of(glyph.x_offset);
|
||||
positions.push(position);
|
||||
}
|
||||
// In visual order, as HarfRust gives them.
|
||||
if rtl {
|
||||
infos.reverse();
|
||||
positions.reverse();
|
||||
}
|
||||
shaped_text.push_run(
|
||||
text,
|
||||
range,
|
||||
segment,
|
||||
options,
|
||||
char_info,
|
||||
char_style_indices,
|
||||
font,
|
||||
&infos,
|
||||
&positions,
|
||||
&[],
|
||||
(FontMetrics::from_skrifa_metrics(&metrics, options.font_size), upem),
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn script_to_harfrust(script: fontique::Script) -> harfrust::Script {
|
||||
harfrust::Script::from_iso15924_tag(harfrust::Tag::new(&script.to_bytes()))
|
||||
.unwrap_or(harfrust::script::UNKNOWN)
|
||||
}
|
||||
|
||||
/// Implements font selection for shaping.
|
||||
pub trait FontSelector {
|
||||
/// Called when a new segment starts.
|
||||
///
|
||||
/// This can be useful to inspect, e.g., the segment's script.
|
||||
fn begin_segment(&mut self, segment: &Segment, options: &ShapeOptions<'_>) {
|
||||
let _ = (segment, options);
|
||||
}
|
||||
|
||||
/// Called once per character cluster within the current segment.
|
||||
///
|
||||
/// A character cluster will usually be a grapheme, though if text direction or script changes
|
||||
/// mid-grapheme, it will be split over segments.
|
||||
///
|
||||
/// Shaping is aborted if this returns `None`; [`ShapedText`] then contains a partial result.
|
||||
fn select_font(
|
||||
&mut self,
|
||||
segment: &Segment,
|
||||
options: &ShapeOptions<'_>,
|
||||
cluster: &mut CharCluster,
|
||||
) -> Option<FontInstanceRef<'_>>;
|
||||
}
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
# Use rustc's bundled rust-lld on Windows MSVC instead of link.exe (zero extra installs).
|
||||
# On Rust 1.90+, x86_64-unknown-linux-gnu already defaults to rust-lld; `-C linker-features=+lld`
|
||||
# remains unstable on Rust 1.99.1, so Linux and macOS use their toolchain defaults.
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
linker = "rust-lld"
|
||||
|
||||
[target.aarch64-pc-windows-msvc]
|
||||
linker = "rust-lld"
|
||||
|
||||
# Opt-in local developer shortcuts (default-members fast paths and wasm/webgl checks).
|
||||
[alias]
|
||||
lint = "clippy --lib --bins --tests"
|
||||
lint-all = "clippy --workspace --all-targets"
|
||||
check-wasm = "check -p rune --no-default-features --target wasm32-unknown-unknown"
|
||||
check-webgl = "check -p rune --no-default-features --features webgl --target wasm32-unknown-unknown"
|
||||
test-fast = "test -p rune -p rune-mermaid -p rune-kit --features rune-kit/markdown,rune-kit/mermaid"
|
||||
@@ -0,0 +1,17 @@
|
||||
# Text Rune compiles in, hashes or runs is LF in every checkout, whatever core.autocrlf says: the
|
||||
# precompiled shaders are keyed to the WGSL's bytes (crates/rune/build.rs also reads CRLF as LF,
|
||||
# for checkouts made before this file), and a shell script with CRLF doesn't run.
|
||||
*.wgsl text eol=lf
|
||||
*.luau text eol=lf
|
||||
*.json text eol=lf
|
||||
*.jsonl text eol=lf
|
||||
*.mmd text eol=lf
|
||||
*.vert text eol=lf
|
||||
*.frag text eol=lf
|
||||
*.sh text eol=lf
|
||||
|
||||
# Precompiled shaders and raw pixel data, never converted.
|
||||
*.dxbc binary
|
||||
*.metallib binary
|
||||
*.rgba binary
|
||||
*.bin binary
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env bash
|
||||
# Mints a short-lived Cloudflare token for the current release job from the token issuer
|
||||
# (anomalyco/secrets). Run after aws-actions/configure-aws-credentials has assumed
|
||||
# arn:aws:iam::604439173067:role/github/opencode-release: the Lambda identifies the role from the
|
||||
# SigV4 signature and mints only the `opencode/release` token. No repo, stage, permission or TTL
|
||||
# is sent in the request, and the token is pinned to the runner's IP for 30 minutes.
|
||||
#
|
||||
# Step-scoped by default: the token goes to $GITHUB_OUTPUT and only steps that list
|
||||
# `CLOUDFLARE_API_TOKEN: ${{ steps.<id>.outputs.token }}` in their env receive it.
|
||||
set -euo pipefail
|
||||
set +x
|
||||
|
||||
url=${CLOUDFLARE_TOKEN_URL:-https://kjivkui2evldapbok5fhrrl6oy0fctkp.lambda-url.us-east-1.on.aws/}
|
||||
account=${CLOUDFLARE_ACCOUNT_ID:-15d29c8639fd3733b1b5486a2acfd968}
|
||||
|
||||
# One argv value, never a line in curl's config: a newline in an override must not be able to
|
||||
# inject curl options or move the AWS credentials into Basic auth.
|
||||
url_pattern='^https://[a-z0-9]+\.lambda-url\.us-east-1\.on\.aws/$'
|
||||
if ! [[ "$url" =~ $url_pattern ]]; then
|
||||
echo "::error::CLOUDFLARE_TOKEN_URL is not the token issuer's function URL." >&2
|
||||
exit 1
|
||||
fi
|
||||
case "$account" in
|
||||
*[!0-9a-f]*|"")
|
||||
echo "::error::CLOUDFLARE_ACCOUNT_ID must be a 32-character lowercase hex id." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
if [ ${#account} -ne 32 ]; then
|
||||
echo "::error::CLOUDFLARE_ACCOUNT_ID must be a 32-character lowercase hex id." >&2
|
||||
exit 1
|
||||
fi
|
||||
for name in AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN; do
|
||||
if [ -z "${!name:-}" ]; then
|
||||
echo "::error::$name is not set; run aws-actions/configure-aws-credentials first." >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# The response is captured, never streamed: it contains the token. AWS credentials go to curl
|
||||
# through stdin, not argv, so they stay out of `ps` and any trace of this script.
|
||||
response=$(
|
||||
printf 'user = "%s:%s"\nheader = "x-amz-security-token: %s"\n' \
|
||||
"$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" "$AWS_SESSION_TOKEN" |
|
||||
curl --config - \
|
||||
--proto '=https' --proto-redir '=https' \
|
||||
--aws-sigv4 "aws:amz:us-east-1:lambda" \
|
||||
--request POST --url "$url" \
|
||||
--fail-with-body --silent --show-error --max-time 20
|
||||
)
|
||||
|
||||
token=$(printf '%s' "$response" | jq -er 'if (.token | type) == "string" then .token else error("token") end' 2>/dev/null)
|
||||
expires=$(printf '%s' "$response" | jq -er 'if (.expires_on | type) == "string" then .expires_on else error("expires_on") end' 2>/dev/null)
|
||||
|
||||
# Validate before any output. No error below includes the token value.
|
||||
case "$token" in
|
||||
""|*[[:space:]]*)
|
||||
echo "::error::The token issuer returned an invalid token." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
if [ ${#token} -lt 8 ] || [ ${#token} -gt 512 ]; then
|
||||
echo "::error::The token issuer returned an invalid token length." >&2
|
||||
exit 1
|
||||
fi
|
||||
case "$expires" in
|
||||
""|*[[:space:]]*)
|
||||
echo "::error::The token issuer returned an invalid expires_on." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
iso_pattern='^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?Z$'
|
||||
if ! printf '%s' "$response" | jq -e --arg re "$iso_pattern" '(.expires_on | type) == "string" and (.expires_on | test($re))' > /dev/null; then
|
||||
echo "::error::The token issuer returned an invalid expires_on." >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! [[ "$expires" =~ $iso_pattern ]]; then
|
||||
echo "::error::The token issuer returned an invalid expires_on." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# GitHub masks the exact string everywhere after this, including accidental traces and our own
|
||||
# error messages. This is the first output that contains it.
|
||||
printf '::add-mask::%s\n' "$token"
|
||||
|
||||
if [ -n "${GITHUB_OUTPUT:-}" ]; then
|
||||
{
|
||||
printf 'token=%s\n' "$token"
|
||||
printf 'expires_on=%s\n' "$expires"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
elif [ -n "${GITHUB_ENV:-}" ]; then
|
||||
printf 'CLOUDFLARE_API_TOKEN=%s\n' "$token" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
# Verify immediately, with the token on curl's stdin rather than argv. A runner whose Cloudflare
|
||||
# egress address differs from the address Lambda saw (IPv4 vs IPv6, or a different NAT address)
|
||||
# fails here instead of part way through an upload.
|
||||
verify_url="https://api.cloudflare.com/client/v4/accounts/$account/tokens/verify"
|
||||
if ! verify=$(printf 'header = "Authorization: Bearer %s"\nurl = "%s"\n' "$token" "$verify_url" |
|
||||
curl --config - --proto '=https' --proto-redir '=https' --silent --show-error --fail-with-body --max-time 20); then
|
||||
echo "::error::Cloudflare rejected the freshly minted token. The runner's egress IP to Cloudflare may differ from the IP Lambda saw (IPv4 vs IPv6 or a different NAT address). Use a runner with stable egress." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! printf '%s' "$verify" | jq -e '.success == true and .result.status == "active"' > /dev/null; then
|
||||
echo "::error::Cloudflare did not report the freshly minted token as active." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "::notice::Cloudflare token ready; expires $expires"
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
name: file size
|
||||
|
||||
# The Rust file-size and folder-shape check (scripts/file-size.sh), per pull request and per push
|
||||
# to dev: a few seconds on Linux. It ran inside macos-tests.yml until that moved to a schedule.
|
||||
on:
|
||||
push:
|
||||
branches: [dev]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: file-size-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
size:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- run: bash scripts/file-size.sh
|
||||
@@ -0,0 +1,74 @@
|
||||
name: macOS tests
|
||||
|
||||
# On a schedule and on request, never per pull request or per push (the owner's decision,
|
||||
# 2026-11-12): the test job takes over an hour on a Mac runner, Mac runners are scarce and shared
|
||||
# across the organisation, and changes merge straight after their pull request, so a run per
|
||||
# change (twice: the pull request, then the push to dev) was mostly cancelled or ignored. Every six
|
||||
# hours, `changes` (a Linux job) starts the Mac job only when dev is on a commit no run has tested
|
||||
# to the end yet; workflow_dispatch always tests. The Rust file-size check that also ran here
|
||||
# runs per pull request in file-size.yml.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "41 */6 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
# One run at a time: a newer run cancels an older one still testing.
|
||||
concurrency:
|
||||
group: macos-tests
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
changes:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
test: ${{ steps.check.outputs.test }}
|
||||
steps:
|
||||
- id: check
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
EVENT: ${{ github.event_name }}
|
||||
SHA: ${{ github.sha }}
|
||||
REPO: ${{ github.repository }}
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
run: |
|
||||
# The commit the last run that finished its tests (green or red) tested: rerunning the
|
||||
# same commit tells nothing new. A cancelled run doesn't count.
|
||||
last=$(gh api "repos/$REPO/actions/workflows/macos-tests.yml/runs?branch=dev&per_page=50" \
|
||||
--jq "[.workflow_runs[] | select(.id != $RUN_ID and (.conclusion == \"success\" or .conclusion == \"failure\"))][0].head_sha // empty" || true)
|
||||
if [ "$EVENT" = schedule ] && [ "$last" = "$SHA" ]; then
|
||||
echo "test=false" >> "$GITHUB_OUTPUT"
|
||||
echo "dev is still at ${SHA:0:9}, which the last run tested." >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo "test=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
test:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.test == 'true'
|
||||
runs-on: blacksmith-6vcpu-macos-latest
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
# One job per core: serial builds ran past the timeout with no cache, so no cache was ever saved.
|
||||
CARGO_BUILD_JOBS: 3
|
||||
CARGO_INCREMENTAL: 0
|
||||
CARGO_PROFILE_TEST_DEBUG: 0
|
||||
CARGO_PROFILE_TEST_STRIP: debuginfo
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
cache-on-failure: true
|
||||
# The virtual Metal adapter does not expose TIMESTAMP_QUERY. Keep the
|
||||
# shader freshness, pipeline, rendering, font and menu tests enabled.
|
||||
- run: >-
|
||||
cargo test -p rune -p rune-core -p rune-edit -p rune-gpu -p rune-image -p rune-media -p rune-spell -p rune-text -p rune-kit
|
||||
--features rune/test-gpu-counters,rune-gpu/test-gpu-counters,rune-kit/markdown,rune-kit/mermaid --no-fail-fast --
|
||||
--skip metal::compute_tests::passes_sample_timestamps_at_their_boundaries
|
||||
# Kept outside the main invocation above so rune-ref (`libm/force-soft-floats`, `serde/derive`)
|
||||
# and rune-i18n (`icu_provider/sync`) do not alter the core feature set.
|
||||
- run: cargo test -p rune-ref
|
||||
- run: cargo test -p rune-i18n
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
name: site
|
||||
|
||||
# Deploys the docs site in site/. dev deploys https://dev.anoma.ly/team/rune, production deploys https://anoma.ly/team/rune.
|
||||
on:
|
||||
push:
|
||||
branches: [dev, production]
|
||||
paths:
|
||||
- "site/**"
|
||||
- ".github/workflows/site.yml"
|
||||
|
||||
concurrency:
|
||||
group: site-${{ github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
environment: ${{ github.ref_name == 'dev' && 'dev' || 'release' }}
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read
|
||||
defaults:
|
||||
run:
|
||||
working-directory: site
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- name: Configure AWS credentials
|
||||
uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
|
||||
with:
|
||||
role-to-assume: arn:aws:iam::604439173067:role/github/rune-${{ github.ref_name == 'dev' && 'dev' || 'release' }}
|
||||
role-session-name: site-${{ github.run_id }}
|
||||
aws-region: us-east-1
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
- run: bun install --frozen-lockfile
|
||||
- name: Cloudflare token
|
||||
id: cloudflare-token
|
||||
run: bash "$GITHUB_WORKSPACE/.github/release/cloudflare-token.sh"
|
||||
env:
|
||||
CLOUDFLARE_TOKEN_URL: ${{ vars.CLOUDFLARE_TOKEN_URL }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
- run: bun run deploy:${{ github.ref_name == 'production' && 'production' || 'dev' }}
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ steps.cloudflare-token.outputs.token }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
name: www
|
||||
|
||||
# The public page in www/ is the Rune app in www/app. CI builds it to wasm, has the native build write its static
|
||||
# HTML (`--html`), and deploys: dev to https://dev.anoma.ly/rune, production to https://anoma.ly/rune. Rune itself is
|
||||
# the page, so a push that changes crates/ deploys it too. Pull requests build the dev page and deploy nothing, and
|
||||
# only for a change to the page's own files: a change to crates/ merges straight after its pull request, and the
|
||||
# push to dev builds it then, so building it twice told nothing. A newer push to dev replaces a dev deploy still
|
||||
# running; production always finishes.
|
||||
on:
|
||||
push:
|
||||
branches: [dev, production]
|
||||
paths:
|
||||
- "www/**"
|
||||
- "crates/**"
|
||||
- "scripts/web-build.sh"
|
||||
- "Cargo.toml"
|
||||
- "Cargo.lock"
|
||||
- "rust-toolchain.toml"
|
||||
- ".github/workflows/www.yml"
|
||||
pull_request:
|
||||
paths:
|
||||
- "www/**"
|
||||
- "scripts/web-build.sh"
|
||||
- "rust-toolchain.toml"
|
||||
- ".github/workflows/www.yml"
|
||||
|
||||
concurrency:
|
||||
group: www-${{ github.head_ref || github.ref_name }}
|
||||
cancel-in-progress: ${{ github.ref_name != 'production' }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
BINARYEN_VERSION: "133"
|
||||
MODE: ${{ github.ref_name == 'production' && 'production' || 'dev' }}
|
||||
CARGO_INCREMENTAL: "0"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
environment: ${{ github.ref_name == 'dev' && 'dev' || 'release' }}
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read
|
||||
defaults:
|
||||
run:
|
||||
working-directory: www
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
# Pull requests build and deploy nothing, so they never assume the role.
|
||||
- name: Configure AWS credentials
|
||||
if: github.event_name == 'push'
|
||||
uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
|
||||
with:
|
||||
role-to-assume: arn:aws:iam::604439173067:role/github/rune-${{ github.ref_name == 'dev' && 'dev' || 'release' }}
|
||||
role-session-name: www-${{ github.run_id }}
|
||||
aws-region: us-east-1
|
||||
# rust-toolchain.toml picks the toolchain. rust-src is installed up front: otherwise rustup fetches it mid-build
|
||||
# from parallel rustc calls, which race and fail.
|
||||
- name: Rust toolchain
|
||||
working-directory: .
|
||||
run: |
|
||||
rustup toolchain install
|
||||
rustup target add wasm32-unknown-unknown
|
||||
rustup component add rust-src
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
shared-key: www
|
||||
save-if: ${{ github.event_name == 'push' }}
|
||||
- name: wasm-bindgen version from Cargo.lock
|
||||
id: bindgen
|
||||
working-directory: .
|
||||
run: echo "version=$(grep -A1 '^name = "wasm-bindgen"$' Cargo.lock | sed -n 's/^version = "\(.*\)"/\1/p')" >> "$GITHUB_OUTPUT"
|
||||
- uses: taiki-e/install-action@v2
|
||||
with:
|
||||
tool: wasm-bindgen@${{ steps.bindgen.outputs.version }}
|
||||
- uses: actions/cache@v4
|
||||
id: binaryen
|
||||
with:
|
||||
path: ~/.binaryen
|
||||
key: binaryen-${{ env.BINARYEN_VERSION }}
|
||||
- name: Install binaryen
|
||||
if: steps.binaryen.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
mkdir -p ~/.binaryen
|
||||
curl -fsSL "https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-x86_64-linux.tar.gz" \
|
||||
| tar -xz -C ~/.binaryen --strip-components=1
|
||||
- run: echo "$HOME/.binaryen/bin" >> "$GITHUB_PATH"
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
- run: bun install --frozen-lockfile
|
||||
# The native app (tests and the `--html` export) links winit's keyboard library. Its packages are cached, so a
|
||||
# run doesn't need the Ubuntu mirrors (on 2026-11-11 the runners couldn't resolve them for over an hour, and
|
||||
# every run failed here); a run that must fetch them retries.
|
||||
- uses: actions/cache@v4
|
||||
id: debs
|
||||
with:
|
||||
path: ~/.debs
|
||||
key: debs-libxkbcommon-${{ runner.os }}-${{ runner.arch }}-${{ env.ImageOS }}
|
||||
- name: Native libraries
|
||||
run: |
|
||||
if [ "${{ steps.debs.outputs.cache-hit }}" != true ]; then
|
||||
mkdir -p ~/.debs
|
||||
for attempt in 1 2 3; do
|
||||
sudo apt-get -o Acquire::Retries=3 update &&
|
||||
(cd ~/.debs && apt-get -o Acquire::Retries=3 download libxkbcommon-dev libxkbcommon0) && break
|
||||
[ "$attempt" = 3 ] && exit 1
|
||||
sleep $((attempt * 20))
|
||||
done
|
||||
fi
|
||||
sudo dpkg -i ~/.debs/*.deb
|
||||
- name: Test the page
|
||||
working-directory: .
|
||||
run: cargo test -p rune-www
|
||||
- name: Build
|
||||
run: bun run build --mode "$MODE"
|
||||
- name: Cloudflare token
|
||||
id: cloudflare-token
|
||||
if: github.event_name == 'push'
|
||||
run: bash "$GITHUB_WORKSPACE/.github/release/cloudflare-token.sh"
|
||||
env:
|
||||
CLOUDFLARE_TOKEN_URL: ${{ vars.CLOUDFLARE_TOKEN_URL }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
- name: Deploy
|
||||
if: github.event_name == 'push'
|
||||
run: bunx cf deploy --prebuilt --mode "$MODE"
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ steps.cloudflare-token.outputs.token }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
|
||||
@@ -0,0 +1,17 @@
|
||||
target/
|
||||
perf/autoresearch/
|
||||
perf/kit-diff/
|
||||
perf/live-values/
|
||||
perf/live-edit/
|
||||
/REVIEW-TO-PARENT.md
|
||||
*-FROM-PARENT.md
|
||||
.DS_Store
|
||||
demo/**/*.mp4
|
||||
demo/**/*-strip.png
|
||||
!demo/fx/glow-strip.png
|
||||
!demo/fx/motion-quarter-speed.mp4
|
||||
!demo/opencode/switch-strip.png
|
||||
/captures/
|
||||
/.lab-output/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
Vendored
+71
@@ -0,0 +1,71 @@
|
||||
<!-- tallow -->
|
||||
# Rune
|
||||
|
||||
A Rust GPU UI framework (wgpu, winit) for apps that feel like SwiftUI on iOS at 120 Hz on Mac, Windows, Linux, web and iOS. Views are plain Rust. Apps pin `dev` revs.
|
||||
|
||||
## Layout
|
||||
|
||||
- Core crates: `crates/rune`: layout, runtime, renderer, windows, overlays, dev tooling. `crates/rune-core`: foundation primitives (colour, tokens, themes, shapes, state machines, clocks, tasks, tracked reads, growth, live values, latest-wins requests, marks, dirs, prefs; no GPU or windowing). `crates/rune-gpu`: GPU adapter selection, backend dispatch, device error logging, native Apple Metal backend and analytic GPU springs. `crates/rune-image`: content-addressed image decoding, linear-light mips, pixel buffers, SVG/AVIF codecs, OS app icons and placement math. `crates/rune-spell`: platform spellchecking (Windows `ISpellChecker`, macOS `NSSpellChecker`, web Hunspell). `crates/rune-media`: video and audio playback, zero-copy native surfaces (IOSurface, D3D shared textures, dmabufs), and audio recording. `crates/rune-text`: text shaping, layout, font discovery, glyph rasterization and icons. `crates/rune-edit`: the text editing model (`TextEdit`, keys and modifiers, IME composition, undo history, rich text and its HTML form). `crates/rune-motion`: springs and transitions.
|
||||
- Layering: `rune-motion`, `rune-staging` and `rune-taffy` have no Rune dependencies; `rune-core` depends on `rune-motion`; `rune-gpu` depends on `rune-motion` (and `rune-staging` under `metal-backend`); `rune-image` and `rune-spell` depend on `rune-core`; `rune-text` depends on `rune-core`, `rune-image` and `rune-motion`; `rune-edit` depends on `rune-core` and `rune-text`; `rune-media` depends on `rune-core`, `rune-gpu`, `rune-image` and `rune-staging`; `crates/rune` depends on all of them (plus optional `procwatch`) and re-exports their public APIs so apps depend on `rune` only. Above `rune` sit `rune-kit` (also `rune-motion` and optional `rune-highlights`, `rune-mermaid`), `rune-mermaid`, `rune-knobs`, `rune-luau` and optional `rune-ref`; beside it sit `rune-fx` (`rune-motion`, `rune-staging`), `rune-light` (`rune-staging`), `rune-mac` (`rune-notify`) and `rune-perf` (`procwatch`).
|
||||
- Companion crates: `crates/rune-kit`: components. `crates/rune-mermaid`: Mermaid diagrams (flowcharts, sequence and state diagrams). `crates/rune-i18n`: message catalogs generated from JSON, CLDR plurals and numbers, the system's languages. `crates/rune-fx`, `crates/rune-light`: effects. `crates/rune-ref`: reference renderer. `crates/procwatch`: an app's own memory and CPU (footprint, counting allocator, gauges, warnings, loopback JSON); libc only, no Rune dependency.
|
||||
- `examples/`: apps and labs. `themes/`: themes. `site/`: the docs site (see `site/README.md`).
|
||||
- `vendor/winit`: winit as published plus `vendor/winit.patch` (Windows: no TaskbarList COM call when a window is made, and system DLLs loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`; and `WindowExtWayland::content_corner_radius`, the radius a client-side frame leaves the content's bottom corners to), through `[patch.crates-io]`. When winit is bumped, run `scripts/vendor-winit.sh <new version>` (Git Bash on Windows) and update the `[patch.crates-io]` rev in apps that build Rune.
|
||||
- `vendor/sctk-adwaita`: sctk-adwaita as published plus `vendor/sctk-adwaita.patch` (the client-side frame's one-point border follows the window's rounded bottom corners, and `content_corner_radius` says what radius the content leaves them), through `[patch.crates-io]`. When it is bumped, run `scripts/vendor-sctk-adwaita.sh <new version>` (Git Bash on Windows) and update the `[patch.crates-io]` rev in apps that build Rune.
|
||||
- `vendor/tiny-skia-path`: tiny-skia-path as published plus `vendor/tiny-skia-path.patch` (Skia's own conic splitting and stroker steps, so icons stroke as Chromium's Skia strokes them), a plain path dependency of `crates/rune-text`, not a patch (resvg keeps the published one). When it is bumped, run `scripts/vendor-tiny-skia-path.sh <new version>` (Git Bash on Windows).
|
||||
- `vendor/wgpu-hal`: wgpu-hal as published plus `vendor/wgpu-hal.patch` (`dx12::Instance::expose_adapter`, FXC loaded on first compile, and Windows system DLLs loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`), through `[patch.crates-io]`. When wgpu is bumped, run `scripts/vendor-wgpu-hal.sh <new wgpu-hal version>` (Git Bash on Windows) and update the `[patch.crates-io]` rev in apps that build Rune.
|
||||
- `PLAN.md`: direction and milestones. `research/`: notes behind decisions. `demo/`: images the docs show.
|
||||
|
||||
## Commands
|
||||
|
||||
- `cargo test -p rune -p rune-mermaid -p rune-kit --features rune-kit/markdown,rune-kit/mermaid`
|
||||
- `cargo check --workspace --all-targets`
|
||||
- `bash scripts/check-local.sh` runs opt-in local checks (file sizes, folder shape, public-repo hygiene, `cargo check`, `cargo clippy --lib --bins`; supports `--wasm`, `--all`, `--tests`).
|
||||
- Cargo aliases in `.cargo/config.toml`: `cargo lint`, `cargo lint-all`, `cargo check-wasm`, `cargo check-webgl`, and `cargo test-fast`.
|
||||
- Tests that count GPU work or need wgpu's no-op backend are behind features so plain builds don't compile those backends: add `--features rune/test-gpu-counters,rune-gpu/test-gpu-counters` (and `rune/test-gpu-noop` on Linux) to run them. `rune-ref` and `rune-i18n` are not default members: test them with `-p`.
|
||||
- Tests run in debug. `--release` is incremental, for looking at an app. Benchmarks use `--profile perf`; the runtime bench scripts refuse other builds.
|
||||
- CI's macOS tests (`.github/workflows/macos-tests.yml`) run on a schedule and on `workflow_dispatch`, not per pull request or push: the owner's decision on 2026-11-12. Don't add those triggers back; run the workflow by hand when a change needs it.
|
||||
|
||||
## Changes
|
||||
|
||||
- Work on `dev`. `production` deploys the site.
|
||||
- `dev` is fast-forward-only: never force-push or rewrite it. Apps pin its revs, so a rewrite breaks every app's build on a clean fetch.
|
||||
- For any change that can move an app's output or break its build, add `changelog/unreleased/<YYYY-MM-DD>-<slug>.md` with one top-level bullet, in the style of the `CHANGELOG.md` entries. `scripts/changelog-fold` folds them into `## dev`.
|
||||
- Keep Rust files under 800 non-test lines (`#[cfg(test)]` code excluded); 1,500 is a hard cap. The point is to stop god files and edit collisions, not to chop a file that reads fine as one piece. Older files over the cap are listed in `scripts/file-size-exceptions.txt` with ceilings that only go down. Run `scripts/file-size.sh` to check.
|
||||
- Keep folders shaped by capability: `x.rs` or `x/` beside two or more `x_*.rs` (or three or more `x_*.rs` alone) means move them into `x/`; a folder over 40 source files warns and over 60 is an error (tests aren't counted; `examples/`, `benches/` and `bin/` are skipped). `scripts/folder-shape.sh` runs inside `scripts/file-size.sh`; old violations are in `scripts/folder-shape-exceptions.txt` with ceilings that only go down.
|
||||
- Put tests in a sibling `tests.rs` or `*_tests.rs`, and keep any test file or module under 1,000 lines.
|
||||
- Before adding to a file over the cap, move the area you touch into its own module, in its own PR.
|
||||
- A feature owns its state, keys and registrations so it plugs in with one line. New runtime state goes in the owning subsystem's struct, not a flat `Runtime` field.
|
||||
- In `lib.rs`, keep `mod` and `pub use` lists one item per line, sorted.
|
||||
- Apps build these types as literals, so adding a pub field breaks them: `AppSpec`, `Env`, `Elevation`, `PaletteSeed`, `OverlaySpec`, `TextStyle`, `RunOptions`, `ScrollSpec`, `Span`, `ByteFrame`, `SurfaceDraw`, `LayerSpec`. Add a builder method instead.
|
||||
|
||||
## State
|
||||
|
||||
- Behaviour with modes or phases (hover delays, drags, IME composition, scroll modes, requests and retries) is an explicit state machine: one `enum State` whose variants carry only the data valid in them, and one `fn step(state: &mut State, event: Event) -> Effects<Effect>` (`rune::machine`) that returns effects instead of performing them. No clusters of booleans, `Option`s and timestamps whose combinations encode the mode.
|
||||
- Timers are events: a timed variant stores its `Attempt` and due time on `Tx::clock`/the runtime clock, the caller turns its effect into `Tx::wake_at`, and `poll` (or the runtime's frame) feeds the timer back into `step`. An answer whose attempt the state no longer holds changes nothing.
|
||||
|
||||
## Performance
|
||||
|
||||
App-side rules live in "Launching fast" in `crates/rune/README.md` and the "Launch fast" docs page. In examples and in Rune itself:
|
||||
|
||||
- Start slow work (network, indexing, status items) from `on_ready`, after the first frame. Land state that arrives just after launch with `tx.instant()`, so the first second stays still.
|
||||
- `poll` returns true only when visible state changed, and a loop stops asking for frames when its work ends. An idle window draws nothing.
|
||||
- Read sizes with `Cx::layout_size` or `Cx::layout_with`, not whole rects, so a scroll doesn't rebuild the view every frame. A handler that only moves a live value (scroll, zoom, a transform) calls `Tx::live_only()`.
|
||||
- Build only mounted rows: `virtual_rows`, with row content built inside its closure; `memo` for rows that rarely change.
|
||||
- Bound every cache in entries and in bytes, counting decoded pixels, not encoded size.
|
||||
- Take numbers from `--profile perf`. Compare paired, alternating runs by median, keep outliers, and say what a headless number leaves out (GPU upload, presentation).
|
||||
- A motion change passes `scripts/motion-audit` with its scenario added. Fix a finding in Rune rather than allowing it.
|
||||
- No file I/O in the frame loop: never read, stat, write, sync or rename a file on the UI thread during frames, input or animation. On Windows each open and `MoveFileExW` rename runs antivirus filter callbacks and can fail with a sharing violation.
|
||||
- No background rewrite churn: diagnostics and logs (`rune-perf`, traces) keep one open handle and write a summary on an incident or at shutdown, never on a repeating timer while idle.
|
||||
- Keep persistence APIs free of `std::fs` and `PathBuf` so `wasm32` targets can back them with browser storage.
|
||||
|
||||
## This repo is public
|
||||
|
||||
Everything pushed stays public in history. Before committing, run `git diff --cached | rg -n '/Users/|/private/var/|\.ts\.net|ses_[A-Za-z0-9]{20}'` and keep these out:
|
||||
|
||||
- secrets, tokens and credential file contents;
|
||||
- home folder and temp paths, machine names and tailnet hostnames. Write repo-relative paths, and use `host.example.ts.net` in tests;
|
||||
- session IDs, chat or Slack links, and quotes from private sessions, chats or calls;
|
||||
- teammates' names attached to their plans, opinions or internal discussions, and private repos or branches;
|
||||
- quotes of, or citations to, internal guides and rules. Say what the code does and why on its own terms;
|
||||
- agent handoff notes (`REVIEW-TO-PARENT.md` and similar), raw evidence, logs and benchmark dumps;
|
||||
- generated videos and strips nothing links to. Commit the stills a doc shows.
|
||||
Vendored
+3239
File diff suppressed because it is too large.
Load diff
Vendored
+1
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
+4008
-3329
File diff suppressed because it is too large.
Load diff
Vendored
+293
@@ -0,0 +1,293 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = [
|
||||
"crates/rune",
|
||||
"crates/rune-core",
|
||||
"crates/rune-edit",
|
||||
"crates/rune-gpu",
|
||||
"crates/rune-image",
|
||||
"crates/rune-media",
|
||||
"crates/rune-spell",
|
||||
"crates/rune-text",
|
||||
"crates/rune-ref",
|
||||
"crates/rune-motion",
|
||||
"crates/rune-i18n",
|
||||
"crates/rune-staging",
|
||||
"crates/rune-kit",
|
||||
"crates/rune-highlights",
|
||||
"crates/rune-fx",
|
||||
"crates/rune-light",
|
||||
"crates/procwatch",
|
||||
"crates/rune-register",
|
||||
"crates/rune-knobs",
|
||||
"crates/rune-mac",
|
||||
"crates/rune-notify",
|
||||
"crates/rune-mermaid",
|
||||
"crates/rune-perf",
|
||||
"crates/rune-luau",
|
||||
"crates/rune-taffy",
|
||||
"themes/opencode",
|
||||
"examples/hello",
|
||||
"examples/web-hello",
|
||||
"examples/web-showcase",
|
||||
"www/app",
|
||||
"examples/todo",
|
||||
"examples/settings",
|
||||
"examples/playground",
|
||||
"examples/knobs",
|
||||
"examples/kit-gallery",
|
||||
"examples/background",
|
||||
"examples/live-values",
|
||||
"examples/shapes",
|
||||
"examples/overlay",
|
||||
"examples/overlay-lab",
|
||||
"examples/lab",
|
||||
"examples/showreel",
|
||||
"examples/video-player",
|
||||
"examples/video-tiles",
|
||||
"examples/cursed-settings",
|
||||
"examples/drag-out",
|
||||
"examples/sketch",
|
||||
"examples/drop-files",
|
||||
"examples/rich-clipboard",
|
||||
"examples/matched",
|
||||
"examples/launcher",
|
||||
"examples/glass-card",
|
||||
"examples/glass-panel",
|
||||
"examples/frosted-bar",
|
||||
"examples/odometer",
|
||||
"examples/motion-bento",
|
||||
"examples/motion-bento/chaos",
|
||||
"examples/site-scenes",
|
||||
"examples/luau-panel",
|
||||
]
|
||||
# Default cargo check/test targets: the core framework, libraries and theme.
|
||||
# Excludes examples/*, www/app, rune-luau (C++ Luau build via cc/mlua), rune-notify/rune-mac
|
||||
# (WinRT features on `windows`), rune-ref (`libm/force-soft-floats` and `serde/derive`), and
|
||||
# rune-i18n (`icu_provider/sync`, `writeable/default`, `smallvec/const_generics`); pass
|
||||
# `--workspace` to check everything.
|
||||
default-members = [
|
||||
"crates/rune",
|
||||
"crates/rune-core",
|
||||
"crates/rune-edit",
|
||||
"crates/rune-gpu",
|
||||
"crates/rune-image",
|
||||
"crates/rune-media",
|
||||
"crates/rune-spell",
|
||||
"crates/rune-text",
|
||||
"crates/rune-motion",
|
||||
"crates/rune-staging",
|
||||
"crates/rune-kit",
|
||||
"crates/rune-highlights",
|
||||
"crates/rune-fx",
|
||||
"crates/rune-light",
|
||||
"crates/procwatch",
|
||||
"crates/rune-register",
|
||||
"crates/rune-knobs",
|
||||
"crates/rune-mermaid",
|
||||
"crates/rune-perf",
|
||||
"crates/rune-taffy",
|
||||
"themes/opencode",
|
||||
]
|
||||
exclude = ["tools/rune-dev-guard", "tools/ratex-math-wasm", "tools/ratex-math-wasm/pack", "vendor/accesskit_macos", "vendor/accesskit_windows", "vendor/parley_engine", "vendor/sctk-adwaita", "vendor/tiny-skia-path", "vendor/wgpu-hal", "vendor/winit"]
|
||||
|
||||
# wgpu-hal as published plus `vendor/wgpu-hal.patch`: `dx12::Instance::expose_adapter` (a `wgpu::Adapter` for the
|
||||
# one adapter Rune picks through DXGI, with no device made on the others, `crates/rune-gpu/src/pick.rs`), FXC loaded on
|
||||
# the first compile rather than with the instance (Rune's uber shader is precompiled), partial presents
|
||||
# (`Surface::set_present_rects`: `Present1` dirty rectangles on a sequential flip-model swap chain, for
|
||||
# `render::damaged`), Windows system DLLs (`d3d12.dll`, `dxgi.dll`, `dcomp.dll`, `d3dcompiler_47.dll`,
|
||||
# `opengl32.dll`) loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`, a removed D3D12 device's work left
|
||||
# pending rather than read as finished (`Device::reached`; Rune sees the removal through
|
||||
# `rune_gpu::health::removed`), and GPU-written drain markers (`WriteBufferImmediate`) on software
|
||||
# adapters (`DXGI_ADAPTER_FLAG_SOFTWARE`, WARP) so releasing a removed WARP device or unconfiguring
|
||||
# its surface waits until queued command lists finish executing instead of freeing resources under
|
||||
# its worker threads (`DrainTracker`; hardware adapters pay zero marker cost, while skipping
|
||||
# `ExecuteCommandLists` and `allocator.Reset()` once removed on every adapter). Re-made by
|
||||
# `scripts/vendor-wgpu-hal.sh <version>` when wgpu is bumped. An app that builds Rune patches it too:
|
||||
# a dependency's `[patch]` doesn't apply to the workspace that depends on it.
|
||||
[patch.crates-io]
|
||||
wgpu-hal = { path = "vendor/wgpu-hal" }
|
||||
# winit as published plus `vendor/winit.patch`: on Windows a new window isn't added again to the
|
||||
# taskbar it's already on (that took CoInitializeEx and a TaskbarList COM object, about 7,800 µs
|
||||
# and nine shell DLLs, before every window's first frame), a window given a position is made there, so it is
|
||||
# born at that display's scale instead of crossing to it and being resized, and Windows system DLLs
|
||||
# (`uxtheme.dll`, `user32.dll`, `shcore.dll`, `ntdll.dll`) load via `LoadLibraryExA` with
|
||||
# `LOAD_LIBRARY_SEARCH_SYSTEM32`; and
|
||||
# `WindowExtWayland::content_corner_radius` tells an app the radius its content leaves its bottom
|
||||
# corners to while a client-side frame rounds the window (see `vendor/sctk-adwaita`). Re-made by
|
||||
# `scripts/vendor-winit.sh <version>` when winit is bumped; apps that build Rune patch it too.
|
||||
winit = { path = "vendor/winit" }
|
||||
# sctk-adwaita as published plus `vendor/sctk-adwaita.patch`: the visible one-point border a
|
||||
# Wayland client-side frame draws follows the window's rounded bottom corners, as the headerbar it
|
||||
# draws above them rounds the top two, instead of drawing a square L over the shadow's rounded
|
||||
# cut-out; and `AdwaitaFrame::content_corner_radius` says what radius the content's own bottom
|
||||
# corners take, for the app to clear outside (`window/surface/corners.rs`). Re-made by
|
||||
# `scripts/vendor-sctk-adwaita.sh <version>` when sctk-adwaita is bumped; apps that build Rune
|
||||
# patch it too.
|
||||
sctk-adwaita = { path = "vendor/sctk-adwaita" }
|
||||
# parley_engine as published plus `vendor/parley_engine.patch`: UAX #9 rule L1 for a paragraph's
|
||||
# trailing whitespace and isolates (BidiTest.txt 770,241 of 770,241; 644,283 without it), and
|
||||
# shaping that stops redoing work from the same inputs: an analyzer keeps the ICU segmenters it
|
||||
# made, and a run's or a style's font metrics are made once per font instance and size (14% off
|
||||
# a text's shaping, layouts identical). Re-made by `scripts/vendor-parley-engine.sh <version>` when parley is bumped; apps that build
|
||||
# Rune patch it too.
|
||||
parley_engine = { path = "vendor/parley_engine" }
|
||||
# accesskit_windows as published plus `vendor/accesskit_windows.patch`: headings and landmarks reach
|
||||
# UI Automation (HeadingLevel, LandmarkType, LocalizedLandmarkType), which Narrator's and NVDA's
|
||||
# heading and landmark navigation read; and a field past Rune's 64 KiB text-run limit keeps its text
|
||||
# pattern, its lines answered from its value when a reader asks (`src/long_text.rs`). Re-made by
|
||||
# `scripts/vendor-accesskit-windows.sh <version>`
|
||||
# when AccessKit is bumped; apps that build Rune patch it too.
|
||||
accesskit_windows = { path = "vendor/accesskit_windows" }
|
||||
# accesskit_macos as published plus `vendor/accesskit_macos.patch`: headings reach NSAccessibility as
|
||||
# AppKit's `AXHeading` with their level as the value (the published role, `Heading`, is none VoiceOver
|
||||
# knows), so VoiceOver's rotor and VO-Command-H find them and say their level; and the accessibility
|
||||
# children, focused element and hit test leave the adapter alone off the main thread, which AppKit
|
||||
# calls them on while the process queries itself, so they answer from the superclass instead of
|
||||
# racing or panicking on the main thread's borrow; and a field past Rune's 64 KiB text-run limit keeps
|
||||
# its line, string and selection ranges, answered from its value when a reader asks. Re-made by
|
||||
# `scripts/vendor-accesskit-macos.sh <version>` when AccessKit is bumped; apps that build Rune patch it too.
|
||||
accesskit_macos = { path = "vendor/accesskit_macos" }
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Internal workspace crates.
|
||||
procwatch = { path = "crates/procwatch" }
|
||||
rune = { path = "crates/rune", default-features = false }
|
||||
rune-core = { path = "crates/rune-core" }
|
||||
rune-edit = { path = "crates/rune-edit" }
|
||||
rune-fx = { path = "crates/rune-fx" }
|
||||
rune-gpu = { path = "crates/rune-gpu", default-features = false }
|
||||
rune-highlights = { path = "crates/rune-highlights" }
|
||||
rune-image = { path = "crates/rune-image", default-features = false }
|
||||
rune-kit = { path = "crates/rune-kit", default-features = false }
|
||||
rune-knobs = { path = "crates/rune-knobs" }
|
||||
rune-light = { path = "crates/rune-light" }
|
||||
rune-luau = { path = "crates/rune-luau" }
|
||||
rune-media = { path = "crates/rune-media", default-features = false }
|
||||
rune-mermaid = { path = "crates/rune-mermaid" }
|
||||
rune-motion = { path = "crates/rune-motion" }
|
||||
rune-notify = { path = "crates/rune-notify" }
|
||||
rune-ref = { path = "crates/rune-ref" }
|
||||
rune-spell = { path = "crates/rune-spell" }
|
||||
rune-staging = { path = "crates/rune-staging" }
|
||||
rune-taffy = { path = "crates/rune-taffy" }
|
||||
rune-text = { path = "crates/rune-text", default-features = false }
|
||||
rune-theme-opencode = { path = "themes/opencode" }
|
||||
|
||||
# Shared external crates.
|
||||
blake3 = "1"
|
||||
block2 = "0.6"
|
||||
bytemuck = { version = "1.25", features = ["derive"] }
|
||||
half = "2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
js-sys = "0.3"
|
||||
libc = "0.2"
|
||||
miniz_oxide = { version = "0.9", default-features = false, features = ["with-alloc"] }
|
||||
objc2 = "0.6"
|
||||
objc2-app-kit = { version = "0.3", default-features = false }
|
||||
objc2-core-foundation = { version = "0.3", default-features = false }
|
||||
objc2-core-graphics = { version = "0.3", default-features = false }
|
||||
objc2-core-video = { version = "0.3", default-features = false }
|
||||
objc2-foundation = { version = "0.3", default-features = false }
|
||||
objc2-metal = { version = "0.3", default-features = false }
|
||||
parley = { version = "0.12", default-features = false }
|
||||
parley_engine = { version = "0.12", default-features = false }
|
||||
png = "0.18"
|
||||
pollster = "1"
|
||||
resvg = { version = "0.45", default-features = false }
|
||||
rustc-hash = "2"
|
||||
serde = "1"
|
||||
serde_json = "1"
|
||||
skrifa = "0.44"
|
||||
swash = "0.2.10"
|
||||
taffy = { version = "0.15", default-features = false }
|
||||
tiny-skia = { version = "0.11", default-features = false, features = ["std", "simd"] }
|
||||
unicode-segmentation = "1.13"
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
wasmi = { version = "1.1", default-features = false }
|
||||
web-sys = "0.3"
|
||||
wgpu = { version = "~30.0.1", default-features = false }
|
||||
wgpu-naga-bridge = "~30.0.1"
|
||||
windows = "0.62"
|
||||
windows-numerics = "0.3"
|
||||
windows-core = "0.62"
|
||||
windows-sys = "0.61"
|
||||
winit = { version = "0.30.13", default-features = false }
|
||||
zeroize = "1.8"
|
||||
|
||||
# Full debug info for the workspace crates made a single `rune` test build use 18-23 GB of RAM;
|
||||
# line tables keep backtraces and file:line in panics at a fraction of that.
|
||||
[profile.dev]
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.dev.package."*"]
|
||||
debug = false
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 16
|
||||
incremental = true
|
||||
|
||||
# Keep the optional `math` sandbox interpreter compact (saves ~558 KiB in FAT-LTO release builds
|
||||
# with zero effect on the UI thread since math typesets on a background worker and caches results).
|
||||
[profile.release.package.wasmi]
|
||||
opt-level = "z"
|
||||
[profile.release.package.wasmi_core]
|
||||
opt-level = "z"
|
||||
[profile.release.package.wasmi_ir]
|
||||
opt-level = "z"
|
||||
[profile.release.package.wasmi_collections]
|
||||
opt-level = "z"
|
||||
[profile.release.package.wasmparser]
|
||||
opt-level = "z"
|
||||
|
||||
# Benchmarks and perf numbers. Same codegen as release, without incremental, which can move
|
||||
# frame timings. The runtime bench scripts refuse binaries built with any other profile.
|
||||
[profile.perf]
|
||||
inherits = "release"
|
||||
opt-level = 3
|
||||
codegen-units = 16
|
||||
lto = false
|
||||
debug = false
|
||||
incremental = false
|
||||
|
||||
# `cargo bench` inherits release; scripts/check-reference-instructions.sh compares its instruction
|
||||
# counts across revisions.
|
||||
[profile.bench]
|
||||
incremental = false
|
||||
|
||||
[profile.rune-hot]
|
||||
inherits = "dev"
|
||||
debug = 0
|
||||
incremental = true
|
||||
|
||||
[profile.rune-hot.package.png]
|
||||
opt-level = 3
|
||||
|
||||
[profile.rune-hot.package.fdeflate]
|
||||
opt-level = 3
|
||||
|
||||
[workspace.lints.rust]
|
||||
# shared-lints begin
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
unused_must_use = "deny"
|
||||
# shared-lints end
|
||||
unsafe_code = "deny" # pure-Rust crates use #![forbid(unsafe_code)]; FFI/SIMD leaf modules opt in locally
|
||||
|
||||
[workspace.lints.clippy]
|
||||
# shared-lints begin
|
||||
await_holding_lock = "deny"
|
||||
await_holding_refcell_ref = "deny"
|
||||
dbg_macro = "deny"
|
||||
disallowed_methods = "deny"
|
||||
disallowed_types = "deny"
|
||||
expect_used = "warn"
|
||||
let_underscore_must_use = "deny"
|
||||
todo = "warn"
|
||||
undocumented_unsafe_blocks = "deny"
|
||||
unwrap_used = "warn"
|
||||
# shared-lints end
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Anomaly
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+617
@@ -0,0 +1,617 @@
|
||||
# Rune: plan
|
||||
|
||||
*Research notes behind every claim are in [`research/`](research/). Numbers marked "target" are commitments to
|
||||
measure against, not results.*
|
||||
|
||||
## The short version
|
||||
|
||||
Rune is a Rust UI framework with its own renderer, text, layout, state,
|
||||
animation and platform shells, built to feel like SwiftUI-on-iOS at 120 Hz and to be written and checked by agents.
|
||||
|
||||
**Direction:** Rune apps carry **their own design language on every
|
||||
platform, Mac included**, rather than imitating each OS. Rune itself bakes in no brand: it ships a token-driven theming
|
||||
system, and OpenCode's theme is the first theme built on it and the reference example. The flagship test is
|
||||
**recreating OpenCode Desktop** in Rune and raising its bar, which makes Windows and Linux
|
||||
first-class from the start. Native stays where it's behaviour, not looks: text input/IME, accessibility, window
|
||||
management, clipboard, scroll momentum. A Rust component library with the same names as `@opencode/ui`, gallery
|
||||
and screenshot tests, and Hex Settings as the first real screen fold in here instead of becoming a second stack on
|
||||
Slint.
|
||||
|
||||
| Layer | Pick | Instead of |
|
||||
|---|---|---|
|
||||
| Language | Rust (2024), thin `objc2`/Swift shims on Apple | Zig, C++, Swift, Mojo |
|
||||
| GPU | wgpu on every platform first (one backend ships Mac, Windows, Linux and web); a raw Metal backend later only where a measured need shows up (live-resize sync, IOSurface video), via wgpu-hal escape hatches first | Raw Metal first, Vulkan/D3D12 by hand |
|
||||
| Renderer | One instanced "uber-quad" SDF pass + glyph atlas + Slug for big/animated text and icons + `vello_gpu` sparse strips for complex vectors; soft-edge masks in-shader on every clip | Full compute Vello, Skia, MSAA path textures |
|
||||
| Look | Unbranded core with a token-driven theming system (semantic tokens, themes with light/dark, runtime switching, codegen); the same look on every platform. OpenCode's theme (from `@opencode/ui`) is the first theme and the main example, kept outside the core | A theme baked into the framework; per-OS native look; Liquid Glass as the base (it's an optional Apple extra) |
|
||||
| Text | Parley + HarfRust + skrifa + fontique, GPUI-style two-tier line cache, kitlangton/gpui glyph dilation | CoreText-only, cosmic-text |
|
||||
| Text editing / IME | Zed's `sum_tree` + rope; each platform's own text protocol, implemented directly (`NSTextInputClient`, `UITextInput`, …) | winit's IME, a hidden native text field |
|
||||
| Layout | Taffy (flex, grid, block) on Rune's own node arena, plus a sum-tree height index for huge lists | Own layout engine, SwiftUI-style proposals |
|
||||
| State | Keyed retained tree rebuilt from plain view functions; typed models; reads subscribe; handlers queued with `&mut` | Signals, GPUI entities, immediate mode |
|
||||
| Animation | Render thread owns the presented tree; every property is an analytic spring track (duration + bounce, SwiftUI's formula) that retargets with velocity | Animating through view re-renders on the main thread |
|
||||
| Accessibility | AccessKit, and the same tree is the agent inspector's tree | Own a11y bridges |
|
||||
| Shells | winit to start (the prototype runs on it); own thin shells per platform (borrowing from Zed's Apache-2.0 `gpui_macos`/`gpui_windows`/`gpui_linux`/`gpui_ios`/`gpui_web`) as soon as text input lands, because winit's IME is incomplete | winit forever, SDL3 |
|
||||
| Hot reload | Tokens and live literals with no rebuild (≤ 100 ms), subsecond hot-patching for structural Rust edits on Mac (~1 s measured, goal 300 ms), **split-process dev mode** for the iPhone (renderer on the phone, app code on the Mac) | A view DSL interpreter, code loading on the device |
|
||||
| Platform order | macOS + Windows + Linux together (one wgpu backend) → web (docs site, demos) → iOS → Android | |
|
||||
|
||||
**Top three risks:** text input and text quality (IME on three desktops, then iOS `UITextInput`), matching
|
||||
OpenCode Desktop's Chromium-rendered look closely enough (text above all), and sheer scope.
|
||||
|
||||
**First milestones:** Rune's theming system plus an OpenCode theme generated from `@opencode/ui` as its first
|
||||
consumer, and a component gallery styled by it; Hex's Settings as the first real screen on Mac, Windows and Linux; then OpenCode Desktop's main screens.
|
||||
A docs/marketing site comes first to explain it.
|
||||
|
||||
---
|
||||
|
||||
## 1. Why build this at all
|
||||
|
||||
Kit has rebuilt the same small surfaces three times in ten days:
|
||||
the Scrawl pill went GPUI → hand-written Metal → SwiftUI helper process, the launcher app went GPUI → SwiftUI with a
|
||||
Core Animation glass morph, and Hex's native branch stalled because Hex also ships on Windows and Linux. Each time,
|
||||
the reasons were the same:
|
||||
|
||||
1. **No backdrop or glass.** GPUI draws one forward pass into one layer; Liquid Glass only exists in the window server.
|
||||
2. **Animation waited behind the main thread.** The Metal pill dropped 85 frames on finish until it got its own
|
||||
display-link thread.
|
||||
3. **Windows and focus were wrong for HUDs and launchers** (late focus events, Dock policy, no non-activating panels,
|
||||
per-frame window resizes).
|
||||
4. **Text looked thin and colours were off,** and unseen glyphs stalled the first frame by ~13 ms.
|
||||
5. **No springs or layout animation,** so every app hand-rolled them.
|
||||
6. **Upstream was frozen** at 0.2.2 for Kit's apps, so every fix lived in a fork.
|
||||
|
||||
Upstream GPUI has since moved a lot: Zed's tree at `5447804` has `gpui_ios`, `gpui_web`, a wgpu backend,
|
||||
`spring.rs`, AccessKit and subsecond hot reload (verified in a clone). It still redraws the whole window every dirty
|
||||
frame, has no layer compositing or group opacity, runs animations by re-rendering views on the main thread, and
|
||||
panics on re-entrant entity borrows ([01](research/01-gpui-zed-warp.md)). Those are the exact things that sent Kit
|
||||
to Apple frameworks, and they're architectural. **Verdict: don't fork GPUI; start fresh and lift its best parts**
|
||||
(rope/sum_tree, BoundsTree, line layout cache, the macOS/iOS IME code, the web textarea bridge, the shader fixes in
|
||||
Kit's fork) under its Apache-2.0 licence.
|
||||
|
||||
## 2. Tenets
|
||||
|
||||
1. **Feel is the product.** 120 Hz, interruptible springs, nothing pops, jumps or hard-clips. Kit's motion rules
|
||||
are runtime defaults, not discipline.
|
||||
2. **Animation never runs through app code.** Views state targets; the render thread animates.
|
||||
3. **Everything observable.** Every frame, node, layout rect, spring and timing can be queried, traced and replayed.
|
||||
The agent's view of the app is the same tree as accessibility's.
|
||||
4. **One way to do things.** Small explicit APIs, no macro DSL for views, errors that say how to fix.
|
||||
5. **Native behaviour, one look.** Text input, accessibility, scroll momentum, clipboard and window behaviour are
|
||||
native per platform. Controls, type, motion and materials come from the app's theme, the same on every platform,
|
||||
Mac included. The framework ships no brand of its own.
|
||||
6. **Owned, not wrapped.** Depend on foundational crates (Taffy, Parley, AccessKit), never on another UI framework.
|
||||
7. **Optimise for performance, correctness, speed of change and prototyping; not for human readability**.
|
||||
Agents write and maintain the code, so:
|
||||
- **Fast path plus reference path.** Each hard subsystem (layout, text, renderer, springs) has a slow, obviously
|
||||
correct reference implementation (CPU, no tricks) and a fast one (SoA, SIMD, `unsafe` where measured, specialised,
|
||||
duplicated). Every change differential-tests the fast one against the reference on generated inputs. Correctness
|
||||
comes from the reference and the oracles, not from the fast code being easy to read.
|
||||
- **Data-oriented everything:** flat arenas indexed by ids, struct-of-arrays, no `Rc`/`RefCell`, zero allocation
|
||||
per frame (enforced by a counting allocator in tests), precomputed tables, pipelines built ahead of time.
|
||||
- **Specialise by codegen, not by generics.** Generated, repetitive, per-component code is fine; deep trait towers
|
||||
and proc-macro DSLs are not, because they slow compiles and bury errors. Debug builds stay type-erased and fast
|
||||
to compile; release builds specialise.
|
||||
- **Edits are safe because checks are instant:** invariants as `debug_assert`s everywhere, scenes, goldens,
|
||||
motion/layout lint and exact perf counters run on every change, so an agent sees breakage in seconds.
|
||||
- **Comments state invariants and intent for the next agent,** not prose for a human reader.
|
||||
- **Perf is measured by counts** (instructions, instances, glyphs, layout nodes, allocations) so gates are exact
|
||||
and bisectable; wall-clock numbers come from reserved hardware.
|
||||
- **Prototypes are cheap and throwaway:** live literals, scenes, the playground and hot reload make trying ten variants
|
||||
faster than debating one.
|
||||
|
||||
## 3. Architecture
|
||||
|
||||
```
|
||||
┌──────────────────────── dev only: same protocol over USB/Wi-Fi ────────────────────────┐
|
||||
│ │
|
||||
┌────────────────┴─────────────────────────────┐ commands: tree diff, ┌──────────────────────┴─────────────────────────┐
|
||||
│ APP SIDE (platform main thread by default) │ layout rects, targets, │ RENDER THREAD (display-link paced) │
|
||||
│ │ springs, text runs │ │
|
||||
│ models (typed state, keyed by stable ids) │ ───────────────────────────────▶ │ presented tree (what's on screen right now) │
|
||||
│ view fns → keyed El tree → diff │ │ property tracks: analytic springs, retarget │
|
||||
│ Taffy layout at the *target* state │ ◀─────────────────────────────── │ presence (exiting nodes), layout edge tracks │
|
||||
│ Parley shaping, line cache │ events: hits, gestures, │ scroll physics, drag bindings (1:1, local) │
|
||||
│ handlers: queued, get &mut model │ settles, presented-frame ids│ scene build → instance buffers │
|
||||
│ AccessKit tree updates │ │ encode (Metal / wgpu) → present │
|
||||
└──────────────┬───────────────────────────────┘ └──────────────┬─────────────────────────────────┘
|
||||
│ platform calls │ CATransaction: Metal drawable +
|
||||
┌──────────────┴───────────────────────────────┐ ┌───────────────┴────────────────────────────────┐
|
||||
│ SHELL (per platform) │ │ NATIVE LAYERS (Apple) │
|
||||
│ windows/panels, menus, clipboard, DnD, │ │ NSGlassEffectView / UIGlassEffect underlays, │
|
||||
│ IME protocol, a11y adapter, lifecycle │ │ AVPlayerLayer, MapKit; masks driven per frame │
|
||||
└──────────────────────────────────────────────┘ └────────────────────────────────────────────────┘
|
||||
background pool: image decode, big-paragraph shaping, vector flattening, file IO
|
||||
inspector socket (dev + test builds): tree, rects, a11y, source locations, springs, timings, traces, input injection
|
||||
```
|
||||
|
||||
The one boundary that matters is the **command channel between the app side and the render thread**. It carries
|
||||
tree diffs, target layout rects, shaped text runs and spring targets one way, and hits, gesture results, settles and
|
||||
presented-frame ids the other. Three things fall out of making it a real, serializable protocol:
|
||||
|
||||
- **Animations survive a busy app.** When one value animates, the app side does no work at all: no view re-run, no
|
||||
layout, no diff ([06](research/06-reactivity-animation.md)).
|
||||
- **The iPhone hot-reload path.** In dev, the channel can run over USB: the renderer runs on the phone and the app
|
||||
side runs on the Mac, where subsecond hot-patches it (§5).
|
||||
- **Agents and tests get the same stream.** Recording the channel gives deterministic replay, frame traces and an
|
||||
inspector for free (§6).
|
||||
|
||||
## 4. Each layer
|
||||
|
||||
### 4.1 Language: Rust
|
||||
|
||||
Rust is the only option with production text, layout and accessibility crates (Taffy, Parley, HarfRust, fontations,
|
||||
AccessKit), no GC, reach to every target including wasm, and a working hot-patcher (subsecond). Agents write it well;
|
||||
the borrow checker is the main cost, which the state model below is designed around (no `RefCell` re-entry, no
|
||||
borrows held across async). Zig lacks the ecosystem and a dependable incremental patch path on Mach-O; Swift is great
|
||||
on Apple and weak everywhere else; C++ gives up safety and agent reliability for nothing; Mojo isn't a UI language
|
||||
yet ([04 §1](research/04-language-gpu-renderer.md)). Swift is used only for thin host pieces Apple exposes no other
|
||||
way (SwiftUI-only glass morphing, the `RuneView` representable).
|
||||
|
||||
### 4.2 GPU API: wgpu everywhere, raw Metal on Apple only where measured
|
||||
|
||||
wgpu runs on every platform, since the desktop trio ships together. Zed's own move from blade to wgpu in 2026 is
|
||||
the evidence that it's good enough ([04 §2](research/04-language-gpu-renderer.md),
|
||||
[01](research/01-gpui-zed-warp.md)). A raw Metal (`objc2-metal`) backend behind a thin internal trait is a later
|
||||
optimization, added only where measurements show wgpu falls short: precompiled `.metallib` (no shader compile at
|
||||
launch), `IOSurface` zero-copy video, framebuffer fetch for cheap group opacity on Apple silicon, and exact control
|
||||
of `CAMetalLayer` presentation (`presentsWithTransaction`, drawable count). Rejected: hand-written Vulkan/D3D12 (Zed
|
||||
just deleted theirs).
|
||||
|
||||
### 4.3 Renderer
|
||||
|
||||
A typical frame is one render pass. Six primitives, all instanced, all clipped by a GPU clip table that gives
|
||||
rounded clips **and soft gradient edges per side for free**, so "no hard edges" costs nothing extra
|
||||
([04 §3](research/04-language-gpu-renderer.md)):
|
||||
|
||||
| Primitive | Does |
|
||||
|---|---|
|
||||
| `UberQuad` | rounded/squircle rects, borders, analytic Gaussian shadows (inner/outer), Oklab gradients with dithering, surface material |
|
||||
| `AtlasSprite` | body text from a greyscale glyph atlas, images, emoji |
|
||||
| `Slug` | big, rotating or scaling text and icons straight from Bézier curves (patent dedicated to the public domain on 2026-03-17; reference shaders MIT/Apache) |
|
||||
| `SparseStrips` | complex vector art via `vello_gpu` (Linebender moved compute Vello to `research/` in 2026) |
|
||||
| `Backdrop` | in-app blur/saturate of what's already drawn (dual Kawase, scissored), with Scrawl's peak-alpha boost for legible blurred text |
|
||||
| `NativeSurface` | zero-copy video and camera frames |
|
||||
|
||||
Plus: offscreen layers only when needed (group opacity with blur, cached complex subtrees), dirty-rect scissoring
|
||||
for idle-ish frames, linear-light blending, Display P3, and dithering on every gradient and shadow (Kit's GPUI fork (`kitlangton/gpui`)
|
||||
fixes, now partly upstream).
|
||||
|
||||
**Frame pacing and latency.** `CADisplayLink` with `preferredFrameRateRange` up to 120 while anything animates, zero
|
||||
ticks at rest. Discrete input (key, click) draws immediately instead of waiting for the next tick, with at most two
|
||||
drawables in flight. Animation time is the display link's *target* timestamp, so a late frame still lands on the
|
||||
right pose. `CAMetalDisplayLink` is suspect: one 2026 measurement shows windowed macOS scheduling it 3–5 refreshes
|
||||
ahead ([04 §4](research/04-language-gpu-renderer.md)); spike S3 checks this before we rely on either.
|
||||
|
||||
### 4.4 Compositing with native layers (Apple)
|
||||
|
||||
*Optional now that Rune carries OpenCode's look on every platform; kept for Kit's Mac surfaces (M4).*
|
||||
|
||||
Rune can't draw Liquid Glass: the shaders that sample behind the window live in the window server. So the Apple
|
||||
shell composes **native underlays and overlays** with Rune's Metal layer: a system glass view sits behind a
|
||||
transparent region of the Metal layer, and its shape is driven by a mask layer that the render thread updates in the
|
||||
same `CATransaction` as the drawable (`presentsWithTransaction`). This is how Scrawl's Metal pill already hosts
|
||||
`NSGlassEffectView`, and the launcher's CA glass recipe is the fallback material backend
|
||||
([11 §2](research/11-platform-shells.md)). Popovers, HUDs and pills use a
|
||||
fixed, transparent, max-size surface with shape hit-testing, never per-frame window resizes.
|
||||
|
||||
Two caveats: glass *morphing* between shapes is SwiftUI-only on iOS, and NSViews are main-thread objects. Spike S2
|
||||
measures whether a glass underlay can track a Rune-animated shape at 120 Hz with the main thread blocked.
|
||||
|
||||
### 4.5 Text
|
||||
|
||||
- **Fonts and shaping:** HarfRust (pure-Rust HarfBuzz port), skrifa/fontations (hinting, variable fonts, COLRv1),
|
||||
fontique (system fonts and fallback), plus SF's tracking tables on Apple.
|
||||
- **Layout:** Parley for bidi, line breaking, rich text and inline boxes, wrapped in GPUI's two-tier cache (shaped
|
||||
runs separate from wrap points), so resizing a container never re-shapes text
|
||||
([05](research/05-text-ime-a11y-layout.md)). Overflow is a soft fade mask by default, never an ellipsis.
|
||||
- **Rasterizing:** greyscale atlas, 4× horizontal subpixel positioning, and the kitlangton/gpui luminance glyph dilation
|
||||
that fixed "thin text" by matching macOS font smoothing. Text under a scale animation switches to Slug outlines so
|
||||
springs never re-rasterize glyphs every frame.
|
||||
- **Quality bar:** a side-by-side diff against CoreText on the same strings (spike S5). If Rune text doesn't match
|
||||
native on a Retina Mac, nothing else matters.
|
||||
|
||||
### 4.6 Text editing and IME
|
||||
|
||||
Zed's `sum_tree` and rope for storage (O(log n) UTF-8↔UTF-16 offsets, large files). Each platform's real protocol,
|
||||
implemented directly: `NSTextInputClient` (with `doCommandBySelector:` for Kit's key bindings), `UITextInput` plus
|
||||
`UITextInteraction` on iOS (selection handles, loupe, autocorrect, dictation, marked text), `InputConnection` on
|
||||
Android, TSF on Windows, `text-input-v3` on Wayland, and a sliding-window hidden `<textarea>` on the web (Zed's
|
||||
`gpui_web` approach) with `EditContext` where available. This is the single riskiest area; Flutter's iOS text shim is
|
||||
3,400 lines and still feels off ([03](research/03-flutter-apple-rive-figma.md)).
|
||||
|
||||
### 4.7 Layout
|
||||
|
||||
Taffy (flexbox, grid, block) running over Rune's own node arena through its traversal traits, so there's one tree,
|
||||
not two. Agents already know flexbox. Huge lists use a sum tree of row heights (cached or estimated) and build views
|
||||
only for visible rows plus overscan. Layout runs once, at the *target* state; layout animation is the render thread's
|
||||
job (§4.9). Rejected: an own engine (no gain worth the cost), SwiftUI-style proposals (agents know it less well, and
|
||||
it's harder to make incremental).
|
||||
|
||||
### 4.8 State
|
||||
|
||||
A keyed retained tree rebuilt from plain view functions ([06 §1](research/06-reactivity-animation.md)):
|
||||
|
||||
```rust
|
||||
fn pill(cx: &mut Cx, rec: &Model<Recorder>) -> El {
|
||||
let r = cx.read(rec); // reading subscribes this view; no notify() to forget
|
||||
row().key("pill")
|
||||
.padding(tok::space::S2).gap(tok::space::S1)
|
||||
.shape(Shape::Capsule)
|
||||
.material(Material::Glass)
|
||||
.motion(tok::motion::MORPH) // layout + shape changes animate on this spring
|
||||
.child(dot().key("dot").fill(tok::color::RECORD).present(r.recording)) // exits animate, then unmount
|
||||
.child(text(r.elapsed()).key("time").style(tok::type_::MONO_CAPTION))
|
||||
.on_press(rec, |r, _| r.stop()) // queued between frames, gets &mut Recorder
|
||||
}
|
||||
```
|
||||
|
||||
- App state lives in typed `Model<T>`s in a store, outside any view, keyed by stable ids. That's what lets state
|
||||
survive hot patches.
|
||||
- Views return a type-erased `El` (fast compiles, small generics surface). Keys are explicit.
|
||||
- Handlers never run inside render, so there's no double-borrow panic.
|
||||
- High-frequency values (audio meters, scroll offset, drag position) never go through models; they bind straight to
|
||||
render properties.
|
||||
|
||||
Rejected: fine-grained signals (state lost on reload, reads outside tracking silently do nothing), GPUI's entities
|
||||
(re-render on the main thread for animation, re-entrancy panics), immediate mode (rebuilds everything every frame;
|
||||
fine for tools, wrong for feel).
|
||||
|
||||
### 4.9 Animation, a first-class primitive
|
||||
|
||||
- **Springs** are `Spring::new(duration, bounce)` with ω = 2π/duration and ζ = 1 − bounce, exactly SwiftUI's
|
||||
parameterisation (the launcher's convention differs by ~20%; Rune standardises). Default tokens come from
|
||||
Kit's motion presets.
|
||||
- **Every property is a track** of analytic segments `{t0, x0, v0, target, spring}`: position and velocity are exact
|
||||
at any time, so retargeting samples `(x, v)` at the presentation time and starts a new segment. This is
|
||||
Psychopomp's model generalised.
|
||||
- **Layout animation** animates each *edge* of a node whose frame changed, one spring per axis. A stationary edge
|
||||
gets no track so it can't jiggle; width can lead with a faster X spring; shapes, borders and shadows are drawn at
|
||||
the presented size, so there's no scale distortion. Both edges snap to 1/64 px.
|
||||
- **Presence:** removing a keyed node moves it to *exiting*; it leaves flow, plays its exit and unmounts only once its
|
||||
opacity has settled at 0. A key that returns mid-exit revives from where it is.
|
||||
- **Gestures:** drags apply 1:1 on the render thread (no animation on Kit's own hand); release hands velocity to a
|
||||
spring. Scroll physics are per platform (iOS: 0.998/ms deceleration, 0.55 rubber band; macOS: the OS's momentum
|
||||
phases).
|
||||
- **Kit's rules as defaults:** nothing animates on first mount, direct manipulation is instant, reduced motion swaps
|
||||
travel for a short fade per property class, blur only on things entering or leaving in place, soft masks on every
|
||||
clip.
|
||||
- **One clock** with time scale (slow-mo), pause and manual stepping, shared by tests, traces and the inspector. The
|
||||
render thread emits motion-trace JSONL natively, with exact "this was animated on purpose" flags.
|
||||
|
||||
## 5. Hot reload
|
||||
|
||||
Goal: edit to pixels in under 300 ms with state kept, on the Mac and on a connected iPhone. Today that's reachable
|
||||
for tokens, literals and shaders; structural Rust edits measure about a second.
|
||||
|
||||
Code loading on a physical iPhone is a dead end for now. Subsecond explicitly excludes physical iOS devices; JIT and
|
||||
loading code signed after install aren't available without a debugger; InjectionNext's device support has an
|
||||
unresolved 2026 failure report; Kit's HotReloadKit is simulator- and Mac-only for the same reasons
|
||||
([07](research/07-hot-reload.md)). So Rune layers it:
|
||||
|
||||
Views stay plain Rust; there is no separate view language.
|
||||
|
||||
| Layer | What changes | How | Target (edit → presented frame) |
|
||||
|---|---|---|---|
|
||||
| 0. Tokens and knobs | colours, spacing, type, springs, any `Tunable` | token file watched; render thread re-resolves live, in-flight springs retarget | ≤ 50 ms Mac, ≤ 100 ms iPhone |
|
||||
| 1. Live literals | any edit that only changes literals in view code (a number, colour, string, spring, enum variant) | Xcode-Previews-style: in dev builds a macro gives each literal in a view function a `file:line:col` id; the watcher re-parses the saved file and, if only literals changed, pushes the new values down the token channel. No compile. | ≤ 100 ms Mac and iPhone |
|
||||
| 2. Shaders | Metal/WGSL | rebuild the one pipeline at runtime in dev | ≤ 150 ms |
|
||||
| 3. Rust on the Mac | structural edits: view functions, handlers, layout, logic | subsecond hot-patching through `dx` (the same path upstream GPUI now uses); models live outside patched code, so state stays | **measured ~1 s** (989 ms median, S1); goal ≤ 300 ms |
|
||||
| 4. Rust on the iPhone | the same edits | **split-process dev mode** (below) | layer 3 + one USB round trip *(spike S4)* |
|
||||
| 5. Everything else | struct layout changes, new deps | full rebuild; models restored from a snapshot keyed by id, incompatible ones reset | ≤ 2 s Mac incremental (1.85 s measured for a tiny crate); device install as fast as Xcode allows |
|
||||
|
||||
**What spike S1 found** ([08](research/08-spike-hot-patch.md)). Subsecond 0.7.10 hot-patches a plain Rust binary
|
||||
with no Dioxus UI, keeping main-owned state across ten edits: 989 ms median, 1,150 ms p95 from save to new output
|
||||
(826 ms to patch applied; the CLI's own patch time was 687 ms median), on an M2 Max build worker at background
|
||||
priority. A normal incremental rebuild was 1.85 s, and cold 71 s. It also found traps Rune's integration has to
|
||||
close: a single-reference closure capture silently kept running old code (use `HotFn::current(f).call(args)` at
|
||||
explicit boundaries), statics and thread locals reset on patch, cached `Box<dyn Trait>` objects keep their old
|
||||
methods, and adding a struct field isn't detected. So the ≤ 300 ms target holds for layers 0–2, which cover
|
||||
most tuning edits; structural Rust edits are about a second. Getting those under 300 ms is M1 work: measure at
|
||||
foreground priority on the Mac, keep each app's views in a tiny leaf crate, use the fastest linker, and try the
|
||||
cranelift backend for dev builds. Patch boundaries are Rune's view functions and handlers, not arbitrary code; a
|
||||
type change in a model triggers the snapshot-and-restore path instead of a silent patch. Layer 3 ships as the
|
||||
opt-in `hot` feature and `scripts/rune-dev` (see "Live Rust editing" in [`crates/rune/README.md`](crates/rune/README.md)).
|
||||
|
||||
**Split-process dev mode.** In dev builds the iPhone runs a generic Rune "player": shell, renderer, render thread,
|
||||
animation, text rasterizing, scroll and drag physics. The app side (models, views, layout, shaping) runs on the Mac
|
||||
as an ordinary process that subsecond can patch, and talks to the phone over the same command channel the two
|
||||
threads already use (§3), across USB. Because animation, scrolling and drags run on the phone, feel is local; only
|
||||
discrete state changes cross the cable (~1–3 ms each way over USB, to be measured). Platform services the app calls
|
||||
(haptics, camera, keyboard, permissions) go through Rune's capability interfaces, which are injected anyway for
|
||||
deterministic tests, and in dev mode are proxied to the phone. React Native's old remote JS debugging ran app code on
|
||||
the desktop the same way; the difference here is that the protocol is the one Rune ships in production between
|
||||
threads, not a debug-only bridge. Release builds are a single native binary with no player and no socket.
|
||||
|
||||
What it can't do: measure real on-device app-side performance (use a native build for that), or exercise iOS-only
|
||||
code paths in the app side without the capability proxy. Both are acceptable for a dev loop.
|
||||
|
||||
State rules (from React Fast Refresh and Flutter): model state survives any patch whose type is unchanged; view-local
|
||||
state keyed by explicit string keys survives; a changed struct layout resets only the affected models (or migrates
|
||||
via a declared function); each reload is applied atomically and acknowledged by its first presented frame id, which
|
||||
is what the latency numbers measure.
|
||||
|
||||
## 6. Agent tooling
|
||||
|
||||
Agents need to build UI, look at it, and prove it works without a person. Built in from the first commit
|
||||
([09](research/09-agent-native-and-perf-targets.md)):
|
||||
|
||||
- **Scenes.** Every component registers named scenes (states with fixture data and fake services), like
|
||||
`scrawl lab pill tap-then-area`. Scenes render in the real app, offscreen in tests, and in a gallery.
|
||||
- **Headless, deterministic rendering.** Offscreen Metal (and wgpu) with pinned fonts, fixed clock, seeded randomness
|
||||
and a recorded environment manifest. Two pixel lanes: exact hashes on a pinned worker, and per-platform baselines
|
||||
with explicit tolerances. Failures save expected/actual/diff plus the tree.
|
||||
- **Inspector protocol** (versioned JSON over a socket, CLI and GUI are clients): query nodes by role/key/text,
|
||||
layout rects, styles, a11y roles, the source `file:line` of the view that made each node, live springs and their
|
||||
tokens, per-phase timings, and input injection with exact timestamps.
|
||||
- **Time control:** pause, step, scale, seek. `settle` with a deadline that lists what's still pending, instead of
|
||||
"wait until idle".
|
||||
- **Traces:** motion-trace JSONL from the render thread (no recorder needed), the internal layout linter's rules ported to the layout
|
||||
tree, Perfetto/Tracy spans per phase, presented-frame ids.
|
||||
- **Auditing:** `App::playground` lists every scene and page inside the running app, live, with light/dark,
|
||||
sizes and reduced motion; tunables are plain constants edited under hot reload.
|
||||
- **APIs agents can't misuse:** no notify to forget, no borrows across `await`, explicit keys, errors with fixes
|
||||
("`Text` has no key inside a dynamic list; add `.key(id)`"), `llms.txt`, and examples that are also tests.
|
||||
|
||||
The CLI, sketched:
|
||||
|
||||
```
|
||||
mk run [--device iphone] [--split] # app with hot reload; --split = split-process dev mode on the phone
|
||||
mk scenes / mk snap <scene> [--at 0.25s] # list scenes; render one to PNG + tree JSON, deterministic
|
||||
mk inspect <query> # e.g. mk inspect 'role=button text~"Stop"' → rects, source, springs
|
||||
mk trace <scene> --script tap.json # motion-trace JSONL + frame timings; mk lint runs motion/layout rules
|
||||
mk run --playground [scene] # open the app in its playground
|
||||
mk bench <workload> # the perf workloads in §8, with machine manifest
|
||||
```
|
||||
|
||||
## 6b. Guarantees and built-in motion debugging
|
||||
|
||||
Things few UI libraries promise, which owning the whole stack and a deterministic clock make possible. Each one is
|
||||
checked automatically, not by eye.
|
||||
|
||||
**Motion you can prove is smooth (Kit's motion toolkit, built in).** Everything Kit's motion tooling does today
|
||||
with external recorders becomes part of the runtime, because Rune owns every presented value on every frame:
|
||||
|
||||
- The motion linter's rules (pop-in/out, opacity/size/shape snaps, jumps, reversals, jitter, clip snaps, overlaps,
|
||||
flicker, hitches, fade cutoffs, stop-dead, velocity snaps) run live in debug builds, every frame, with the node, its
|
||||
spring token and the source `file:line` in the finding; in tests they are hard failures.
|
||||
- Animated properties can only change through tracks, so a one-frame jump can't be written; a node can't unmount at
|
||||
opacity > 0; persistent items can't blur; stationary edges are two-edge snapped to 1/64 px.
|
||||
- A motion-inspector overlay (an idea from a private iOS client): live presented rects, velocities, active springs and their
|
||||
tokens, intent flags, hitch markers, drawn over the app; toggled by a key or the inspector.
|
||||
- Render-time slow motion and frame stepping (true time scale, not stretched video), plus `rune trace` → motion-trace
|
||||
JSONL, frame strips and slowed before/after clips produced from deterministic
|
||||
replays, so a fix is shown with evidence before Kit looks.
|
||||
- Every hitch is charged to the named interval and node that caused it (HitchProbe-style), with the phase
|
||||
(view, layout, shaping, encode, GPU) that ran long.
|
||||
|
||||
**Other guarantees, in rough order of how soon:**
|
||||
|
||||
| Guarantee | How it's checked |
|
||||
|---|---|
|
||||
| **Instant first frame.** The first frame is rendered at build time (per appearance and common window size) and shown the moment the process starts; the live tree takes over invisibly once ready. Target: pixels in ≤ 50 ms from process start on a cold launch. | Launch timestamps in CI; a golden diff between the pre-rendered and the first live frame must be zero (no visible handoff). |
|
||||
| **No dropped frames by budget.** Each scene's cost (instances, glyphs, layout nodes, shaping, allocations) is counted exactly; CI fails if a scene exceeds the 8.33 ms budget model for the reference device. | Exact counters, bisectable; wall-clock confirmation on reserved hardware. |
|
||||
| **Zero cost at rest.** No ticks, no GPU submissions, no wake-ups once settled. | Counters over a 10 s idle sample. |
|
||||
| **Real contrast.** Text contrast is checked against the actual composited pixels behind each glyph (after blur and glass), in every theme. | Per-scene accessibility pass. |
|
||||
| **No clipped text, any locale or size.** Every scene is fuzzed across window sizes, text scale, long German, RTL, CJK, light/dark; fails on overflow, overlap, hard clips, tap targets < 44 pt, off-spine alignment (layout-linter rules). | Scene fuzzing in CI. |
|
||||
| **Every pixel traces to code.** Any pixel → node → `file:line` → commit; screenshot diffs explain themselves. | Inspector query; PR visual diffs. |
|
||||
| **Bug reports are replays.** Sessions record inputs and timing (KB, not video) and replay to identical pixels; Scrawl attaches one. | Replay determinism test on every change. |
|
||||
| **Same pixels on every platform** for the canonical lane, from a CPU reference renderer that the GPU path is diffed against. | Differential renderer tests. |
|
||||
|
||||
## 6c. Research round 2: tricks to use
|
||||
|
||||
Six more notes ([12](research/12-research-rendering.md)–[17](research/17-research-perf-architecture.md)), aimed
|
||||
at cutting-edge work that suits agent-maintained code. Web search was down for most of these agents, so many sources
|
||||
were recalled rather than re-read; each note marks which. Cite-check before relying on a number.
|
||||
|
||||
**Adopt now**
|
||||
|
||||
- **Sample every animation at the display's target presentation time**, never "now". Frame-time *variance* hurts
|
||||
perceived smoothness more than average fps (12 ms variation is noticeable, 4 ms barely); with analytic springs a
|
||||
late frame is a time gap, not a velocity jump ([15](research/15-research-motion-perception.md)).
|
||||
- **Smoothness metrics from the frame trace:** position error against the ideal analytic value, hitch-time ratio,
|
||||
cadence deviation, velocity continuity at retarget, plus a jitter fuzzer in CI ([15]).
|
||||
- **Late-latched input on the render thread** with Android's resampling constants, the impulse velocity estimator
|
||||
(least-squares as reference), tuned on a recorded gesture corpus. Hand springs measured velocity, never predicted
|
||||
([13](research/13-research-latency-startup.md), [15]).
|
||||
- **Text under motion:** snap y, ¼-px x phases while moving, end the track at the analytic settle time to avoid
|
||||
shimmer; spatial springs may overshoot, opacity/colour springs never do ([15]).
|
||||
- **CPU reference renderer:** `crates/rune-ref` evaluates Rune's own instance formulas on the CPU, the exact lane
|
||||
with hash goldens; GPU lanes get per-channel tolerances, because the WGSL spec allows FMA fusion and
|
||||
reassociation, so GPU bit-exactness can't be promised ([24](research/24-reference-renderer.md),
|
||||
[12](research/12-research-rendering.md), [14](research/14-research-determinism-verification.md)).
|
||||
- **Differential fuzzing of fast vs reference** from one structured scene generator (Vello's
|
||||
`cpu_gpu_differential` fuzz target is the model), plus metamorphic and model-based tests from the same generator
|
||||
([14]).
|
||||
- **App-level record/replay** (inputs, clock, RNG, a state hash per frame, periodic keyframes for seeking); `rr`
|
||||
doesn't run on macOS ([14]). The command channel becomes a byte SPSC ring that doubles as the replay log
|
||||
([17](research/17-research-perf-architecture.md)).
|
||||
- **Exact CI gates:** instruction counts (gungraun) and allocation counts on Linux, shuttle for the app↔render
|
||||
thread handoff, Miri on every PR ([14]).
|
||||
- **Pixel provenance:** the CPU renderer also writes a node-id buffer, so pixel diffs blame a node and its
|
||||
`file:line`; a semantic diff (tree, rects, springs) runs before the pixel diff ([14]).
|
||||
- **Per-node dirty classes** (Unreal Slate's model) with early cutoff: one measured case went 34 ms → 0.35 ms for
|
||||
10k widgets ([17]). A **per-frame arena** built into `El`'s lifetime, with a counting-allocator test ([17]).
|
||||
- **Blur and shadows:** Jimenez-style pyramid backdrop blur with a fractional radius (an animated radius never
|
||||
steps), capped radius with upscale; closed-form blurred rounded rects and shadows; Oklab with deterministic dither
|
||||
([12]).
|
||||
- **Startup:** precompiled shaders / Metal binary archive and parallel init so device, fonts and pipelines stay off
|
||||
the first-frame path; the first-frame layer of §6b with a bit-identical handoff gate; order-file/PGO layout trained
|
||||
on replayed command streams ([13], [17]).
|
||||
- **Compile speed:** no debug info for dependencies (22–30% faster clean builds in one measured project); skip
|
||||
Cranelift on Apple for now (unwinding/ABI gaps) ([17]).
|
||||
- **Agents:** one component catalog generated from the Rust definitions (schema, `llms.txt`, validator, prompt),
|
||||
props that accept only theme tokens, a single `rune check` (build → render scene → layout/motion lint → tree
|
||||
diff → fixes keyed to source), a compact text tree with stable ids derived from keys ("tap n17"), and a small
|
||||
Rune-Bench of 30–50 scenes measuring first-try correctness ([16](research/16-research-agent-generative-ui.md)).
|
||||
|
||||
**Spike**
|
||||
|
||||
- **Springs evaluated on the GPU.** Two notes reached this independently ([12], [17]): instances reference
|
||||
transform/clip/effect property nodes (Chromium's property trees) whose analytic spring tracks a shader evaluates,
|
||||
so an animating frame costs the CPU about one uniform write regardless of how many things move. Verified against
|
||||
the CPU evaluator. Spiked as opt-in translation/opacity tracks in `crates/rune-gpu/src/springs.rs`.
|
||||
- Liquid-glass lens in our own shader (SDF height field, refraction, dispersion, smooth-union morphing) ([12]).
|
||||
- Word-level FLIP when text reflows during a resize ([15]); Slug for scale-animated text ([12]).
|
||||
- Runtime-generated UI: an A2UI-shaped protocol (flat ids, separate data model, patches) on the command channel, with
|
||||
validate-then-commit, budgets and capability grants ([16]).
|
||||
- Perceptual diffs (NVIDIA FLIP) and Kani on core invariants ([14]).
|
||||
|
||||
**Effects: motion blur and friends.** Research [15] said motion blur isn't needed at 120 Hz,
|
||||
but Kit wants it as an effect, and Rune can do it better than anyone because every track is analytic: true
|
||||
**shutter motion blur** samples a node's exact position/scale/opacity at several instants inside the frame's shutter
|
||||
interval (sample count scaled by on-screen speed, zero cost at rest) and accumulates them, instead of guessing from
|
||||
velocity; a cheap directional blur along the analytic velocity is the fallback for big surfaces. Shutter angle is a
|
||||
motion token and a knob, so Kit tunes it live (and can say where it belongs: flings, page/camera moves, flights like
|
||||
the timeline's send flight). Kit's "persistent items never blur" rule is about Gaussian blur during reorders;
|
||||
motion blur is a separate, opt-in effect that Kit judges by eye. Same family, all spikes: liquid-glass lensing, glow
|
||||
that cools rather than cuts, feathered streaming-text reveal (from Desktop's timeline-motion branch), soft edge masks
|
||||
everywhere.
|
||||
|
||||
**Skip:** GPU-driven indirect draws and partial present for now ([12]); synthetic motion blur at 120 Hz (maybe for
|
||||
flings only) ([15]); process snapshot/restore for GPU state ([13]).
|
||||
|
||||
**Open:** whether wgpu exposes enough Metal present control and framebuffer fetch, or the Apple shell must own
|
||||
`CAMetalLayer` and a raw Metal backend sooner ([12], [13]).
|
||||
|
||||
## 7. The design language
|
||||
|
||||
Rune ships a design system, not just primitives:
|
||||
|
||||
- **Theming is a framework feature; no theme is baked in.** Rune defines a semantic token schema (background
|
||||
layers, text, icon, border, accent, status colours; space, radius, type scale, elevation, materials, motion) and
|
||||
components read only semantic tokens. A theme supplies values for light and dark, can be switched at runtime (every
|
||||
colour retargets on a spring), can be derived from seed colours, and can be loaded from data (for hot reload and
|
||||
user themes) or generated as Rust constants. Colour in OKLCH/P3. A lint fails on raw style literals in app code.
|
||||
The core ships one plain neutral default so examples render.
|
||||
- **OpenCode's theme is the first consumer and the main example,** in its own crate outside the core
|
||||
(`themes/opencode` or an example): generated from `@opencode/ui`'s theme (`packages/ui/src/theme`:
|
||||
`desktop-theme.schema.json`, 36 themes with seed colours; the `--v2-*` semantic tokens in `styles/tokens/`), the
|
||||
same source that feeds Tailwind on the web. The pipeline's output should be a Rune theme,
|
||||
not changes to Rune. Motion tokens default to Kit's motion presets.
|
||||
- **Components are generic and themable.** The OpenCode example kit can mirror `@opencode/ui`'s names and variants
|
||||
(card, list, popover, context-menu, hover-card, text-field, collapsible, scroll-view, …) so screens port from the
|
||||
Solid app by name, and its screenshot tests diff each component against its web story.
|
||||
- **Materials:** in-app blur and tinted surfaces everywhere; system Liquid Glass on Apple only as an optional extra
|
||||
via underlays.
|
||||
- **Motion:** Kit's palette (instant, snappy, default, calm, smooth, morph, playful, slow) as named tokens with
|
||||
enter/exit pairs; transitions as primitives (morph one surface, width leads, soft exits).
|
||||
- **Components** grown from dogfooding, not designed up front: capsule/pill, chips, list rows with selection, search
|
||||
field, menus and command palette, tray/popover morph, toast/HUD, sheet, segmented control, keycap. Each with scenes,
|
||||
a11y, reduced motion and knobs.
|
||||
|
||||
## 8. Performance targets
|
||||
|
||||
Reference devices get pinned before any number becomes a gate (a 120 Hz Apple-silicon Mac and a ProMotion iPhone,
|
||||
never a developer's desk display). CI runs deterministic correctness on every change and performance on reserved hardware
|
||||
([09 §C](research/09-agent-native-and-perf-targets.md)).
|
||||
|
||||
| Metric | Target |
|
||||
|---|---|
|
||||
| Mac hello app, fresh process → first presented frame | p50 ≤ 150 ms, p95 ≤ 200 ms live; ≤ 50 ms with the pre-rendered first frame (§6b) |
|
||||
| iPhone hello, app entry → first present | p95 ≤ 250 ms |
|
||||
| Event → presented frame (software, 120 Hz) | p50 ≤ 8.3 ms, p95 ≤ 16.7 ms; app-side dispatch → submit p95 ≤ 4 ms |
|
||||
| Physical key → photon (Mac, photodiode rig) | p95 ≤ 35 ms, compared against native AppKit on the same rig |
|
||||
| App-side work while one value animates | zero (no view, layout or diff) |
|
||||
| 1,000 spring-animated quads at 120 Hz, Mac and iPhone | CPU p95 ≤ 4 ms, GPU p95 ≤ 4 ms, < 0.1% missed presents |
|
||||
| Effects scene (Scrawl and launcher glass morph, blur, masks, shadows) | same budget |
|
||||
| 1M-row list (fixed and variable height) | list CPU p95 ≤ 1 ms / 2 ms, first viewport ≤ 100 ms, ≤ 200 realized rows |
|
||||
| 100 MB text file (Mac) | first usable viewport p95 ≤ 250 ms, peak extra memory ≤ 2.5× file size |
|
||||
| At rest | zero animation ticks and zero GPU submissions |
|
||||
| Idle memory | Mac ≤ 50 MiB RSS, iPhone ≤ 40 MiB footprint |
|
||||
| Binary | Mac stripped arm64 hello ≤ 5 MiB |
|
||||
| Reload: tokens / live literals / structural Rust edit on Mac / same on iPhone split | ≤ 50 ms / ≤ 100 ms / ≤ 300 ms goal (≈ 1 s measured) / Mac + USB |
|
||||
| Incremental compile after a view edit | ≤ 2 s on the build worker |
|
||||
|
||||
## 9. Risks
|
||||
|
||||
1. **Text input and text quality.** Desktop IME on three platforms comes first now; iOS `UITextInput` (selection handles, loupe, autocorrect, dictation, marked text)
|
||||
is where custom-rendered frameworks most visibly fail, and text that's a shade thinner than CoreText reads as
|
||||
cheap. Mitigation: implement the native protocols directly from day one of each platform, borrow Zed's macOS/iOS
|
||||
code, and gate on a CoreText side-by-side diff.
|
||||
2. **Matching OpenCode Desktop's look.** The bar is a Chromium-rendered app (the reason Slint with Skia was
|
||||
considered). Text rendering on Windows/Linux, shadows, gradients and borders must be indistinguishable from the web kit
|
||||
or better. Mitigation: per-component screenshot diffs against the `@opencode/ui` stories, rendered by headless
|
||||
Chromium beside Rune's headless renderer. (Native glass sync is now an optional-extra risk, spike S2.)
|
||||
3. **Scope.** Renderer, text, IME, a11y, six shells, tooling: this is years of work for a human team. Mitigation:
|
||||
agents write it, but only inside the verification harness (scenes, goldens, traces, perf gates) built first;
|
||||
ship one real surface at a time and delete the old one each time; depend on Taffy/Parley/AccessKit instead of
|
||||
rewriting them.
|
||||
4. **Accessibility** on every platform (AccessKit's iOS and Android adapters are young). Use the a11y tree as the
|
||||
inspector tree so it's exercised by every agent test.
|
||||
5. **Platform feel drift** (scroll, menus, focus rings change each OS release). Keep those native or measured against
|
||||
native, as Flutter does with its scroll-physics overlay test.
|
||||
6. **Split-process dev mode** is new. If S4 fails, fall back to subsecond in the simulator plus token/knobs reload on
|
||||
the device, and fast full installs.
|
||||
|
||||
## 10. Milestones
|
||||
|
||||
**M0 — Spikes (1–2 weeks).** Each answers one question with a number.
|
||||
|
||||
| Spike | Question | Where |
|
||||
|---|---|---|
|
||||
| S1 hot patch | edit → patched function running, with state, via subsecond in a non-Dioxus Rust binary | **done:** works; 989 ms median, 1,150 ms p95 ([08](research/08-spike-hot-patch.md)) |
|
||||
| S1b fast patch | same edit at foreground priority, views in a leaf crate, fastest linker, cranelift: can it reach 300 ms? | build Mac |
|
||||
| S2 glass sync | can an `NSGlassEffectView` underlay track a render-thread-animated shape at 120 Hz with the main thread blocked, no edge glitches? | GUI test Mac, recorded off the desk display |
|
||||
| S3 pacing | `CADisplayLink` vs `CAMetalDisplayLink` latency and stability; immediate draw on input; event → present numbers | **probe built:** `CVDisplayLink` and `CADisplayLink` both tick at 120 Hz; Rune paces one submission per tick ([native-pacing](scripts/native-pacing/README.md)) |
|
||||
| S4 split mode | renderer on an iPhone, app side on the Mac over USB: round-trip latency and edit → pixels | build Mac + an iPhone |
|
||||
| S5 text | Parley + atlas + dilation vs CoreText, pixel diff on 200 strings at 1× and 2× | **done:** raster and blend calibrated against CoreText ([23](research/23-text-quality.md)) |
|
||||
|
||||
**M0.5 — Rendering smoke test (now).** Before any of the theming or component work: one small window (a settings
|
||||
panel) that proves the basics render correctly. Rounded rects, borders, shadows, soft edges, crisp text that isn't
|
||||
thin, correct Retina scale, a few springs, clicks. Checked by headless `--snap` renders and frame sequences, then
|
||||
by Kit on a real window.
|
||||
|
||||
**M1 — Theming, gallery, docs site (now).** Rune's token
|
||||
schema and theme system, with the OpenCode theme generated from `@opencode/ui` as its first consumer; core tree, Taffy, springs and presence, wgpu renderer (`UberQuad` + atlas text with
|
||||
dilation), winit window, scenes, `--snap` headless goldens, inspector, motion traces, playground. A gallery of the
|
||||
first components with the same names as the web kit, each diffed against its web story. A docs/marketing site that
|
||||
explains Rune with headless-rendered stills first and live WebGPU demos once the web build works. The settings demo
|
||||
being built now is the seed.
|
||||
|
||||
**M2 — Hex Settings on Mac, Windows and Linux.** The first real screen. Forms, toggles, keycap recorder, lists,
|
||||
text field (own shells start here: `NSTextInputClient`, TSF, `text-input-v3`), AccessKit, CI goldens on all three.
|
||||
Replaces GPUI for that screen in Hex.
|
||||
|
||||
**M3 — OpenCode Desktop's main screens.** Sidebar and session list, the streaming transcript (markdown, code blocks,
|
||||
tool pills), composer, diff view, command palette, popovers and menus, at 120 Hz with Kit's motion. Done when it looks
|
||||
like OpenCode Desktop side by side and feels clearly better, on all three desktops. This is the flagship test.
|
||||
It runs against **real data**: a live mode connects to the OpenCode server (by default `127.0.0.1:4096`, with basic auth
|
||||
read from local config and never printed), lists real projects and
|
||||
sessions, renders real transcripts, follows the event stream as turns arrive, and can send a prompt when Kit types one
|
||||
in the composer. Not every feature, just enough to use it. Rules: agents building and testing it only use read-only
|
||||
GETs and never send prompts or create sessions on the live server (never `GET /api/experimental/session/stats`);
|
||||
goldens and committed fixtures are synthetic, never real session content; screenshots of real sessions stay local.
|
||||
|
||||
**M4 — Kit's Mac surfaces.** Scrawl pill (zero motion-linter findings, no more dropped frames than the Metal pill, Kit
|
||||
picks it blind), the launcher's tray and panel, Scrawl review/Settings. Optional Liquid Glass underlays here (spike S2).
|
||||
|
||||
**M5 — Web.** The same app in the browser over WebGPU (docs site demos, knobs, gpu-gallery).
|
||||
|
||||
**M6 — iOS.** iOS shell, `UITextInput`, `RuneView` for embedding in SwiftUI, split-process dev mode; first surface
|
||||
embedded in the private iOS client. **M7 — Android.**
|
||||
|
||||
## 11. Where Rune fits at Anomaly
|
||||
|
||||
One native stack for every Anomaly product, themed with OpenCode's design language (as a theme, not baked in). OpenCode Desktop is the flagship
|
||||
test: recreate it and raise the bar, so every app built on Rune inherits that quality, the way Zed built GPUI for Zed
|
||||
(but with the compositing, animation and text Zed's lacks). Hex Settings is the first real screen, then Hex, Scrawl
|
||||
and the launcher, then the private iOS client one embedded surface at a time. Psychopomp should share Rune's spring, timeline and text
|
||||
primitives rather than duplicate them. Because agents write Rune apps against scenes, an inspector and
|
||||
deterministic goldens, it fits "build infinite software": every new app starts with the design language, motion and
|
||||
verification harness already in place.
|
||||
|
||||
## 12. Open questions
|
||||
|
||||
1. App side on the platform main thread (default) or its own thread? Needs S3's latency numbers.
|
||||
2. How far to lean on Core Animation for simple transform/opacity animations (the launcher's "promote to render server") vs
|
||||
always animating on our own render thread.
|
||||
3. Glass morphing on iOS needs SwiftUI: host a tiny SwiftUI glass container per morph, or accept static glass shapes
|
||||
with our own morph on top?
|
||||
4. Does Rune eventually *replace* OpenCode Desktop's Electron app, or ship beside it? M3 decides with evidence.
|
||||
5. Text on Windows/Linux: grayscale everywhere, or ClearType-style subpixel where the web kit has it?
|
||||
|
||||
## 13. Web target status
|
||||
|
||||
The first experimental M5 target is implemented: winit 0.30 owns a single canvas, rAF and
|
||||
ResizeObserver; GPU initialization is asynchronous, and a sliding textarea supplies text
|
||||
services. It runs on the main thread without SharedArrayBuffer. See [WEB.md](WEB.md) and
|
||||
`examples/web-hello`. Real-device Safari keyboard verification, accessibility mirroring,
|
||||
WebGL fallback and EditContext remain follow-up work.
|
||||
Vendored
+66
@@ -0,0 +1,66 @@
|
||||
# Rune
|
||||
|
||||
A native GPU-rendered Rust UI framework for macOS, Windows, Linux and the web, with its own renderer, text, layout and springs.
|
||||
|
||||
Every app can run headless, so an agent can render to PNG, dump the element tree and drive it with scripted input.
|
||||
|
||||
<p align="center">
|
||||
<a href="demo/rune.mp4">
|
||||
<img src="demo/rune-poster.png" alt="Rune in motion: real apps, rune-kit components and GPU effects" width="100%">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="demo/opencode/session-top.png" alt="A coding agent app built with Rune" width="100%">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="demo/light/chat.png" alt="Lit chat interface" width="49%">
|
||||
<img src="demo/kit/diff-split-dark.png" alt="Split diff component" width="49%">
|
||||
</p>
|
||||
<p align="center">
|
||||
<img src="demo/fx/liquid-metal.png" alt="Liquid metal effect" width="49%">
|
||||
<img src="demo/settings-dark.png" alt="Settings window" width="49%">
|
||||
</p>
|
||||
|
||||
```rust
|
||||
fn view(s: &State, _: &mut Cx<State>) -> El {
|
||||
let t = tok::theme(true);
|
||||
let label = text(if s.on { "Lights on" } else { "Lights off" })
|
||||
.font(type_::TITLE).color(t.text);
|
||||
let knob = el().key("knob").size(18.0, 18.0).radius(9.0).fill(t.knob)
|
||||
.absolute(if s.on { 18.0 } else { 2.0 }, 2.0);
|
||||
let switch = el().key("switch").role("switch").label("Lights").checked(s.on)
|
||||
.focusable(true).size(38.0, 22.0).radius(11.0)
|
||||
.fill(if s.on { tok::accent(0, true) } else { t.control_off })
|
||||
.motion(motion::SNAPPY)
|
||||
.on_press(|s: &mut State| s.on = !s.on)
|
||||
.child(knob);
|
||||
col().w_full().h_full().center().gap(16.0).fill(t.bg).child(label).child(switch)
|
||||
}
|
||||
```
|
||||
|
||||
## Use it with your agent
|
||||
|
||||
Give your coding agent this repo. Have it start from [`examples/hello`](examples/hello) and [`crates/rune/README.md`](crates/rune/README.md), then check its own work headlessly by rendering PNGs and inspecting the element tree.
|
||||
|
||||
> Build me a <thing> with Rune (github.com/anomalyco/rune). Start from examples/hello and check your work headlessly.
|
||||
|
||||
## Add it
|
||||
|
||||
```toml
|
||||
rune = { git = "https://github.com/anomalyco/rune", rev = "<dev rev>" }
|
||||
```
|
||||
|
||||
Rune is pre-release. Pin a rev of `dev`; `dev` is never rewritten.
|
||||
|
||||
On Windows, the MSVC toolchain (`x86_64-pc-windows-msvc`, rustup's default) needs only the Visual Studio C++ build tools rustup asks for. The GNU toolchain (`x86_64-pc-windows-gnu`) also needs MinGW-w64's binutils on `PATH`: `windows-link` (under `parking_lot`, `libloading`, `windows-core` and `windows-sys`, so under every Windows UI crate) imports with `raw-dylib`, rustc makes those import libraries with `dlltool` on GNU targets, and the `dlltool` in rustup's `rust-mingw` can't run without an `as` it doesn't ship ([rust-lang/rust#140704](https://github.com/rust-lang/rust/issues/140704)). Without binutils the build stops at `windows-result` with `error calling dlltool 'dlltool.exe': program not found`. Install [MSYS2](https://www.msys2.org), run `pacman -S mingw-w64-ucrt-x86_64-binutils`, and put `C:\msys64\ucrt64\bin` on `PATH` (or build with `RUSTFLAGS=-Cdlltool=C:\msys64\ucrt64\bin\dlltool.exe`).
|
||||
|
||||
[Docs](crates/rune/README.md) · [Components](crates/rune-kit/README.md) · [Examples](examples) · [Changelog](CHANGELOG.md)
|
||||
|
||||
## Contributing
|
||||
|
||||
We don't take pull requests. Have your agent [open an issue](https://github.com/anomalyco/rune/issues)
|
||||
describing the bug or idea, and our agents usually turn it around fast.
|
||||
|
||||
MIT, © Anomaly.
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
# Third-Party Notices
|
||||
|
||||
Rune incorporates the third-party assets and libraries listed below. Original copyright notices and license texts are preserved for attribution and redistribution compliance.
|
||||
|
||||
---
|
||||
|
||||
## 1. KaTeX Math Fonts (`crates/rune-kit/assets/math/katex-fonts.pack.deflate`, feature `rune-kit/math`)
|
||||
|
||||
Bundled from `ratex-katex-fonts 0.1.16` (origin: KaTeX, `https://github.com/KaTeX/KaTeX`). Verbatim notices and the full SIL Open Font License 1.1 text are shipped in `crates/rune-kit/assets/math/FONT_NOTICE.txt` and `crates/rune-kit/assets/math/OFL.txt`.
|
||||
|
||||
- **KaTeX Fonts** (20 TrueType faces with Reserved Font Names `KaTeX_*`: `KaTeX_AMS-Regular`, `KaTeX_Caligraphic-Bold`, `KaTeX_Caligraphic-Regular`, `KaTeX_Fraktur-Bold`, `KaTeX_Fraktur-Regular`, `KaTeX_Main-Bold`, `KaTeX_Main-BoldItalic`, `KaTeX_Main-Italic`, `KaTeX_Main-Regular`, `KaTeX_Math-BoldItalic`, `KaTeX_Math-Italic`, `KaTeX_SansSerif-Bold`, `KaTeX_SansSerif-Italic`, `KaTeX_SansSerif-Regular`, `KaTeX_Script-Regular`, `KaTeX_Size1-Regular`, `KaTeX_Size2-Regular`, `KaTeX_Size3-Regular`, `KaTeX_Size4-Regular`, `KaTeX_Typewriter-Regular`)
|
||||
- License: **SIL Open Font License, Version 1.1** (`crates/rune-kit/assets/math/OFL.txt`)
|
||||
- Copyright (c) 2009–2010 Design Science, Inc.
|
||||
- Copyright (c) 2014–2018 Khan Academy (KaTeX)
|
||||
|
||||
---
|
||||
|
||||
## 2. Sandboxed LaTeX Display-Math Typesetter (`crates/rune-kit/assets/math/ratex-math.wasm.deflate`, feature `rune-kit/math`)
|
||||
|
||||
Built reproducibly from `tools/ratex-math-wasm/` (`scripts/build-math-wasm.sh`):
|
||||
|
||||
- **RaTeX** (`ratex-parser`, `ratex-layout`, `ratex-types`, `ratex-font`, `ratex-lexer` `0.1.16`, `https://github.com/erweixin/RaTeX`) — **MIT License**
|
||||
- **unicode-normalization** (`0.1.26`, compiled inside `ratex-math.wasm`, `https://github.com/unicode-rs/unicode-normalization`) — **(MIT OR Apache-2.0) AND Unicode-3.0**
|
||||
- **wasmi** (`wasmi`, `wasmi_core`, `wasmi_ir`, `wasmi_collections` `1.1.0`, native host interpreter, `https://github.com/wasmi-labs/wasmi`) — **MIT OR Apache-2.0**
|
||||
Vendored
+296
@@ -0,0 +1,296 @@
|
||||
# Run a Rune app in the browser
|
||||
|
||||
Rune's experimental web target renders one canvas through WebGPU. It uses the same Rust
|
||||
views, layout, glyph atlas and shaders as native. GPU initialization is asynchronous; the
|
||||
runtime stays on the browser's main thread and requests frames only while work is pending.
|
||||
|
||||
## Build the example
|
||||
|
||||
Install the wasm target, Python 3.11 or newer, and the wasm-bindgen CLI version in Cargo.lock:
|
||||
|
||||
```sh
|
||||
rustup target add wasm32-unknown-unknown
|
||||
cargo install wasm-bindgen-cli --version 0.2.129 --locked
|
||||
scripts/web-build.sh web-hello --out target/web
|
||||
```
|
||||
|
||||
Serve the entire output folder over HTTPS, including `snippets/`. A local HTTP server on
|
||||
`localhost` also works for development. The host must serve `.wasm` as `application/wasm`.
|
||||
No application server, SharedArrayBuffer, COOP or COEP headers are required.
|
||||
`--opt` additionally runs an installed `wasm-opt -Oz`; the default build does not need it.
|
||||
A release build drops the wasm's function-name section, so a panic's stack shows offsets
|
||||
instead of Rust names; `--names` keeps it for profiling, and `--dev` builds always keep it.
|
||||
The script prints the raw and gzip wasm sizes. Configure gzip or Brotli on the static host
|
||||
to get the corresponding transfer size.
|
||||
|
||||
```text
|
||||
usage: web-build.sh PACKAGE [--example NAME] [--out DIR] [--opt] [--dev] [--watch] [--no-html] [--names]
|
||||
```
|
||||
|
||||
The script builds with the toolchain's own cargo (`rustup which cargo`), not a `cargo` wrapper
|
||||
on `PATH` that might build on another machine, and stops with a message if the wasm isn't in
|
||||
the local target folder afterwards. Set `CARGO` to pick the cargo binary.
|
||||
|
||||
The example is a scrollable message list with a composer, Send and Copy last. Its title
|
||||
opens an external link. Refreshing resets the in-memory messages.
|
||||
|
||||
## Edit and reload
|
||||
|
||||
`--dev` builds fast instead of small: the debug profile without debug info, with dependencies
|
||||
(Rune included) at opt-level 1 and your package unoptimized, in its own `web-dev` target folder
|
||||
so it never rebuilds the release cache. It skips `--opt`. The wasm is about twice the release
|
||||
size; don't ship it. On `web-hello`, a one-line change rebuilds in about 2 s, against 12 s for
|
||||
a release build.
|
||||
|
||||
`--watch` rebuilds whenever a file in a workspace member changes (polling, no extra tools), and
|
||||
the page reloads itself after each successful build. Serve the folder from a second terminal:
|
||||
|
||||
```sh
|
||||
scripts/web-build.sh web-hello --dev --watch
|
||||
python3 -m http.server 8000 -d target/web # then open http://localhost:8000
|
||||
```
|
||||
|
||||
WebGPU works over plain HTTP on `localhost`; from another machine the page needs HTTPS. In
|
||||
watch mode the script writes `reload.js`, which polls `.stamp` in the same folder and reloads
|
||||
when a build changes it, and the generated page cache-busts `app.js` and `app_bg.wasm`. A
|
||||
failed build leaves the page as it was. Each build stages its files in `.next` and renames them
|
||||
into place, so a page loading mid-build gets one build's `app.js` and `app_bg.wasm`. Reloading
|
||||
resets the app's state.
|
||||
|
||||
## Your own page
|
||||
|
||||
The script writes `index.html` only if there is none, or if the existing one still has the
|
||||
`generated by rune web-build.sh` comment, so a page of your own (with `App::canvas_id` and
|
||||
`fit_content_height`, say) is kept. Delete that comment line to keep edits to the generated
|
||||
page. `--no-html` never writes `index.html`. To reload your own page in watch mode, add
|
||||
`<script src="reload.js"></script>` while developing.
|
||||
|
||||
## Give your app a wasm entrypoint
|
||||
|
||||
Add a `cdylib` target and a wasm-only wasm-bindgen dependency:
|
||||
|
||||
```toml
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
wasm-bindgen = "0.2"
|
||||
```
|
||||
|
||||
Export a start function that calls the usual Rune entrypoint:
|
||||
|
||||
```rust,ignore
|
||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen(start))]
|
||||
pub fn start() {
|
||||
rune::run(AppSpec::new("My app", (390.0, 760.0), State::default, view));
|
||||
}
|
||||
```
|
||||
|
||||
From your app's workspace, run `path/to/rune/scripts/web-build.sh your-package`. The script
|
||||
selects one cdylib, or one binary if there is no cdylib. `--example NAME` selects a Cargo
|
||||
example. Disable Rune's `dev`, `hot` and `native-file-dialog` features on wasm. Move native
|
||||
filesystem, process and thread dependencies behind target conditions in your app too.
|
||||
Use `rune::time::Instant` for deadlines passed to Rune; it is `std::time::Instant` on native.
|
||||
|
||||
## Luau scripts
|
||||
|
||||
An app that hosts Luau with `rune-luau` builds for the web too: Luau's C++ compiles with
|
||||
[WASI SDK](https://github.com/WebAssembly/wasi-sdk) (33 or newer) against WASI libc, using
|
||||
WebAssembly exception handling. Unpack the SDK and point `WASI_SDK_PATH` at it; `web-build.sh`
|
||||
then sets the C and C++ compilers for the wasm target, and `rune-luau` links the SDK's C runtime
|
||||
and defines the WASI calls libc makes inside the module, so the page loads like any other
|
||||
Rune app. Luau runs as its interpreter there.
|
||||
|
||||
```sh
|
||||
WASI_SDK_PATH=$HOME/wasi-sdk-34.0 scripts/web-build.sh luau-panel --out target/web-luau
|
||||
node examples/luau-panel/web-proof.mjs target/web-luau target/web-luau-proof
|
||||
```
|
||||
|
||||
Browsers with exception handling run it: current Chrome, Edge, Firefox and Safari.
|
||||
|
||||
## Mount in a page
|
||||
|
||||
By default Rune appends its own canvas, covers the viewport and stops the body scrolling.
|
||||
`App::canvas_id("id")` mounts onto a `<canvas id="id">` the page already has instead:
|
||||
|
||||
```rust,ignore
|
||||
// Inline in an article, as tall as its content; the page keeps scrolling.
|
||||
App::new(spec).canvas_id("chart").fit_content_height().try_run()?;
|
||||
// Full screen inside a single-page app's route, which owns the canvas.
|
||||
App::new(spec).canvas_id("route-canvas").full_viewport().try_run()?;
|
||||
```
|
||||
|
||||
Inline, the canvas is as wide as its parent and as tall as `AppSpec::size` (or its content with
|
||||
`fit_content_height`, when vertical wheel and touch pans scroll the page); safe-area insets
|
||||
are zero and the title doesn't touch `document.title`. With `full_viewport` the canvas is fixed to
|
||||
the visual viewport like Rune's own, so an ancestor with a `transform` or `filter` would
|
||||
become its containing block; mount it outside one.
|
||||
|
||||
`AppHandle::quit` unmounts the app when its route goes away: the loop stops, the GPU device is
|
||||
destroyed, Rune's listeners come off the page, and the body style and title it changed go back.
|
||||
Rune removes a canvas it made; a passed-in canvas stays, with its own style and attributes
|
||||
back, for the page to remove. One app runs per page at a time. An app started while another is
|
||||
quitting mounts once that one has gone, so a route can swap apps in the same tick:
|
||||
|
||||
```rust,ignore
|
||||
let handle = app.handle(); // keep it with the route
|
||||
App::new(spec).canvas_id("route-canvas").full_viewport().try_run()?; // after handle.quit()
|
||||
```
|
||||
|
||||
## A whole web page
|
||||
|
||||
`App::web_document()` makes the app the page itself, for a marketing site, docs or an article.
|
||||
The root lays out at its natural height and the browser scrolls the document, so trackpad
|
||||
momentum, the scroll bar, Page Down, Space, find-in-page, anchors and back/forward are the
|
||||
browser's own. The canvas stays fixed to the viewport and draws the band the page is scrolled to;
|
||||
a scroll moves only that band and rebuilds nothing.
|
||||
|
||||
Above the canvas Rune keeps a DOM mirror of the scene: landmarks (`role("main")`,
|
||||
`role("region")`, `role("navigation")`, `role("contentinfo")`), headings with their level,
|
||||
paragraphs, links and images, each at its element's place. Keys become element ids, so
|
||||
`#views` scrolls to the element keyed `views`. Its text is transparent but real, so the browser
|
||||
selects and copies it, and screen readers, crawlers and link previews read it. An element with
|
||||
`El::href(url)` is an `<a href>`: middle-click, Cmd-click and Copy Link work, and a plain click
|
||||
opens it in the same tab. Tab moves through the mirror's links and buttons; a press on one runs
|
||||
the element's handler. The page tints selections and focus rings with `--rune-selection` and
|
||||
`--rune-focus`, and sets the mirror's fonts with `--rune-sans` and `--rune-mono`, so match them
|
||||
to the fonts the app draws with.
|
||||
|
||||
### A static first frame
|
||||
|
||||
`--html out.html` lays the app out without a GPU, lets entrance motion land, and writes the
|
||||
scene as HTML and CSS: each element's flexbox style, paint and text, with the same tags the
|
||||
mirror uses. The browser draws that page before the wasm arrives, and a reader without WebGPU
|
||||
(or with scripts off) keeps a readable page:
|
||||
|
||||
```sh
|
||||
cargo run -p site -- --html dist/index.html --html-widths 360,640,1000 --html-template index.html
|
||||
```
|
||||
|
||||
Each width in `--html-widths` lays the page out again; the narrowest is the base and each wider
|
||||
one adds a `@media (min-width)` block where it differs, so the layout holds between the widths
|
||||
taken. `--html-template` fills `<!-- rune:css -->` and `<!-- rune:body -->` in a page that
|
||||
carries your meta tags. When Rune's first frame is on screen it removes the exported elements
|
||||
(`[data-rune-static]`), keeping the section at the top of the window where it was, and the
|
||||
canvas dispatches a bubbling `runepresent` event. An image is exported as `<img>` when its
|
||||
pixels came from `ImageCache::url` or `ImageCache::file`; shapes become inline SVG. Grid layout
|
||||
and effects drawn by shaders (`rune-fx`, materials) aren't exported; give such an element a
|
||||
fill to stand in for it.
|
||||
|
||||
## Images
|
||||
|
||||
`ImageCache::url` fetches an image and lets the browser decode it with its own codecs
|
||||
(`createImageBitmap`, off the main thread), so WebP, AVIF and anything else the browser reads
|
||||
work, turned upright by EXIF orientation. The pixels land through the same mip path as
|
||||
`ImageCache::rgba` and the cache's waker draws the frame. `ImageCache::file` does the same on
|
||||
web with its path as a URL relative to the page, so one call loads a bundled asset in both
|
||||
builds:
|
||||
|
||||
```rust,ignore
|
||||
let logo = cache.file("assets/logo.webp", 48.0, env.scale); // disk on native, fetched on web
|
||||
let avatar = cache.url(&user.avatar_url, 32.0, env.scale); // size and scale matter for SVG only
|
||||
```
|
||||
|
||||
SVG (by `Content-Type` or a `.svg`/`.svgz` path) rasterizes with Rune's renderer at the size
|
||||
asked for. Images over 8192 pixels a side are refused before their pixels are read, and a
|
||||
failed request or a cross-origin image without CORS headers resolves to `Image::error`.
|
||||
|
||||
`Cursor::Image` sets the canvas's CSS `cursor` to the PNG at 2x (`image-set(url(blob:…) 2x)`),
|
||||
so the browser decodes it and draws it at its size in points on any display.
|
||||
|
||||
## Fonts and browser input
|
||||
|
||||
Web includes Inter Regular and IBM Plex Mono Regular (the `embedded-fonts` feature). There is
|
||||
no system-font discovery. `App::font_url("fonts/brand.ttf")` fetches a TrueType or OpenType
|
||||
font (not WOFF2) alongside GPU setup, before the first frame, and adds it to `AppSpec::fonts`;
|
||||
on native it reads the same path from disk. Point the page's `@font-face` at the same file so the
|
||||
browser downloads it once, and build with `default-features = false` to drop the embedded fonts.
|
||||
Set `AppSpec::fonts` to static font bytes and `AppSpec::families` to your sans/mono family
|
||||
names for branding, additional weights, emoji and scripts outside the default fonts.
|
||||
For example, extend a static slice of `rune_theme_opencode::FONTS` with
|
||||
`include_bytes!("assets/NotoColorEmoji.ttf")` and the CJK fonts your app needs, then assign
|
||||
the combined slice to `spec.fonts`. Keep the theme's sans/mono family names in `spec.families`.
|
||||
Missing emoji and CJK glyphs display fallback boxes; they do not trigger font downloads.
|
||||
|
||||
The embedded Inter is cut to Latin, Greek and Cyrillic text (Latin-1, Latin Extended-A, modern
|
||||
Greek, Cyrillic, punctuation, arrows and the Mac's key symbols), under half its size. Once the
|
||||
first frame is up the app fetches the full faces, `Inter-Regular.ttf`, `Inter-Medium.ttf` and
|
||||
`Inter-SemiBold.ttf`, from beside `app.js`; `scripts/web-build.sh` copies them there. Text the
|
||||
cut covers draws the same before and after; other text (Vietnamese, polytonic Greek, Cyrillic
|
||||
beyond Russian, Ukrainian, Belarusian, Serbian, Macedonian and Bulgarian) draws in fallback
|
||||
fonts or boxes until they arrive, and stays that way, with a console warning, on a host that
|
||||
doesn't serve them.
|
||||
|
||||
In a Mac's browser text draws with macOS font smoothing (`FontSmoothing::On`), as Safari,
|
||||
Chrome and Firefox draw the page's own text there, and without it elsewhere, iPhone and iPad
|
||||
included. `App::font_smoothing` sets it either way.
|
||||
|
||||
Rust supplies the hidden textarea with up to 512 UTF-16 units on each side of the selection,
|
||||
expanding for the selected range, and skips unchanged mirrors. Browser input events supply replacements; Rune validates the mirrored
|
||||
context and converts window-relative UTF-16 positions to UTF-8 boundaries before editing.
|
||||
Composition holds the mirror stable until commit and replaces the composing word's range.
|
||||
Mobile `beforeinput` line breaks use Rune's Enter rules: submit, or Shift/Alt+Enter newline
|
||||
in a multiline field. A completed touch tap focuses the editor synchronously;
|
||||
a pan scrolls instead, with momentum and a damped edge return.
|
||||
|
||||
Secure fields use an `<input type="password">` with autocomplete, autocorrect and spellcheck
|
||||
disabled. It receives only new keystrokes and is emptied after every input; the model's
|
||||
secret is never mirrored into the DOM. Leaving a field returns focus to the canvas so
|
||||
shortcuts and Tab keep working. Continuous pointer movement and wheel events wait for rAF.
|
||||
|
||||
`Tx::copy` and `Tx::request_paste` use the browser clipboard. Call them from a user input
|
||||
handler: permission and transient-activation rules still apply. Native Paste events work
|
||||
without an asynchronous clipboard read. Secret-copy requests report failure because the
|
||||
browser cannot promise native clipboard-history exclusion or conditional timed clearing.
|
||||
|
||||
`rune::web::open_url` accepts HTTP(S) and mail links and opens a tab with `noopener,noreferrer`.
|
||||
Call it from a user input handler. `Tx::open_url_same_tab` (or `rune::web::open_url_same_tab`)
|
||||
replaces the page instead, and takes links relative to the page (`/notes/42`). A single-page
|
||||
app routes those itself with `App::same_tab_router`: it gets the absolute URL of each link on
|
||||
the page's origin and returns true when it handled it; otherwise, and for other origins, the
|
||||
browser loads the link with `location.assign`.
|
||||
|
||||
```rust,ignore
|
||||
App::new(spec).same_tab_router(|href| router.push(href)) // true: routed with pushState
|
||||
tx.open_url_same_tab("/notes/42")?; // from a handler
|
||||
```
|
||||
`Cx::safe_area()` returns top/right/bottom/left insets in
|
||||
points (zero on native). Apply them inside a full-canvas background. The canvas follows
|
||||
`visualViewport` when a software keyboard reduces the visible height. Keep the generated
|
||||
page's `viewport-fit=cover` meta tag and the textarea's 16 px font size.
|
||||
|
||||
## Scope and verification
|
||||
|
||||
This target needs WebGPU. It has no WebGL fallback (a page made with `--html` stays readable
|
||||
without it), overlays,
|
||||
extra windows, native menus, drag-out, native audio/video, networking layer or hot patching.
|
||||
Native configuration types remain source-compatible, but their desktop host paths are not
|
||||
used on wasm. Unsupported window requests warn in the console; Show/Open are ignored.
|
||||
The document title follows `AppSpec::title`, and hidden tabs report `is_visible() == false`.
|
||||
|
||||
The functional proof uses headless Chromium and Playwright:
|
||||
|
||||
```sh
|
||||
node scripts/web-smoke.mjs target/web target/web-proof
|
||||
```
|
||||
|
||||
Install Playwright with its Chromium browser first. `PLAYWRIGHT_MODULE` and `CHROMIUM_PATH`
|
||||
can select an existing installation. `WEB_ENGINE=webkit` tries an installed Playwright WebKit
|
||||
and reports whether it has a WebGPU adapter. The proof checks GPU errors, idle rAF requests
|
||||
and submissions, touch
|
||||
focus and momentum, Unicode edits, a long sliding context, predictive replacement,
|
||||
composition, selection, paste, copied model text, link isolation, theme and viewport resize.
|
||||
In Chromium it also installs Playwright's fake clock after the app has started and checks that
|
||||
a touch fling waits for `clock.runFor` instead of finishing in real time: Rune reads the page's
|
||||
current `performance.now()` on every frame, so a capture can step it frame by frame.
|
||||
The `?input-proof` fixture adds password input, Tab/Escape focus, mobile Enter, recomposition,
|
||||
same-field focus stability, continuous-input coalescing and visibility regression checks.
|
||||
Its mobile DPR check exercises the Safari-style CSS-size fallback because Chromium device
|
||||
emulation does not scale `devicePixelContentBoxSize`. This is not a real iPhone keyboard,
|
||||
dictation, autocorrect or Safari WebGPU test; those still need device verification.
|
||||
|
||||
The shell follows PLAN's winit-first approach, retaining winit 0.30's rAF and ResizeObserver
|
||||
implementation. Unlike research/11's proposed custom shell, it adds a document-aware
|
||||
textarea beside winit rather than replacing winit. This also defers PLAN's proposed switch
|
||||
to an owned shell when text input lands. WebGL fallback and EditContext from that research
|
||||
remain later work.
|
||||
@@ -0,0 +1,10 @@
|
||||
- **A box centred in a painted parent stays centred on the device grid.** Rounding each edge on
|
||||
its own put a compact `Switch`'s knob 2 px from the top of its track and 3 px from the bottom
|
||||
at 1.25× (and the same for every `ControlSize` at some fractional scale): its 2 pt inset is
|
||||
2.5 px. Pixel snapping now gives a box whose resting edges are centred in its parent's equal
|
||||
whole-pixel gaps to the parent's snapped edges, and lets its size round by up to a pixel to
|
||||
make room: the Small knob draws 19 px in a 25 px track, 3 px from each edge. Only a parent
|
||||
that paints something (a fill, border, gradient, or hover or press colour) counts, so a box
|
||||
centred in a plain row keeps its own rounding. It is decided at rest, so a box gliding into
|
||||
or out of a centred spot, or one whose parent grows or shrinks around it, eases between the
|
||||
two roundings with no jump.
|
||||
@@ -0,0 +1 @@
|
||||
- **Wayland overlays set their cursor.** A layer-shell overlay never set one, so the pointer kept whatever cursor it arrived with, such as a terminal's I-beam over a card. It now shows the runtime's cursor through cursor-shape-v1, as a window does, and the arrow off its hit areas.
|
||||
@@ -0,0 +1,6 @@
|
||||
- **A finger can tap a Wayland layer-shell overlay.** The overlay bound `wl_pointer` and `wl_keyboard`
|
||||
but never `wl_touch`, so cards and buttons drawn on a layer surface ignored a touchscreen even
|
||||
though the compositor offered touch. A touch on the surface now acts as the primary button: down
|
||||
presses where the finger landed, motion follows it, and up releases and clears hover, so a tap
|
||||
clicks and a drag off a button doesn't. A touch the compositor cancels (a system gesture) leaves
|
||||
before it releases, so it never counts as a click. One finger at a time; extra fingers are ignored.
|
||||
@@ -0,0 +1,11 @@
|
||||
- **An opt-in native Metal backend on macOS.** Build with the `metal-backend` feature and launch
|
||||
with `RUNE_GPU_BACKEND=metal`, and Rune draws through its own Metal backend, plugged in under
|
||||
wgpu's API through wgpu's `custom` backend. wgpu stays the default everywhere: without the
|
||||
variable, or without the feature, nothing changes. It covers what Rune itself draws, in windows,
|
||||
overlays and headless renders, with the same pixels as wgpu: render pipelines from WGSL, buffers,
|
||||
the common 8-, 10-, 16- and 32-bit colour formats, samplers, copies and presentation. It doesn't
|
||||
cover yet: `NativeSurface` video (it needs wgpu's backend and says so once on stderr), compute,
|
||||
query sets and timestamps, render bundles, indirect and mesh draws, multisampling, depth and
|
||||
stencil, more than four colour targets, ray tracing, shaders other than WGSL, and iOS. A
|
||||
compositor that needs those stays on wgpu; reaching one on Metal panics with its name rather than
|
||||
drawing wrong.
|
||||
@@ -0,0 +1,7 @@
|
||||
- **A Metal frame is one command buffer, submitted and presented where it was drawn.** On
|
||||
`RUNE_GPU_BACKEND=metal`, overlays submit and present on their own thread instead of handing
|
||||
the frame to a present thread, which only paid off for wgpu's costlier submit. A
|
||||
`Queue::write_buffer` to a buffer that only submitted work still reads takes a spare storage
|
||||
instead of a staged copy, so a compositor writing a uniform each frame adds no command buffer.
|
||||
`examples/window_scroll_cost.rs` scrolls a real window and prints its CPU, instructions and
|
||||
Metal calls per frame; `scripts/motion-audit` records a sticky-header scroll.
|
||||
@@ -0,0 +1,9 @@
|
||||
- **Uploads write in place on Metal, and only the instances that changed.** On
|
||||
`RUNE_GPU_BACKEND=metal`, buffer writes through `Staging` and `Queue::write_buffer` go straight
|
||||
into the buffer's shared memory; while the GPU may still read the old bytes, a spare brought up
|
||||
to date takes the buffer's place, so a frame records no copy and allocates no buffer.
|
||||
`rune_staging::set_direct` registers such a writer, and `Stats::direct` counts its writes. On
|
||||
every backend, `Renderer::prepare` writes each span of instances that changed instead of
|
||||
everything from the first to the last, so a frame where a few far-apart instances move uploads
|
||||
only those. `examples/upload_bench.rs` also prints the instructions a frame ran (`kinstr`), which
|
||||
a busy machine leaves unchanged.
|
||||
@@ -0,0 +1,4 @@
|
||||
- **App installs keep the bundle present.** `scripts/mac-app` shares a per-target
|
||||
lock with HiveMind, stages each install separately, and atomically exchanges
|
||||
bundles. A failed launch or missing Rune ready receipt restores the previous
|
||||
bundle; interrupted installs retain both complete bundles for recovery.
|
||||
@@ -0,0 +1 @@
|
||||
- Growth stacks: when a commit changes the gap above a row's contents and the row's height with it (a row that stops sitting close to the one above it), the contents now slide as the row's growth opens instead of on their own spring. In a list pinned to its end, where the row moves by what it grows, contents whose place doesn't change hold still on every frame, instead of sinking about half a point and coming back. A `Tx::launch` flight that has as good as landed (within a quarter of a device pixel of its place, held up only by its springs' settle tails) and that a commit would re-aim now lands and rides its row, instead of setting off on a new path that lags the scroll under it and sinks a few points.
|
||||
@@ -0,0 +1 @@
|
||||
- The motion audit no longer reports a `dog-leg` for an element whose own move is straight against its moving parent, as a chevron that slides along its row while the list scrolls: its path bends on screen only by the parent's motion. An L-shaped move of its own, on a moving parent or a still one, is still reported.
|
||||
@@ -0,0 +1 @@
|
||||
- **Effect slots carry their tag and a payload to the compositor.** `EffectSite::mark` is the slot's `El::effect` tag, so a hook no longer needs `Runtime::marks` (or `track_marks`), and `El::effect_data([f32; 4])` sets four floats the hook reads as `EffectSite::data`, bit for bit. Both ride in the slot's record (`border[0..2]` and `uv`), so a removed element keeps the payload it was last built with through its exit fade while its replacement enters beside it, with no bookkeeping in the app. `compose::Compositor` documents the pattern: draw through `Renderer::draw_with`, keep resources per mark, drop a mark's once a frame passes without it. The slot's rect and `scale` follow `El::scale`, `El::offset` and a transition's scale and offset; under `El::rotate` the slot stays upright inside a turned layer.
|
||||
@@ -0,0 +1,10 @@
|
||||
- **`El::enter_delay` holds a whole entrance.** A new element waits the given seconds at its
|
||||
transition's insertion effect, then offset, scale, blur, opacity and reveal play together on one
|
||||
progress, so a staggered list (`.enter_delay(Stagger::new(0.05).delay(i, n))`; `Stagger` and
|
||||
`StaggerFrom` are now re-exported) no longer shows rows sliding before they fade. It takes its
|
||||
place in layout at once, runs on the element's and the window's time scale, and keeps its
|
||||
delay under Reduce Motion, where the entrance is the short fade. The first frame, instant and
|
||||
settle commits, hidden windows and rows out of sight ignore it; removed while it waits, a row
|
||||
that fades in goes at once. A window that only waits for a delayed start, from `enter_delay` or
|
||||
a delayed `Anim`, draws nothing and wakes once when it starts, and the store no longer samples
|
||||
such tracks every frame.
|
||||
@@ -0,0 +1,8 @@
|
||||
- **`El::fold_glide(spring)`: a growth-stack row that folds like a disclosure.** Its height
|
||||
changes glide on its own spring in place of the stack's, for the spring's own time however far
|
||||
they go (no `WHOLE_REACH` stretch, no `Tx::motion` floor), and keep their velocity when
|
||||
reversed mid-glide. Only what shows of the row moves: shutting, the part below the window goes
|
||||
at once; opening, the spring carries the row to the window's edge and the rest lands there, so
|
||||
a 2,000 pt group shuts as fast as a 200 pt one. Its feather rides the spring and ends with it.
|
||||
Implies `El::arrives_whole`. The growth-stack builders (`growth`, `streaming`,
|
||||
`arrives_whole`) moved from `el.rs` to `el/growth.rs`.
|
||||
@@ -0,0 +1 @@
|
||||
- **`Tx::set_font_families(sans, mono)` switches the fonts behind `Family::Sans` and `Family::Mono` while the app runs**, for a UI or code font picker. Every window and overlay follows on its next frame, and one opened later starts in the new families. Each drops the layouts and glyph runs shaped in the old families, re-runs memoized subtrees and re-measures every text, then draws one frame. `rune::text::measure` and `ink` follow too, and so do rune-kit's table column widths and rune-mermaid's diagram layouts. A cache of measured sizes outside Rune should key on the new `rune::text::font_epoch()`. A missing family falls back as it does at launch, and asking for the families already in place does nothing. `Runtime::set_font_families` and `Runtime::font_families` do the same outside a handler. A 50 KB Markdown note re-shapes in about 34 ms. Apps change nothing.
|
||||
@@ -0,0 +1 @@
|
||||
- **`App::gpu_backend(GpuBackend::Metal)` turns on the native Metal backend from code.** An app launched from Finder can't set `RUNE_GPU_BACKEND`, so the choice now lives on the app, with Rune's `metal-backend` feature. `RUNE_GPU_BACKEND=wgpu` or `=metal` still overrides it without a rebuild. It applies process-wide from the call on, and a `prewarm_gpu` already running on the other backend starts over on the chosen one, so calling `prewarm_gpu` first in `main` keeps working. Without the feature it says so once and draws with wgpu; off macOS it does nothing.
|
||||
@@ -0,0 +1,4 @@
|
||||
- **`El::hover_alone`: a hover target that keeps the row around it unlit.** While the pointer is
|
||||
on an element marked `hover_alone`, the elements it sits inside show no hover overlay and
|
||||
their `group_*` styles rest, as if the pointer had left them; back on the row they light
|
||||
again. For a face or button inside a hoverable row. Paint only, with no commit.
|
||||
@@ -0,0 +1,7 @@
|
||||
- **Commits under `El::hover_motion_within` no longer copy every node's visuals.** Each node
|
||||
inherited the pair by writing it into its own visuals, which gave every node below such a
|
||||
root (the docs suggest setting it on the root) its own copy of the rarely-set visual fields
|
||||
on every commit, and sent apply down its shadow and gradient path for all of them. The pair
|
||||
now rides beside the visuals. A 2,300-element card's commit drops from 1.9 to 1.6 ms
|
||||
headless, and a long board card's committing frames from about 11 to 9 ms. Removed nodes
|
||||
that drew nothing are also matched against the last build in step instead of through two hash maps.
|
||||
@@ -0,0 +1 @@
|
||||
- Debug builds warn once on stderr about three more slow patterns: a `poll` that returns true for 30 frames in a row while nothing on screen changes, a window that draws 120 frames within 2 s with no input, motion or visible change (naming what woke it, such as a `wake_after` loop), and a launch whose `main` setup, `init` and first view take over 100 ms before the first frame (naming the slowest part and pointing to `on_ready`). `RUNE_PERF_WARN=0` silences them; release builds are unchanged.
|
||||
@@ -0,0 +1 @@
|
||||
- **Images decode on up to four threads.** An `ImageCache` runs one decoder per core, up to four, instead of one, so a small image queued behind a large one no longer waits for it, and a view opening on several images decodes them side by side. Completion order between images is no longer the order they were queued.
|
||||
@@ -0,0 +1 @@
|
||||
- **`ImageCache::url` loads an image by URL; on web the browser fetches and decodes it.** Decoding uses `createImageBitmap` off the main thread, so WebP and AVIF work on web, and the pixels land through the same mip path as `ImageCache::rgba`, with the cache's waker drawing the frame. On web `ImageCache::file` now fetches its path relative to the page instead of failing. Native `url` takes a path or `file:` URL and refuses network URLs (Rune has no HTTP client); native `file` is unchanged.
|
||||
@@ -0,0 +1 @@
|
||||
- **`rune::embed::LayerHost` and `target_os = "ios"` builds.** `LayerHost::from_core_animation_layer` mounts a `Runtime` and Metal `Renderer` (with optional `LayerHost::with_compositor` effect-slot passes) onto an existing `CAMetalLayer` (for UIKit, SwiftUI and AppKit views that own their own window and display link), sharing one `Gpu` across hosts with `embed::prewarm()`. `rune` now builds cleanly for `aarch64-apple-ios` and `aarch64-apple-ios-sim` (skipping `arboard` on iOS/Android and walking `/System/Library/Fonts` for Apple symbol, SF Mono, emoji and CJK fallbacks).
|
||||
@@ -0,0 +1 @@
|
||||
- **`rune-kit`, `rune-mermaid` and `rune-theme-opencode` no longer turn on Rune's default features.** They depend on `rune` with `default-features = false`, since none of them uses `dbus`, `embedded-fonts`, `ogg-audio` or `svg`. Before, Cargo's feature unification turned all four back on for any app that used one of these crates, so an app that set `default-features = false` on `rune` to leave out symphonia, opuscule, resvg or zbus still built them. An app that depends on `rune` with its defaults is unchanged; an app that reached Rune only through these crates and relied on a default feature now adds `rune` with that feature itself.
|
||||
+1
@@ -0,0 +1 @@
|
||||
- A `Tx::launch` flight whose ancestor springs to a new place in a later commit (a panel pinned to the window's bottom that grows as a row is added) now lands and rides it if it has as good as landed, or heads for its new place from where it's drawn, instead of jumping to where the ancestor will end up (a 33 pt one-frame jump for a row at rest in a growing panel).
|
||||
@@ -0,0 +1,4 @@
|
||||
- **Linux finds fallback fonts through fontconfig too, and ⎋ draws on stock Ubuntu.** Symbol,
|
||||
emoji, CJK and script fallbacks are also looked up among the files `fc-list` names, so fonts
|
||||
outside the XDG font directories (NixOS's store paths) are found. DejaVu Sans Mono follows
|
||||
DejaVu Sans in the symbol fallbacks, since DejaVu Sans has no ⎋ (U+238B).
|
||||
Loaded 100 of 4233 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user