22 Commits
Author SHA1 Message Date
vhaudiquet f8fd8e30dc bump version (0.3.2)
record-daemon / Check and lint (Linux) (push) Successful in 1m17s
record-daemon / Build (Windows x64) (push) Successful in 2m8s
2026-11-23 20:03:30 +01:00
vhaudiquet f85f9b49d3 app: keep the list scroll bar off the clip view
The clip screen fell through to the history and settings branch, so their thumb stayed where its own viewport left it: a grey bar on the clip's right that scrolled nothing. Each screen now names its own bar, and the clip draws none.
2026-11-23 19:50:22 +01:00
vhaudiquet 7463cf3905 app: stop playback when the window closes or hides
Closing the window leaves the app in the tray, so a clip or a review
kept playing with no picture. The window's close and the app's quit now
pause the open clip and every review player, and Hide pauses them too
before the window goes. Reopening shows the same screen, paused where it
was.
2026-11-23 19:47:08 +01:00
vhaudiquet 531238039d app: unmute clips and put their controls on the picture
A clip opened muted, and its transport sat in a row under the stage.
Clips now start with sound on, and the controls sit over the bottom of
the video: a time bar that seeks by press or drag, the clock, play and
pause, two-second jumps either way, and mute. They rest visible while
the clip is paused and hide while it plays, coming back when the pointer
enters the player. The overlay follows the player's clock, so the bar
and the time move with the picture.
2026-11-23 19:47:04 +01:00
vhaudiquet 5377d88ca6 app: show a red tray icon while recording
The tray kept the app's medallion while the daemon recorded, so the
notification area said nothing about it. The icon now becomes a plain
red disc, set with the menu whenever the recording state changes. The
state comes from the daemon's status, so a recording started from
another program shows too.

Rune's tray could only replace its menu and tooltip, so the vendored
rune takes Tray::set_icon: Windows rebuilds the HICON and sends
NIM_MODIFY, Linux swaps IconPixmap and emits NewIcon.
2026-11-23 18:44:12 +01:00
vhaudiquet 9e4349fe42 app: find a clip in the folder it was recorded to
History lists a timeline from the default recordings folder, where
the daemon writes them, but review looked for its clip only there as
well. A recording made into the folder chosen in settings therefore
appeared in history with no video. The app now searches the
configured folder first and the default one after it, and uses the
path stored with the timeline when the recorder wrote one, so a clip
stays playable after the setting moves and an older timeline still
plays.

Settings are read back after a save because the daemon resolves the
chosen folder to an absolute path. The two Open folder buttons open
the configured folder instead of the default one.
2026-11-23 18:24:22 +01:00
vhaudiquet 86fc7cea2f record-daemon: keep a changed recordings folder usable
A folder typed into the settings screen was saved but never made. OBS
does not create directories, so the next recording failed at its
output and no timeline reached history. The daemon now makes the
folder when settings are saved and again before each recording
starts, rejects a folder it cannot use, and resolves it to an
absolute path so both programs name the same place.

Timelines now store the absolute path of their video next to the
file name, so a clip stays reachable after the recording folder
changes.
2026-11-23 18:24:20 +01:00
vhaudiquet f3e44a2132 app: keep a paused clip's layer picture on the pixels it played on
The vendored rune's layer rounded its size and sat at it 1:1, while the
window draws a paused clip itself at the exact fractional rect: pausing
moved the picture by up to a pixel. The layer's visual now sits at that
rect and stretches its buffer onto it (SetTransform2), and the vendored
rune takes windows-numerics for the matrix.

Also snapshot hooks: LR_DEMO_PLAY starts the demo clip and
LR_DEMO_PAUSE_AT pauses it once the clock passes a time.
2026-11-23 18:11:02 +01:00
vhaudiquet 5cbf284841 app: play a recording's own sound and read a pause's place from the player
The review screen carried two workarounds for rune's video player: tick
ignored the player's place while a clip was paused because the first
pause read zero, and the player was muted for good because its sound
never kept the clock, so the soundtrack came from an audio-only player
of the whole file, kept in step by keep_in_step.

Rune now holds the pause's picture and time and reads a video's sound
ahead of the clock, so the video player carries the sound of a
single-track recording itself, and tick reads the place whatever the
playback state. A recording with several tracks still cuts one player
per source, so the channels stay hearable apart; the video stays muted
and keep_in_step keeps those players with the pictures.
2026-11-22 23:54:00 +01:00
vhaudiquet 5bf262b82b app: cherry-pick rune's pause and sound fixes onto the checkout
Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
2026-11-22 22:16:30 +01:00
vhaudiquet 80fef698ce app: bump rune to 63ad020
Moves all three rune git deps from 4ddf696 to the tip of the tree.
Nothing in our own code needed to change for the new revision.
2026-11-22 21:55:59 +01:00
vhaudiquet a85f91e07d app: stop the review soundtrack when an export opens the clip view
Finishing an export jumped straight to the clip view without leaving
the review screen, so its soundtrack channels kept playing under the
clip. The 1, 2 and 3 shortcuts had the same gap: they switched
screens while the soundtrack played on.
2026-11-22 20:34:34 +01:00
vhaudiquet 918e653a0a app: wrap the clip view's title instead of letting it widen the panel
A clip exported from a recording carries the recording's uuid as its
name, long enough to push the title field past the panel and the
window. The field now wraps, one to two lines tall, scrolling inside
when there is more, and the panel holds its width; the header beside
it truncates with an ellipsis as it already did.

Return makes a new line in a wrapping field, so saving is the
button's job alone.
2026-11-22 20:18:58 +01:00
vhaudiquet 9ce2b75568 app: open a clip view from a card and after an export
The grid answers what was exported; the view answers this one clip.
It plays the file muted and looping, with a transport under it, and a
panel on the right for the title and the share.

The title is the file's name, because a file is the only place a clip
keeps one: saving renames it, the miniature follows, and the grid
shows the new name. Share puts the file itself on the clipboard, so
pasting it into a chat attaches the video. The card's share button
does the same now, and an export that finishes opens the view it
produced.
2026-11-22 19:20:16 +01:00
vhaudiquet 146256714b app: keep the clip name out of the delete dialog
A long recording id pushed the wording past the panel's edge. The
dialog now says the deletion plainly and leaves the naming to the
card the dialog was opened from.
2026-11-22 18:59:47 +01:00
vhaudiquet e7c9c5b672 app: drop the play mark from the clip cards
The miniature fills the stage, and the mark rode over it as if the
card were a button, which it is not yet. The stage now shows the
picture alone; playing a clip comes with the click that plays it.

Demo clips pick up a miniature already on disk the way the folder
listing does, so a repeat snapshot does not sit on black stages.
2026-11-22 18:56:51 +01:00
vhaudiquet 83ca4071d4 app: cut miniatures for the clips grid
Each card's stage shows a frame of the clip now, cut once with ffmpeg
into a thumbs folder beside the clips and reused from there. The pass
runs one clip at a time on a thread, skips what is already on disk and
as new as its clip, and poll drops each finished picture into its card
as it lands. Deleting a clip takes its miniature with it.

The frame is the clip's first: an export starts on the moment the clip
was cut for, so the picture shows the action without a seek. A clip
re-exported over the same name keeps its old picture until restart,
because the image cache keys a file by its path alone.
2026-11-22 18:52:57 +01:00
vhaudiquet 3f82f87a81 app: open the clips grid
The clips screen lists the clips folder: one card per mp4 the user
exported, newest first, with the clip's 16:9 stage, the champion it
stars when its recording is in the loaded history, share, and a menu
whose Delete removes the file. The folder read runs when the screen
opens, and again when an export finishes on it.

Computed highlights were the first plan for the grid, but a real
history parses hundreds of timelines and some run to tens of MB, so
the grid now reads only what the user actually exported.
2026-11-22 18:36:00 +01:00
vhaudiquet fac1ec00da bump version (0.3.1)
record-daemon / Check and lint (Linux) (push) Successful in 1m10s
record-daemon / Build (Windows x64) (push) Successful in 1m47s
2026-11-21 19:32:38 +01:00
vhaudiquet b173d75e98 app: use the tauri-app medallion icon on the window, taskbar and tray
record-daemon / Check and lint (Linux) (push) Successful in 1m12s
record-daemon / Build (Windows x64) (push) Successful in 1m44s
The exe carried no icon resource and the tray drew a stand-in disc, so
Explorer, the taskbar and the tray each guessed at what to show. The
old front end's medallion was already in the tree and identical to the
installer's icon.ico, so the whole shell now draws it: set_app_icon
feeds icons/icon_full.png to rune before the event loop, the tray
decodes the bundled 32 px, and build.rs bakes icon.ico into the exe
for Explorer and shortcuts. The 128 px variants stay in tauri-app,
which rune's own resizing makes redundant here.
2026-11-21 19:19:58 +01:00
vhaudiquet 6ca825990d app: delete a recording from its card's menu
The list could only open the review, so a clip that was not worth
keeping stayed on disk forever. The dots beside Review open a menu
drawn over this window, so it stays inside it, with room for more
actions later. Delete asks before the clip and its timeline leave
the disk and the row leaves the list.
2026-11-21 19:01:41 +01:00
vhaudiquet b1cde7e783 record: size recordings from the screen, not the quality preset
The quality preset chose the OBS canvas while the capture ran at the
game's real size, and the scene item carries no transform, so picking
1080p on a 1440p screen recorded only the top-left 1920x1080 crop of
the game.

Recordings now always run at the primary monitor's resolution, queried
in device pixels so display scaling cannot skew them, and a recording
start re-checks the screen so a display change mid-session cannot
bring the crop back. Quality presets keep their bitrate meaning and
nothing else; they never reached the encoder before, so High, Ultra
and friends now actually change what a recording costs on disk.
2026-11-21 18:15:52 +01:00
3828 changed files with 665988 additions and 332 deletions

No files matched your search

+1
View File
@@ -1 +1,2 @@
/.rhema/
/app/vendor/rune/target
+253 -127
View File
@@ -64,7 +64,7 @@ dependencies = [
"futures-lite",
"futures-util",
"serde",
"zbus 5.19.0",
"zbus",
]
[[package]]
@@ -146,6 +146,15 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "ar_archive_writer"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec"
dependencies = [
"object",
]
[[package]]
name = "arboard"
version = "3.7.0"
@@ -350,7 +359,7 @@ dependencies = [
"enumflags2",
"serde",
"static_assertions",
"zbus 5.19.0",
"zbus",
"zbus-lockstep",
"zbus-lockstep-macros",
"zbus_names",
@@ -365,7 +374,7 @@ checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc"
dependencies = [
"atspi-common",
"serde",
"zbus 5.19.0",
"zbus",
]
[[package]]
@@ -1536,11 +1545,12 @@ checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]]
name = "leaguerecorder"
version = "0.3.0"
version = "0.3.2"
dependencies = [
"chrono",
"directories",
"ffmpeg-sidecar",
"image",
"rune",
"rune-kit",
"rune-notify",
@@ -1551,6 +1561,7 @@ dependencies = [
"uuid",
"windows",
"winreg",
"winresource",
]
[[package]]
@@ -1884,6 +1895,7 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
dependencies = [
"bitflags 2.13.2",
"objc2 0.6.5",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-foundation 0.3.2",
]
@@ -1968,9 +1980,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
dependencies = [
"bitflags 2.13.2",
"block2 0.6.2",
"dispatch2",
"libc",
"objc2 0.6.5",
]
@@ -2043,7 +2053,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6"
dependencies = [
"bitflags 2.13.2",
"block2 0.6.2",
"objc2 0.6.5",
"objc2-core-foundation",
"objc2-core-graphics",
@@ -2088,10 +2097,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
dependencies = [
"bitflags 2.13.2",
"libc",
"objc2 0.6.5",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
]
[[package]]
@@ -2126,7 +2133,6 @@ checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
dependencies = [
"bitflags 2.13.2",
"block2 0.6.2",
"dispatch2",
"objc2 0.6.5",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
@@ -2214,6 +2220,15 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "object"
version = "0.39.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
dependencies = [
"memchr",
]
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -2571,6 +2586,16 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
[[package]]
name = "psm"
version = "0.1.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"
dependencies = [
"ar_archive_writer",
"cc",
]
[[package]]
name = "pxfm"
version = "0.1.30"
@@ -2746,65 +2771,51 @@ dependencies = [
[[package]]
name = "rune"
version = "0.0.1"
source = "git+https://github.com/anomalyco/rune?rev=4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1#4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1"
dependencies = [
"accesskit",
"accesskit_macos",
"accesskit_unix",
"accesskit_windows",
"arboard",
"async-channel",
"async-executor",
"async-io",
"blake3",
"block2 0.5.1",
"block2 0.6.2",
"bytemuck",
"console_error_panic_hook",
"fontique",
"futures-util",
"futures-lite",
"half",
"icu_properties",
"icu_segmenter",
"image",
"js-sys",
"libc",
"libloading",
"objc2 0.5.3",
"objc2 0.6.5",
"objc2-app-kit 0.2.2",
"objc2-av-foundation",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-core-media",
"objc2-core-text",
"objc2-core-video",
"objc2-foundation 0.2.2",
"objc2-foundation 0.3.2",
"objc2-io-surface",
"objc2-metal 0.3.2",
"objc2-quartz-core 0.3.2",
"opuscule",
"parking_lot",
"parley",
"parley_engine",
"png 0.18.1",
"pollster",
"portable-atomic",
"raw-window-handle",
"raw-window-metal",
"resvg",
"rune-core",
"rune-edit",
"rune-gpu",
"rune-image",
"rune-media",
"rune-motion",
"rune-spell",
"rune-staging",
"rune-taffy",
"rune-text",
"rustc-demangle",
"rustc-hash 2.1.3",
"serde",
"serde_json",
"skrifa",
"spellbook",
"swash",
"symphonia",
"taffy",
"tiny-skia-path 0.11.4 (git+https://github.com/anomalyco/rune?rev=4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1)",
"tokio",
"unicode-segmentation",
"wasm-bindgen",
"wasm-bindgen-futures",
@@ -2813,34 +2824,102 @@ dependencies = [
"wayland-protocols",
"wayland-protocols-wlr",
"web-sys",
"web-time",
"wgpu",
"wgpu-core",
"wgpu-hal",
"wgpu-naga-bridge",
"windows",
"windows-core",
"windows-sys 0.59.0",
"windows-numerics",
"windows-sys 0.61.2",
"winit",
"x11rb",
"xkbcommon",
"zbus 6.3.0",
"zbus",
"zeroize",
]
[[package]]
name = "rune-core"
version = "0.0.1"
dependencies = [
"js-sys",
"libc",
"portable-atomic",
"rune-motion",
"rustc-hash 2.1.3",
"serde",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"web-time",
"windows-sys 0.61.2",
]
[[package]]
name = "rune-edit"
version = "0.0.1"
dependencies = [
"js-sys",
"parley",
"rune-core",
"rune-text",
"serde_json",
"unicode-segmentation",
"zeroize",
]
[[package]]
name = "rune-gpu"
version = "0.0.1"
dependencies = [
"blake3",
"bytemuck",
"libc",
"objc2 0.6.5",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"objc2-metal 0.3.2",
"objc2-quartz-core 0.3.2",
"parking_lot",
"pollster",
"raw-window-metal",
"rune-core",
"rune-motion",
"rune-staging",
"wayland-client",
"wayland-protocols",
"wgpu",
"wgpu-naga-bridge",
"windows",
"windows-sys 0.61.2",
]
[[package]]
name = "rune-highlights"
version = "0.0.1"
source = "git+https://github.com/anomalyco/rune?rev=4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1#4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1"
dependencies = [
"unicode-ident",
"wasmparser",
]
[[package]]
name = "rune-image"
version = "0.0.1"
dependencies = [
"blake3",
"image",
"js-sys",
"objc2 0.6.5",
"objc2-foundation 0.3.2",
"resvg",
"rune-core",
"wasm-bindgen",
"wasm-bindgen-futures",
"windows-sys 0.61.2",
]
[[package]]
name = "rune-kit"
version = "0.0.1"
source = "git+https://github.com/anomalyco/rune?rev=4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1#4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1"
dependencies = [
"icu_normalizer",
"rune",
@@ -2849,39 +2928,110 @@ dependencies = [
"unicode-segmentation",
]
[[package]]
name = "rune-media"
version = "0.0.1"
dependencies = [
"ash",
"block2 0.6.2",
"bytemuck",
"libc",
"objc2 0.6.5",
"objc2-av-foundation",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-core-media",
"objc2-core-video",
"objc2-foundation 0.3.2",
"objc2-io-surface",
"objc2-metal 0.3.2",
"opuscule",
"rune-core",
"rune-gpu",
"rune-image",
"rune-staging",
"symphonia",
"wgpu",
"windows",
"windows-sys 0.61.2",
]
[[package]]
name = "rune-motion"
version = "0.1.0"
source = "git+https://github.com/anomalyco/rune?rev=4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1#4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1"
[[package]]
name = "rune-notify"
version = "0.0.1"
source = "git+https://github.com/anomalyco/rune?rev=4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1#4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1"
dependencies = [
"block2 0.5.1",
"objc2 0.5.3",
"block2 0.6.2",
"objc2 0.6.5",
"windows",
"windows-core",
"windows-registry",
]
[[package]]
name = "rune-spell"
version = "0.0.1"
dependencies = [
"js-sys",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"rune-core",
"rustc-hash 2.1.3",
"spellbook",
"unicode-segmentation",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"windows",
"windows-sys 0.61.2",
]
[[package]]
name = "rune-staging"
version = "0.0.1"
source = "git+https://github.com/anomalyco/rune?rev=4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1#4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1"
dependencies = [
"wgpu",
"windows",
]
[[package]]
name = "rune-taffy"
version = "0.0.1"
source = "git+https://github.com/anomalyco/rune?rev=4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1#4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1"
dependencies = [
"stacker",
"taffy",
]
[[package]]
name = "rune-text"
version = "0.0.1"
dependencies = [
"bytemuck",
"fontique",
"icu_properties",
"icu_segmenter",
"objc2-core-foundation",
"objc2-core-text",
"parley",
"parley_engine",
"rune-core",
"rune-image",
"rune-motion",
"rustc-hash 2.1.3",
"skrifa",
"swash",
"tiny-skia-path 0.11.4",
"unicode-segmentation",
"wasm-bindgen",
"windows",
"windows-core",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "rustc-demangle"
version = "0.1.28"
@@ -3068,6 +3218,15 @@ dependencies = [
"syn 3.0.10",
]
[[package]]
name = "serde_spanned"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
dependencies = [
"serde_core",
]
[[package]]
name = "shlex"
version = "2.0.1"
@@ -3221,6 +3380,19 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "stacker"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"
dependencies = [
"cc",
"cfg-if",
"libc",
"psm",
"windows-sys 0.61.2",
]
[[package]]
name = "static_assertions"
version = "1.1.0"
@@ -3497,8 +3669,6 @@ dependencies = [
[[package]]
name = "tiny-skia-path"
version = "0.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"
dependencies = [
"arrayref",
"bytemuck",
@@ -3508,7 +3678,8 @@ dependencies = [
[[package]]
name = "tiny-skia-path"
version = "0.11.4"
source = "git+https://github.com/anomalyco/rune?rev=4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1#4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"
dependencies = [
"arrayref",
"bytemuck",
@@ -3536,21 +3707,23 @@ dependencies = [
"libc",
"mio",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys 0.61.2",
]
[[package]]
name = "tokio-macros"
version = "2.7.2"
name = "toml"
version = "1.2.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
@@ -3576,13 +3749,19 @@ dependencies = [
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
version = "1.1.6+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31"
dependencies = [
"winnow",
]
[[package]]
name = "toml_writer"
version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]]
name = "tracing"
version = "0.1.44"
@@ -4432,6 +4611,16 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "winresource"
version = "0.1.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b"
dependencies = [
"toml",
"version_check",
]
[[package]]
name = "wit-bindgen"
version = "0.57.1"
@@ -4625,39 +4814,11 @@ dependencies = [
"uuid",
"windows-sys 0.61.2",
"winnow",
"zbus_macros 5.19.0",
"zbus_macros",
"zbus_names",
"zvariant",
]
[[package]]
name = "zbus"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4"
dependencies = [
"async-trait",
"bitflags 2.13.2",
"endi",
"futures-core",
"hex",
"libc",
"ordered-stream",
"rustix 1.1.6",
"serde",
"serde_repr",
"socket2",
"tokio",
"uds_windows",
"uuid",
"windows-sys 0.61.2",
"winnow",
"zbus_macros 6.3.0",
"zbus_utils",
"zcheapstr",
"zruntime",
]
[[package]]
name = "zbus-lockstep"
version = "0.5.2"
@@ -4697,18 +4858,6 @@ dependencies = [
"zvariant_utils",
]
[[package]]
name = "zbus_macros"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
"zbus_utils",
]
[[package]]
name = "zbus_names"
version = "4.3.5"
@@ -4720,19 +4869,6 @@ dependencies = [
"zvariant",
]
[[package]]
name = "zbus_utils"
version = "6.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 3.0.10",
"winnow",
]
[[package]]
name = "zbus_xml"
version = "5.2.1"
@@ -4900,16 +5036,6 @@ dependencies = [
"simd-adler32",
]
[[package]]
name = "zruntime"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72"
dependencies = [
"futures-core",
"futures-io",
]
[[package]]
name = "zune-core"
version = "0.5.3"
+13 -5
View File
@@ -1,6 +1,6 @@
[package]
name = "leaguerecorder"
version = "0.3.0"
version = "0.3.2"
edition = "2024"
description = "Native League Recorder desktop app (rune)"
license = "MIT"
@@ -9,10 +9,14 @@ license = "MIT"
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 = { git = "https://github.com/anomalyco/rune", rev = "4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1" }
rune-kit = { git = "https://github.com/anomalyco/rune", rev = "4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1" }
rune-notify = { git = "https://github.com/anomalyco/rune", rev = "4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1" }
rune = { path = "vendor/rune/crates/rune" }
rune-kit = { path = "vendor/rune/crates/rune-kit" }
rune-notify = { path = "vendor/rune/crates/rune-notify" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
@@ -22,6 +26,8 @@ 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"
@@ -32,7 +38,9 @@ windows = { version = "0.62", features = [
"Win32_System_Threading",
] }
# Rune is patched in the workspace that builds it. A dependency's `[patch]` doesn't apply to
# 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" }
+5 -2
View File
@@ -26,6 +26,9 @@ cargo run -- --snap settings.png --scene settings
cargo run -- --snap recording.png --scene recording
cargo run -- --snap audio.png --scene audio
cargo run -- --snap review.png --scene review
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
```
@@ -64,10 +67,10 @@ reading (`history::tests`), highlight clipping (`highlight::tests`) and formatti
| `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 |
| `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, game review |
| `src/screens/` | Settings, match history, clips, game review |
## Where this stands against TODO.txt
+11
View File
@@ -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");
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 797 KiB

+1 -1
View File
@@ -8,7 +8,7 @@
name = "leaguerecorder"
product-name = "League Recorder"
identifier = "v.leaguerecorder"
version = "0.3.0"
version = "0.3.2"
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
+314 -24
View File
@@ -7,7 +7,7 @@ use std::time::Duration;
use rune::tok::type_;
use rune::{Cx, El, Key, KeyEvent, Tx, col, el, row, text};
use crate::export;
use crate::export::{self, Clip};
use crate::history::{self, QueueCategory, Summary, Timeline};
use crate::ipc::{self, Daemon};
use crate::os;
@@ -21,6 +21,8 @@ use crate::ui::{self, Paint, body, heading};
pub enum Screen {
Settings,
History,
Clips,
Clip,
Review,
}
@@ -133,6 +135,26 @@ pub struct App {
/// The timeline the review is waiting for, once a row is opened.
pub review_rx: Option<Receiver<Option<Timeline>>>,
pub filter: Option<QueueCategory>,
/// The row the delete dialog is about, once its menu has asked to delete it.
pub confirm_delete: Option<String>,
/// The card whose actions menu is open, if any. The card's position, not its recording:
/// demo data repeats ids across rows, and a menu opens for one card alone.
pub menu_open: Option<usize>,
/// Every clip the user exported, newest first. Read when the screen opens.
pub clips: Vec<Clip>,
pub clips_loaded: bool,
/// The open clip: its view, with the title being set and its player.
pub clip: Option<screens::clip::ClipView>,
/// A clip waiting for the clipboard: its file. Handled off the handler, in poll.
pub share_clip: Option<PathBuf>,
/// The clips' miniatures, decoded off the render path and cached by file.
pub thumbs: Option<rune::ImageCache>,
/// A miniature on its way: the clip's name and the file that holds it.
pub thumbs_rx: Option<Receiver<(String, PathBuf)>>,
/// The clip card whose actions menu is open, if any: its position, like the history's.
pub clips_menu_open: Option<usize>,
/// The clip the delete dialog is about, by its `id@start` key.
pub confirm_clip_delete: Option<String>,
pub review: screens::review::Review,
pub portraits: Option<portraits::Portraits>,
/// The icons of the processes the audio sources name, decoded from their executables.
@@ -143,6 +165,7 @@ pub struct App {
/// When the process table was last read, in the clock `poll` gets.
pub processes_at: f64,
pub scroll: ui::ScrollBar,
pub clips_scroll: ui::ScrollBar,
pub highlights_scroll: ui::ScrollBar,
pub events_scroll: ui::ScrollBar,
pub notice: Option<Notice>,
@@ -183,6 +206,16 @@ impl App {
games_next: 0,
review_rx: None,
filter: None,
confirm_delete: None,
menu_open: None,
clips: Vec::new(),
clips_loaded: false,
clip: None,
share_clip: None,
thumbs: None,
thumbs_rx: None,
clips_menu_open: None,
confirm_clip_delete: None,
review: screens::review::Review::default(),
portraits: None,
icons: None,
@@ -190,6 +223,7 @@ impl App {
processes_rx: None,
processes_at: 0.0,
scroll: ui::ScrollBar::new(),
clips_scroll: ui::ScrollBar::new(),
highlights_scroll: ui::ScrollBar::new(),
events_scroll: ui::ScrollBar::new(),
notice: None,
@@ -224,6 +258,22 @@ impl App {
}
/// State for `--scene` snapshots: sample history, a connected daemon, default settings.
/// A demo clip like one the export writes: a name, an export time, a size.
pub fn demo_clip(name: String, hours_ago: i64, bytes: u64) -> Clip {
Clip {
name,
path: PathBuf::new(),
thumb: None,
exported: Some(
std::time::SystemTime::now()
- chrono::Duration::hours(hours_ago)
.to_std()
.unwrap_or_default(),
),
bytes,
}
}
pub fn demo(&mut self) {
self.connected = true;
self.status = Status {
@@ -232,11 +282,22 @@ impl App {
current_game_id: None,
client_connected: true,
};
self.games = history::sample()
.iter()
.map(|game| game.summary())
.collect();
let sample = history::sample();
self.games = sample.iter().map(|game| game.summary()).collect();
self.games_loaded = true;
let id = |game: &Timeline| game.recording_id.clone();
self.clips = vec![
Self::demo_clip(format!("{}-clip", id(&sample[0])), 3, 22_000_000),
Self::demo_clip("baron-steal".into(), 5, 9_400_000),
Self::demo_clip(format!("{}-clip", id(&sample[1])), 26, 15_800_000),
Self::demo_clip("pentakill".into(), 74, 31_200_000),
];
// Like the folder listing: a miniature already on disk and as new as its clip shows
// at once, and the thumbnail pass only cuts what is missing.
for clip in &mut self.clips {
clip.thumb = export::thumb_of(clip);
}
self.clips_loaded = true;
self.devices = AudioDevices {
input_devices: vec![AudioDevice {
id: "mic-1".into(),
@@ -327,6 +388,16 @@ impl App {
}
}
/// Stop the clip and the review where they are. The window is going away and the app stays
/// in the tray, so sound with no picture should not carry on: reopening shows the same
/// screen, paused at the same second.
pub fn pause_playback(&mut self) {
if let Some(player) = self.clip.as_ref().and_then(|view| view.player.as_ref()) {
player.pause();
}
self.review.pause();
}
pub fn refresh_settings(&self) {
self.daemon.get_settings();
}
@@ -412,6 +483,35 @@ impl App {
self.processes_rx = Some(rx);
}
/// Where the daemon writes new recordings, as the settings it holds say.
///
/// The draft stands in until the daemon has answered, so a first launch points at the
/// default folder the daemon would use anyway.
pub fn output_dir(&self) -> PathBuf {
let path = self
.settings
.as_ref()
.map(|settings| settings.output.path.as_str())
.unwrap_or(self.form.draft.output.path.as_str());
if path.is_empty() {
crate::daemon::recordings_dir()
} else {
PathBuf::from(path)
}
}
/// The folders a recording's clip may be in: the configured output folder first, then the
/// default one, where timelines and the clips folder live.
pub fn video_roots(&self) -> Vec<PathBuf> {
let default = crate::daemon::recordings_dir();
let output = self.output_dir();
if output == default {
vec![output]
} else {
vec![output, default]
}
}
/// List the timelines on disk and read the first page of rows on a thread of their own.
/// `poll` picks them up.
pub fn refresh_games(&mut self) {
@@ -432,6 +532,41 @@ impl App {
self.games_rx = Some(rx);
}
/// Read the clips folder into the grid. A directory read, quick enough for the UI thread.
/// The miniatures are ffmpeg work, so their pass runs on a thread of its own and `poll`
/// picks each one up as it lands.
pub fn refresh_clips(&mut self) {
self.clips = export::list_clips();
self.clips_loaded = true;
self.spawn_thumbs();
}
/// Cut every missing miniature, one clip at a time, on a thread of its own; `poll` picks
/// each one up as it lands. One pass at a time: the next refresh starts another.
pub fn spawn_thumbs(&mut self) {
if self.thumbs_rx.is_some() {
return;
}
let clips = self.clips.clone();
let (tx, rx) = channel();
std::thread::spawn(move || {
for clip in &clips {
if export::thumb_of(clip).is_some() {
continue;
}
let Some(source) = export::source_of(clip) else {
continue;
};
let thumb = export::thumb_path(clip);
let cut = export::make_thumb(&source, &thumb);
if cut && tx.send((clip.name.clone(), thumb)).is_err() {
break;
}
}
});
self.thumbs_rx = Some(rx);
}
/// Read the next page of rows, if the list has one and none is already on its way.
///
/// Called from `poll` while the history list is scrolled near its end, and while the
@@ -461,6 +596,23 @@ impl App {
self.games_next < self.games_paths.len()
}
/// Drop a recording out of the list once it has been deleted from disk, and drop a page
/// of rows already on its way: it may still hold the deleted file.
pub fn forget_game(&mut self, recording_id: &str) {
self.games.retain(|game| game.recording_id != recording_id);
if let Some(at) = self
.games_paths
.iter()
.position(|path| path.file_stem().and_then(|s| s.to_str()) == Some(recording_id))
{
self.games_paths.remove(at);
if at < self.games_next {
self.games_next -= 1;
}
}
self.games_rx = None;
}
/// The game the review screen is showing, if any.
pub fn reviewed(&self) -> Option<&Timeline> {
self.review.game.as_ref()
@@ -478,6 +630,13 @@ thread_local! {
const { std::cell::RefCell::new(None) };
}
/// Stop whatever the window was playing when it closes or the app quits. Closing the window
/// leaves the app in the tray, so a clip or a review left playing would keep making sound with
/// no picture. Reopening brings the same screen back, paused where it was.
pub fn window_closed(app: &mut App, _tx: &mut Tx) {
app.pause_playback();
}
pub fn remember_window(handle: &rune::WindowHandle) {
WINDOW.with(|slot| *slot.borrow_mut() = Some(handle.clone()));
}
@@ -503,6 +662,7 @@ pub fn setup(app: &mut App, waker: rune::Waker) {
app.waker = Some(waker.clone());
app.portraits = Some(portraits::Portraits::new(waker.clone()));
app.icons = Some(rune::ImageCache::new(waker.clone()));
app.thumbs = Some(rune::ImageCache::new(waker.clone()));
app.daemon.set_waker(waker.clone());
app.refresh_settings();
app.refresh_games();
@@ -514,7 +674,7 @@ pub fn setup(app: &mut App, waker: rune::Waker) {
}
let (tx, rx) = channel::<rune::TrayEvent>();
let spec = rune::TraySpec::new(os::APP_ID, os::APP_NAME, os::tray_icon())
let spec = rune::TraySpec::new(os::APP_ID, os::APP_NAME, os::tray_icon(false))
.tooltip("League Recorder")
.menu(os::tray_menu(false));
let wake = waker.clone();
@@ -542,6 +702,7 @@ impl App {
if self.status.is_recording != was_recording {
if let Some(tray) = &self.tray {
tray.set_menu(os::tray_menu(self.status.is_recording));
tray.set_icon(os::tray_icon(self.status.is_recording));
}
if self.status.is_recording {
os::notify(
@@ -586,14 +747,15 @@ impl App {
Err(e) => self.notify_error(e),
}
}
// The daemon answers a save with `{"success": true}`; the draft is already what
// it holds, so there is nothing to read back.
// The daemon answers a save with `{"success": true}`. Read the settings back:
// it may have resolved the recordings folder to an absolute path.
(ipc::Request::SaveSettings, Ok(_)) => {
self.settings = Some(self.form.settings());
self.form.saving = false;
self.form.dirty = false;
self.form.loaded = true;
self.notify("Settings saved");
self.daemon.get_settings();
}
(ipc::Request::SaveSettings, Err(e)) => {
self.form.saving = false;
@@ -689,6 +851,32 @@ impl App {
}
}
if let Some(rx) = &self.thumbs_rx {
let mut landed = false;
loop {
match rx.try_recv() {
Ok((name, thumb)) => {
if let Some(clip) = self.clips.iter_mut().find(|clip| clip.name == name) {
clip.thumb = Some(thumb);
landed = true;
}
}
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => {
self.thumbs_rx = None;
break;
}
}
}
changed |= landed;
}
// The clips grid reads the clips folder, so it loads once it is on screen, not at launch.
if self.screen == Screen::Clips && !self.clips_loaded {
self.refresh_clips();
changed = true;
}
// Taken out of the field so the notice helpers below can borrow the app.
if let Some(rx) = self.ffmpeg_rx.take() {
let mut finished = false;
@@ -775,7 +963,10 @@ impl App {
match event {
rune::TrayEvent::Activate { .. } => show_window(),
rune::TrayEvent::Menu(id) if id == "show" => show_window(),
rune::TrayEvent::Menu(id) if id == "hide" => hide_window(),
rune::TrayEvent::Menu(id) if id == "hide" => {
self.pause_playback();
hide_window();
}
rune::TrayEvent::Menu(id) if id == "record" => {
if self.status.is_recording {
self.daemon.stop_recording();
@@ -805,9 +996,14 @@ impl App {
// Keep the clock running so the status stays live even when nothing draws.
tx.wake_after(Duration::from_millis(1000));
// The clip view plays its file; leaving the screen behind stops it with the view.
if self.screen != Screen::Clip && self.clip.take().is_some() {
changed = true;
}
if self.screen == Screen::Review {
changed |= screens::review::tick(self, tx);
}
changed |= screens::clip::tick(self, tx);
changed
}
}
@@ -817,6 +1013,16 @@ impl App {
// ---------------------------------------------------------------------------
pub fn poll(app: &mut App, t: f64, tx: &mut Tx) -> bool {
// Snapshot hook: pause the demo clip when its clock passes `LR_DEMO_PAUSE_AT` seconds.
if let Some(at) = std::env::var("LR_DEMO_PAUSE_AT")
.ok()
.and_then(|v| v.parse::<f64>().ok())
&& let Some(player) = &app.review.player
&& player.is_playing()
&& player.time() >= at
{
app.review.playback();
}
app.handle_poll(t, tx)
}
@@ -824,23 +1030,65 @@ pub fn on_key(app: &mut App, event: &KeyEvent, _tx: &mut Tx) -> bool {
let command = event.mods.ctrl || event.mods.cmd;
match (&event.key, command) {
(Key::Text(t), false) if t == "1" => {
if app.screen == Screen::Review {
screens::review::leave(app);
}
app.menu_open = None;
app.clips_menu_open = None;
app.screen = Screen::History;
true
}
(Key::Text(t), false) if t == "2" => {
if app.screen == Screen::Review {
screens::review::leave(app);
}
app.menu_open = None;
app.clips_menu_open = None;
app.screen = Screen::Settings;
true
}
(Key::Text(t), false) if t == "3" => {
if app.screen == Screen::Review {
screens::review::leave(app);
}
app.menu_open = None;
app.clips_menu_open = None;
app.screen = Screen::Clips;
true
}
(Key::Escape, _) if app.form.add_open => {
app.form.close_add();
true
}
(Key::Escape, _) if app.confirm_delete.is_some() => {
app.confirm_delete = None;
true
}
(Key::Escape, _) if app.confirm_clip_delete.is_some() => {
app.confirm_clip_delete = None;
true
}
(Key::Escape, _) if app.clips_menu_open.is_some() => {
app.clips_menu_open = None;
true
}
(Key::Escape, _) if app.screen == Screen::Clip => {
app.menu_open = None;
app.screen = Screen::Clips;
true
}
(Key::Escape, _) if app.screen == Screen::Clips => {
app.menu_open = None;
app.screen = Screen::History;
true
}
(Key::Escape, _) if app.screen == Screen::Review => {
screens::review::leave(app);
app.screen = Screen::History;
true
}
(Key::Escape, _) if app.screen == Screen::Settings => {
app.menu_open = None;
app.screen = Screen::History;
true
}
@@ -917,17 +1165,29 @@ fn titlebar(p: Paint, app: &App) -> El {
// Leaving a screen is on the left, where a window's back arrow lives; the app's own
// actions stay on the right.
let mut leading = row().key("leading").gap(8.0).center_y();
if matches!(app.screen, Screen::Settings | Screen::Review) {
if matches!(
app.screen,
Screen::Settings | Screen::Clips | Screen::Clip | Screen::Review
) {
let from_clip = app.screen == Screen::Clip;
leading = leading.child(ui::button(
p,
"back",
"← Match history",
if from_clip {
"← Clips"
} else {
"← Match history"
},
false,
|app: &mut App| {
if app.screen == Screen::Review {
screens::review::leave(app);
}
app.screen = Screen::History;
app.screen = if app.screen == Screen::Clip {
Screen::Clips
} else {
Screen::History
};
},
));
}
@@ -941,6 +1201,20 @@ fn titlebar(p: Paint, app: &App) -> El {
// On the settings screen the title bar has nothing to offer: refreshing and opening
// settings again would only repeat what the screen already does.
if app.screen != Screen::Settings {
if !matches!(app.screen, Screen::Clips | Screen::Clip) {
actions = actions.child(ui::button(
p,
"open-clips",
"Clips",
false,
|app: &mut App| {
app.menu_open = None;
app.clips_menu_open = None;
screens::review::leave(app);
app.screen = Screen::Clips;
},
));
}
actions = actions
.child(ui::button(
p,
@@ -950,6 +1224,10 @@ fn titlebar(p: Paint, app: &App) -> El {
|app: &mut App| {
app.refresh_games();
app.daemon.get_status();
if app.screen == Screen::Clips {
app.clips_loaded = false;
app.refresh_clips();
}
},
))
.child(ui::button(
@@ -958,6 +1236,7 @@ fn titlebar(p: Paint, app: &App) -> El {
"Settings",
false,
|app: &mut App| {
app.menu_open = None;
screens::review::leave(app);
app.screen = Screen::Settings;
},
@@ -1011,9 +1290,14 @@ fn notice(p: Paint, notice: &Notice) -> El {
pub fn view(app: &App, cx: &mut Cx<App>) -> El {
let p = Paint::new(app.dark, cx.env().scale);
// Menus and dialogs cover the whole window, title bar and status bar included: the
// history row menus, the add-application form and the delete confirmation.
let mut overlays = Vec::new();
let content = match app.screen {
Screen::Settings => screens::settings::view(app, p),
Screen::History => screens::history::view(app, p),
Screen::History => screens::history::view(app, p, &mut overlays),
Screen::Clips => screens::clips::view(app, p, &mut overlays),
Screen::Clip => screens::clip::view(app, p),
Screen::Review => screens::review::view(app, p),
};
let mut main = col().key("main").grow(1.0).min_h(0.0).w_full().fill(p.t.bg);
@@ -1039,21 +1323,22 @@ pub fn view(app: &App, cx: &mut Cx<App>) -> El {
)
.child(app.events_scroll.thumb(p, "events-thumb", "event-scroller")),
Screen::Review => window,
_ => window.child(app.scroll.thumb(
p,
"scroll-thumb",
if app.screen == Screen::Settings {
"scroller"
} else {
"list-scroller"
},
)),
Screen::Clips => window.child(app.clips_scroll.thumb(p, "clips-thumb", "clips-scroller")),
Screen::Settings => window.child(app.scroll.thumb(p, "scroll-thumb", "scroller")),
Screen::History => window.child(app.scroll.thumb(p, "scroll-thumb", "list-scroller")),
// A clip fills its screen with a player, not a list: the history or settings thumb would
// stay where its own viewport left it, a bar on the clip's right that scrolls nothing.
Screen::Clip => window,
};
// The add-application dialog covers the whole window, title bar included.
let mut overlays = Vec::new();
if app.screen == Screen::Settings && app.form.add_open {
screens::settings::add_dialog(app, p, &mut overlays);
}
if app.confirm_delete.is_some() {
screens::history::delete_dialog(app, p, &mut overlays);
}
if app.confirm_clip_delete.is_some() {
screens::clips::delete_dialog(app, p, &mut overlays);
}
rune_kit::root(content, overlays)
}
@@ -1109,6 +1394,11 @@ pub fn demo_review(app: &mut App) {
player.set_looping(false);
app.review.player = Some(player);
app.review.error = None;
if std::env::var("LR_DEMO_PLAY").is_ok()
&& let Some(player) = &app.review.player
{
player.play();
}
if let Ok(tracks) = std::env::var("LR_DEMO_TRACKS") {
if let Some(game) = app.review.game.as_mut() {
game.audio_tracks = tracks
+140
View File
@@ -13,8 +13,148 @@ use ffmpeg_sidecar::download::{
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>,
}
/// 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,
};
clip.thumb = thumb_of(&clip);
Some(clip)
})
.collect();
clips.sort_by_key(|clip| std::cmp::Reverse(clip.exported));
clips
}
/// The clips folder beside the recordings.
pub fn clips_dir() -> PathBuf {
let dir = daemon::recordings_dir().join("clips");
+17
View File
@@ -12,6 +12,13 @@ pub fn clock(secs: f64) -> String {
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);
@@ -79,6 +86,16 @@ pub fn gold_per_min(stats: &crate::history::Stats) -> String {
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)
+147 -4
View File
@@ -38,6 +38,13 @@ pub struct Timeline {
pub raw_end_game_stats: Option<Value>,
#[serde(default)]
pub video_file: Option<String>,
/// The absolute path the recorder wrote the video to, when it recorded one.
///
/// The recordings folder can change while older clips stay where they were, so the path
/// travels with the timeline. A recording made before the recorder wrote it has only
/// `video_file`, and is found by name in the folders the app searches.
#[serde(default)]
pub video_path: Option<PathBuf>,
/// What each audio track of the video carries, in file order. Empty for recordings made
/// before the recorder wrote one track per source.
#[serde(default)]
@@ -186,6 +193,11 @@ pub struct Summary {
pub recording_id: String,
pub start_time: DateTime<Utc>,
pub duration_secs: i64,
/// The video file the row names, kept so deleting a row does not re-read its timeline.
pub video_file: Option<String>,
/// The absolute path the recorder stored with the timeline, when it did, so a row still
/// finds its clip after the recordings folder changes.
pub video_path: Option<PathBuf>,
champion: Option<String>,
summoner: Option<String>,
queue_label: String,
@@ -224,6 +236,15 @@ impl Summary {
pub fn lp_change(&self) -> Option<LpChange> {
self.lp.clone()
}
/// The video file of this row: its stored path, or its name in `roots`.
pub fn video_path(&self, roots: &[PathBuf]) -> Option<PathBuf> {
video_path_of(
self.video_path.as_deref(),
self.video_file.as_deref(),
roots,
)
}
}
impl Timeline {
@@ -233,6 +254,8 @@ impl Timeline {
recording_id: self.recording_id.clone(),
start_time: self.start_time,
duration_secs: self.duration_secs,
video_file: self.video_file.clone(),
video_path: self.video_path.clone(),
champion: self.champion(),
summoner: self.summoner(),
queue_label: self.queue_label(),
@@ -251,6 +274,32 @@ pub fn load(recording_id: &str) -> Option<Timeline> {
serde_json::from_str(&text).ok()
}
/// Remove a recording: its timeline JSON and its video file.
///
/// The caller resolves the video, searching the folders the app records to; the path stored
/// with the timeline keeps a clip reachable after the recordings folder changes. A file that
/// is already gone is fine: the list shows what was read earlier, and a tidy-up elsewhere
/// should not turn into an error here.
pub fn delete(recording_id: &str, video: Option<&Path>) -> Result<(), String> {
delete_in(recording_id, video, &daemon::recordings_dir())
}
/// [`delete`] inside one recordings folder, so a test can point it at a temporary one.
fn delete_in(recording_id: &str, video: Option<&Path>, recordings: &Path) -> Result<(), String> {
let json = recordings
.join("timelines")
.join(format!("{recording_id}.json"));
if json.exists() {
std::fs::remove_file(&json)
.map_err(|e| format!("could not delete {}: {e}", json.display()))?;
}
if let Some(video) = video.filter(|path| path.exists()) {
std::fs::remove_file(video)
.map_err(|e| format!("could not delete {}: {e}", video.display()))?;
}
Ok(())
}
impl Timeline {
fn end_stats(&self) -> Option<&Value> {
self.raw_end_game_stats.as_ref()
@@ -463,13 +512,33 @@ impl Timeline {
})
}
/// The recording's video file, by name or by the timestamp prefix.
pub fn video_path(&self) -> Option<PathBuf> {
let dir = daemon::recordings_dir();
find_video_file(&dir, self.video_file.as_deref()?)
/// The recording's video file: the path stored with the timeline, or its name in `roots`.
pub fn video_path(&self, roots: &[PathBuf]) -> Option<PathBuf> {
video_path_of(
self.video_path.as_deref(),
self.video_file.as_deref(),
roots,
)
}
}
/// The video file of a recording, as the stored path or a name in one of `roots`.
///
/// The stored path is what the recorder wrote, so a clip stays with its timeline after the
/// recordings folder changes. A timeline from before the recorder wrote the path has only the
/// name, and is looked up in every folder the app records to.
fn video_path_of(
stored: Option<&Path>,
video_file: Option<&str>,
roots: &[PathBuf],
) -> Option<PathBuf> {
if let Some(path) = stored.filter(|path| path.exists()) {
return Some(path.to_path_buf());
}
let name = video_file?;
roots.iter().find_map(|dir| find_video_file(dir, name))
}
/// Exact name first, then a file sharing the timestamp prefix.
pub fn find_video_file(dir: &Path, filename: &str) -> Option<PathBuf> {
let exact = dir.join(filename);
@@ -585,6 +654,7 @@ pub fn sample() -> Vec<Timeline> {
}
})),
video_file: None,
video_path: None,
audio_tracks: Vec::new(),
}
};
@@ -630,6 +700,20 @@ mod tests {
assert!((timeline.events[1].time() - 1500.5).abs() < 1e-6);
}
#[test]
fn a_timeline_reads_the_path_the_recorder_stored() {
let json = TIMELINE.replacen(
"\"video_file\"",
r#""video_path": "C:/clips/game.mp4", "video_file""#,
1,
);
let timeline: Timeline = serde_json::from_str(&json).unwrap();
assert_eq!(
timeline.video_path.as_deref(),
Some(Path::new("C:/clips/game.mp4"))
);
}
#[test]
fn the_game_values_come_out_of_the_raw_responses() {
let timeline = parsed();
@@ -682,4 +766,63 @@ mod tests {
assert!(found.ends_with("2026-03-27_16-42-52_kai_sa.mp4"));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn deleting_a_recording_removes_its_timeline_and_its_clip() {
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(dir.join("timelines")).unwrap();
std::fs::write(dir.join("timelines").join("game.json"), TIMELINE).unwrap();
std::fs::write(dir.join("2026-03-27_16-42-52_kai_sa.mp4"), b"x").unwrap();
let video = dir.join("2026-03-27_16-42-52_kai_sa.mp4");
delete_in("game", Some(&video), &dir).unwrap();
assert!(!dir.join("timelines").join("game.json").exists());
assert!(!dir.join("2026-03-27_16-42-52_kai_sa.mp4").exists());
// What is already gone is not an error.
delete_in("game", Some(&video), &dir).unwrap();
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_clip_is_found_in_the_folder_it_was_recorded_to() {
let default = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
let output = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&default).unwrap();
std::fs::create_dir_all(&output).unwrap();
let video = output.join("2026-03-27_16-42-52_kai_sa.mp4");
std::fs::write(&video, b"x").unwrap();
let timeline = parsed();
let roots = [output, default];
assert_eq!(timeline.video_path(&roots), Some(video.clone()));
assert_eq!(timeline.summary().video_path(&roots), Some(video));
let _ = std::fs::remove_dir_all(&roots[0]);
let _ = std::fs::remove_dir_all(&roots[1]);
}
#[test]
fn a_finished_timeline_keeps_the_path_of_its_clip() {
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let video = dir.join("old-folder").join("game.mp4");
std::fs::create_dir_all(video.parent().unwrap()).unwrap();
std::fs::write(&video, b"x").unwrap();
let mut timeline = parsed();
timeline.video_path = Some(video.clone());
// The folders the app knows now hold nothing: the stored path still finds the clip.
assert_eq!(timeline.video_path(&[]), Some(video.clone()));
// A stored path that is gone falls back to the name in the folders it is given.
timeline.video_path = Some(dir.join("moved.mp4"));
std::fs::write(dir.join("2026-03-27_16-42-52_kai_sa.mp4"), b"x").unwrap();
assert_eq!(
timeline.video_path(std::slice::from_ref(&dir)),
Some(dir.join("2026-03-27_16-42-52_kai_sa.mp4"))
);
let _ = std::fs::remove_dir_all(dir);
}
}
+28
View File
@@ -42,3 +42,31 @@ pub static CHEVRON_RIGHT: Icon = Icon {
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"/>"#,
};
+45
View File
@@ -63,6 +63,7 @@ fn main() {
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());
@@ -97,6 +98,9 @@ fn main() {
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.screen = app::Screen::Settings;
app.settings_tab = app::SettingsTab::Advanced;
@@ -106,6 +110,45 @@ fn main() {
app::demo_review(app);
app.review.show_details = true;
}),
("clips-empty", |app| {
app.screen = app::Screen::Clips;
app.clips.clear();
app.clips_loaded = true;
}),
("clips", |app| {
app.screen = 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();
}
app.spawn_thumbs();
if let Some(first) = app.clips.first().cloned() {
screens::clip::open(app, &first.name);
}
}),
("clips-many", |app| {
app.screen = 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.screen = app::Screen::Clips;
app.spawn_thumbs();
app.confirm_clip_delete = app.clips.first().map(|clip| clip.name.clone());
}),
("many", |app| {
app.screen = app::Screen::History;
app.games = (0..30)
@@ -122,6 +165,8 @@ fn main() {
})
.args(args)
.keep_running()
.on_close(app::window_closed)
.on_quit(app::window_closed)
.on_ready(move |handle| {
app::remember_window(handle);
if hidden {
+72 -34
View File
@@ -71,45 +71,52 @@ pub fn notify(id: &str, title: &str, body: &str) {
rune_notify::post(&notification);
}
/// A 32 px tray icon: an accent disc with a white play mark.
pub fn tray_icon() -> rune::TrayIcon {
const SIZE: u32 = 32;
let mut pixels = vec![0u8; (SIZE * SIZE * 4) as usize];
let accent = [0x5b, 0x7c, 0xfa];
let half = SIZE as f32 / 2.0;
let radius = half - 1.0;
// Play triangle: apex right of centre, base left of centre.
let (ax, ay) = (half + 4.5, half);
let (bx, by) = (half - 4.0, half - 6.0);
let (cx, cy) = (half - 4.0, half + 6.0);
let edge = |px: f32, py: f32, x1: f32, y1: f32, x2: f32, y2: f32| {
(x2 - x1) * (py - y1) - (y2 - y1) * (px - x1)
/// 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 px = x as f32 + 0.5;
let py = y as f32 + 0.5;
let dx = px - half;
let dy = py - half;
// Three pixels of antialiasing at the disc edge.
let coverage = (radius - (dx * dx + dy * dy).sqrt()).clamp(0.0, 1.0);
if coverage <= 0.0 {
continue;
}
let e1 = edge(px, py, ax, ay, bx, by);
let e2 = edge(px, py, bx, by, cx, cy);
let e3 = edge(px, py, cx, cy, ax, ay);
let inside =
(e1 >= 0.0 && e2 >= 0.0 && e3 >= 0.0) || (e1 <= 0.0 && e2 <= 0.0 && e3 <= 0.0);
let ink = if inside { [255, 255, 255] } else { accent };
let i = ((y * SIZE + x) * 4) as usize;
pixels[i] = ink[0];
pixels[i + 1] = ink[1];
pixels[i + 2] = ink[2];
pixels[i + 3] = (coverage * 255.0) as u8;
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]);
}
}
rune::TrayIcon::rgba(SIZE, SIZE, pixels)
(SIZE, SIZE, pixels)
}
/// The tray menu. `recording` flips the record item's label.
@@ -130,3 +137,34 @@ pub fn tray_menu(recording: bool) -> Vec<rune::TrayItem> {
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])
);
}
}
+604
View File
@@ -0,0 +1,604 @@
//! 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::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::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,
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()),
player: Some(player),
error: None,
muted: false,
bar_width: 0.0,
at: 0.0,
long: 0.0,
});
app.screen = Screen::Clip;
}
/// 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);
let entry = &mut app.clips[index];
entry.name = wanted.clone();
entry.path = to;
entry.thumb = to_thumb.exists().then_some(to_thumb);
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();
}
/// 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 = clip.and_then(|clip| {
app.games
.iter()
.find(|game| clip.name.contains(&game.recording_id))
});
let title = game
.map(|game| game.champion().unwrap_or_else(|| view.name.clone()))
.unwrap_or_else(|| view.name.clone());
let detail = match (clip, game) {
(Some(clip), Some(game)) => {
format!("{} · {}", game.queue_label(), format::age(clip.exported))
}
(Some(clip), None) => format!(
"{} · {}",
format::bytes(clip.bytes),
format::age(clip.exported)
),
_ => String::new(),
};
// The player takes the window; the side panel holds the title, the share and the facts.
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);
})),
),
);
col()
.key("clip-view")
.w_full()
.grow(1.0)
.min_h(0.0)
.padding(space::S6)
.child(body)
}
/// 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::title_name;
#[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);
}
}
+363
View File
@@ -0,0 +1,363 @@
//! 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. Export names carry the
/// recording's id somewhere in them, so a match is a contains check away.
fn of(app: &App, clip: &Clip, index: usize) -> Card {
let game = 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));
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);
}
}
}
+143 -4
View File
@@ -8,10 +8,13 @@ use rune::{Color, El, col, el, row, text};
use crate::app::App;
use crate::format;
use crate::history::{Outcome, QueueCategory, Summary};
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),
@@ -33,7 +36,8 @@ fn outcome_color(p: Paint, outcome: Outcome) -> Color {
}
}
pub fn view(app: &App, p: Paint) -> El {
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()
@@ -64,7 +68,7 @@ pub fn view(app: &App, p: Paint) -> El {
));
} else {
for (index, game) in filtered.iter().enumerate() {
list = list.child(game_card(app, p, game, index));
list = list.child(game_card(app, p, &kit, layer, game, index));
}
}
@@ -159,7 +163,14 @@ fn empty(p: Paint, title: &str, detail: &str) -> El {
)
}
fn game_card(app: &App, p: Paint, game: &Summary, index: usize) -> El {
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();
@@ -304,11 +315,18 @@ fn game_card(app: &App, p: Paint, game: &Summary, index: usize) -> El {
),
)
.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)),
),
),
)
@@ -326,3 +344,124 @@ fn stat(p: Paint, value: &str, label: &str) -> El {
)
.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");
}
+3 -1
View File
@@ -1,5 +1,7 @@
//! The three screens: settings, match history and the game review.
//! The screens: settings, match history, the clips grid, one open clip and the game review.
pub mod clip;
pub mod clips;
pub mod history;
pub mod review;
pub mod settings;
+67 -34
View File
@@ -1,5 +1,6 @@
//! Game review: the recorded clip, a scrubber with event markers, highlights and export.
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, TryRecvError, channel};
use rune::tok::{radius, space, type_};
@@ -15,11 +16,17 @@ use crate::ui::{self, Paint, body, heading};
pub struct Review {
/// The opened recording, once its file has been read.
pub game: Option<Timeline>,
/// The folders the clip may be in, as the settings named them when the row opened.
pub video_roots: Vec<PathBuf>,
/// Set while that file is on its way to the screen.
pub loading: bool,
pub player: Option<Player>,
/// The clip's audio tracks, one player each, so the channels are heard apart.
pub sounds: Vec<Channel>,
/// The video player carries the clip's own sound: one track, or a recording made before
/// the recorder split them, so there is nothing to cut and no channel to hear apart. Off,
/// the video is muted and the cut tracks carry the sound.
pub video_sound: bool,
/// Tracks being cut out of the clip on a thread. `tick` opens their players when they land,
/// so a long clip does not hold the frame while ffmpeg reads it.
pub sound_rx: Option<Receiver<Result<Vec<std::path::PathBuf>, String>>>,
@@ -54,17 +61,18 @@ pub struct Review {
}
impl Review {
/// The video player only draws; the audio players carry the gain and the mute.
fn mute_video(player: &Player) {
player.set_muted(true);
}
/// Set the gain from the transport bar. Sliding off zero is also how a viewer unmutes.
pub fn set_volume(&mut self, volume: f32) {
self.volume = volume.clamp(0.0, 1.0);
if self.volume > 0.0 {
self.muted = false;
}
if self.video_sound
&& let Some(player) = &self.player
{
player.set_volume(self.volume);
player.set_muted(self.muted);
}
for channel in &self.sounds {
channel.sound.set_volume(self.volume);
channel.sound.set_muted(!channel.heard(self.muted));
@@ -73,6 +81,11 @@ impl Review {
pub fn toggle_muted(&mut self) {
self.muted = !self.muted;
if self.video_sound
&& let Some(player) = &self.player
{
player.set_muted(self.muted);
}
for channel in &self.sounds {
channel.sound.set_muted(!channel.heard(self.muted));
}
@@ -107,13 +120,7 @@ impl Review {
let labels = self.track_labels();
if labels.len() < 2 {
// One track, or a recording made before the recorder split them: the file's own
// sound is the whole mix, and an audio player reads it as it is.
let label = labels
.first()
.cloned()
.unwrap_or_else(|| "All audio".to_string());
let channel = self.channel(0, label, path);
self.sounds.push(channel);
// sound is the whole mix, and the video player reads it as it is.
return;
}
let stem = self.stem(path);
@@ -131,15 +138,14 @@ impl Review {
return;
}
self.sound_tried = true;
let labels = self.track_labels();
if labels.len() < 2 {
self.open_sound(path);
if self.track_labels().len() < 2 {
// The video player carries the whole mix itself.
return;
}
self.channel_error = None;
let path = path.to_string();
let stem = self.stem(&path);
let count = labels.len();
let count = self.track_labels().len();
let (tx, rx) = channel();
std::thread::spawn(move || {
let _ = tx.send(crate::export::extract_tracks(&path, &stem, count));
@@ -226,7 +232,18 @@ impl Review {
}
}
fn playback(&mut self) {
/// Stop the video and its soundtrack players. The window is closing under them and the app
/// stays in the tray, so sound with no picture should not carry on.
pub fn pause(&mut self) {
if let Some(player) = &self.player {
player.pause();
}
for channel in &self.sounds {
channel.sound.pause();
}
}
pub(crate) fn playback(&mut self) {
let playing = self.player.as_ref().is_some_and(Player::is_playing);
if let Some(player) = &self.player {
if playing {
@@ -311,10 +328,6 @@ impl Review {
}
/// One audio track of the clip, copied to a file of its own and played on its own, so the
/// channels are heard apart and can be kept apart.
/// Rune's video player asks Media Foundation for pictures and sound from one reader, and that
/// reader stamps the sound from its own clock instead of the clip's, so the sound never lines
/// up with the clock and plays silent. Audio-only players read one track each and need no
/// video, so their sound starts at zero.
pub struct Channel {
/// What the track carries, as the recorder named it.
pub label: String,
@@ -349,11 +362,13 @@ impl Default for Review {
fn default() -> Self {
Self {
game: None,
video_roots: Vec::new(),
loading: false,
player: None,
sounds: Vec::new(),
sound_rx: None,
sound_tried: false,
video_sound: false,
steady_at: 0.0,
time: 0.0,
duration: 0.0,
@@ -396,7 +411,8 @@ pub fn open(app: &mut App, recording_id: &str) {
/// Fill the review screen with a timeline that has been read, and load its clip.
pub fn show(app: &mut App, game: Timeline) {
let path = game.video_path();
let roots = app.video_roots();
let path = game.video_path(&roots);
let highlights = highlight::compute(
&game,
game.summoner().as_deref(),
@@ -405,6 +421,7 @@ pub fn show(app: &mut App, game: Timeline) {
app.review.highlights = highlights;
app.review.duration = game.duration_secs.max(0) as f64;
let video_file = game.video_file.clone();
app.review.video_roots = roots;
app.review.game = Some(game);
let Some(path) = path else {
@@ -425,15 +442,23 @@ pub fn show(app: &mut App, game: Timeline) {
app.review.sound_tried = false;
app.review.channel_error = None;
app.review.steady_at = 0.0;
Review::mute_video(app.review.player.as_ref().expect("just set"));
// The timeline names several tracks, and cutting them is the slow part of opening a
// recording. Start it on a thread now, while the first picture decodes.
let many_tracks = app
let tracks = app
.review
.game
.as_ref()
.is_some_and(|game| game.audio_tracks.len() >= 2);
if many_tracks {
.map(|game| game.audio_tracks.len())
.unwrap_or_default();
// One track, or a recording made before the recorder split them: the clip's own sound is
// the whole mix, and the video player reads it as it is now that its sound keeps the
// clock. Several tracks: cut them, so the video is muted and the channels carry the sound.
app.review.video_sound = tracks < 2;
if let Some(player) = &app.review.player {
player.set_muted(app.review.muted || tracks >= 2);
player.set_volume(app.review.volume);
}
if tracks >= 2 {
app.review.request_sound(&path.to_string_lossy());
}
}
@@ -451,7 +476,7 @@ fn follow_sound(app: &mut App) {
.review
.game
.as_ref()
.and_then(history::Timeline::video_path)
.and_then(|game| game.video_path(&app.review.video_roots))
else {
return;
};
@@ -507,16 +532,11 @@ fn keep_in_step(app: &mut App) {
pub fn tick(app: &mut App, tx: &mut Tx) -> bool {
let mut changed = false;
if let Some(player) = &app.review.player {
// Rune reads a layered clip's place from the compositor clock, and that clock stops with
// playback, so the first pause can read zero and send the scrubber to the start. While
// the clip is paused the place is ours: only a seek moves it.
if player.is_playing() {
let time = player.time();
if (time - app.review.time).abs() > 0.001 {
app.review.time = time;
changed = true;
}
}
if let Some(duration) = player.duration()
&& duration > 0.0
&& (duration - app.review.duration).abs() > 0.05
@@ -557,6 +577,17 @@ pub fn tick(app: &mut App, tx: &mut Tx) -> bool {
app.review.export_note = Some(format!("Clip saved to {path}"));
app.review.export = None;
changed = true;
// The exported clip is what the user was after: open its view, with the
// folder listing refreshed so the view finds it.
if let Some(name) = std::path::Path::new(&path)
.file_stem()
.and_then(|stem| stem.to_str())
{
// The review's soundtrack would keep playing under the clip view.
leave(app);
app.refresh_clips();
crate::screens::clip::open(app, name);
}
}
Ok(Err(e)) => {
app.review.export_note = Some(format!("Export failed: {e}"));
@@ -898,7 +929,7 @@ fn channels(app: &App, p: Paint) -> Option<El> {
fn clip_row(app: &App, p: Paint, clip: Clip) -> El {
let video = app
.reviewed()
.and_then(|game| game.video_path())
.and_then(|game| game.video_path(&app.review.video_roots))
.map(|path| path.display().to_string());
let name = app
.reviewed()
@@ -1189,7 +1220,9 @@ fn highlights(app: &App, p: Paint, game: &Timeline) -> El {
for (index, clip) in app.review.highlights.iter().enumerate() {
let start = clip.start;
let end = clip.end;
let video = game.video_path().map(|path| path.display().to_string());
let video = game
.video_path(&app.review.video_roots)
.map(|path| path.display().to_string());
let name = format!("{}-highlight-{}", game.recording_id, index);
let kind_ink = match clip.kind {
highlight::Kind::Death => p.danger,
+4 -4
View File
@@ -397,8 +397,8 @@ fn quick(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, content:
"open-recordings",
"Open folder",
false,
|_app: &mut App| {
crate::daemon::open_folder(&crate::daemon::recordings_dir());
|app: &mut App| {
crate::daemon::open_folder(&app.output_dir());
},
)),
vec![ui::setting_row(
@@ -479,8 +479,8 @@ fn recording(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, cont
"open-output",
"Open folder",
false,
|_app: &mut App| {
crate::daemon::open_folder(&crate::daemon::recordings_dir());
|app: &mut App| {
crate::daemon::open_folder(&app.output_dir());
},
)),
vec![
+5 -4
View File
@@ -171,12 +171,13 @@ impl Quality {
}
}
/// What a quality level records at: the screen's resolution, at this bitrate.
pub fn detail(self) -> &'static str {
match self {
Quality::Low => "720p @ 30fps",
Quality::Medium => "1080p @ 30fps",
Quality::High => "1080p @ 60fps",
Quality::Ultra => "1440p @ 60fps",
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",
}
}
}
+51
View File
@@ -754,3 +754,54 @@ fn place(thumb: &rune::Live<[f32; 4]>, [x, y, w, h]: [f32; 4], at: rune::ScrollP
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(),
)
}
+16
View File
@@ -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"
+17
View File
@@ -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
View File
@@ -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
View File
@@ -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
+74
View File
@@ -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
View File
@@ -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
View File
@@ -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 }}
+17
View File
@@ -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
+71
View File
@@ -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.
+3239
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
Generated Vendored
+6407
View File
File diff suppressed because it is too large. Load diff
+293
View File
@@ -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
+21
View File
@@ -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.
+617
View File
@@ -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.
+66
View File
@@ -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
View File
@@ -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**
+296
View File
@@ -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.
@@ -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).
@@ -0,0 +1 @@
- **`rune::text::with_families` scopes `measure` to one thread.** Tests that switch font families (`Tx::set_font_families`) shared one process-wide set, so they had to run one at a time. `let _g = rune::text::with_families(sans, mono);` makes `measure`, `advance`, `ink` and `font_epoch` on this thread use those families until the guard drops; guards nest, and a headless window's switch under a guard moves only that thread. Real apps are unchanged: one switch still moves every thread.
@@ -0,0 +1 @@
- **`memo(id, ..)` warns in debug builds when its root already had a different key.** The memo still keys its root `id`, as before, but a closure returning `col().key("foo")` inside `memo("bar", ..)` now prints one stderr warning per call site saying `"foo"` was replaced, instead of silently breaking `find("foo")`. `RUNE_PERF_WARN=0` silences it; release builds are unchanged.
@@ -0,0 +1 @@
- **Mermaid edge labels follow hover.** On flowcharts, state and class diagrams, a node's hover now lights its edges' labels too (text and backing, in the hover colour), and pointing at an edge (within 8 pt of its line) or at its label lights that edge and its label. Nodes still win where they overlap; nothing in the API changed (t1058).
@@ -0,0 +1 @@
- **Mermaid draws ER diagrams, gantt charts and pie charts.** `erDiagram` entities are attribute tables (type, name, keys, comment) joined in crow's-foot notation, symbolic or worded, with labels. `gantt` reads `dateFormat`, `axisFormat`, `tickInterval`, sections, `done`/`active`/`crit`/`milestone`/`vert` tasks, durations, `after`/`until` links, `excludes` and `inclusiveEndDates`, on a calendar-aligned time axis. `pie` draws slices with percentages and a legend, with values under `showData`. Charts colour their series from a palette that follows the diagram's light or dark surface. These three no longer fall back to source (t1058).
@@ -0,0 +1 @@
- **Mermaid diagrams draw what they can read instead of falling back to source.** A statement that doesn't parse is skipped and the rest draws; a shape opener without its closer (`B[/items split view]`) is a plain rectangle with the text as written; subgraphs, composite states, frames and class bodies left open close at the end; unknown `@{ shape: … }` names are rectangles. Only an unknown diagram type, a source where nothing reads, or one past the size bounds (400 items, nesting 8 deep, now also for sequence frames) still falls back. Also adds `classDiagram`, sequence `box` groups and `rect` bands, `@{ shape, label }` nodes, edges to subgraph ids, `linkStyle` and diagram titles (front-matter `title:` or a `title` line), on one shared layered renderer for flowchart, state and class diagrams (t1058).
@@ -0,0 +1 @@
- **Mermaid draws mindmaps, timelines, user journeys, git graphs and quadrant charts.** `mindmap` nests by indentation and splits its branches to either side of the root, each in its own colour, with the square, rounded, circle, bang, cloud and hexagon shapes. `timeline` draws periods and their events by section, running top to bottom when they don't fit across. `journey` draws tasks under their sections with a face for each score and a legend of actors. `gitGraph` draws a lane per branch with merges, cherry-picks, tags and the reverse and highlight commit types, left to right or (`TB:`/`BT:`) down and up. `quadrantChart` draws the four named quadrants, axis ends and styled points. These no longer fall back to source (t1058).
@@ -0,0 +1 @@
- **rune-kit Markdown: a Mermaid chart that can't be drawn shows only its code block.** The "Diagram not supported" caption under it is gone, along with its `hint` element.
@@ -0,0 +1 @@
- **Mermaid flowcharts draw every node shape, and sequence and state diagrams fill their gaps.** Flowcharts add `(((double circle)))`, every v11 `@{ shape: … }` name and alias (documents, stacked shapes, cylinders, braces, markers, bang, cloud and the rest), and edge ids (`A e1@--> B`); `[\lean left\]` and `[\inverted trapezoid/]` now draw as their own shapes instead of copying `[/text/]` and `[/text\]`. Sequence diagrams add `create` and `destroy`, `autonumber` with a start, step or `off`, and v11 participant types (boundary, control, entity, database, collections, queue). State diagrams draw notes, split composites into `--` regions, and treat a state named before its `state X {` as that composite (t1058).
@@ -0,0 +1 @@
- **Mermaid draws XY charts, sankey, block, requirement and C4 diagrams.** `xychart-beta` draws bar and line series over category or numeric axes, upright or `horizontal`. `sankey-beta` reads CSV rows and draws columns of nodes joined by bands as thick as their flow. `block-beta` lays blocks out in `columns` with spans, `space`, nested groups, block arrows and edges. `requirementDiagram` draws requirements and elements with their fields, joined by the seven relationship kinds. `C4Context`, `C4Container`, `C4Component`, `C4Dynamic` and `C4Deployment` draw people, systems, containers and components (stores as cylinders, queues on their side, external ones in grey) in nested boundaries, with relationships and their technology. These no longer fall back to source (t1058).
@@ -0,0 +1 @@
- **rune-fx and rune-light run on the native Metal backend.** It gains compute passes and timestamps at pass boundaries (`TIMESTAMP_QUERY`), as wgpu's Metal backend has them, and new textures read as zero as wgpu promises (a fill's backdrop read garbage before). Simulated fire matches wgpu's frame for frame. A frame of 16 rune-fx layers with 4 backdrop blurs commits 1 command buffer instead of wgpu's 65 and takes 55% fewer instructions to record and submit (1.65 million against 3.69); rune-light with glass commits 1 instead of 31 or 47, with 53–55% fewer. `Device::poll` on Metal no longer reports an empty queue while a completion callback is still waiting, which could stall video timing.
@@ -0,0 +1 @@
- **The native Metal backend sets up as fast as wgpu.** Its adapter lists the Mac's GPUs with `MTLCopyAllDevices`, as wgpu-hal does, instead of `MTLCreateSystemDefaultDevice`, which connects to the window server to find the main display's GPU. A headless run's GPU setup (adapter, device, renderer and offscreen target) takes 7.5 ms instead of 16.1 (wgpu: 7.6), and a launch's `prewarm_gpu` thread finishes about 8 ms sooner. On a Mac with two GPUs the backend now picks the integrated one unless asked for `HighPerformance`, as wgpu does, and `enumerate_adapters` lists every GPU.
@@ -0,0 +1 @@
- **The native Metal backend loads a precompiled uber shader.** With `metal-backend` on and the backend picked, `Renderer::new` loads `uber_native.metallib` (the MSL that backend emits, compiled ahead) instead of translating WGSL and compiling Metal source. The first renderer takes 0.9 ms and 7.1 million instructions instead of 4.0 ms and 40 million on a warm shader cache, 90 ms instead of 222 ms on a cold one (the first launch after an install or update), and each later renderer 0.2 ms instead of 2.6 ms. The WGSL path stays the fallback, and `RUNE_DISABLE_METALLIB=1` still selects it. Shader edits now need `--features metal-backend` on the freshness test, and `scripts/precompile-metal-shaders.sh` rewrites both libraries.
@@ -0,0 +1 @@
- **Video plays on the native Metal backend.** `NativeSurface` frames from CoreVideo (AVPlayer, VideoToolbox, IOSurfaces) import without a copy through a `CVMetalTextureCache` made on the backend's own device, where they were inert before. Each plane's CoreVideo texture stays alive while any bind group or command buffer using it is, as on wgpu. A 1080p NV12 frame with GPU timing on both backends takes about 1.05 million instructions to import, draw and submit (2.15 million on wgpu), and 1.95 million through its timing readback (4.3 million on wgpu).
@@ -0,0 +1 @@
- **Delayed hover opens in a window that isn't key.** `on_hover_change` with `hover_delays` (tooltips, hover cards) no longer stays shut while the window is unfocused: blur still ends a shown hover and cancels a wait, and the pointer's next move over the window starts the wait again, as undelayed hover and hover styles already did. Clicks are unchanged; the first click on a background window still focuses it and acts. A window or overlay that ignores the mouse (`click_through`, `OverlayInput::None`) hears no hover; `OverlayInput::Regions` is the opt-in for an overlay that passes clicks through but still hovers (t1136).
@@ -0,0 +1 @@
- A page of rows prepended while a virtual list sits at its very top (its top padding showing) no longer pushes the reader's rows down as the new rows measure: the list anchors to the first visible row with a measured height, not a row still at its estimate.
@@ -0,0 +1 @@
- **Hidden prewarmed overlays no longer blank Mission Control.** On macOS, `OverlayOptions::exclude_from_capture` (and `MacWindowOptions::exclude_from_capture` on a nonactivating panel) now applies only while the overlay is shown. A prewarmed panel stays ordered in at alpha zero on every Space while hidden, and its `sharingType` none blanked every Space's thumbnail. The panel now turns `sharingType` none before a show's alpha starts rising and back to read-only once a hide's fade-out finishes; a show during that fade keeps it excluded. `OverlayHandle::set_exclude_from_capture` while hidden records the request for the next show, and `capture_exclusion()` still reports `Requested`. Apps that toggled exclusion around every show and hide can drop that. Windows already hides overlays with `SW_HIDE`, so nothing changes there.
@@ -0,0 +1 @@
- **Apps can build their own popovers from the kit's pieces.** New `rune_kit::popover` has `anchored` (mount a surface next to a keyed trigger, flipping and fitting to the window), `raised` (the popover surface style), `fit_scroll` (a long list that scrolls inside a fitted surface) and `anchor_rect` (the pure geometry: where a surface of a given size goes beside a trigger rect in a window, flipped and clamped). `rune::anchor_rect` is the same geometry for an `El::anchored` side and align. Apps no longer need local copies of the kit's private helpers. (t886)
@@ -0,0 +1,6 @@
- **`on_ready` runs for a window launched out of sight.** A window launched covered, occluded,
on another Space or hidden by the system (`open -g`) could go without a drawn first frame until
it was uncovered, so `App::on_ready`, and the live work an app starts there, never ran. It now
runs at the first frame skipped for being off screen, or a second after the window opens when
no frame comes at all. A window on screen still runs it after its first frame, and
`WindowHandle::is_ready` still waits for a drawn one.
@@ -0,0 +1,7 @@
- **A launcher can wait for readiness.** With `RUNE_READY_DIR` set, the process writes
`$RUNE_READY_DIR/<bundle id>.<pid>` right after its first `on_ready` returns (the main bundle's
identifier on macOS, else the executable's name), as one line of JSON:
`{"pid":123,"bundle_id":"com.example.app","ready_ms":412,"rune":"0.1.0"}`, `ready_ms` counted
from the process's start. It makes the directory 0700 if missing, writes through a renamed
temporary file, and removes the file when the process exits normally; one left by a killed
process names a PID that isn't running. Without the variable nothing is written.
@@ -0,0 +1,11 @@
- **Programmatic scrolls pick their spring, and an app's own glide holds hover.**
`Tx::scroll_to_with(key, x, y, spring)` glides like `Tx::scroll_to` on the given spring; a
request sent mid-glide keeps its speed, as `scroll_to` already did, so ↑/↓ key repeat keeping a
selection in view scrolls as one motion on a quicker spring than `GLIDE`. `scroll_to` itself is
unchanged. A viewport an app moves with `Tx::scroll_to_instant` (or `scroll_to_x`, `scroll_to_y`,
`scroll_key_to`) now counts as moving layout for that frame and the next, so hover under a
still pointer holds while an app steps its own glide frame by frame, as it does during a glide,
and resolves once at the pointer after the last step. A single instant jump under a still pointer now
re-hovers a frame later than before. A held hover whose row the scroll carried out of view lets go at once
instead of fading where nothing shows. The new `scroll_keys` example and its
`scripts/motion-audit` scenario hold ↓ at 30 Hz key repeat.
@@ -0,0 +1,5 @@
- **`Cx::selection_rects` finds selected text inside a reused `memo`.** A commit that reused
the memo holding the selection moved its nodes out of the last build before the view's
layout reads settled, so the boxes came back empty and a menu placed over the selection
never showed. Since commits under `El::hover_motion_within` started reusing memos, this hit
every app that sets it on its root. The selection is now read by path before the measure.
@@ -0,0 +1 @@
- **Scroll commit warnings, `RUNE_COMMIT_BUDGET_MS` and `El::scroll_anchor`.** Debug builds warn once per source when something commits the view on most frames of a scroll, which a scroll itself never needs, and name it: `poll`, a handler with its element and where it was set (`on_hover`, `on_hover_change`, `on_pointer_move`, `on_layout`, `on_drawn_layout` and `on_visible_rows` now record their call site), or the `Cx::layout` / `Cx::window_layout` read that moved. They also warn when an app steps a viewport with an instant scroll on 8 committing frames in a row, and when one hover handler commits for 8 different elements. `RUNE_COMMIT_BUDGET_MS=N` prints a line for each commit over `N` ms in any build, with view, layout, text and apply times and what made the frame commit, at most once a second. `El::scroll_anchor()` keeps the row at the top of a scroll viewport where it is when a commit changes the content above it, like CSS `overflow-anchor`. rune-kit's table and tree viewports and header cells no longer commit on every frame of an outer page's scroll, and a diff view's code lines no longer commit for each line the pointer crosses. `scripts/app-audit` checks for `window_layout`, layout and hover handlers without `live_only`, and instant scrolls stepped by `wake_after`. The README and the docs site's Fast apps page have a "Smooth scrolling" section.
@@ -0,0 +1 @@
- **`glyphs::STAR` and `glyphs::STAR_FILLED`.** Two five-point star icons on the 16 pt grid, outline and filled, drawn with the same 1 pt stroke and round joins as the other glyphs. They are not `Glyphs` slots: `icon(&glyphs::STAR, 16.0)`. (t886)
@@ -0,0 +1 @@
- **An `El::on_key_up` on any element hears releases while nothing is focused.** Only a handler on the root (or the open modal's root) fired, so one on a stage or other nested element never did. With no focus, the release is now offered to every element with a handler, deepest first and confined to the open modal, until one takes it; a focused element, and the element focused when the key went down, still hear it first.
@@ -0,0 +1,8 @@
- **Layout reads don't follow scrolling.** `Cx::layout`, `layout_with`, `layout_size` and
`memo::layout` now give where layout puts an element with every scroll viewport at its
origin, so a view reading a row inside a scrolling list no longer re-runs every frame of the
scroll; a commit that moves or resizes the element still re-runs it. A view that needs where
the window shows the element now, after scrolling, reads `Cx::window_layout` or
`window_layout_with` (and `memo::window_layout`). `El::on_layout` still reports after scrolling,
and the new `El::on_layout_tx` takes a `Tx`, so a handler that only moves live values says
`Tx::live_only` and a scroll runs no view.
@@ -0,0 +1,7 @@
- **What mounts out of sight enters at once.** An element new under one that drew nothing last
frame and still lies outside the window or its clips (a ticking digit in a row scrolled out of
view, or in a virtual list's overscan) skips its entrance, as its exit already did, so nothing
animates where nobody sees it. A matched element still flies to its match.
- **Colours out of sight land at once.** A node that drew nothing last frame and still lies
outside the window or its clips lands its colour, hover and blur changes instead of fading them
where nobody sees them (a list's selected row scrolled out of view when focus moves away).
@@ -0,0 +1,5 @@
- **A video scrolling across a clip edge no longer commits.** A list holding a video re-ran its
views each time the video scrolled into or out of sight, because only drawn videos counted
toward the state views read. Every video counts now, drawn or not, so a pure scroll stays
live-only. Frames are still pulled only while the video draws, and one scrolling back into
sight shows its current frame.
@@ -0,0 +1 @@
- `scripts/web-build.sh` stages each build in `$out/.next` and renames the files into place, so a page that loads mid-build no longer mixes `app.js` and `app_bg.wasm` from different builds (a `LinkError`); `--dev` skips the gzip size report.
@@ -0,0 +1 @@
- **`scripts/web-build.sh`: `--dev`, `--watch` and `--no-html`, and it keeps your own page.** `--dev` builds the debug profile without debug info, with dependencies at opt-level 1, in a `web-dev` target folder, skipping `--opt` (about 2 s for a one-line change to `web-hello`, against 12 s for release). `--watch` rebuilds when a workspace member's files change, and the generated page reloads itself through a `reload.js` that polls `.stamp`. `index.html` is now written only if it is missing or still carries the generated-by comment; `--no-html` never writes it. The script builds with the toolchain's own cargo (`rustup which cargo`, or `CARGO`) instead of a `cargo` on `PATH`, and says so if the wasm is missing afterwards.
@@ -0,0 +1 @@
- **`App::full_viewport` covers the browser viewport from a canvas the page passed in.** `App::canvas_id` still mounts inline at the parent's width, as before; adding `.full_viewport()` gives that canvas what Rune's own canvas gets: fixed to the visual viewport, body scrolling off, `Cx::safe_area` insets and `document.title` from the window title. For a single-page app's full-screen route. `fit_content_height` wins over it. The body lock now sets its three properties instead of replacing the body's inline style.
@@ -0,0 +1 @@
- **Web: `Tx::open_url_same_tab`, `App::same_tab_router` and unmount on `AppHandle::quit`.** `open_url_same_tab` replaces the page instead of opening a tab, taking page-relative links on web; a link on the page's origin goes to the app's router first (a single-page app pushes history and returns true), else `location.assign` loads it. Native opens it as `open_url` does. On web, `AppHandle::quit` now unmounts cleanly: the GPU device is destroyed, listeners come off, the body style, title and a passed-in canvas's style and attributes are restored, and an app started while another quits mounts once it has gone. `Runtime::take_url_requests` lists same-tab links with the rest.
@@ -0,0 +1 @@
- **Overlays show on GNOME Wayland through XWayland.** When the Wayland compositor has no layer-shell (Mutter), an overlay that takes no input (no pointer regions, no keys) now opens as an override-redirect ARGB X11 window on XWayland with an empty input shape, at its edge of the primary display (or the pointer's), instead of reporting `Availability::Unavailable`. Its scale comes from `Xft.dpi`. The rest of the app stays on Wayland; without `DISPLAY` nothing changes.
@@ -0,0 +1 @@
- **`El::drawn_rect_into(&Live<[f32; 4]>)` writes where each frame draws an element into a live value, with no handler and no commit.** It tracks every frame the element moves, through a scroll, a glide (`Tx::scroll_to`) and springs, where `on_drawn_layout` reports only once motion rests and commits unless its handler says `Tx::live_only`. An element bound to the value with `live_rect` follows a frame behind.
@@ -0,0 +1 @@
- **A fold's moving edge feathers shutting as well as opening.** An `El::fold_glide` row used to feather its bottom edge only while it opened; shutting, the edge was a hard cut. Now the edge softens both ways. The feather grows over the first ~50 ms of motion, holds steady through a reversal, and thins to nothing as the glide lands, so nothing is faded at rest. The top edge isn't feathered, so a header above the fold stays sharp. The new `El::fold_feather(pt)` sets one fold's feather depth, overriding its stack's `StreamEdge::mask_max`.
@@ -0,0 +1 @@
- **`rune-fx` builds an effect's pipeline the first time a frame draws it.** `FxRenderer::new` and `add_format` no longer build all eight effect families in both blends up front, along with the mask pyramid and backdrop blur passes. Each pipeline for a format and blend is built the first time a layer draws with it, and those one `prepare` needs are built in parallel. On a cold Metal shader cache on macOS, a renderer that adds a layer format and draws one glow reaches its first frame in 71 ms instead of 1.80 s: `new` takes 0.1 ms instead of 919, and `add_format` takes no time instead of 865. Warm, that's 6.2 ms instead of 7.9. Each family, blend or format a later frame draws for the first time costs 20 to 150 ms on a cold cache, once. Pixels are unchanged.
@@ -0,0 +1 @@
- **A virtual list keeps the rows still on screen mounted while a fold glides open over them, and the motion gate stops counting one-shots and toggled lists as loops.** A list windowed by the open fold's full height while it still glided, so a view that ran again mid-glide unmounted the rows under it at full opacity two frames before the fold covered them. The window now also keeps the rows drawn inside the viewport on the last frame, within an overscan of it. In `rune::motion_gate::check`, a phase that rests at 1 (a `.sequence` that played out, such as a one-shot fade) is no longer a loop: it isn't checked for `loop-jump`, and what it does after isn't hidden. A track without a phase loops only when it turns back on its own, not within half a second of an input, so a list toggled again and again no longer hides every finding in it. `loop-jump` also catches a loop back from a blink of up to 0.1 s off its rhythm, and an opacity dip that one input starts and another reverses is no longer a `flicker`.
Loaded 100 of 3828 files, more files were not shown because too many files have changed in this diff. Show more