Merge pull request #188 from storytold/m8/accessibility-2

feat(a11y): stage elements, timeline frames, keyboard menu bar, system contrast (M8)
This commit is contained in:
Tanish Manku authored and GitHub committed 2026-11-11 19:23:48 -07:00
commit 07e5bee2ae
22 files changed
+1739 -37

No files matched your search

+2
View File
@@ -82,6 +82,8 @@ OR Apache-2.0) is noted in the table.
| Tile binning on the GPU: count, prefix sum, scatter, per-tile lists | `crates/gpu/src/gpu_binning.rs`, `crates/gpu/src/bin.wgsl`, `crates/gpu/src/scan.wgsl` | The binning stages described for *Vello* (above) and Patrick Walton's *Pathfinder* (<https://github.com/servo/pathfinder>, Apache-2.0 OR MIT) design posts; the work-efficient scan of G. E. Blelloch, *Prefix Sums and Their Applications* (CMU-CS-90-190, 1990) | Our own arrangement (one invocation per row of a fill's tiles, no atomics) written from the public descriptions; no code or shaders copied (ADR 0048). |
| Hairlines: coverage falling off with the distance from the pixel centre to the line | `crates/render/src/hairline.rs`, `crates/gpu/src/fine.wgsl` | S. Gupta and R. F. Sproull, *Filtering Edges for Gray-Scale Displays* (SIGGRAPH 1981): anti-aliased lines by distance; standard | Public method; a one-pixel tent filter of the distance (ADR 0048). |
| Plural categories for whole numbers (zero, one, two, few, many, other) | `src/i18n/plural.rs` | Unicode CLDR, *Language Plural Rules* (`common/supplemental/plurals.xml`), <https://cldr.unicode.org>, Unicode License v3 (Unicode-3.0) | The integer rules rewritten as Rust `match`es from the published rules; no CLDR data file is bundled. |
| Stage elements as a multi-select list box; menu bar keyboard model (Alt/F10, arrows, access keys) | `src/stage_a11y.rs`, `src/menus.rs` | W3C *WAI-ARIA Authoring Practices Guide*, Listbox and Menubar patterns, <https://www.w3.org/WAI/ARIA/apg/> (W3C Software and Document License) | Keyboard behaviour learned from the published patterns; no code or text copied. |
| Reading the desktop's contrast setting | `src/platform.rs` | *XDG Desktop Portal*, Settings interface, `org.freedesktop.appearance` `contrast` key, <https://flatpak.github.io/xdg-desktop-portal/> (LGPL documentation, read only; nothing bundled or linked) | One value read through the `gdbus` tool. |
| Interface catalog format (TSV keyed by English, `@plural`/`@id` rows, fallback order) | `src/i18n/catalog.rs`, `build.rs` | storytold/craft-i18n `docs/catalog-format.md` and `docs/integration.md` (MIT OR Apache-2.0, same project family) | Our own parser written from those documents; the craft-libs `craft-i18n` crate is not used (ADR 0040). |
| Adaptive Bézier flattening (Wang's formula) | `crates/geom/src/path.rs` | G.-J. Wang (1984); public mathematical result | |
| Porter–Duff "source over" compositing, premultiplied alpha | `crates/render/src/lib.rs` | Porter & Duff, *Compositing Digital Images*, SIGGRAPH 1984 | Public; standard in every graphics stack. |
+25
View File
@@ -2,6 +2,31 @@
## Unreleased
* **Accessibility, second pass** (ADR 0064, M8).
* **Select on the stage from the keyboard.** With the stage focused (Ctrl+F6), Tab goes to
its elements, and a ring shows the focused one on the artwork.
* Tab, Shift+Tab and the arrows move between elements.
* Enter or Space selects one; Shift+Enter or Shift+Space adds it to the selection or
takes it out.
* Esc goes back to the stage.
* **Screen readers hear what is on the stage.** While the stage has focus, its elements are
a list ("Rectangle", "Text: Hello", "ball · Graphic: Ball"), each with its layer, place,
size, on-screen bounds and whether it is selected.
* **The active layer's frames are a list too.** Each item reads "Frames 1–24: keyframe ·
motion tween · label “walk”", and activating one moves the playhead there.
* **The timeline from the keyboard.** On the focused timeline, the arrows move the playhead
and the active layer, and each move is announced.
* **The menu bar from the keyboard** on Windows and Linux.
* Press and let go of Alt, or press F10. Then the arrows, Enter and Esc work as in other
applications.
* Alt+F, Alt+E and the rest open a menu directly. While Alt is held, each title shows its
letter underlined.
* **Follow system** is the new default theme. AniCraft switches to high contrast while
Windows uses a contrast theme, macOS has Increase Contrast on, the Linux desktop asks for
high contrast, or the browser prefers more contrast. Choosing Graphite or High contrast
keeps that palette.
* Headless: `element.select` takes `toggle`.
* **Test Movie in its own window, and opening documents on macOS** (ADR 0062, M8).
* **Control › Test Movie** (Ctrl+Enter) now opens in a **window of its own** on the desktop,
as in Animate. It is sized to the stage at 100 % (smaller if that wouldn't fit the
Generated
+1
View File
@@ -239,6 +239,7 @@ dependencies = [
"wasm-bindgen-futures",
"web-sys",
"web-time",
"winreg",
"winresource",
]
+6 -1
View File
@@ -124,6 +124,11 @@ cpal = { version = "0.18", optional = true }
[target.'cfg(target_os = "macos")'.dependencies]
fmv-macos-events = "=0.1.0"
# The system's high-contrast setting (ADR 0064): one registry value. MIT, already in the tree
# through craft-update.
[target.'cfg(windows)'.dependencies]
winreg = "0.55"
# The web build (ADR 0036, docs/web.md). The window draws with WebGL2 (glow): every current
# browser has it, the stage is drawn on the CPU there, and leaving wgpu out keeps the download
# smaller. The browser glue is wasm-bindgen's (MIT OR Apache-2.0), already under eframe's web
@@ -135,7 +140,7 @@ wasm-bindgen-futures = "0.4"
js-sys = "0.3"
# In the browser the page's language (navigator.languages) is the system's.
sys-locale = { version = "0.3", features = ["js"] }
web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "Navigator", "Storage", "Url", "Window", "console"] }
web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "MediaQueryList", "Navigator", "Storage", "Url", "Window", "console"] }
[build-dependencies]
# Embeds the app icon in anicraft.exe on Windows (build.rs); does nothing on other targets.
+13 -6
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
}),
c("edit.delete", "Clear", "Edit", Some("Delete"), "{} (on every layer with selected items)", true, delete_selection),
c("edit.duplicate", "Duplicate", "Edit", Some("Ctrl+D"), "{dx?, dy?} (each copy on its original's layer)", true, |s, p| s.each_layer(true, |s| duplicate(s, p))),
c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); the active layer becomes the first one's unless it has some of them", false, select),
c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool, toggle?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); `toggle` takes each one that is selected out of the selection and adds the others (Shift+Space on a stage element); the active layer becomes the first one's unless it has some of them", false, select),
c("element.pick", "Select at Point", "", None, "{x, y, add?: bool} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer", false, pick),
c("element.translate", "Move", "", None, "{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends (the nearest to `from`) then snaps onto a point, line or fill edge of the rest within that distance", true, translate),
c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, |s, p| s.each_layer(true, |s| set_transform(s, p))),
@@ -210,6 +210,7 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Param(format!("param 'ids' has more than {MAX_SELECT} ids")));
}
let add = opt_bool(p, "add")?.unwrap_or(false);
let toggle = opt_bool(p, "toggle")?.unwrap_or(false);
// Where each element is at the playhead: on `layer`, else the active layer first, then the
// others top to bottom.
let order: Vec<LayerId> = match opt_u64(p, "layer")?.map(LayerId) {
@@ -234,11 +235,17 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
}
picked.push((l, id));
}
if !add {
s.selection.clear();
}
for &(l, id) in &picked {
s.selection.insert(l, id);
if toggle {
for &(l, id) in &picked {
s.selection.toggle(l, id);
}
} else {
if !add {
s.selection.clear();
}
for &(l, id) in &picked {
s.selection.insert(l, id);
}
}
// As a click does: the active layer is where the artwork is.
if let Some(&(l, _)) = picked.first()
+11
View File
@@ -562,3 +562,14 @@ fn clicking_a_layer_name_selects_its_artwork() {
run(&mut s, "layer.select", json!({"layer": bottom.0, "select": true}));
assert!(s.selection.is_empty());
}
#[test]
fn select_with_toggle_takes_one_out_and_puts_it_back_across_layers() {
// Shift+Space on a stage element (ADR 0064): the others stay selected, on either layer.
let (mut s, top, bottom, a, b) = two_layers();
run(&mut s, "element.select", json!({"ids": [b.0], "toggle": true}));
assert!(s.selection.contains(top, a) && !s.selection.contains(bottom, b));
run(&mut s, "element.select", json!({"ids": [b.0], "toggle": true}));
assert!(s.selection.contains(top, a) && s.selection.contains(bottom, b));
assert!(s.execute("element.select", &json!({"ids": [b.0], "toggle": "yes"})).is_err(), "toggle is a bool");
}
+86 -19
View File
@@ -2,7 +2,8 @@
AniCraft aims to be usable with the keyboard alone, with a screen reader, at large interface
sizes and in high contrast. This page says what works today, how to check it, and what doesn't
work yet. Design decisions are in ADR 0022; the rules for contributors are in
work yet. Design decisions are in ADR 0022 (first pass) and ADR 0064 (stage elements, timeline
frames, the keyboard menu bar, the system's contrast setting); the rules for contributors are in
`docs/ui-guidelines.md`.
## What is supported
@@ -29,9 +30,32 @@ work yet. Design decisions are in ADR 0022; the rules for contributors are in
the selected items at the centre of the view on the active layer (sounds on its keyframe at
the playhead), as dragging them onto the stage does; F2 renames and Delete deletes. Place on
Stage is also a button under the list and in each row's right-click menu.
* Frames are reached with `,` and `.` (previous and next), Home and End, F5/F6/F7 to insert,
and Shift+`,`/`.`; layers with the layer rows (Tab from the timeline anchor) and the
Up/Down buttons under them.
* **Select on the stage without a pointer** (ADR 0064). With the stage focused (Ctrl+F6),
press **Tab**: focus goes to the first selected element, or the first one, and a ring shows
it on the artwork.
* **Tab**, **Shift+Tab** and the **arrow keys** move between elements, layers top to bottom
and each front to back, wrapping.
* **Enter** or **Space** selects the focused element alone. **Shift+Enter** or
**Shift+Space** adds it to the selection or takes it out, as Shift-click does.
* The other shortcuts keep working: select with Space, then Delete, F8 (Convert to Symbol)
or Ctrl+D.
* **Esc** goes back to the stage itself, where the arrows nudge the selection again.
* Elements on locked layers are listed, but can't be selected.
* **The timeline from the keyboard.** With the timeline focused, **Left** and **Right** move
the playhead a frame, and **Up** and **Down** move to the layer above or below.
* Each move is announced: "Frame 12 · Ball · Frames 1–24: keyframe · motion tween".
* `,` `.` Home and End go to frames as always, F5/F6/F7 insert, and Shift+`,`/`.` extend.
* **The menu bar from the keyboard** (Windows and Linux, ADR 0064). Press **Alt** alone (press
and let go) or **F10**: File gets focus, and each menu title shows its letter underlined.
* **Left** and **Right** move between menus. **Down**, **Enter** or **Space** opens one.
* **Up** and **Down** move through its items, wrapping.
* **Right** goes into a submenu (or on to the next menu), and **Left** comes back.
* **Enter** runs an item, and the keyboard returns to where it was.
* **Esc** closes the menu; press it again (or Alt, or F10) to leave the bar.
* **Alt+letter** opens a menu directly: Alt+F File, Alt+E Edit, Alt+V View, Alt+I Insert,
Alt+M Modify, Alt+C Commands, Alt+O Control, Alt+W Window, Alt+H Help. An Alt+letter you
have bound in the shortcut sheet keeps your binding.
* On macOS the menus stay as they are: ⌘K (the command palette) reaches every menu command.
### Screen readers
@@ -45,14 +69,44 @@ UI Automation on Windows, NSAccessibility on macOS, AT-SPI on Linux.
* Number fields say what they are and what they hold: "Position X, spin button, 120".
* The stage is announced as a canvas with the tool in hand, the frame and the selection:
"Stage · Selection tool · frame 12 · 1 element selected".
* **While the stage has focus, its elements are a list** under it: "5 elements on frame 1".
* Each element is an option with a name: the instance name first, then what it is, such as
"Rectangle", "Oval", "Polygon", "Line", "Bitmap", "Text: Hello" or "ball · Graphic: Ball".
* Its description gives the layer, place and size ("Layer Hills · x 120, y 80 · 200 × 40
px").
* It says whether it is selected, and its position in the list. Its bounds are where it is
on screen.
* A reader's "click" (activate) on an option selects it.
* A frame with more than 2,000 elements lists the first 2,000, and says how many more there
are.
* **The active layer's frames are a list** under its frame grid, one item per keyframe span:
"Frames 1–24: keyframe · motion tween · label “walk” · sound · actions".
* The span under the playhead is marked selected.
* Activating a span moves the playhead to it.
* The status bar is a live region: after an action a screen reader reads its result ("Deleted
layer — Ctrl+Z to undo") without moving focus.
* A test (`a11y::tests`) runs the whole interface without a window in 23 states and fails if
any interactive control has no name or no role.
* A test (`a11y::tests`) runs the whole interface without a window and fails if any
interactive control has no name or no role. It covers 23 states, plus the stage list with an
element focused, the timeline's span list and an open menu. Other tests drive the keyboard:
stage selection, the timeline arrows, and the menu bar.
### High contrast
Preferences › Appearance › Theme › **High contrast**: white text on black, yellow for focus,
Preferences › Appearance › Theme › **Follow system** is the default: AniCraft switches to high
contrast while the system asks for more contrast, and back when it doesn't, within a few
seconds. It reads:
* **Windows:** a contrast theme (Settings › Accessibility › Contrast themes, or Left Alt +
Left Shift + Print Screen).
* **macOS:** Increase Contrast (System Settings › Accessibility › Display).
* **Linux:** the desktop's contrast setting, through the XDG desktop portal, or GNOME's High
Contrast where there is no portal.
* **The web:** the browser's `prefers-contrast: more`.
The note under the choice says what the system says now. Choosing **Graphite** or **High
contrast** keeps that palette whatever the system says.
Theme › **High contrast**: white text on black, yellow for focus,
selection and the active tool, a visible outline on every button and field, brighter timeline
blocks with black marks. Every text colour reads at 7:1 or more on its background (WCAG AAA);
controls, focus rings and timeline blocks at 3:1 or more. The default Graphite theme meets WCAG
@@ -74,7 +128,9 @@ Run from a checkout:
cargo run # as you use it
cargo run -- --theme high-contrast --scale 200 # high contrast at 200 %, not saved
cargo run -- --theme high-contrast --open prefs --screenshot shots/hc.png
cargo test --bin anicraft a11y # the AccessKit audit and panel focus
cargo test --bin anicraft a11y # the AccessKit audit, panel focus, stage, timeline and menu keys
cargo run -- --open stagekeys --screenshot shots/s.png # an element focused on the stage
cargo run -- --open menukeys --screenshot shots/m.png # the menu bar from the keyboard
cargo test --bin anicraft palette # the contrast checks
```
@@ -88,7 +144,11 @@ cargo test --bin anicraft palette # the contrast checks
3. **Tab** through the tools and Properties: every control is read with a name, number fields
with their value ("Stage width, 1280 px").
4. Press **Delete** with something selected: Narrator reads the status message.
5. Accessibility Insights for Windows (free, from Microsoft) shows the UI Automation tree if you
5. On the stage, press **Tab**: Narrator reads the element ("star · Graphic: Star, not
selected, 2 of 5"). Use the arrows to move, and **Space** to select. Narrator's scan mode
(Caps Lock+Space) also walks the list.
6. Press **Alt**, then the arrows: Narrator reads each menu and item.
7. Accessibility Insights for Windows (free, from Microsoft) shows the UI Automation tree if you
want to inspect names and roles directly.
### macOS: VoiceOver
@@ -107,20 +167,23 @@ cargo test --bin anicraft palette # the contrast checks
## Known gaps
* **Elements on the stage are not exposed one by one.** A screen reader hears the stage, the
tool and how many elements are selected, not each shape. Select with the keyboard
(Ctrl+A, Tab through Properties) and edit values in Properties.
* **Single frames are not exposed.** Each layer's frames are one clickable area; the keyboard
route is `,` `.` Home End and F5/F6/F7 at the playhead.
* **Stage elements are named by what they look like.** A shape is a rectangle, oval, polygon
or line only when its outline is one; a brush or pencil stroke is a "Shape". Give an
instance a name in Properties to hear it. Moving or transforming the focused element uses
the nudge keys (after Esc) or the Properties fields.
* **Only the active layer's frames are listed**, as spans (a keyframe and the frames after
it), not one item per frame. Up and Down on the focused timeline change the active layer.
* **Menus have no per-item letters.** Inside an open menu, use the arrows. While a menu is
open, single-letter tool shortcuts still work.
* **The Motion Editor graph is pointer only.** Its values are editable in the property list
beside it, and so are the eases (the Ease menu).
* **Adding a point in Edit Envelope takes a click.** Each point is named for screen readers
("Point 2 of 4, Left channel: 80 % at 0.400 s"), and the selected point's time and levels
are fields that take typed values; the Effect menu sets any preset from the keyboard.
* **The system's high-contrast or "increase contrast" setting is not followed automatically.**
Choose High contrast in Preferences.
* **The menu bar can't be opened from the keyboard** (no Alt or F10 yet). Every menu command is
in the command palette (Ctrl+K) and most have a shortcut.
* **The system's light or dark setting is not followed**: AniCraft has one standard (dark)
palette. Windows' white contrast themes get the black high-contrast palette.
* **macOS has no keyboard route to AniCraft's own menu row**: use ⌘K, which lists every menu
command.
* **Tab order across panels** follows how the window is built (menu bar, edit bar, tools,
right-hand panels, timeline, stage). Ctrl+F6 gives the panel order listed above.
* **Scroll bars inside lists** have no name (egui doesn't offer one).
@@ -129,4 +192,8 @@ cargo test --bin anicraft palette # the contrast checks
pseudo-locale too and fails on a name that stayed English. Document text (layer and symbol
names) is announced as written.
* **Manual passes with Narrator, VoiceOver and Orca** are still to do on real machines for each
platform. The automated audit checks names and roles, not how each reader phrases them.
platform. **What has been verified (ADR 0064):** the AccessKit tree AniCraft publishes, by
automated tests on Windows: names, roles, selected states, bounds, focus, the list box under
the stage canvas and the span list under the frame grid. Screenshots show the keyboard
states. No live screen reader has been run against the second pass yet, so how each reader
phrases the stage options and announces the status bar is still to check.
+146
View File
@@ -0,0 +1,146 @@
# ADR 0064: Accessibility, second pass: stage elements, timeline frames, keyboard menu bar, system contrast
* Status: accepted (2026-11-11)
* Relates to: ADR 0022 (first pass), ADR 0004 (no modal interruptions), ADR 0006 (platforms),
ADR 0040 (translatable interface), ADR 0044 (selection across layers); `docs/accessibility.md`
is the user guide
## Context
The first pass (ADR 0022) named every control, added Ctrl+F6 panel focus, a high-contrast
palette and a 200 % scale. Its known gaps were the parts of the window where the work happens,
plus two platform conventions:
* The stage was one canvas node. A screen reader heard "Stage · Selection tool · frame 12 ·
1 element selected" and nothing about what was on it. Selecting anything took a pointer
(or Ctrl+A).
* Each layer's frames were one clickable area: a screen reader couldn't hear what was at a
frame (keyframe, tween, label), and the arrow keys on the focused timeline nudged artwork.
* The menu bar couldn't be reached from the keyboard. On Windows and Linux Alt and F10 do that
in every application.
* Windows' contrast themes, macOS' Increase Contrast and the GNOME/portal contrast switch were
ignored. High contrast had to be chosen in Preferences.
egui 0.36 publishes its widgets through AccessKit but has no API for nodes that aren't
widgets, and no keyboard navigation of its menu bar.
## Decisions
1. **Stage elements are a list box under the stage, only while the stage has the keyboard**
(`src/stage_a11y.rs`). The canvas node gets one child, a multi-select `ListBox` "12 elements
on frame 4". It has one `ListBoxOption` per element on the current frame: layers top to
bottom, each front to back (picking order). An option carries:
* its **name**: the instance name first (document text), then what the element is.
Shapes are named by their outline: "Rectangle" (axis-aligned four sides, or rounded),
"Oval" (four curves), "Polygon", "Line", else "Shape". The rest are "Bitmap",
"Movie clip: Ball", "Text: Hello…" (one line, 80 characters).
* its **description**: the layer, position and size in pixels.
* its **bounds** on screen, so the reader's highlight lands on the artwork.
* **selected**, its place in the set, **disabled** on a locked layer, and a Click action.
The tree stays the size it was while the stage isn't focused, and the rest of the window
keeps its tab order. **At most 2,000 options**; beyond that one label says how many more
there are and how to reach them (picking, Select All, Find). Options are egui widgets with a
zero-size interaction rect: keyboard focus stops with the right AccessKit focus, but no
pointer area over the canvas. Their parent is set with `UiBuilder::accessibility_parent`.
The bounds of all elements come from one pass over the display list, not one per element.
Rejected: options for every element at all times (thousands of nodes and Tab stops in every
frame), and patching AccessKit's tree after egui (no API; it would fight egui's ids).
2. **Keyboard selection on the stage.** Tab on the focused stage goes to the first selected
element, or the first one. From there Tab, Shift+Tab and the arrows move between elements,
wrapping (a composite widget, like a grid). Enter or Space selects the element alone;
Shift+Enter or Shift+Space adds it to the selection or takes it out (Shift-click). Esc goes
back to the stage itself, where the arrows nudge again, and Ctrl+F6 leaves the panel.
* The focused element has a 2 px accent ring on the artwork, and the status bar (a live
region) says its name and state.
* Selection runs `element.select`, the command a click, the CLI and MCP use. It gains
`toggle?: bool` for Shift+Space. A locked layer's element is listed but refuses, as a
click does.
* Other shortcuts keep working on a focused element: select with Space, then Delete,
F8 or Ctrl+D.
3. **Timeline frames.** The active layer's frame grid gets a `List` of its keyframe spans.
Each item says "Frames 1–24: keyframe · motion tween · label “walk” · sound · actions"
(blank keyframe; classic, shape, motion or broken tween). The span under the playhead is
selected, and a reader's Click moves the playhead there. At most 1,000 items, then a
summary. On the **focused timeline** Left/Right move the playhead a frame and Up/Down move
the active layer (keyboard focus follows the row), instead of nudging artwork. Moves made
while the timeline has the keyboard (arrows, `,` `.` Home End) are announced through the
status bar: "Frame 12 · Ball · Frames 1–24: keyframe · motion tween". Nothing is announced
during playback.
4. **The menu bar from the keyboard, Windows and Linux conventions** (`menus::MenuKeys`).
* **Alt** pressed and let go alone, or **F10**, focuses File; again (or Esc) gives the
keyboard back to where it was.
* Left/Right move between menus (and keep a menu open if one was). Down, Enter or Space
opens one and focuses its first enabled item.
* In a menu, Up/Down wrap. Right enters an open submenu, or else goes on to the next menu.
Left comes back out of a submenu, or else goes to the previous menu.
* Esc closes the menu, back on its title. An item chosen with Enter runs, and the keyboard
returns to where it was before the bar.
* **Alt+letter** opens a menu directly, and titles show their letter underlined while Alt
is held or the bar has the keyboard. The letters are computed from the titles in the
interface language: the first free letter, word starts first, ASCII only (File, Edit,
View, Insert, Modify, Commands, c**O**ntrol, Window, Help). They are also each title's
AccessKit access key.
* Access keys run **before** the shortcut table because egui matches a plain "V" with Alt
held. An Alt+letter the user has bound in the shortcut editor keeps its binding.
* The Enter or Space that pressed an item is used up there, so it can't also press a button
in what the item opens (the command palette's field).
* Navigation reads each menu's focusable widgets from egui's widget list for that popup
layer, sorted top to bottom. egui's own arrow navigation is geometric across the whole
window and would leave the menu.
* **macOS is unchanged.** Its conventions differ (Ctrl+F2 reaches the system menu bar, and
Option isn't a menu key), and ⌘K reaches every menu command. `platform::menu_bar_keys`
makes the choice, and a browser on a Mac follows the Mac.
5. **Following the system's contrast setting** (`platform::system_high_contrast`), each system
read without `unsafe`:
* Windows: the `HighContrast` `Flags` value in the user's registry (`HCF_HIGHCONTRASTON`),
through `winreg` (MIT, already in the tree through craft-update).
* macOS: `defaults read com.apple.universalaccess increaseContrast`.
* Linux and the BSDs: the XDG desktop portal's `org.freedesktop.appearance contrast` through
`gdbus` (1 s timeout), else GNOME's `high-contrast` through `gsettings`.
* The web: `matchMedia("(prefers-contrast: more)")`.
The app asks on a worker thread at start, every 4 s and when the window comes back to the
front. A changed answer switches the palette in the same frame. Screenshot runs and tests
never ask, so they look the same on every machine.
**Preferences › Theme** gains **Follow system**, the default: high contrast while the system
asks for it, graphite otherwise. Its note says what the system says now. The choice is
`theme_follows_system: Option<bool>`. `None` (every file from before) follows the system,
unless the file had chosen high contrast, which keeps it. `--theme` turns following off for
the run.
Rejected: a D-Bus crate for Linux (another dependency tree for one value; `zbus` is in the
tree only async, under AccessKit), and a native API on each system (each needs `unsafe`).
6. **Light themes are not followed.** AniCraft has one standard palette (dark, as Animate's
default). The system's light/dark setting has nothing to map to until a light palette
exists. Windows' white contrast themes get our black high-contrast palette.
## Consequences
* The AccessKit audit now also covers the stage list with an element focused, the active
layer's span list, and an open menu (egui's menu area node is named as a `Menu`, which the
audit had never seen open).
* New tests drive the window headless:
* keyboard selection on the stage (Tab, arrows, wrap, Space, Shift+Space, Enter, a locked
element, Esc);
* timeline arrows with announcements and layer focus;
* menu bar navigation (F10, an Alt tap, Alt+letter, arrows, wrap, Esc twice, Enter running
an item and focus returning);
* the palette following the system;
* old preference files.
* `--open stagekeys` and `--open menukeys` replay key presses for screenshots of those states.
* Not in this slice:
* element names beyond the outline heuristic (a pencil stroke is a "Shape");
* moving or transforming the focused element with keys other than nudge (Free Transform's
fields do that);
* per-item access keys inside menus;
* a light palette;
* Windows' white contrast theme as a white palette;
* live screen-reader passes on real machines (`docs/accessibility.md` says what was
verified).
+7
View File
@@ -76,6 +76,13 @@ Apache-2.0) and `aho-corasick` (Unlicense OR MIT), built with only the `std`, `p
`unicode-case` and `unicode-perl` features. They match Find and Replace's patterns in linear
time with size limits. No new licence.
### System contrast setting (2026-11-11, ADR 0064)
New direct dependency on Windows only: `winreg` 0.55 (MIT, crates.io), already in the tree
through `craft-update`. It reads one registry value, the high-contrast flag. The web build
turns on web-sys's `MediaQueryList` feature (same crate, same licence). macOS and Linux ask
system tools (`defaults`, `gdbus`, `gsettings`), so nothing is linked. No new licence.
### Interface languages (2026-11-10, ADR 0040)
New crate: `sys-locale` 0.3 (MIT OR Apache-2.0, crates.io), which reads the system's interface
+3 -3
View File
@@ -24,7 +24,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
| Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). Not yet: native macOS NSMenu, macOS/Linux CI runners. Verified on Windows only so far. |
| Installers & release | **Packaging** (ADR 0026, `docs/release.md`): the Craft family's `packaging/` layout behind the shared release workflow. Windows MSI (x64, arm64; per-user by default, everyone on request, upgrades in place), portable and symbols zips; macOS universal DMG with a laid-out window and CLI zip; Linux AppImage, deb, rpm, tar.gz, Flatpak and Arch (x86_64, aarch64; riscv64 deb/rpm/tar). `.anicraft` opens AniCraft by default; `.fla`/`.xfl` offered under Open with. Signed and notarized on the `release` branch (missing secrets fail it), unsigned elsewhere; ends in a draft release. Packaging lint and a fixture WiX build guard PRs; `src/packaging_tests.rs` keeps ids and types in step. **Opening documents on macOS** (ADR 0062): a double-click in Finder, a drop on the Dock icon or Open With opens the document, at launch or while running (the open-documents Apple Event through `platform.rs`, by `fmv-macos-events`, so no `unsafe` of ours), through the unsaved-changes guard; the Dock's Quit asks to save too; Windows and Linux command-line hand-over covered by a test. Not yet: verified on a Mac (the checklist is in ADR 0062), a single running AniCraft taking a second document on Windows and Linux, AppImage desktop integration, portable mode, store listings, video export inside the Flatpak. |
| Languages | **First slice** (ADR 0040, `docs/localisation.md`): every shell string goes through `tr!`/`trn!` (keyed by its English; placeholders; CLDR plurals for whole numbers), menus translate the registry's labels when drawn (ids, CLI, MCP and the file format stay English), screen-reader names too. Catalogs are craft-i18n's TSV, read by our own parser and embedded from `CRAFT_I18N_DIR` (fallback app → shared → base language → English). Preferences › Appearance › Language (system language by default) and `--lang`. A **pseudo-locale** (`--lang pseudo`: accented, a third longer, bracketed) tests layout; checked by a source guideline test and a pseudo-locale accessibility audit; `scripts/i18n-extract.sh` writes the translators' template and per-locale coverage. Not yet: a real language (craft-i18n has no `anicraft.tsv` yet), engine messages and confirmation bodies (`@msg`), default document names, right to left (needs bidi and shaping in egui upstream), CJK and Georgian (need a font), shaped scripts. |
| Accessibility | **First pass** (ADR 0022, `docs/accessibility.md`): AccessKit (via eframe) gives every control a name and role, checked by a headless test that walks the tree in 23 interface states (custom-painted tools, layer rows and toggles, icon buttons, Library rows, every Properties field, the Motion Editor, every dialog; the stage is a named canvas; the status bar a polite live region). **Ctrl+F6 / Ctrl+Shift+F6** move focus between Stage, Timeline, Properties, Library and Tools (rebindable); focused controls keep Enter/Space/arrows while other shortcuts still work; pointer-only surfaces are not Tab stops. **High contrast** palette (Preferences › Theme) from the same roles, text ≥ 7:1, controls and focus ≥ 3:1; both palettes checked by the contrast test (the graphite one now meets AA everywhere). **Interface scale** 75–200 % holds up (stage refits, tools and timeline header scroll, status truncates). Not yet: stage elements and single frames exposed one by one, keyboard menu bar, following the OS contrast setting, manual passes with Narrator, VoiceOver and Orca. |
| Accessibility | **First pass** (ADR 0022, `docs/accessibility.md`): AccessKit (via eframe) gives every control a name and role, checked by a headless test that walks the tree in 23 interface states (custom-painted tools, layer rows and toggles, icon buttons, Library rows, every Properties field, the Motion Editor, every dialog; the stage is a named canvas; the status bar a polite live region). **Ctrl+F6 / Ctrl+Shift+F6** move focus between Stage, Timeline, Properties, Library and Tools (rebindable); focused controls keep Enter/Space/arrows while other shortcuts still work; pointer-only surfaces are not Tab stops. **High contrast** palette (Preferences › Theme) from the same roles, text ≥ 7:1, controls and focus ≥ 3:1; both palettes checked by the contrast test (the graphite one now meets AA everywhere). **Interface scale** 75–200 % holds up (stage refits, tools and timeline header scroll, status truncates). **Second pass** (ADR 0064): while the stage has focus its elements are a list box under the canvas (name from the instance name and outline or kind, layer, place and size, bounds, selected; 2,000 at most plus a summary); **Tab, arrows, Enter/Space and Shift+Space select on the stage** through `element.select` (new `toggle`); the active layer's keyframe spans are a list (frames, tween, label, sound, actions; activating one moves the playhead); on the focused timeline the arrows move the playhead and layer, announced through the status bar; **the menu bar from the keyboard** on Windows and Linux (Alt tap or F10, arrows, submenus, Esc, Alt+letter with underlined access keys); **Follow system** (the default theme) switches to high contrast with Windows' contrast themes, macOS' Increase Contrast, the portal/GNOME contrast setting and `prefers-contrast` in browsers. Not yet: names beyond the outline heuristic, per-item menu letters, a light palette, a keyboard route to the menu row on macOS (⌘K covers it), manual passes with Narrator, VoiceOver and Orca. |
| Stage rendering & build | **Tiled stage** (ADR 0007): 512 px cached tiles, batched per frame with one scene evaluation per frame, look-ahead ring and playback prefetch, scaled older tiles instead of blank areas, pixel-aligned (no seams). **Space-biased build**: debug build 6.9 GB → 1.04 GB, fresh build 44 s, edit rebuild 4–6 s (`docs/development.md`). |
| Scale & performance | Pulled forward from M2: persistent document with snapshot undo (memory-budgeted history, save-point dirty tracking, History panel), background render worker with frame cache and playback look-ahead, band-parallel renderer with culling, compact streaming file format v2, `anicraft-cli bench`. Measured numbers are in `docs/performance.md`. Memory, sharing, file-size and culling budgets are a test on every PR; timing budgets are `anicraft-cli bench --check yes` (all met; the 1080p render is 15.3–15.8 ms against 16.7 ms). |
@@ -40,7 +40,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. |
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. |
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. |
| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails; next: exact desktop drop positions with winit 0.31, SVG into the Library, drops on the timeline, templates); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); documentation book. |
| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node; next: Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), next: live screen-reader passes on each platform, a light palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails; next: exact desktop drop positions with winit 0.31, SVG into the Library, drops on the timeline, templates); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); documentation book. |
## Releases
@@ -61,7 +61,7 @@ titled with its milestone.
| M5 | Audio layers: import, waveform, playback sync | timeline, layers |
| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player |
| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation |
| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); next: the accessibility follow-ups | `.anicraft` format, session, AccessKit in eframe |
| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); ~~accessibility second pass~~ ✅ (ADR 0064); next: live screen-reader passes | `.anicraft` format, session, AccessKit in eframe |
Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and
ActionScript (on M6's plug-in host).
+237
View File
@@ -437,6 +437,243 @@ mod tests {
assert!(app.playing, "Enter on the focused stage plays");
}
/// Presses `key` and lets a frame pass for focus to settle. Returns the last frame's tree.
fn key(ctx: &egui::Context, app: &mut App, key: egui::Key, modifiers: egui::Modifiers) -> Option<TreeUpdate> {
frame(ctx, app, press(key, modifiers));
frame(ctx, app, input(1.0)).platform_output.accesskit_update
}
fn focus_stage(ctx: &egui::Context, app: &mut App) {
while focused_region(ctx) != Some(Region::Stage) {
key(ctx, app, egui::Key::F6, egui::Modifiers::COMMAND);
}
}
fn node(t: &TreeUpdate, id: egui::Id) -> Option<&Node> {
t.nodes.iter().find(|(n, _)| *n == id.accesskit_id()).map(|(_, n)| n)
}
#[test]
fn the_stage_lists_its_elements_and_selects_them_from_the_keyboard() {
let (_, mut app, ctx) = tree(|_, _| {});
// Unfocused, the stage has no element nodes: the tree stays small.
assert!(app.stage_nav.focused(&ctx).is_none());
focus_stage(&ctx, &mut app);
app.run("edit.deselect", serde_json::json!({}));
let (items, total) = crate::stage_a11y::items(&app);
assert!(items.len() >= 2 && total == items.len(), "the sample frame has a few elements: {items:?}");
// Tab goes into the list, to the first element.
let t = key(&ctx, &mut app, egui::Key::Tab, egui::Modifiers::NONE).unwrap_or_else(|| panic!("no tree"));
let first = app.stage_nav.focused(&ctx).unwrap_or_else(|| panic!("Tab on the stage focuses an element"));
assert_eq!(first, (items[0].layer, items[0].element));
let n = node(&t, crate::stage_a11y::node_id(first.0, first.1)).unwrap_or_else(|| panic!("the element has a node"));
assert_eq!(n.role(), Role::ListBoxOption);
assert_eq!(n.label(), Some(items[0].name.as_str()));
assert_eq!(n.is_selected(), Some(false));
assert!(n.bounds().is_some_and(|b| b.x1 > b.x0 || b.y1 > b.y0) || items[0].bounds.is_empty(), "bounds on screen");
assert_eq!(t.focus, crate::stage_a11y::node_id(first.0, first.1).accesskit_id(), "the reader's focus is on it");
// The list box is the canvas's child, and its options are the list's.
let list = t.nodes.iter().find(|(_, n)| n.role() == Role::ListBox && n.children().contains(&crate::stage_a11y::node_id(first.0, first.1).accesskit_id()));
assert!(list.is_some(), "the options sit in a list box");
let canvas = t.nodes.iter().find(|(_, n)| n.role() == Role::Canvas && n.label().is_some_and(|l| l.starts_with("Stage"))).map(|(_, n)| n);
assert!(canvas.is_some_and(|c| list.is_some_and(|(id, _)| c.children().contains(id))), "the list box is the stage's child");
// Space selects it alone; the arrows move on without nudging; Shift+Space adds the next.
key(&ctx, &mut app, egui::Key::Space, egui::Modifiers::NONE);
assert!(app.s.selection.contains(first.0, first.1) && app.s.selection.len() == 1);
let before = crate::stage_a11y::items(&app).0.iter().map(|i| i.bounds).collect::<Vec<_>>();
key(&ctx, &mut app, egui::Key::ArrowRight, egui::Modifiers::NONE);
let second = app.stage_nav.focused(&ctx).unwrap_or_else(|| panic!("an element has focus"));
assert_eq!(second, (items[1].layer, items[1].element));
assert_eq!(crate::stage_a11y::items(&app).0.iter().map(|i| i.bounds).collect::<Vec<_>>(), before, "the arrows moved focus, not the artwork");
key(&ctx, &mut app, egui::Key::Space, egui::Modifiers::SHIFT);
assert!(app.s.selection.contains(second.0, second.1) && app.s.selection.contains(first.0, first.1));
let t = key(&ctx, &mut app, egui::Key::Space, egui::Modifiers::SHIFT).unwrap_or_else(|| panic!("no tree"));
assert!(!app.s.selection.contains(second.0, second.1) && app.s.selection.len() == 1, "Shift+Space again takes it out");
assert_eq!(node(&t, crate::stage_a11y::node_id(first.0, first.1)).and_then(Node::is_selected), Some(true));
// Left from the first wraps to the last; Enter selects it alone.
key(&ctx, &mut app, egui::Key::ArrowLeft, egui::Modifiers::NONE);
key(&ctx, &mut app, egui::Key::ArrowLeft, egui::Modifiers::NONE);
let last = items.last().map(|i| (i.layer, i.element));
assert_eq!(app.stage_nav.focused(&ctx), last);
key(&ctx, &mut app, egui::Key::Enter, egui::Modifiers::NONE);
assert!(!app.playing, "Enter on an element selects, it doesn't play");
// The sample's sky is on a locked layer: listed (unavailable), never selected.
assert!(items.last().is_some_and(|i| i.locked));
assert!(app.s.selection.contains(first.0, first.1) && app.s.selection.len() == 1, "a locked element isn't selected");
key(&ctx, &mut app, egui::Key::ArrowLeft, egui::Modifiers::NONE);
key(&ctx, &mut app, egui::Key::Enter, egui::Modifiers::NONE);
let before_last = items.get(items.len() - 2).map(|i| (i.layer, i.element));
assert!(before_last.is_some_and(|(l, e)| app.s.selection.contains(l, e)) && app.s.selection.len() == 1, "Enter selects it alone");
// Esc goes back to the stage itself.
key(&ctx, &mut app, egui::Key::Escape, egui::Modifiers::NONE);
assert!(app.stage_nav.focused(&ctx).is_none());
assert_eq!(focused_region(&ctx), Some(Region::Stage));
assert_eq!(keyboard(&ctx), Keyboard::App, "the stage has the keyboard again: arrows nudge");
}
#[test]
fn stage_elements_and_timeline_frames_pass_the_audit() {
let (_, mut app, ctx) = tree(|_, _| {});
focus_stage(&ctx, &mut app);
let t = key(&ctx, &mut app, egui::Key::Tab, egui::Modifiers::NONE).unwrap_or_else(|| panic!("no tree"));
assert!(t.nodes.iter().filter(|(_, n)| n.role() == Role::ListBoxOption).count() >= 2);
let found = audit(&t);
assert!(found.is_empty(), "{}", found.join("\n"));
}
#[test]
fn the_focused_timeline_moves_and_announces_the_playhead_and_layer_and_lists_its_spans() {
let (_, mut app, ctx) = tree(|_, _| {});
while focused_region(&ctx) != Some(Region::Timeline) {
key(&ctx, &mut app, egui::Key::F6, egui::Modifiers::COMMAND);
}
app.run("layer.select", serde_json::json!({"index": 0}));
app.tl_refocus = true;
frame(&ctx, &mut app, input(1.0));
frame(&ctx, &mut app, input(1.0));
let (frame0, layer0) = (app.s.frame, app.s.layer);
let t = key(&ctx, &mut app, egui::Key::ArrowRight, egui::Modifiers::NONE).unwrap_or_else(|| panic!("no tree"));
assert_eq!(app.s.frame, frame0 + 1, "Right is the next frame");
let said = app.status.as_ref().map(|s| s.text.clone()).unwrap_or_default();
assert!(said.starts_with(&format!("Frame {}", frame0 + 2)), "announced: {said}");
// The active layer's spans are list items under its frame grid, the playhead's selected.
let items: Vec<&Node> = t.nodes.iter().filter(|(_, n)| n.role() == Role::ListItem).map(|(_, n)| n).collect();
assert!(!items.is_empty(), "the active layer's spans are listed");
assert!(items.iter().all(|n| n.label().is_some_and(|l| l.starts_with("Frame"))), "{:?}", items.iter().map(|n| n.label()).collect::<Vec<_>>());
assert_eq!(items.iter().filter(|n| n.is_selected() == Some(true)).count(), 1, "one span holds the playhead");
let grid = t.nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.starts_with("Frames of")) && !n.children().is_empty());
assert!(grid.is_some(), "the list sits under the active layer's frame grid");
assert!(audit(&t).is_empty(), "{}", audit(&t).join("\n"));
// Left goes back; Down moves to the next layer and keeps the keyboard on the timeline.
key(&ctx, &mut app, egui::Key::ArrowLeft, egui::Modifiers::NONE);
assert_eq!(app.s.frame, frame0);
key(&ctx, &mut app, egui::Key::ArrowDown, egui::Modifiers::NONE);
assert_ne!(app.s.layer, layer0, "Down is the layer below");
assert_eq!(app.s.timeline().layers.iter().position(|l| l.id == app.s.layer), Some(1));
assert_eq!((focused_region(&ctx), keyboard(&ctx)), (Some(Region::Timeline), Keyboard::App), "the new row has the keyboard");
key(&ctx, &mut app, egui::Key::ArrowUp, egui::Modifiers::NONE);
assert_eq!(app.s.layer, layer0);
let said = app.status.as_ref().map(|s| s.text.clone()).unwrap_or_default();
let name = app.s.timeline().layer(layer0).map(|l| l.name.clone()).unwrap_or_default();
assert!(said.contains(&name), "the layer is announced: {said}");
}
#[test]
fn access_keys_take_the_first_free_letter() {
let keys = crate::menus::access_keys(&["File", "Edit", "View", "Insert", "Modify", "Commands", "Control", "Window", "Help"]);
let letters: String = keys.iter().map(|k| k.map_or('-', |(_, c)| c)).collect();
assert_eq!(letters, "FEVIMCOWH", "Control takes its O, as in Animate");
assert_eq!(crate::menus::access_keys(&["Fichier", "Édition", "Ändern", "日本"]), vec![Some((0, 'F')), Some((1, 'D')), Some((1, 'N')), None]);
}
#[test]
fn the_menu_bar_works_from_the_keyboard() {
if !crate::menus::MenuKeys::available() {
return; // macOS keeps its own menu conventions (ADR 0064).
}
use egui::{Key, Modifiers as M};
let (_, mut app, ctx) = tree(|_, _| {});
let tops = app.menu_keys.top_ids().to_vec();
assert_eq!(tops.len(), crate::menus::TOP_MENUS.len());
let focused = |ctx: &egui::Context| ctx.memory(|m| m.focused());
let open = |ctx: &egui::Context, i: usize| egui::Popup::is_id_open(ctx, tops[i].with("popup"));
// F10 focuses File; the titles show their access keys.
let t = key(&ctx, &mut app, Key::F10, M::NONE).unwrap_or_else(|| panic!("no tree"));
assert_eq!(focused(&ctx), Some(tops[0]));
assert!(app.menu_keys.show_keys);
assert_eq!(node(&t, tops[0]).and_then(Node::access_key), Some("Alt+F"));
// Right: Edit; Down opens it on its first item; Down, Up and Up wrap round.
key(&ctx, &mut app, Key::ArrowRight, M::NONE);
assert_eq!(focused(&ctx), Some(tops[1]));
key(&ctx, &mut app, Key::ArrowDown, M::NONE);
frame(&ctx, &mut app, input(1.0));
assert!(open(&ctx, 1), "Down opens Edit");
let items = app.menu_keys.open_items(&ctx);
assert!(items.len() > 3, "Edit has items: {}", items.len());
assert_eq!(focused(&ctx), items.first().copied(), "on its first item");
key(&ctx, &mut app, Key::ArrowDown, M::NONE);
assert_eq!(focused(&ctx), items.get(1).copied());
key(&ctx, &mut app, Key::ArrowUp, M::NONE);
key(&ctx, &mut app, Key::ArrowUp, M::NONE);
assert_eq!(focused(&ctx), items.last().copied(), "Up from the first wraps to the last");
assert_eq!(keyboard(&ctx), Keyboard::Control, "the menu keeps Enter and the arrows");
// Right on an item: the next menu, open, on its first item.
key(&ctx, &mut app, Key::ArrowRight, M::NONE);
frame(&ctx, &mut app, input(1.0));
assert!(open(&ctx, 2) && !open(&ctx, 1), "Right goes on to View");
assert_eq!(focused(&ctx), app.menu_keys.open_items(&ctx).first().copied());
// Esc closes the menu, back on its title; Esc again leaves the bar.
key(&ctx, &mut app, Key::Escape, M::NONE);
assert!(!open(&ctx, 2));
assert_eq!(focused(&ctx), Some(tops[2]));
key(&ctx, &mut app, Key::Escape, M::NONE);
assert_eq!(focused(&ctx), None, "nothing had focus before");
assert!(!app.menu_keys.show_keys);
// Alt pressed and let go alone also focuses the bar (and again leaves it).
let mods = |m: M| {
let mut i = input(1.0);
i.events.push(egui::Event::ModifiersChanged(m));
i
};
frame(&ctx, &mut app, mods(M::ALT));
frame(&ctx, &mut app, input(1.0));
assert!(app.menu_keys.show_keys, "titles are underlined while Alt is held");
frame(&ctx, &mut app, mods(M::NONE));
frame(&ctx, &mut app, input(1.0));
assert_eq!(focused(&ctx), Some(tops[0]), "an Alt tap focuses File");
key(&ctx, &mut app, Key::Escape, M::NONE);
// Alt+H opens Help from the stage; an item chosen with Enter runs (and its Enter goes no
// further than the item).
focus_stage(&ctx, &mut app);
key(&ctx, &mut app, Key::H, M::ALT);
frame(&ctx, &mut app, input(1.0));
let help = crate::menus::TOP_MENUS.iter().position(|t| *t == "Help").unwrap_or(0);
assert!(open(&ctx, help), "Alt+H opens Help");
let t = frame(&ctx, &mut app, input(1.0)).platform_output.accesskit_update.unwrap_or_else(|| panic!("no tree"));
let found = audit(&t);
assert!(found.is_empty(), "the open menu passes the audit:\n{}", found.join("\n"));
let palette = app.menu_keys.open_items(&ctx).into_iter().position(|id| node(&t, id).and_then(Node::label).is_some_and(|l| l.starts_with("Command Palette")));
let palette = palette.unwrap_or_else(|| panic!("Help has Command Palette…"));
while app.menu_keys.open_items(&ctx).iter().position(|id| Some(*id) == focused(&ctx)) != Some(palette) {
key(&ctx, &mut app, Key::ArrowDown, M::NONE);
}
key(&ctx, &mut app, Key::Enter, M::NONE);
frame(&ctx, &mut app, input(1.0));
assert!(app.palette.is_some(), "Enter ran the item");
assert!(!open(&ctx, help));
app.palette = None;
// View's first item is Zoom In: chosen with Enter, it zooms and the keyboard goes back
// to the stage.
focus_stage(&ctx, &mut app);
let stage = focused(&ctx);
let zoom = app.view.zoom;
key(&ctx, &mut app, Key::V, M::ALT);
frame(&ctx, &mut app, input(1.0));
assert!(open(&ctx, 2), "Alt+V opens View");
key(&ctx, &mut app, Key::Enter, M::NONE);
frame(&ctx, &mut app, input(1.0));
assert!(app.view.zoom > zoom, "Zoom In ran");
assert_eq!(focused(&ctx), stage, "the keyboard went back to the stage");
assert_eq!(app.tool, crate::app::Tool::Select, "Alt+V opened View; it didn't pick the Selection tool's V");
}
#[test]
fn the_palette_follows_the_system_contrast_setting_in_the_same_frame() {
let (_, mut app, ctx) = tree(|_, _| {});
app.set_system_contrast(&ctx, Some(true));
let followed = crate::theme::palette();
app.set_system_contrast(&ctx, Some(false));
let back = crate::theme::palette();
// Chosen by hand: the system's setting no longer changes it.
let mut p = app.prefs.clone();
p.theme_follows_system = Some(false);
app.set_prefs(&ctx, p);
app.set_system_contrast(&ctx, Some(true));
let manual = crate::theme::palette();
crate::theme::apply_palette(&egui::Context::default(), crate::theme::Palette::Graphite);
assert_eq!((followed, back, manual), (crate::theme::Palette::HighContrast, crate::theme::Palette::Graphite, crate::theme::Palette::Graphite));
}
#[test]
fn ctrl_f6_moves_focus_through_the_panels_and_back() {
let (_, mut app, ctx) = tree(|_, _| {});
+157 -3
View File
@@ -440,6 +440,23 @@ pub struct App {
heard: Option<(usize, u32)>,
/// The panel Ctrl+F6 last moved focus to (where the next press continues from).
pub last_panel: Option<crate::a11y::Region>,
/// The stage's elements as keyboard stops and screen-reader nodes (ADR 0064).
pub stage_nav: crate::stage_a11y::StageNav,
/// The layer and frame the focused timeline last announced (ADR 0064).
pub tl_heard: Option<(anicraft_engine::doc::LayerId, u32)>,
/// The arrows moved the active layer: its row takes keyboard focus when drawn.
pub tl_refocus: bool,
/// The menu bar from the keyboard: Alt, F10 and the arrows (ADR 0064).
pub menu_keys: menus::MenuKeys,
/// What the system last said about contrast (ADR 0064): `None` until it has, or if it
/// can't. Screenshot runs never ask, so they look the same everywhere.
pub system_contrast: Option<bool>,
/// Keys to press, a few frames apart (screenshots of keyboard states).
pub key_script: std::collections::VecDeque<(Key, Modifiers)>,
key_script_wait: u8,
/// The system's contrast setting being read off the UI thread, and when it last was.
contrast_probe: Option<std::sync::mpsc::Receiver<Option<bool>>>,
contrast_asked: Option<f64>,
/// The start screen, while it is up (ADR 0059).
pub start: Option<crate::start::StartScreen>,
/// Files dragged over and dropped onto the window (ADR 0059).
@@ -448,6 +465,9 @@ pub struct App {
pub thumbs: crate::recent::Thumbs,
}
/// How often (seconds) the system's contrast setting is asked again (ADR 0064).
const SYSTEM_CONTRAST_EVERY: f64 = 4.0;
/// How finished this version is, shown next to the version number (docs/release.md). English:
/// translated where the interface shows it (`--version` prints it as is).
pub const RELEASE_STAGE: &str = tr_noop!("early alpha");
@@ -612,6 +632,15 @@ impl App {
audio_clock: false,
heard: None,
last_panel: None,
stage_nav: Default::default(),
tl_heard: None,
tl_refocus: false,
menu_keys: Default::default(),
system_contrast: None,
key_script: Default::default(),
key_script_wait: 0,
contrast_probe: None,
contrast_asked: None,
start: None,
drop: Default::default(),
thumbs: Default::default(),
@@ -706,7 +735,7 @@ impl App {
crate::i18n::set_language(&self.prefs.language);
ctx.request_repaint();
ctx.set_zoom_factor(self.prefs.ui_scale);
theme::apply_palette(ctx, self.prefs.theme);
theme::apply_palette(ctx, self.prefs.palette(self.system_contrast));
crate::onion::refresh_colors(self);
self.keymap = keymap::Keymap::new(&self.prefs.shortcuts);
self.shortcuts = self.keymap.table();
@@ -746,7 +775,10 @@ impl App {
return;
}
let mut p = self.prefs.clone();
p.theme = theme.unwrap_or(p.theme);
if let Some(t) = theme {
p.theme = t;
p.theme_follows_system = Some(false);
}
p.ui_scale = scale.unwrap_or(p.ui_scale);
self.prefs = p.sanitized();
self.apply_prefs(ctx);
@@ -772,6 +804,88 @@ impl App {
}
}
/// Presses `keys` once the window has settled, a few frames apart.
fn script_keys(&mut self, keys: impl IntoIterator<Item = (Key, Modifiers)>) {
self.key_script.extend(keys);
self.key_script_wait = 10;
}
/// The next scripted key press, once the frames before it have settled.
fn press_scripted_key(&mut self, ctx: &egui::Context) {
if self.key_script.is_empty() {
return;
}
ctx.request_repaint();
if self.key_script_wait > 0 {
self.key_script_wait -= 1;
return;
}
if let Some((key, modifiers)) = self.key_script.pop_front() {
ctx.input_mut(|i| i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }));
self.key_script_wait = 3;
}
}
/// Follows the system's contrast setting (ADR 0064): asks it on a worker now and then (at
/// start, every few seconds, and when the window comes back to the front), and switches the
/// palette in the same frame the answer changes, while Preferences says "Follow system".
fn follow_system_contrast(&mut self, ctx: &egui::Context) {
if self.shot.is_some() {
return;
}
if let Some(rx) = &self.contrast_probe {
match rx.try_recv() {
Ok(v) => {
self.contrast_probe = None;
self.set_system_contrast(ctx, v);
}
Err(std::sync::mpsc::TryRecvError::Empty) => return,
Err(std::sync::mpsc::TryRecvError::Disconnected) => self.contrast_probe = None,
}
}
let (now, came_back) = ctx.input(|i| (i.time, i.events.iter().any(|e| matches!(e, egui::Event::WindowFocused(true)))));
let due = self.contrast_asked.is_none_or(|t| now - t >= SYSTEM_CONTRAST_EVERY || came_back);
if !due {
return;
}
self.contrast_asked = Some(now);
let (tx, rx) = std::sync::mpsc::channel();
#[cfg(not(target_arch = "wasm32"))]
let started = {
let ctx2 = ctx.clone();
std::thread::Builder::new()
.name("anicraft-contrast".into())
.spawn(move || {
let _ = tx.send(platform::system_high_contrast());
ctx2.request_repaint();
})
.is_ok()
};
// (No threads in a browser: the media query answers at once.)
#[cfg(target_arch = "wasm32")]
let started = tx.send(platform::system_high_contrast()).is_ok();
if started {
self.contrast_probe = Some(rx);
}
// Ask again later even if nothing else happens.
ctx.request_repaint_after(std::time::Duration::from_secs_f64(SYSTEM_CONTRAST_EVERY));
}
/// What the system says about contrast: the palette follows at once, if it follows.
pub fn set_system_contrast(&mut self, ctx: &egui::Context, v: Option<bool>) {
if v == self.system_contrast {
return;
}
let before = self.prefs.palette(self.system_contrast);
self.system_contrast = v;
let after = self.prefs.palette(v);
if after != before {
theme::apply_palette(ctx, after);
crate::onion::refresh_colors(self);
ctx.request_repaint();
}
}
/// Starts scanning installed fonts on a background thread (once).
pub fn scan_system_fonts(&mut self) {
if self.system_fonts.is_some() || self.fonts_rx.is_some() {
@@ -820,7 +934,11 @@ impl App {
}
pub fn open_panel(&mut self, which: Option<&str>) {
use egui::{Key as K, Modifiers as M};
match which {
// Keyboard states for screenshots (ADR 0064): keys pressed a few frames apart.
Some("stagekeys") => self.script_keys([(K::F6, M::COMMAND), (K::Tab, M::NONE), (K::Space, M::NONE), (K::ArrowRight, M::NONE)]),
Some("menukeys") => self.script_keys([(K::F10, M::NONE), (K::ArrowRight, M::NONE), (K::ArrowDown, M::NONE), (K::ArrowDown, M::NONE)]),
Some("palette") => self.palette = Some(dialogs::Palette { query: "key".into(), selected: 0 }),
Some("shortcuts") => self.show_shortcuts = true,
Some("lastscene") => {
@@ -2103,6 +2221,12 @@ impl App {
if self.modal_open() || self.key_capture.is_some() {
return;
}
// Alt+letter opens a menu (ADR 0064), before the tool letters: egui would match those
// with Alt held too.
let alt_bound = |k: Key| self.shortcuts.iter().any(|(m, key, _)| *key == k && m.alt && !m.ctrl && !m.command && !m.shift);
let mut menu_keys = std::mem::take(&mut self.menu_keys);
menu_keys.access_key(ctx, alt_bound);
self.menu_keys = menu_keys;
// Palette, shortcut sheet, preferences and quit work even while a text field has focus.
// Preferences: Ctrl+U (the shortcut Animate users know) and Ctrl/⌘+, (platform norm).
let (palette, sheet, prefs_key, quit) = ctx.input_mut(|i| {
@@ -2166,6 +2290,10 @@ impl App {
let mut play = false;
let mut nudge = egui::Vec2::ZERO;
let surface_focused = ctx.memory(|m| m.focused().is_some());
// On the focused timeline the arrows move the playhead (Left, Right) and the active
// layer (Up, Down) instead of nudging artwork (ADR 0064).
let on_timeline = surface_focused && crate::a11y::focused_region(ctx) == Some(crate::a11y::Region::Timeline);
let (mut frame_step, mut layer_step) = (0i64, 0i64);
ctx.input_mut(|i| {
for (m, k, id) in &self.shortcuts {
if i.consume_key(*m, *k) {
@@ -2185,7 +2313,14 @@ impl App {
// Screen pixels, as in Animate: a press moves less the further you zoom in.
let step = if i.modifiers.shift { 10.0 } else { 1.0 } / self.view.zoom.max(1e-3);
for (k, d) in [(Key::ArrowLeft, egui::vec2(-step, 0.0)), (Key::ArrowRight, egui::vec2(step, 0.0)), (Key::ArrowUp, egui::vec2(0.0, -step)), (Key::ArrowDown, egui::vec2(0.0, step))] {
if i.key_pressed(k) && !i.modifiers.command {
if on_timeline && i.consume_key(Modifiers::NONE, k) {
match k {
Key::ArrowLeft => frame_step -= 1,
Key::ArrowRight => frame_step += 1,
Key::ArrowUp => layer_step -= 1,
_ => layer_step += 1,
}
} else if i.key_pressed(k) && !i.modifiers.command {
nudge += d;
}
}
@@ -2221,6 +2356,22 @@ impl App {
if let Some(t) = tool {
self.tool = t;
}
if frame_step != 0 {
self.playing = false;
let last = i64::from(self.s.frame_count().saturating_sub(1));
let to = (i64::from(self.s.frame) + frame_step).clamp(0, last.max(0));
self.run("timeline.goto", json!({"frame": to}));
}
if layer_step != 0 {
let layers = &self.s.timeline().layers;
if let Some(at) = layers.iter().position(|l| l.id == self.s.layer) {
let to = (at as i64 + layer_step).clamp(0, layers.len() as i64 - 1);
if to != at as i64 && self.run("layer.select", json!({"index": to})).is_some() {
// The keyboard goes with it, to the new active row.
self.tl_refocus = true;
}
}
}
if play {
self.toggle_play();
}
@@ -2453,6 +2604,7 @@ impl App {
}
self.handle_screenshot(&ctx);
self.poll_font_scan(&ctx);
self.follow_system_contrast(&ctx);
if let Some(p) = platform::picked_file() {
self.open_picked(p);
}
@@ -2466,7 +2618,9 @@ impl App {
platform::set_mac_glyphs(ok);
self.glyph_check = false;
}
self.press_scripted_key(&ctx);
self.handle_shortcuts(&ctx);
timeline::announce(self, &ctx);
// Switching away from a path tool keeps its work: a Pen path in progress is finished.
if self.tool != Tool::Pen && self.pen.is_some() {
pathtools::commit_pen(self, false);
+18 -1
View File
@@ -417,11 +417,28 @@ fn preferences(app: &mut App, ctx: &egui::Context) {
ui.add_space(4.0);
form_row(ui, LW, tr!("Theme"), |ui| {
ui.vertical(|ui| {
// Follow system (ADR 0064), then each palette by hand.
let was = if p.follows_system() { None } else { Some(p.theme) };
let mut choice = was;
crate::theme::radio_value(ui, &mut choice, None, text(Type::Body, tr!("Follow system")));
let says = match app.system_contrast {
Some(true) => tr!("High contrast while the system asks for more contrast (it does now), graphite otherwise."),
Some(false) => tr!("High contrast while the system asks for more contrast (it doesn't now), graphite otherwise."),
None => tr!("High contrast while the system asks for more contrast, graphite otherwise. This system doesn't say, so it is graphite."),
};
form_note(ui, toggle_indent, text(Type::Caption, says));
ui.add_space(2.0);
for (palette, name, tip) in crate::theme::Palette::ALL {
crate::theme::radio_value(ui, &mut p.theme, palette, text(Type::Body, crate::i18n::t(name)));
crate::theme::radio_value(ui, &mut choice, Some(palette), text(Type::Body, crate::i18n::t(name)));
form_note(ui, toggle_indent, text(Type::Caption, crate::i18n::t(tip)));
ui.add_space(2.0);
}
if choice != was {
p.theme_follows_system = Some(choice.is_none());
if let Some(t) = choice {
p.theme = t;
}
}
});
});
ui.add_space(4.0);
+2 -1
View File
@@ -1,6 +1,6 @@
//! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values.
const SOURCES: [(&str, &str); 26] = [
const SOURCES: [(&str, &str); 27] = [
("drop.rs", include_str!("drop.rs")),
("recent.rs", include_str!("recent.rs")),
("start.rs", include_str!("start.rs")),
@@ -18,6 +18,7 @@ const SOURCES: [(&str, &str); 26] = [
("menus.rs", include_str!("menus.rs")),
("panels.rs", include_str!("panels.rs")),
("stage.rs", include_str!("stage.rs")),
("stage_a11y.rs", include_str!("stage_a11y.rs")),
("timeline.rs", include_str!("timeline.rs")),
("widthtool.rs", include_str!("widthtool.rs")),
("motion_editor.rs", include_str!("motion_editor.rs")),
+1
View File
@@ -58,6 +58,7 @@ mod scale_grid;
mod sound;
mod shape_hints;
mod stage;
mod stage_a11y;
mod start;
mod test_movie;
mod theme;
+387 -2
View File
@@ -11,6 +11,12 @@ pub(crate) const TOP_MENUS: [&str; 9] = [tr_noop!("File"), tr_noop!("Edit"), tr_
pub fn bar(app: &mut App, ui: &mut egui::Ui) {
let cmds = commands();
let ctx = ui.ctx().clone();
let labels = top_labels();
let keys = access_keys(&labels.iter().map(String::as_str).collect::<Vec<_>>());
app.menu_keys.before(&ctx);
let underline = app.menu_keys.show_keys;
let mut tops = Vec::with_capacity(TOP_MENUS.len());
egui::MenuBar::new().ui(ui, |ui| {
// macOS: leave room for the traffic lights over the unified title bar.
ui.add_space(platform::menu_inset());
@@ -32,13 +38,380 @@ pub fn bar(app: &mut App, ui: &mut egui::Ui) {
});
}
// Windows and Linux: no name before the menus; the window title already shows it.
for top in TOP_MENUS {
ui.menu_button(crate::i18n::t(top), |ui| {
for ((top, label), key) in TOP_MENUS.into_iter().zip(&labels).zip(&keys) {
let title = if underline { egui::WidgetText::from(crate::theme::access_key_label(label, key.map(|(i, _)| i))) } else { egui::WidgetText::from(label.as_str()) };
let r = ui.menu_button(title, |ui| {
ui.set_min_width(230.0);
// The menu's own area, which egui leaves anonymous: a menu named by its title.
ui.ctx().accesskit_node_builder(ui.layer_id().id.with("move"), |n| {
n.set_role(egui::accesskit::Role::Menu);
n.set_label(label.as_str());
});
menu_contents(app, ui, top, &cmds);
});
if let Some((_, c)) = key
&& MenuKeys::available()
{
let k = platform::shortcut_label(&format!("Alt+{c}"));
ctx.accesskit_node_builder(r.response.id, |n| n.set_access_key(k));
}
tops.push(r.response.id);
}
});
app.menu_keys.after(&ctx, tops);
}
/// The top menus' titles in the interface language.
fn top_labels() -> Vec<String> {
TOP_MENUS.iter().map(|t| crate::i18n::t(t).to_string()).collect()
}
/// Each top menu's access key: `(character index, letter)`, the first letter of its title that
/// no menu before it took (word starts first); ASCII letters only, so a title without one has
/// none.
pub fn access_keys(labels: &[&str]) -> Vec<Option<(usize, char)>> {
let mut used: Vec<char> = Vec::new();
labels
.iter()
.map(|l| {
let chars: Vec<char> = l.chars().collect();
let starts = (0..chars.len()).filter(|&i| i == 0 || chars.get(i - 1).is_some_and(|c| c.is_whitespace()));
let pick = starts.chain(0..chars.len()).find_map(|i| {
let c = chars.get(i)?.to_ascii_uppercase();
(c.is_ascii_alphabetic() && !used.contains(&c)).then_some((i, c))
});
if let Some((_, c)) = pick {
used.push(c);
}
pick
})
.collect()
}
/// The menu bar from the keyboard (ADR 0064), as on Windows and Linux: Alt (pressed and let go
/// alone) or F10 focuses the first menu; Left and Right move between menus; Down, Enter or Space
/// opens one and goes to its first item; Up and Down move through items (wrapping), Right opens
/// a submenu (or goes on to the next menu), Left comes back; Esc closes the menu, and again
/// gives the keyboard back to where it was. Alt+letter opens a menu directly; while Alt is held,
/// or the bar has the keyboard, each title shows its letter underlined. macOS keeps its own
/// conventions (the command palette, ⌘K, reaches every menu command): nothing here runs there.
#[derive(Default)]
pub struct MenuKeys {
/// The top menu buttons, as drawn last.
tops: Vec<egui::Id>,
alt_down: bool,
/// Alt went down with nothing else since: letting go of it is a tap.
alt_clean: bool,
/// Where the keyboard was before the bar took it.
back: Option<egui::Id>,
/// The bar or a menu had the keyboard last frame.
engaged: bool,
focus_top: Option<usize>,
/// A menu or submenu just opened from the keyboard: its first item takes focus once drawn
/// (within the frames left).
into: Option<(egui::LayerId, u8)>,
/// Submenus entered from the keyboard: their buttons and layers, outermost first.
stack: Vec<(egui::Id, egui::LayerId)>,
/// Underline the access keys.
pub show_keys: bool,
}
enum At {
Top(usize),
Item(egui::Id, egui::LayerId),
Elsewhere,
}
impl MenuKeys {
/// Alt and F10 work on Windows, Linux and the web, not on a Mac (in a browser or not).
pub fn available() -> bool {
platform::menu_bar_keys()
}
fn popup(top: egui::Id) -> egui::Id {
top.with("popup")
}
fn layer(top: egui::Id) -> egui::LayerId {
egui::LayerId::new(egui::Order::Foreground, Self::popup(top))
}
fn open_top(&self, ctx: &egui::Context) -> Option<usize> {
self.tops.iter().position(|t| egui::Popup::is_id_open(ctx, Self::popup(*t)))
}
/// Where the keyboard is: on a top menu, on an item of an open menu, or elsewhere.
fn at(&self, ctx: &egui::Context) -> At {
let Some(f) = ctx.memory(|m| m.focused()) else { return At::Elsewhere };
if let Some(i) = self.tops.iter().position(|t| *t == f) {
return At::Top(i);
}
match ctx.read_response(f) {
Some(r) if self.open_top(ctx).is_some() && r.layer_id.order == egui::Order::Foreground => At::Item(f, r.layer_id),
_ => At::Elsewhere,
}
}
/// The top menu buttons (tests).
#[cfg(test)]
pub fn top_ids(&self) -> &[egui::Id] {
&self.tops
}
/// The open menu's items, top to bottom (tests).
#[cfg(test)]
pub fn open_items(&self, ctx: &egui::Context) -> Vec<egui::Id> {
self.open_top(ctx).and_then(|i| self.tops.get(i)).map(|t| Self::items(ctx, Self::layer(*t), false)).unwrap_or_default()
}
/// Whether the menu bar or one of its menus has the keyboard.
pub fn engaged(&self, ctx: &egui::Context) -> bool {
!matches!(self.at(ctx), At::Elsewhere)
}
/// The items of a menu drawn in `layer`, top to bottom: from this pass (`now`) or the last.
fn items(ctx: &egui::Context, layer: egui::LayerId, now: bool) -> Vec<egui::Id> {
let mut v: Vec<(f32, f32, egui::Id)> = ctx.viewport(|vp| {
let pass = if now { &vp.this_pass } else { &vp.prev_pass };
// (Not the menu's own area, which egui makes clickable.)
let area = layer.id.with("move");
pass.widgets.get_layer(layer).filter(|w| w.enabled && w.sense.is_focusable() && w.id != area).map(|w| (w.rect.top(), w.rect.left(), w.id)).collect()
});
v.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)));
v.into_iter().map(|(_, _, id)| id).collect()
}
fn step(&self, i: usize, forward: bool) -> usize {
let n = self.tops.len().max(1);
if forward { (i + 1) % n } else { (i + n - 1) % n }
}
fn open(&mut self, ctx: &egui::Context, i: usize) {
if let Some(t) = self.tops.get(i).copied() {
egui::Popup::open_id(ctx, Self::popup(t));
self.into = Some((Self::layer(t), 3));
self.focus_top = Some(i);
self.stack.clear();
}
}
fn leave(&mut self, ctx: &egui::Context) {
egui::Popup::close_all(ctx);
self.stack.clear();
self.into = None;
self.focus_top = None;
let back = self.back.take();
ctx.memory_mut(|m| match back {
Some(id) => m.request_focus(id),
None => {
if let Some(f) = m.focused() {
m.surrender_focus(f);
}
}
});
}
/// Alt pressed and let go with nothing else in between.
fn alt_tap(&mut self, ctx: &egui::Context) -> bool {
let (alt, other, focused) = ctx.input(|i| {
let events = i.events.iter().any(|e| matches!(e, egui::Event::Key { .. } | egui::Event::PointerButton { .. } | egui::Event::Text(_) | egui::Event::MouseWheel { .. }));
(i.modifiers.alt, events || i.modifiers.ctrl || i.modifiers.shift || i.modifiers.mac_cmd, i.focused)
});
let mut tap = false;
if alt && focused {
if !self.alt_down {
self.alt_clean = true;
}
if other {
self.alt_clean = false;
}
} else {
tap = self.alt_down && self.alt_clean && !other && focused;
self.alt_clean = false;
}
self.alt_down = alt && focused;
tap
}
/// Alt+letter opens that menu, unless the shortcut table has the key (the user bound it).
/// Runs before the shortcuts: egui matches a plain "H" with Alt held too.
pub fn access_key(&mut self, ctx: &egui::Context, bound: impl Fn(egui::Key) -> bool) {
if !Self::available() || !ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, modifiers, .. } if modifiers.alt))) {
return;
}
let labels = top_labels();
for (i, k) in access_keys(&labels.iter().map(String::as_str).collect::<Vec<_>>()).into_iter().enumerate() {
let Some(key) = k.and_then(|(_, c)| egui::Key::from_name(&c.to_string())) else { continue };
if !bound(key) && ctx.input_mut(|inp| inp.consume_key(egui::Modifiers::ALT, key)) {
if !self.engaged(ctx) {
self.back = ctx.memory(|m| m.focused());
}
self.open(ctx, i);
return;
}
}
}
/// The keyboard left the bar: a chosen item closed its menu (the keyboard goes back where it
/// was), or a click went elsewhere (it stays there).
fn settle(&mut self, ctx: &egui::Context, engaged: bool) {
if self.engaged && !engaged && self.into.is_none() && self.focus_top.is_none() {
// (A closed menu's item keeps the focus until the end of the frame.)
let lost = ctx.memory(|m| m.focused()).is_none_or(|f| ctx.read_response(f).is_none_or(|r| r.layer_id.order == egui::Order::Foreground));
if let Some(id) = self.back.take().filter(|_| lost) {
ctx.memory_mut(|m| m.request_focus(id));
}
self.stack.clear();
self.engaged = false;
}
}
/// Before the bar draws: the keys that reach it.
fn before(&mut self, ctx: &egui::Context) {
use egui::{Key, Modifiers};
if !Self::available() {
self.show_keys = false;
return;
}
let at = self.at(ctx);
let engaged = !matches!(at, At::Elsewhere);
self.settle(ctx, engaged);
let tap = self.alt_tap(ctx);
let f10 = ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::F10));
if tap || f10 {
if engaged || self.open_top(ctx).is_some() {
self.leave(ctx);
} else {
self.back = ctx.memory(|m| m.focused());
self.focus_top = Some(0);
}
return;
}
let pressed = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k));
let enter = || ctx.input(|i| i.key_pressed(Key::Enter) || i.key_pressed(Key::Space));
match at {
At::Top(i) => {
let open = self.open_top(ctx).is_some();
let side = if pressed(Key::ArrowLeft) {
Some(false)
} else if pressed(Key::ArrowRight) {
Some(true)
} else {
None
};
if let Some(forward) = side {
let j = self.step(i, forward);
if open {
self.open(ctx, j);
} else {
self.focus_top = Some(j);
}
} else if pressed(Key::ArrowDown) {
self.open(ctx, i);
} else if pressed(Key::ArrowUp) {
// (Nothing above the bar.)
} else if pressed(Key::Escape) {
if open {
egui::Popup::close_all(ctx);
} else {
self.leave(ctx);
}
} else if enter()
&& let Some(t) = self.tops.get(i)
{
// egui presses the button, which opens its menu: its first item comes next.
self.into = Some((Self::layer(*t), 3));
}
}
At::Item(f, layer) => {
let items = Self::items(ctx, layer, false);
let pos = items.iter().position(|x| *x == f).unwrap_or(0);
let n = items.len().max(1);
let open = self.open_top(ctx).unwrap_or(0);
let focus = |id: Option<&egui::Id>| {
if let Some(id) = id.copied() {
ctx.memory_mut(|m| m.request_focus(id));
}
};
let sub = egui::LayerId::new(egui::Order::Foreground, f.with("submenu"));
if pressed(Key::ArrowDown) {
focus(items.get((pos + 1) % n));
} else if pressed(Key::ArrowUp) {
focus(items.get((pos + n - 1) % n));
} else if pressed(Key::ArrowRight) {
// On an open submenu's button: into it. Elsewhere: the next menu.
let inside = Self::items(ctx, sub, false);
if inside.is_empty() {
let j = self.step(open, true);
self.open(ctx, j);
} else {
self.stack.push((f, sub));
focus(inside.first());
}
} else if pressed(Key::ArrowLeft) {
match self.stack.last().copied() {
Some((button, l)) if l == layer => {
self.stack.pop();
focus(Some(&button));
}
_ => {
let j = self.step(open, false);
self.open(ctx, j);
}
}
} else if pressed(Key::Escape) {
egui::Popup::close_all(ctx);
self.stack.clear();
self.focus_top = Some(open);
} else if enter() {
// Pressing a submenu's button opens it: go in once it shows.
self.into = Some((sub, 3));
}
}
At::Elsewhere => {}
}
}
/// After the bar drew: focus moves, and the arrows and Esc stay with the bar.
fn after(&mut self, ctx: &egui::Context, tops: Vec<egui::Id>) {
self.tops = tops;
if !Self::available() {
return;
}
if let Some(i) = self.focus_top.take()
&& let Some(t) = self.tops.get(i).copied()
&& ctx.memory(|m| m.focused()) != Some(t)
{
ctx.memory_mut(|m| m.request_focus(t));
}
if let Some((layer, left)) = self.into.take() {
match Self::items(ctx, layer, true).first().copied() {
Some(first) => {
let top_layer = self.tops.iter().any(|t| Self::layer(*t) == layer);
if !top_layer && let Some(button) = ctx.memory(|m| m.focused()) {
// A submenu opened with Enter: Left comes back to its button.
self.stack.push((button, layer));
}
ctx.memory_mut(|m| m.request_focus(first));
}
None if left > 1 => self.into = Some((layer, left - 1)),
None => {}
}
ctx.request_repaint();
}
let engaged = self.engaged(ctx);
self.settle(ctx, engaged);
if engaged && let Some(f) = ctx.memory(|m| m.focused()) {
let filter = egui::EventFilter { tab: false, horizontal_arrows: true, vertical_arrows: true, escape: true };
ctx.memory_mut(|m| m.set_focus_lock_filter(f, filter));
}
self.engaged = engaged || self.focus_top.is_some() || self.into.is_some();
let show = engaged || ctx.input(|i| i.modifiers.alt && !i.modifiers.ctrl);
if show != self.show_keys {
ctx.request_repaint();
}
self.show_keys = show;
}
}
fn enabled(app: &App, id: &str) -> bool {
@@ -98,11 +471,21 @@ fn item(app: &mut App, ui: &mut egui::Ui, spec: &CommandSpec) {
None => r,
};
if r.clicked() {
pressed(ui);
app.invoke(spec.id);
ui.close();
}
}
/// An item was pressed: the Enter or Space that pressed it from the keyboard is used up, so it
/// doesn't also reach what the item opens (the command palette's field, a dialog's button).
fn pressed(ui: &egui::Ui) {
ui.input_mut(|i| {
i.consume_key(egui::Modifiers::NONE, egui::Key::Enter);
i.consume_key(egui::Modifiers::NONE, egui::Key::Space);
});
}
/// A registry command as a menu item (label and shortcut from the registry); used by context
/// menus so every surface shows the same names and keys.
pub fn cmd_item(app: &mut App, ui: &mut egui::Ui, id: &str) {
@@ -117,6 +500,7 @@ pub fn check_item(ui: &mut egui::Ui, label: &str, checked: bool, enabled: bool)
let label = if checked { format!("✔ {label}") } else { format!(" {label}") };
let clicked = ui.add_enabled(enabled, egui::Button::new(label)).clicked();
if clicked {
pressed(ui);
ui.close();
}
clicked
@@ -131,6 +515,7 @@ fn ui_item(ui: &mut egui::Ui, label: &str, shortcut: &str, checked: Option<bool>
};
let clicked = ui.add(egui::Button::new(label_text).shortcut_text(text(Type::Key, platform::shortcut_label(shortcut)))).clicked();
if clicked {
pressed(ui);
ui.close();
}
clicked
+78
View File
@@ -53,6 +53,64 @@ pub fn system_locale() -> Option<String> {
sys_locale::get_locale().filter(|l| !l.is_empty() && l.len() <= 64)
}
/// Whether the system asks for more contrast (ADR 0064): Windows' contrast themes (high
/// contrast), macOS' Increase Contrast, the desktop portal's contrast setting on Linux (GNOME's
/// High Contrast where there is no portal), the browser's `prefers-contrast: more`. `None`:
/// this system doesn't say. Can block for a moment (it may ask another process): call it off
/// the UI thread.
pub fn system_high_contrast() -> Option<bool> {
#[cfg(windows)]
{
// HIGHCONTRAST's flags as the system keeps them; bit 0 is HCF_HIGHCONTRASTON.
let key = winreg::RegKey::predef(winreg::enums::HKEY_CURRENT_USER).open_subkey(r"Control Panel\Accessibility\HighContrast").ok()?; // i18n-exempt: a registry path
let flags: String = key.get_value("Flags").ok()?; // i18n-exempt: a registry value name
flags.trim().parse::<u32>().ok().map(|f| f & 1 == 1)
}
#[cfg(target_os = "macos")]
{
// Missing until the user first changes it: off.
let out = std::process::Command::new("defaults").args(["read", "com.apple.universalaccess", "increaseContrast"]).output().ok()?; // i18n-exempt: a command line
Some(String::from_utf8_lossy(&out.stdout).trim() == "1")
}
#[cfg(target_arch = "wasm32")]
{
web_sys::window()?.match_media("(prefers-contrast: more)").ok()??.matches().into() // i18n-exempt: a media query
}
#[cfg(not(any(windows, target_os = "macos", target_arch = "wasm32")))]
{
portal_contrast().or_else(gnome_high_contrast)
}
}
/// The XDG desktop portal's `org.freedesktop.appearance contrast` (1: high), through `gdbus`.
#[cfg(not(any(windows, target_os = "macos", target_arch = "wasm32")))]
fn portal_contrast() -> Option<bool> {
let out = std::process::Command::new("gdbus") // i18n-exempt: a command line
.args(["call", "--session", "--timeout", "1", "--dest", "org.freedesktop.portal.Desktop", "--object-path", "/org/freedesktop/portal/desktop", "--method", "org.freedesktop.portal.Settings.ReadOne", "org.freedesktop.appearance", "contrast"]) // i18n-exempt: a command line
.output()
.ok()
.filter(|o| o.status.success())?;
parse_portal_uint(&String::from_utf8_lossy(&out.stdout)).map(|v| v == 1)
}
/// GNOME's own switch, for desktops without the portal setting.
#[cfg(not(any(windows, target_os = "macos", target_arch = "wasm32")))]
fn gnome_high_contrast() -> Option<bool> {
let out = std::process::Command::new("gsettings").args(["get", "org.gnome.desktop.a11y.interface", "high-contrast"]).output().ok().filter(|o| o.status.success())?; // i18n-exempt: a command line
match String::from_utf8_lossy(&out.stdout).trim() {
"true" => Some(true),
"false" => Some(false),
_ => None,
}
}
/// The number in a `gdbus` reply such as `(<<uint32 1>>,)` or `(<uint32 0>,)`.
#[cfg_attr(any(windows, target_os = "macos", target_arch = "wasm32"), allow(dead_code))]
fn parse_portal_uint(reply: &str) -> Option<u32> {
let rest = reply.split("uint32").nth(1)?;
rest.trim_start().split(|c: char| !c.is_ascii_digit()).next()?.parse().ok()
}
/// Whether the active fonts can draw ⌘ ⇧ ⌥ ⌃ (set once fonts are installed).
static MAC_GLYPHS: AtomicBool = AtomicBool::new(false);
@@ -69,6 +127,12 @@ fn keys_os() -> Os {
if OS == Os::Web && WEB_ON_MAC.load(Ordering::Relaxed) { Os::Mac } else { OS }
}
/// Whether Alt and F10 reach the menu bar (ADR 0064): on Windows, Linux and the web, as their
/// applications do, but not on a Mac (in a browser or not), whose menu conventions differ.
pub fn menu_bar_keys() -> bool {
keys_os() != Os::Mac
}
pub fn set_mac_glyphs(available: bool) {
MAC_GLYPHS.store(available, Ordering::Relaxed);
}
@@ -598,6 +662,20 @@ mod tests {
assert!(is_system_argument("-psn_0_8194") && !is_system_argument("walk.anicraft"));
}
#[test]
fn portal_replies_parse() {
assert_eq!(parse_portal_uint("(<<uint32 1>>,)"), Some(1));
assert_eq!(parse_portal_uint("(<uint32 0>,)
"), Some(0));
assert_eq!(parse_portal_uint("Error: no such key"), None);
}
#[test]
fn the_system_contrast_setting_can_be_read_without_panicking() {
// Whatever this machine says (or doesn't), asking never fails loudly.
let _ = system_high_contrast();
}
#[test]
fn renderer_override() {
assert_eq!(forced_renderer(Some("gl")), Some(eframe::Renderer::Glow));
+44 -1
View File
@@ -63,8 +63,13 @@ pub struct Prefs {
pub language: String,
pub ui_font: FontChoice,
pub data_font: FontChoice,
/// Graphite or high contrast (ADR 0022).
/// Graphite or high contrast (ADR 0022), when chosen by hand.
pub theme: crate::theme::Palette,
/// Follow the system's contrast setting (ADR 0064): high contrast while the system asks for
/// more contrast, graphite otherwise. `None` (files from before): it follows, unless the
/// file chose high contrast.
#[serde(skip_serializing_if = "Option::is_none")]
pub theme_follows_system: Option<bool>,
/// Interface scale (1.0 = 100%).
pub ui_scale: f32,
pub render_mode: RenderMode,
@@ -150,6 +155,7 @@ impl Default for Prefs {
ui_font: FontChoice::Bundled,
data_font: FontChoice::Bundled,
theme: crate::theme::Palette::Graphite,
theme_follows_system: None,
ui_scale: 1.0,
render_mode: RenderMode::Auto,
stage_renderer: StageRenderer::Gpu,
@@ -192,6 +198,21 @@ pub const SCALE_RANGE: std::ops::RangeInclusive<f32> = 0.75..=2.0;
pub const GAP_RANGE: std::ops::RangeInclusive<f32> = 0.0..=48.0;
impl Prefs {
/// Whether the theme follows the system's contrast setting ("Follow system", the default).
pub fn follows_system(&self) -> bool {
self.theme_follows_system.unwrap_or(self.theme != crate::theme::Palette::HighContrast)
}
/// The palette to draw with, given what the system says about contrast (`None`: it
/// doesn't say, or hasn't yet).
pub fn palette(&self, system_high_contrast: Option<bool>) -> crate::theme::Palette {
match (self.follows_system(), system_high_contrast) {
(true, Some(true)) => crate::theme::Palette::HighContrast,
(true, _) => crate::theme::Palette::Graphite,
(false, _) => self.theme,
}
}
pub fn sanitized(mut self) -> Prefs {
self.ui_scale = if self.ui_scale.is_finite() { self.ui_scale.clamp(*SCALE_RANGE.start(), *SCALE_RANGE.end()) } else { 1.0 };
self.timeline_start_gap = if self.timeline_start_gap.is_finite() { self.timeline_start_gap.clamp(*GAP_RANGE.start(), *GAP_RANGE.end()) } else { 0.0 };
@@ -281,6 +302,28 @@ impl SystemFonts {
mod tests {
use super::*;
#[test]
fn the_theme_follows_the_system_unless_one_was_chosen() {
use crate::theme::Palette;
// New installs, and files from before ADR 0064 that kept the default, follow the system.
for p in [Prefs::default(), Prefs::from_json(r#"{"theme": "Graphite"}"#)] {
assert!(p.follows_system());
assert_eq!(p.palette(Some(true)), Palette::HighContrast);
assert_eq!(p.palette(Some(false)), Palette::Graphite);
assert_eq!(p.palette(None), Palette::Graphite, "a system that doesn't say: graphite");
}
// A file that chose high contrast keeps it whatever the system says.
let hc = Prefs::from_json(r#"{"theme": "HighContrast"}"#);
assert!(!hc.follows_system());
assert_eq!(hc.palette(Some(false)), Palette::HighContrast);
// Graphite chosen by hand stays graphite; the choice survives a round trip.
let manual = Prefs { theme_follows_system: Some(false), ..Prefs::default() };
assert_eq!(manual.palette(Some(true)), Palette::Graphite);
let back = Prefs::from_json(&serde_json::to_string(&manual).unwrap_or_default());
assert_eq!(back.theme_follows_system, Some(false));
assert!(!serde_json::to_string(&Prefs::default()).unwrap_or_default().contains("theme_follows_system"), "nothing new written until chosen");
}
#[test]
fn system_font_scan_is_safe_and_loads_a_face() {
// Machine-dependent (CI containers may have no fonts); must never panic.
+2
View File
@@ -1145,6 +1145,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
),
};
crate::a11y::surface(ui, &resp, &name);
// Its elements, one by one, while it has the keyboard (ADR 0064).
crate::stage_a11y::show(app, ui, &resp, to_screen);
}
// ----- raw shapes (ADR 0031, 0041) ----------------------------------------------------------------
+376
View File
@@ -0,0 +1,376 @@
//! The stage's elements for screen readers and the keyboard (ADR 0064).
//!
//! While the stage has keyboard focus, its canvas node gets one child: a multi-select list box,
//! "Elements on frame 12", with one option per element on the frame (layers top to bottom, each
//! front to back). An option says what the element is ("Rectangle", "Text: Hello", "hero ·
//! Movie clip: Ball"), its layer, place and size, and whether it is selected; its bounds are
//! where it is on screen, so a reader's highlight lands on the artwork.
//!
//! Keys: Tab on the stage goes to the first selected element (or the first one); then Tab,
//! Shift+Tab and the arrow keys move between elements (wrapping), Enter or Space selects the
//! element alone, Shift+Enter or Shift+Space adds it to the selection or takes it out, and Esc
//! goes back to the stage itself (where the arrows nudge again). Selection goes through
//! `element.select`, so it is the same command a click, the CLI and MCP use.
//!
//! Nothing here exists while the stage doesn't have focus, so the rest of the interface keeps
//! its tab order and the tree stays small. A frame with more than [`MAX_NODES`] elements lists
//! the first ones and a summary of the rest.
use crate::app::App;
use crate::theme::T;
use anicraft_engine::doc::{Document, Element, ElementId, ElementKind, LayerId, LayerKind, Paint, SymbolKind};
use anicraft_engine::geom::{Path, PathCmd, Rect as GRect};
use egui::accesskit::{Action, Role};
use egui::{Id, Key, Modifiers, Pos2, Rect, Response, Sense, Stroke, StrokeKind, UiBuilder, Vec2};
use serde_json::json;
use std::collections::HashMap;
/// Most elements exposed one by one; the rest are summed up in one node.
pub const MAX_NODES: usize = 2_000;
/// One element as a screen reader hears it.
#[derive(Clone, Debug)]
pub struct Item {
pub layer: LayerId,
pub element: ElementId,
/// What it is: "Rectangle", "Text: Hello", "hero · Movie clip: Ball".
pub name: String,
/// Where: "Layer Hills · x 120, y 80 · 200 × 40 px".
pub detail: String,
/// Bounds in the space the stage draws in (the open symbol's, while one is open).
pub bounds: GRect,
pub selected: bool,
/// On a locked layer: listed, but it can't be selected.
pub locked: bool,
}
/// The stage's keyboard state: the element nodes made last frame, to tell which one has focus.
#[derive(Default)]
pub struct StageNav {
ids: Vec<(Id, LayerId, ElementId)>,
}
impl StageNav {
/// The element with keyboard focus, if one has it.
pub fn focused(&self, ctx: &egui::Context) -> Option<(LayerId, ElementId)> {
let f = ctx.memory(|m| m.focused())?;
self.ids.iter().find(|(id, _, _)| *id == f).map(|(_, l, e)| (*l, *e))
}
}
pub fn node_id(layer: LayerId, element: ElementId) -> Id {
Id::new(("stage_element", layer.0, element.0))
}
/// What a path looks like it was drawn with (English, a key): the Rectangle, Oval and PolyStar
/// tools' outlines and the Line tool's segment; anything else is a shape.
pub fn shape_kind(p: &Path) -> &'static str {
let (mut moves, mut lines, mut curves, mut closes) = (0usize, 0usize, 0usize, 0usize);
let mut pts: Vec<anicraft_engine::geom::Vec2> = Vec::new();
for c in p.cmds.iter().take(64) {
match c {
PathCmd::MoveTo(v) => {
moves += 1;
pts.push(*v);
}
PathCmd::LineTo(v) => {
lines += 1;
pts.push(*v);
}
PathCmd::QuadTo(..) | PathCmd::CubicTo(..) => curves += 1,
PathCmd::Close => closes += 1,
}
}
if p.cmds.len() > 64 || moves != 1 {
return tr_noop!("Shape");
}
let axis_aligned = || {
let mut ring = pts.clone();
if let Some(first) = pts.first() {
ring.push(*first);
}
ring.windows(2).all(|w| matches!(w, [a, b] if (a.x - b.x).abs() < 1e-3 || (a.y - b.y).abs() < 1e-3))
};
match (lines, curves, closes) {
(1, 0, 0) => tr_noop!("Line"),
(3 | 4, 0, 1) if axis_aligned() => tr_noop!("Rectangle"),
// A rounded rectangle: four sides and four corners.
(4, 4, 1) => tr_noop!("Rectangle"),
(0, 4, 1) => tr_noop!("Oval"),
(n, 0, 1) if n >= 2 => tr_noop!("Polygon"),
_ => tr_noop!("Shape"),
}
}
fn symbol_kind(k: SymbolKind) -> &'static str {
match k {
SymbolKind::Graphic => tr_noop!("Graphic"),
SymbolKind::MovieClip => tr_noop!("Movie clip"),
SymbolKind::Button => tr_noop!("Button"),
}
}
/// The first `max` characters of `s` on one line, with "…" when cut.
fn excerpt(s: &str, max: usize) -> String {
let one: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
if one.chars().count() <= max {
return one;
}
let mut cut: String = one.chars().take(max).collect();
cut.push('…');
cut
}
/// What an element is, in the interface language; its instance name (document text) first.
pub fn element_name(doc: &Document, e: &Element) -> String {
let what = match &e.kind {
ElementKind::Shape(sh) if matches!(sh.fill, Some(Paint::Bitmap { .. })) => tr!("Bitmap").to_string(),
ElementKind::Shape(sh) => crate::i18n::t(shape_kind(&sh.path)).to_string(),
ElementKind::Symbol { symbol, .. } => match doc.symbol(*symbol) {
Some(sym) => tr!("{kind}: {symbol}", kind = crate::i18n::t(symbol_kind(sym.kind)), symbol = sym.name),
None => tr!("Symbol instance").to_string(),
},
ElementKind::Text(tb) if tb.text.trim().is_empty() => tr!("Empty text").to_string(),
ElementKind::Text(tb) => tr!("Text: {text}", text = excerpt(&tb.text, 80)),
ElementKind::Camera => tr!("Camera").to_string(),
};
let name = excerpt(&e.name, 80);
if name.is_empty() { what } else { tr!("{name} · {what}", name = name, what = what) }
}
/// The current frame's elements, as the list shows them, and how many there are in all.
pub fn items(app: &App) -> (Vec<Item>, usize) {
let s = &app.s;
let tl = s.timeline();
// Bounds of every element in one pass over what the stage draws.
let mut bounds: HashMap<(LayerId, ElementId), GRect> = HashMap::new();
for item in s.display_list().items.iter() {
let pad = item.stroke.as_ref().map_or(0.0, anicraft_engine::doc::Stroke::reach);
let r = item.path.bounds().inflate(pad).transformed(&item.transform);
let e = bounds.entry((item.layer, item.element)).or_insert(GRect::EMPTY);
*e = e.union(&r);
}
let mut out = Vec::new();
let mut total = 0usize;
for (i, layer) in tl.layers.iter().enumerate() {
// Only what is on the stage: shown layers with artwork, not the camera.
if !layer.visible || tl.hidden_by_folder(i) || matches!(layer.kind, LayerKind::Folder | LayerKind::Camera) {
continue;
}
let locked = !s.selectable(layer.id);
let elements = s.elements_on(layer.id);
for e in elements.iter().rev().filter(|e| !matches!(e.kind, ElementKind::Camera)) {
total += 1;
if out.len() >= MAX_NODES {
continue;
}
let b = bounds.get(&(layer.id, e.id)).copied().unwrap_or_else(|| e.bounds(&s.doc));
let detail = if b.is_empty() {
tr!("Layer {layer}", layer = layer.name)
} else {
tr!("Layer {layer} · x {x}, y {y} · {w} × {h} px", layer = layer.name, x = format!("{:.0}", b.min.x), y = format!("{:.0}", b.min.y), w = format!("{:.0}", b.width()), h = format!("{:.0}", b.height()))
};
let detail = if locked { tr!("{detail} · locked", detail = detail) } else { detail };
out.push(Item { layer: layer.id, element: e.id, name: element_name(&s.doc, e), detail, bounds: b, selected: s.selection.contains(layer.id, e.id), locked });
}
}
(out, total)
}
fn ak_rect(r: Rect) -> egui::accesskit::Rect {
egui::accesskit::Rect { x0: r.min.x.into(), y0: r.min.y.into(), x1: r.max.x.into(), y1: r.max.y.into() }
}
/// What a key press on a focused element does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Step {
Next,
Prev,
Select,
Toggle,
Leave,
}
fn element_keys(i: &mut egui::InputState) -> Option<Step> {
for (m, k, step) in [
(Modifiers::SHIFT, Key::Tab, Step::Prev),
(Modifiers::NONE, Key::Tab, Step::Next),
(Modifiers::NONE, Key::ArrowRight, Step::Next),
(Modifiers::NONE, Key::ArrowDown, Step::Next),
(Modifiers::NONE, Key::ArrowLeft, Step::Prev),
(Modifiers::NONE, Key::ArrowUp, Step::Prev),
(Modifiers::SHIFT, Key::Enter, Step::Toggle),
(Modifiers::SHIFT, Key::Space, Step::Toggle),
(Modifiers::NONE, Key::Enter, Step::Select),
(Modifiers::NONE, Key::Space, Step::Select),
(Modifiers::NONE, Key::Escape, Step::Leave),
] {
if i.consume_key(m, k) {
return Some(step);
}
}
None
}
/// Selects `it` alone (`toggle`: adds it to the selection or takes it out) and says so.
fn select(app: &mut App, it: &Item, toggle: bool) {
let params = if toggle { json!({"ids": [it.element.0], "layer": it.layer.0, "toggle": true}) } else { json!({"ids": [it.element.0], "layer": it.layer.0}) };
if app.run("element.select", params).is_some() {
let n = app.s.selection.len();
let now = app.s.selection.contains(it.layer, it.element);
let what = if now { tr!("Selected {name}", name = it.name) } else { tr!("Deselected {name}", name = it.name) };
app.status_ok(trn!("{what} · {n} element selected", "{what} · {n} elements selected", n, what = what));
}
}
/// The element list under the stage's node, and its keys. `to_screen` maps the stage's drawing
/// space to the screen. Call after the stage has drawn, while `stage` is its canvas response.
pub fn show(app: &mut App, ui: &mut egui::Ui, stage: &Response, to_screen: impl Fn(anicraft_engine::geom::Vec2) -> Pos2) {
let ctx = ui.ctx().clone();
let focused = ctx.memory(|m| m.focused());
let on_canvas = focused == Some(stage.id);
let on_element = app.stage_nav.focused(&ctx);
if !on_canvas && on_element.is_none() {
app.stage_nav.ids.clear();
return;
}
let (mut list, mut total) = items(app);
let screen = |b: GRect| -> Rect {
if b.is_empty() {
return Rect::from_center_size(stage.rect.center(), Vec2::ZERO);
}
Rect::from_two_pos(to_screen(b.min), to_screen(b.max))
};
// ---- keys -----------------------------------------------------------------------------
let mut focus_to: Option<Id> = None;
if on_canvas && !list.is_empty() {
// Tab goes into the list: to the selection, or the first element.
let (fwd, back) = ctx.input_mut(|i| (i.consume_key(Modifiers::NONE, Key::Tab), i.consume_key(Modifiers::SHIFT, Key::Tab)));
let pick = if fwd {
list.iter().position(|it| it.selected).or(Some(0))
} else if back {
list.iter().rposition(|it| it.selected).or(Some(list.len() - 1))
} else {
None
};
if let Some(it) = pick.and_then(|i| list.get(i)) {
focus_to = Some(node_id(it.layer, it.element));
}
}
if let Some((layer, el)) = on_element {
let at = list.iter().position(|it| it.layer == layer && it.element == el);
match (at, ctx.input_mut(element_keys)) {
// Gone from the frame (deleted, or the playhead moved): back to the stage.
(None, _) => focus_to = Some(stage.id),
(Some(i), Some(Step::Next)) => focus_to = list.get((i + 1) % list.len()).map(|it| node_id(it.layer, it.element)),
(Some(i), Some(Step::Prev)) => focus_to = list.get((i + list.len() - 1) % list.len()).map(|it| node_id(it.layer, it.element)),
(Some(i), Some(step @ (Step::Select | Step::Toggle))) => {
if let Some(it) = list.get(i).cloned() {
select(app, &it, step == Step::Toggle);
(list, total) = items(app);
}
}
(Some(_), Some(Step::Leave)) => focus_to = Some(stage.id),
(Some(_), None) => {}
}
}
// A screen reader's "click" on an option selects it, as Enter does.
let clicked = list.iter().find(|it| ctx.input(|i| i.has_accesskit_action_request(node_id(it.layer, it.element), Action::Click))).cloned();
if let Some(it) = clicked {
select(app, &it, false);
(list, total) = items(app);
}
// ---- nodes ----------------------------------------------------------------------------
let child = ui.new_child(UiBuilder::new().id_salt("stage_elements").accessibility_parent(stage.id).max_rect(stage.rect).sense(Sense::hover()));
let frame = app.s.frame + 1;
ctx.accesskit_node_builder(child.unique_id(), |n| {
n.set_role(Role::ListBox);
n.set_label(trn!("{n} element on frame {frame}", "{n} elements on frame {frame}", total, frame = frame));
n.set_multiselectable();
n.set_bounds(ak_rect(stage.rect));
});
app.stage_nav.ids.clear();
let count = list.len();
let filter = egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true };
for (i, it) in list.iter().enumerate() {
let id = node_id(it.layer, it.element);
let r = screen(it.bounds);
// No pointer area (the canvas takes the clicks): a focus stop with its bounds.
let resp = child.interact(Rect::from_center_size(r.center(), Vec2::ZERO), id, Sense::FOCUSABLE);
ctx.accesskit_node_builder(id, |n| {
n.set_role(Role::ListBoxOption);
n.set_label(it.name.as_str());
n.set_description(it.detail.as_str());
n.set_selected(it.selected);
n.set_bounds(ak_rect(r));
n.set_position_in_set(i + 1);
n.set_size_of_set(total);
n.add_action(Action::Click);
if it.locked {
n.set_disabled();
}
});
if resp.has_focus() {
ctx.memory_mut(|m| m.set_focus_lock_filter(id, filter));
// The keyboard focus, drawn on the artwork.
ui.painter().rect_stroke(r.expand(3.0), T.rc(), Stroke::new(2.0, T.accent), StrokeKind::Outside);
}
app.stage_nav.ids.push((id, it.layer, it.element));
}
if total > count {
let id = child.unique_id().with("more");
child.interact(Rect::from_center_size(stage.rect.center(), Vec2::ZERO), id, Sense::hover());
ctx.accesskit_node_builder(id, |n| {
n.set_role(Role::Label);
n.set_label(trn!(
"{n} more element is not listed: pick it on the stage, or use Select All or Find",
"{n} more elements are not listed: pick them on the stage, or use Select All or Find",
total - count
));
});
}
if on_canvas {
// Tab goes into the list (when there is one); the arrows nudge, as before.
let tab = !list.is_empty();
ctx.memory_mut(|m| m.set_focus_lock_filter(stage.id, egui::EventFilter { tab, horizontal_arrows: true, vertical_arrows: true, ..Default::default() }));
}
if let Some(id) = focus_to {
ctx.memory_mut(|m| m.request_focus(id));
if id != stage.id
&& let Some(it) = list.iter().find(|it| node_id(it.layer, it.element) == id)
{
// A reader says the newly focused option itself; the status bar says it for everyone.
let state = if it.selected { tr!("selected") } else { tr!("not selected") };
app.status_ok(tr!("{name} · {state} · Enter selects, Esc goes back to the stage", name = it.name, state = state));
}
ctx.request_repaint();
}
}
#[cfg(test)]
mod tests {
use super::*;
use anicraft_engine::geom::Vec2 as V;
#[test]
fn shapes_are_named_by_the_tool_that_draws_them() {
assert_eq!(shape_kind(&Path::rect(0.0, 0.0, 10.0, 5.0)), "Rectangle");
assert_eq!(shape_kind(&Path::rounded_rect(0.0, 0.0, 10.0, 5.0, 2.0)), "Rectangle");
assert_eq!(shape_kind(&Path::ellipse(0.0, 0.0, 4.0, 3.0)), "Oval");
assert_eq!(shape_kind(&Path::star(0.0, 0.0, 10.0, 4.0, 5)), "Polygon");
assert_eq!(shape_kind(&Path::line(V::new(0.0, 0.0), V::new(3.0, 4.0))), "Line");
// A slanted quadrilateral is a polygon, not a rectangle.
let mut p = Path::new();
p.move_to(V::new(0.0, 0.0)).line_to(V::new(10.0, 1.0)).line_to(V::new(10.0, 6.0)).line_to(V::new(0.0, 5.0)).close();
assert_eq!(shape_kind(&p), "Polygon");
assert_eq!(shape_kind(&Path::new()), "Shape");
}
#[test]
fn long_text_is_cut_to_one_line() {
assert_eq!(excerpt("Hello\n world", 80), "Hello world");
assert_eq!(excerpt(&"a".repeat(100), 5), "aaaaa…");
}
}
+19
View File
@@ -478,6 +478,25 @@ pub fn color(t: Type) -> Color32 {
}
}
/// A menu title with its access key underlined (ADR 0064), as Windows and Linux show it while
/// Alt is held or the menu bar has the keyboard. `at`: the character (not byte) to underline.
pub fn access_key_label(s: &str, at: Option<usize>) -> egui::text::LayoutJob {
let mut job = egui::text::LayoutJob::default();
let plain = egui::TextFormat { font_id: font(Type::Body), color: Color32::PLACEHOLDER, ..Default::default() };
let marked = egui::TextFormat { underline: Stroke::new(1.0, T.text), ..plain.clone() };
let cut = |n: usize| s.char_indices().nth(n).map_or(s.len(), |(b, _)| b);
match at {
Some(i) if i < s.chars().count() => {
let (a, b) = (cut(i), cut(i + 1));
job.append(s.get(..a).unwrap_or(""), 0.0, plain.clone());
job.append(s.get(a..b).unwrap_or(""), 0.0, marked);
job.append(s.get(b..).unwrap_or(""), 0.0, plain);
}
_ => job.append(s, 0.0, plain),
}
job
}
/// Text in a role: font, size, colour (and weight for titles and headings).
pub fn text(t: Type, s: impl Into<String>) -> egui::RichText {
let rt = egui::RichText::new(s).font(font(t)).color(color(t));
+118
View File
@@ -548,6 +548,13 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
if is_active || r == first_row {
a11y::anchor(ui, a11y::Region::Timeline, dock, &nr);
}
if is_active && app.tl_refocus {
app.tl_refocus = false;
// (Asking again would reset the focus filter that keeps the arrows here.)
if !nr.has_focus() {
nr.request_focus();
}
}
for (r, id, salt, label, on) in [(eye, "layer.toggle_visible", "eye", tr!("Show {name}", name = name), layer.visible), (lock, "layer.toggle_lock", "lock", tr!("Lock {name}", name = name), layer.locked), (outl, "layer.toggle_outline", "outline", tr!("Outline {name}", name = name), layer.outline)].into_iter().take(if is_camera { 2 } else { 3 }) {
let rr = ui.interact(r, ui.id().with((salt, layer.id.0)), Sense::click());
a11y::control(ui, &rr, WidgetType::Checkbox, &label, Some(on));
@@ -844,6 +851,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
}
let cr = ui.interact(cells, ui.id().with(("cells", layer.id.0)), a11y::pointer_only());
a11y::control(ui, &cr, WidgetType::Button, &tr!("Frames of {name}", name = layer.name), None);
if is_active {
// Its keyframes and spans, one by one, for screen readers (ADR 0064).
frame_nodes(app, ui, &cr, layer, x_of, y);
}
let shift = ui.input(|inp| inp.modifiers.shift);
if cr.clicked() || cr.drag_started() || cr.secondary_clicked() {
app.timeline_focus = true;
@@ -1224,6 +1235,113 @@ fn frame_view_button(app: &mut App, ui: &mut egui::Ui) {
}
}
/// While the timeline has the keyboard, says where the playhead went (through the status bar,
/// a live region): "Frame 12 · Ball · Frames 1–24: keyframe · motion tween". Quiet while playing,
/// and on the frame the focus arrived at (Ctrl+F6 has just said the panel).
pub fn announce(app: &mut App, ctx: &egui::Context) {
let focused = ctx.memory(|m| m.focused().is_some()) && a11y::focused_region(ctx) == Some(a11y::Region::Timeline);
let now = (app.s.layer, app.s.frame);
if !focused || app.playing {
app.tl_heard = if focused { Some(now) } else { None };
return;
}
if app.tl_heard.is_some_and(|h| h != now) {
let Some(layer) = app.s.timeline().layer(now.0) else { return };
let what = frame_text(layer, now.1).unwrap_or_else(|| tr!("no frame").to_string());
let msg = tr!("Frame {frame} · {layer} · {what}", frame = now.1 + 1, layer = layer.name, what = what);
app.status_ok(msg);
}
app.tl_heard = Some(now);
}
/// Most spans of the active layer listed one by one; the rest are summed up.
pub const MAX_SPAN_NODES: usize = 1_000;
/// What a span is, as a screen reader hears it: "Frames 1–24: keyframe · motion tween · label
/// “walk”". `next_adjacent`: the next keyframe starts where this one ends (a tween reaches it).
pub fn span_text(k: &anicraft_engine::doc::Keyframe, next_adjacent: bool) -> String {
let (a, b) = (k.start + 1, k.end());
let frames = if k.duration <= 1 { tr!("Frame {a}", a = a) } else { tr!("Frames {a}–{b}", a = a, b = b) };
let mut parts: Vec<String> = vec![if k.elements.is_empty() { tr!("blank keyframe").to_string() } else { tr!("keyframe").to_string() }];
if k.motion.is_some() {
parts.push(tr!("motion tween").to_string());
} else if let Some(t) = k.tween {
parts.push(match (t.kind, next_adjacent) {
(_, false) => tr!("broken tween").to_string(),
(TweenKind::Shape, true) => tr!("shape tween").to_string(),
(TweenKind::Classic, true) => tr!("classic tween").to_string(),
});
}
if !k.label.is_empty() {
parts.push(tr!("label “{label}”", label = k.label));
}
if k.sound.is_some() {
parts.push(tr!("sound").to_string());
}
if k.script.is_some() {
parts.push(tr!("actions").to_string());
}
tr!("{frames}: {what}", frames = frames, what = parts.join(" · "))
}
/// The span of `layer` at `frame`, described (`None`: no frame there).
pub fn frame_text(layer: &Layer, frame: u32) -> Option<String> {
let ki = layer.keyframes.iter().position(|k| k.covers(frame))?;
let k = layer.keyframes.get(ki)?;
Some(span_text(k, layer.keyframes.get(ki + 1).is_some_and(|n| n.start == k.end())))
}
/// The active layer's spans as a list under its frame grid's node: each says its frames, what
/// is there and its tween; the one under the playhead is selected; a reader's click moves the
/// playhead there.
fn frame_nodes(app: &mut App, ui: &mut egui::Ui, grid: &egui::Response, layer: &Layer, x_of: impl Fn(u32) -> f32, y: f32) {
use egui::accesskit::{Action, Role};
let ctx = ui.ctx().clone();
let child = ui.new_child(egui::UiBuilder::new().id_salt(("frame_list", layer.id.0)).accessibility_parent(grid.id).max_rect(grid.rect).sense(Sense::hover()));
let ak = |r: Rect| egui::accesskit::Rect { x0: r.min.x.into(), y0: r.min.y.into(), x1: r.max.x.into(), y1: r.max.y.into() };
let total = layer.keyframes.len();
ctx.accesskit_node_builder(child.unique_id(), |n| {
n.set_role(Role::List);
n.set_label(trn!("{n} keyframe span on {name}", "{n} keyframe spans on {name}", total, name = layer.name));
n.set_bounds(ak(grid.rect));
});
let mut goto = None;
for (ki, k) in layer.keyframes.iter().enumerate().take(MAX_SPAN_NODES) {
let id = child.unique_id().with(("span", k.start));
let r = Rect::from_min_max(pos2(x_of(k.start), y), pos2(x_of(k.end()), y + ROW_H)).intersect(grid.rect);
child.interact(Rect::from_center_size(r.center(), egui::Vec2::ZERO), id, Sense::hover());
let next_adjacent = layer.keyframes.get(ki + 1).is_some_and(|n| n.start == k.end());
let name = span_text(k, next_adjacent);
ctx.accesskit_node_builder(id, |n| {
n.set_role(Role::ListItem);
n.set_label(name);
n.set_selected(k.covers(app.s.frame));
if r.is_positive() {
n.set_bounds(ak(r));
}
n.set_position_in_set(ki + 1);
n.set_size_of_set(total);
n.add_action(Action::Click);
});
if ctx.input(|i| i.has_accesskit_action_request(id, Action::Click)) {
goto = Some(k.start);
}
}
if total > MAX_SPAN_NODES {
let id = child.unique_id().with("more");
child.interact(Rect::from_center_size(grid.rect.center(), egui::Vec2::ZERO), id, Sense::hover());
ctx.accesskit_node_builder(id, |n| {
n.set_role(Role::Label);
n.set_label(trn!("{n} more span is not listed: go there with , and . or Home and End", "{n} more spans are not listed: go there with , and . or Home and End", total - MAX_SPAN_NODES));
});
}
if let Some(f) = goto {
app.playing = false;
app.run("timeline.goto", json!({"frame": f}));
}
}
/// Engine param for an easing preset.
/// A keyframe's sound over its span: the waveform from the keyframe on, repeated as the sound
/// repeats, as far as the span reaches (all a stream sound plays; an event sound plays on past