From 73aec4dc3aa522cc86f4c6095a22b1418804ebe4 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 12 Nov 2026 18:06:23 -0700 Subject: [PATCH] feat(shell): a light theme, and Follow system for light or dark (M8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A third palette, Light, over the same roles as Graphite and high contrast, designed for light and checked by the same contrast rules. Preferences › Appearance › Theme offers Follow system, Dark (Graphite), Light and High contrast, applied live. Follow system now also follows the system's light or dark mode (Windows, macOS, portal/GNOME, prefers-color-scheme). --theme light|dark|high-contrast for one run. ADR 0077. Fixes #227 --- CHANGELOG.md | 11 ++ docs/accessibility.md | 4 +- docs/adr/0008-visual-language.md | 1 + docs/adr/0077-a-light-theme.md | 85 +++++++++ docs/adr/README.md | 1 - .../preferences-shortcuts-accessibility.md | 21 ++- docs/legal/compliance.md | 3 +- docs/roadmap.md | 8 +- docs/ui-guidelines.md | 10 +- src/a11y.rs | 47 ++++- src/app.rs | 63 +++---- src/dialogs.rs | 11 +- src/guidelines_tests.rs | 30 +++- src/main.rs | 9 +- src/platform.rs | 85 ++++++++- src/prefs.rs | 64 +++++-- src/stage.rs | 2 +- src/theme.rs | 168 ++++++++++++++++-- src/timeline.rs | 6 +- 19 files changed, 521 insertions(+), 108 deletions(-) create mode 100644 docs/adr/0077-a-light-theme.md diff --git a/CHANGELOG.md b/CHANGELOG.md index b29e903b..adcfcbf3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased +* **A light theme** (ADR 0077, M8). Fixes #227. + * **Preferences › Appearance › Theme** offers **Light** beside **Dark (Graphite)** and **High + contrast**: light grey panels, near-black text, hairline-edged buttons and fields, soft + shadows, and the timeline's mint, violet, amber and sky blocks in deeper tones made for a light + background. Applied as you click, no restart. + * **Follow system** (the default) now follows your system's light or dark mode as well as its + contrast setting: Windows' app mode, macOS' Appearance, the Linux desktop's colour scheme and + the browser's `prefers-color-scheme`. The window's title bar follows too. + * `anicraft --theme light` (also `dark`, `high-contrast`) previews a theme for one run. + * Every palette is checked by the contrast test (WCAG AA text, 3:1 controls and focus). + * **Dockable panels and workspaces** (M8, ADR 0075, fixes #249). * Drag any panel's tab to dock it on any side of the stage (the timeline above the stage, for example), stack it with other panels as a tab, or float it in a window of its own (inside diff --git a/docs/accessibility.md b/docs/accessibility.md index e1e7ead3..159ad37f 100644 --- a/docs/accessibility.md +++ b/docs/accessibility.md @@ -180,8 +180,8 @@ cargo test --bin anicraft palette # the contrast checks * **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 light or dark setting is not followed**: AniCraft has one standard (dark) - palette. Windows' white contrast themes get the black high-contrast palette. +* **Windows' white contrast themes get the black high-contrast palette**: the Light palette + (ADR 0077) follows the system's light mode, but it is not a 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, diff --git a/docs/adr/0008-visual-language.md b/docs/adr/0008-visual-language.md index ef40fdfa..02a4ea2e 100644 --- a/docs/adr/0008-visual-language.md +++ b/docs/adr/0008-visual-language.md @@ -2,6 +2,7 @@ * Status: accepted (2026-10-29), revised the same day (see "Revision 1") * Extends: ADR 0005 (typography and fonts), `docs/ui-guidelines.md` +* Extended by: ADR 0077 (a light palette over the same roles and rules) ## Context diff --git a/docs/adr/0077-a-light-theme.md b/docs/adr/0077-a-light-theme.md new file mode 100644 index 00000000..fda85b65 --- /dev/null +++ b/docs/adr/0077-a-light-theme.md @@ -0,0 +1,85 @@ +# ADR 0077: A light theme, and Follow system for light or dark + +* Status: accepted (2026-11-12) +* Relates to: ADR 0008 (visual language), ADR 0022 (high contrast), ADR 0064 (following the + system's contrast), ADR 0005 (UI guidelines), ADR 0006 (platforms); issue #227 + +## Context + +The shell had two palettes over the same roles in `src/theme.rs`: Graphite (dark, ADR 0008) and +high contrast (white on black, ADR 0022). Some people can't work on dark interfaces at all (#227: +"my eyes can't see a darn thing with dark themes, even with the high contrast one"), and many +work in bright rooms. Every operating system has a light/dark switch, and "Follow system" +(ADR 0064) only followed contrast. + +A light theme done badly is an inverted dark one: muddy greys, timeline blocks that glow on white, +shadows that look like smudges, invisible field edges. It has to be designed against the same +rules as Graphite. + +## Decisions + +1. **A third palette, `LIGHT`, over the same roles.** Every colour still comes from `Tokens`; the + guideline test (no raw colours outside `theme.rs`) is unchanged, so a light palette applies + everywhere at once. The look: + * *Surfaces* are cool paper greys a step apart, lightest where you type: fields white, raised + surfaces (windows, section bands, headers) `#f8f8fa`, panels `#f0f0f3`, the frame around the + work (menu and status bars) `#e1e1e6`, buttons `#e3e3e8`. The pasteboard (`#d2d2d9`) is a + step darker than the panels so a white stage stands off it. + * *Text* is near-black ink (`#17171b`) at 7:1 and more; dim and faint steps keep 4.5:1 on every + surface, as in Graphite. Icons follow text colours. + * *Controls* carry a hairline in the border colour at rest (`control_hairline`): a flat grey on + a light panel reads as a printed box, not a button. Graphite keeps flat buttons; high + contrast keeps its 3:1 outlines. + * *The accent* is a deeper blue (`#2457e0`) for focus, selection and the active tool; the + active tool is a pale blue block with dark-navy icon (7:1); selected rows `#d3dffb`. + * *Timeline blocks* keep their meaning and hue (mint artwork, violet classic tween, amber shape + tween, sky motion tween, red playhead) re-tuned as deeper mid-tones: each sits at 3:1 + against the panels (a component) and keeps its dark marks (keyframe dots, arrows, labels) at + 4.5:1. That window is narrow on light grey (relative luminance about 0.20 to 0.25), so each + colour was chosen inside it, not lightened from Graphite's. + * *Depth* is soft: window and menu shadows at about a third of Graphite's opacity, a light + stage shadow and a 27 % black edge around the stage. The every-fifth-frame tint is a shade, + not a light. + * Drag marks on the timeline (a drop outline, a span's new end) were hard-coded white; they now + use `text`, so they show on light cells too. +2. **`Tokens` gained the parts that differed by palette but were hard-coded**: `dark` (which of + egui's base styles to start from, so the text cursor, scroll bars and resize grips are right, + and which theme to give the native title bar through `ctx.set_theme`), `control_hairline`, + `cell_tint`, `stage_edge`, `window_shadow` and `popup_shadow`. +3. **The contrast test checks all three palettes** with the same rules (text 4.5:1, body text + 7:1, components and focus 3:1, marks on blocks 4.5:1, blocks against panels 3:1, waveforms, + hint letters, selection on a white stage), plus light-only rules (text on the pasteboard, + selection on panels, the pasteboard against a white stage) and a structural one: `dark` must + agree with which way the text goes, and light surfaces step from fields down to the frame. +4. **Preferences › Appearance › Theme** lists Follow system, Dark (Graphite), Light and High + contrast, applied live on click (as before). The palette is saved as it was (`"theme": + "Light"`; Graphite keeps its old name, so files from before still open). A palette name this + build doesn't know reads as Graphite instead of resetting every preference. +5. **Follow system follows light or dark too.** `platform::system_look()` asks, off the UI thread + and on the same schedule as ADR 0064 (start, every 4 s, when the window comes back), both + whether more contrast is asked for and whether apps are dark: + * Windows: `HKCU\…\Themes\Personalize\AppsUseLightTheme` (0 = dark). + * macOS: `defaults read -g AppleInterfaceStyle` (`Dark` while dark, also in Auto). + * Linux: the desktop portal's `org.freedesktop.appearance color-scheme` (1 dark, 2 light, 0 no + preference), else GNOME's `color-scheme` through `gsettings`. + * Web: `prefers-color-scheme: dark`. + + More contrast wins; otherwise a light system gets Light and a dark one, or one that doesn't + say, Graphite. Follow system stays the default (ADR 0064). +6. **`--theme dark|light|high-contrast`** previews a palette for one run (`graphite` still works), + for screenshots. +7. **Tests get a palette per thread.** The palette in use is process-wide view state; under + `cfg(test)` it is thread-local, so tests that switch themes run side by side without seeing + each other's. + +## Consequences + +* People on a light system who never touched the setting now get the light theme. That matches + the platform conventions (macOS and Windows apps follow the appearance setting) and the people + who asked for it, but creative tools traditionally open dark; the lead may prefer Graphite as + the default for systems that are light (one line in `Prefs::palette`). +* A new role must be given a value in three palettes; the contrast test fails until it meets the + rules in each. +* Not yet: a light high-contrast palette (Windows' white contrast themes still get the black one), + a user accent colour, following the system's accent colour, and the guide's screenshots in + light. diff --git a/docs/adr/README.md b/docs/adr/README.md index 2e2cb335..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0077 | m8/light-theme | A light theme | diff --git a/docs/guide/preferences-shortcuts-accessibility.md b/docs/guide/preferences-shortcuts-accessibility.md index 97272917..c7d18c11 100644 --- a/docs/guide/preferences-shortcuts-accessibility.md +++ b/docs/guide/preferences-shortcuts-accessibility.md @@ -20,9 +20,17 @@ bottom says which system you are on and where your settings are kept. * **Language**: the language of menus, panels and dialogs. See [Interface languages](#interface-languages) below. -* **Theme**: **Follow system** (the default), **Graphite** or **High contrast**. Follow system - uses Graphite, and switches to High contrast while your computer asks for more contrast. The - note under it says what your system is asking for right now. +* **Theme**: **Follow system** (the default), **Dark (Graphite)**, **Light** or **High + contrast**. Follow system is light or dark as your computer's apps are, and switches to High + contrast while your computer asks for more contrast; it changes within a few seconds of your + system, without a restart. The note under it says what your system is set to right now. A theme + you pick by hand stays whatever the system says, and every theme applies as soon as you click it. + * **Dark (Graphite)**: graphite panels, with colour where it means something. + * **Light**: light grey panels and near-black text, for bright rooms and for eyes that find dark + interfaces hard to read. Timeline blocks keep their colours (mint artwork, violet classic + tweens, amber shape tweens, sky-blue motion tweens) in deeper tones that stand out on light + grey. + * **High contrast**: see [High contrast](#high-contrast) below. * **Interface font** and **Data font**: the bundled typefaces, or any font installed on your computer. The data font shows numbers, timecode, rulers and shortcuts, so only monospaced families are listed for it. The **Preview** row shows both. @@ -220,19 +228,18 @@ turn on: The **High contrast** theme is white text on black, with yellow for focus, selection and the active tool, and an outline on every button and field. Text reaches at least 7:1 contrast. Your -artwork on the stage keeps its own colours. Choose **Graphite** or **High contrast** by hand to -keep that look whatever the system says. +artwork on the stage keeps its own colours. Choose **Dark (Graphite)**, **Light** or **High +contrast** by hand to keep that look whatever the system says. ### Larger interface Set **Preferences › Appearance › Interface scale** up to 200 %. The stage refits, the tools column scrolls, and the timeline header scrolls sideways (**Shift** and the mouse wheel). To try a look for one session without saving it, start AniCraft from a terminal with -`anicraft --theme high-contrast --scale 200`. +`anicraft --theme high-contrast --scale 200` (or `--theme light`, `--theme dark`). ### Not there yet -* AniCraft has one dark palette; it doesn't follow your system's light or dark setting. * The Motion Editor's graph needs a pointer. Its values and eases can be edited in the property list beside it. * Adding a point in Edit Envelope takes a click; existing points can be edited from the keyboard. diff --git a/docs/legal/compliance.md b/docs/legal/compliance.md index 7c5881de..8cfa9cbe 100644 --- a/docs/legal/compliance.md +++ b/docs/legal/compliance.md @@ -87,7 +87,8 @@ 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 +through `craft-update`. It reads one registry value, the high-contrast flag (and, since ADR 0077, +`AppsUseLightTheme` for the system's light or dark mode, with `prefers-color-scheme` on the web). 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. diff --git a/docs/roadmap.md b/docs/roadmap.md index 95fae35c..23a2c85e 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -21,11 +21,11 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | | Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. | -| 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). **CI on macOS and Windows** (ADR 0067): every code PR builds, tests and lints the workspace on macOS (arm64) and Windows (x64) runners besides Linux. Not yet: native macOS NSMenu, Linux arm64 and Windows ARM64 test legs on PRs, a GPU runner. Verified by hand on Windows only so far. **Robust start-up** (#207): the window opens through a list of ways (the one chosen in Preferences › Stage › Window graphics or `--renderer gl|wgpu|vulkan|dx12|metal`, then wgpu automatic, DirectX 12 on the low-power GPU on Windows, OpenGL), falling through on an error or a panic; a start that died inside a driver tries that way last next time; a start-up log (`Logs/anicraft.log` in the settings folder, the previous run's kept) records each way, the adapter and driver, panics and slow starts; a system message names it when nothing works. Not yet: verified on a hybrid-GPU laptop, the log from the Help menu. | +| 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 (Follow system, Dark (Graphite), Light or High contrast; ADR 0077), 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). **CI on macOS and Windows** (ADR 0067): every code PR builds, tests and lints the workspace on macOS (arm64) and Windows (x64) runners besides Linux. Not yet: native macOS NSMenu, Linux arm64 and Windows ARM64 test legs on PRs, a GPU runner. Verified by hand on Windows only so far. **Robust start-up** (#207): the window opens through a list of ways (the one chosen in Preferences › Stage › Window graphics or `--renderer gl|wgpu|vulkan|dx12|metal`, then wgpu automatic, DirectX 12 on the low-power GPU on Windows, OpenGL), falling through on an error or a panic; a start that died inside a driver tries that way last next time; a start-up log (`Logs/anicraft.log` in the settings folder, the previous run's kept) records each way, the adapter and driver, panics and slow starts; a system message names it when nothing works. Not yet: verified on a hybrid-GPU laptop, the log from the Help menu. | | 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. | | Documentation | **User guide, first slice** (ADR 0069, `docs/guide/`): eighteen chapters for artists (getting started to troubleshooting, and Coming from Animate), a command reference and a shortcut reference (Windows/Linux and macOS) generated from the registry and checked for freshness by tests, every link, anchor and picture checked, eight screenshots from `scripts/guide-shots.sh`. Help › User Guide opens the book bundled in the app, offline, in the browser; the web build serves it beside the editor; `anicraft-cli guide --out ` writes it. Not yet: translated guides, search, a PDF edition, context help from panels, macOS and Linux screenshots. | | 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). **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. | +| 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. **Light theme** (ADR 0077, #227): a third palette designed for light (paper greys, near-black text, hairline controls, timeline blocks re-tuned to 3:1 on the panels with 4.5:1 marks), checked by the same contrast test; Follow system now follows the system's light or dark mode too (Windows, macOS, portal/GNOME, `prefers-color-scheme`). Not yet: names beyond the outline heuristic, per-item menu letters, a light high-contrast 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, over the stage and the visible pasteboard (artwork off the stage shows, on transparent tiles that never cross the stage edge; View › Clip Content Outside the Stage and its edit-bar button hide it, view state), 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). | @@ -41,7 +41,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 later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API 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; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); 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: spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool; not yet: instances and shapes in one armature, reshaping a bound shape, painted weights); ~~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); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~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, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, 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); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~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~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline; next: translated guides, search, PDF, context help); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout; not yet: moving the tools, dragging a floating window back into a dock, several tabs in one floating window, deleting and renaming workspaces, docks collapsed to icons). | +| **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, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, 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), ~~a light theme~~ ✅ (ADR 0077: Light palette, Follow system for light or dark, #227), next: live screen-reader passes on each platform, a light high-contrast 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); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~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~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline; next: translated guides, search, PDF, context help); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout; not yet: moving the tools, dragging a floating window back into a dock, several tabs in one floating window, deleting and renaming workspaces, docks collapsed to icons). | ## Releases @@ -62,7 +62,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), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068); next: Paint Selection/Inside, tilt | 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); ~~templates and drops on the timeline~~ ✅ first slice (ADR 0065); ~~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); ~~CI on macOS and Windows~~ ✅ (ADR 0067); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075); next: live screen-reader passes | `.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); ~~templates and drops on the timeline~~ ✅ first slice (ADR 0065); ~~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); ~~a light theme~~ ✅ (ADR 0077); ~~CI on macOS and Windows~~ ✅ (ADR 0067); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075); 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). diff --git a/docs/ui-guidelines.md b/docs/ui-guidelines.md index a6b8a657..3df42dcd 100644 --- a/docs/ui-guidelines.md +++ b/docs/ui-guidelines.md @@ -70,10 +70,12 @@ are not used for UI text, because they would change metrics per OS. buttons (`on_fill`) and on the active tool (`on_active`) ≥ 4.5:1; marks on timeline blocks and the playhead flag (`ink`) ≥ 4.5:1; focus rings, selection, checkbox edges and timeline blocks ≥ 3:1 against their background. -* **Two palettes, one set of roles** (ADR 0022): Graphite (the default) and High contrast - (Preferences › Appearance › Theme). Code reads `T.role`, never a palette by name, and never - assumes a colour: text on an accent fill is `T.on_fill`, not white; an icon under the pointer - is `T.icon_hot`. A new token needs a value in both palettes and a line in the contrast test. +* **Three palettes, one set of roles** (ADR 0022, ADR 0077): Graphite (dark), Light and High + contrast (Preferences › Appearance › Theme). Code reads `T.role`, never a palette by name, and + never assumes a colour or a direction: text on an accent fill is `T.on_fill`, not white; an icon + under the pointer is `T.icon_hot`; a mark drawn across the timeline is `T.text`, not white, + because the panels may be light. A new token needs a value in every palette and a line in the + contrast test. Check UI changes with `--theme light` as well. * No raw colours outside `theme.rs`: add a token. ## 4. Shapes, borders, spacing and sizes (ADR 0008) diff --git a/src/a11y.rs b/src/a11y.rs index 58c90386..db8bd151 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -435,6 +435,12 @@ mod tests { a.open_panel(Some("motionedit")); a.me_styles = vec![anicraft_engine::doc::ColorStyle::Tint, anicraft_engine::doc::ColorStyle::Advanced, anicraft_engine::doc::ColorStyle::Brightness]; })); + found.extend(check("light", |a, ctx| { + let mut p = a.prefs.clone(); + p.theme = crate::theme::Palette::Light; + p.theme_follows_system = Some(false); + a.set_prefs(ctx, p); + })); found.extend(check("high contrast at 200%", |a, ctx| { let mut p = a.prefs.clone(); p.theme = crate::theme::Palette::HighContrast; @@ -696,19 +702,50 @@ mod tests { #[test] fn the_palette_follows_the_system_contrast_setting_in_the_same_frame() { + use crate::platform::SystemLook; + use crate::theme::Palette; + let look = |high_contrast, dark| SystemLook { high_contrast, dark }; let (_, mut app, ctx) = tree(|_, _| {}); - app.set_system_contrast(&ctx, Some(true)); + app.set_system_look(&ctx, look(Some(true), Some(true))); let followed = crate::theme::palette(); - app.set_system_contrast(&ctx, Some(false)); + app.set_system_look(&ctx, look(Some(false), Some(true))); let back = crate::theme::palette(); + // The system switches its apps to light (ADR 0077): so does the interface, and egui's + // own style with it. + app.set_system_look(&ctx, look(Some(false), Some(false))); + let light = (crate::theme::palette(), ctx.global_style().visuals.panel_fill, ctx.global_style().visuals.dark_mode); // 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)); + app.set_system_look(&ctx, look(Some(true), Some(false))); 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)); + crate::theme::apply_palette(&egui::Context::default(), Palette::Graphite); + assert_eq!((followed, back, manual), (Palette::HighContrast, Palette::Graphite, Palette::Graphite)); + assert_eq!(light, (Palette::Light, crate::theme::LIGHT.panel, false)); + } + + #[test] + fn choosing_a_theme_in_preferences_restyles_everything_in_the_same_frame() { + use crate::theme::{LIGHT, Palette, T}; + let (_, mut app, ctx) = tree(|_, _| {}); + for palette in [Palette::Light, Palette::HighContrast, Palette::Graphite] { + let mut p = app.prefs.clone(); + p.theme = palette; + p.theme_follows_system = Some(false); + app.set_prefs(&ctx, p); + let tokens = palette.tokens(); + // Tokens read from here on, egui's widgets, and both of egui's styles. + for theme in [egui::Theme::Dark, egui::Theme::Light] { + let v = ctx.style_of(theme).visuals.clone(); + assert_eq!((v.panel_fill, v.window_fill, v.widgets.inactive.bg_fill, v.override_text_color), (tokens.panel, tokens.panel_alt, tokens.header, Some(tokens.text)), "{palette:?} in egui's {theme:?} style"); + } + assert_eq!((crate::theme::palette(), T.panel, ctx.theme() == egui::Theme::Dark), (palette, tokens.panel, tokens.dark)); + } + // The light look's controls carry their hairline; Graphite's stay flat. + app.set_prefs(&ctx, crate::prefs::Prefs { theme: Palette::Light, theme_follows_system: Some(false), ..app.prefs.clone() }); + assert_eq!(ctx.global_style().visuals.widgets.inactive.bg_stroke.color, LIGHT.border); + crate::theme::apply_palette(&egui::Context::default(), Palette::Graphite); } #[test] diff --git a/src/app.rs b/src/app.rs index 81e3398d..e63c9e7b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -470,15 +470,16 @@ pub struct App { 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, + /// What the system last said about contrast and light or dark (ADR 0064, ADR 0077): each part + /// `None` until it has, or if it can't. Screenshot runs never ask, so they look the same + /// everywhere. + pub system_look: platform::SystemLook, /// 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>>, - contrast_asked: Option, + /// The system's look being read off the UI thread, and when it last was. + look_probe: Option>, + look_asked: Option, /// The start screen, while it is up (ADR 0059). pub start: Option, /// Files dragged over and dropped onto the window (ADR 0059). @@ -489,8 +490,8 @@ pub struct App { pub templates: crate::templates::Templates, } -/// How often (seconds) the system's contrast setting is asked again (ADR 0064). -const SYSTEM_CONTRAST_EVERY: f64 = 4.0; +/// How often (seconds) the system's contrast and light or dark setting are asked again (ADR 0064). +const SYSTEM_LOOK_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). @@ -667,11 +668,11 @@ impl App { tl_heard: None, tl_refocus: false, menu_keys: Default::default(), - system_contrast: None, + system_look: platform::SystemLook::default(), key_script: Default::default(), key_script_wait: 0, - contrast_probe: None, - contrast_asked: None, + look_probe: None, + look_asked: None, start: None, drop: Default::default(), thumbs: Default::default(), @@ -776,7 +777,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.palette(self.system_contrast)); + theme::apply_palette(ctx, self.prefs.palette(self.system_look)); crate::onion::refresh_colors(self); self.keymap = keymap::Keymap::new(&self.prefs.shortcuts); self.shortcuts = self.keymap.table(); @@ -875,58 +876,58 @@ impl App { } } - /// Follows the system's contrast setting (ADR 0064): asks it on a worker now and then (at + /// Follows the system's look (ADR 0064, ADR 0077): 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) { + fn follow_system_look(&mut self, ctx: &egui::Context) { if self.shot.is_some() { return; } - if let Some(rx) = &self.contrast_probe { + if let Some(rx) = &self.look_probe { match rx.try_recv() { Ok(v) => { - self.contrast_probe = None; - self.set_system_contrast(ctx, v); + self.look_probe = None; + self.set_system_look(ctx, v); } Err(std::sync::mpsc::TryRecvError::Empty) => return, - Err(std::sync::mpsc::TryRecvError::Disconnected) => self.contrast_probe = None, + Err(std::sync::mpsc::TryRecvError::Disconnected) => self.look_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); + let due = self.look_asked.is_none_or(|t| now - t >= SYSTEM_LOOK_EVERY || came_back); if !due { return; } - self.contrast_asked = Some(now); + self.look_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()) + .name("anicraft-look".into()) .spawn(move || { - let _ = tx.send(platform::system_high_contrast()); + let _ = tx.send(platform::system_look()); 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(); + let started = tx.send(platform::system_look()).is_ok(); if started { - self.contrast_probe = Some(rx); + self.look_probe = Some(rx); } // Ask again later even if nothing else happens. - ctx.request_repaint_after(std::time::Duration::from_secs_f64(SYSTEM_CONTRAST_EVERY)); + ctx.request_repaint_after(std::time::Duration::from_secs_f64(SYSTEM_LOOK_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) { - if v == self.system_contrast { + /// What the system says about its look: the palette follows at once, if it follows. + pub fn set_system_look(&mut self, ctx: &egui::Context, v: platform::SystemLook) { + if v == self.system_look { return; } - let before = self.prefs.palette(self.system_contrast); - self.system_contrast = v; + let before = self.prefs.palette(self.system_look); + self.system_look = v; let after = self.prefs.palette(v); if after != before { theme::apply_palette(ctx, after); @@ -2986,7 +2987,7 @@ impl App { } self.handle_screenshot(&ctx); self.poll_font_scan(&ctx); - self.follow_system_contrast(&ctx); + self.follow_system_look(&ctx); if let Some(p) = platform::picked_file() { self.open_picked(p); } diff --git a/src/dialogs.rs b/src/dialogs.rs index 927d25d8..ecb3a3c0 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -422,10 +422,13 @@ fn preferences(app: &mut App, ctx: &egui::Context) { 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."), + // What following would show now, and why (ADR 0064, ADR 0077). + let look = app.system_look; + let says = match (look.high_contrast, look.dark) { + (Some(true), _) => tr!("Light or dark as your system's apps are, and high contrast while it asks for more contrast. It does now, so it is high contrast."), + (_, Some(false)) => tr!("Light or dark as your system's apps are, and high contrast while it asks for more contrast. Your system is light now."), + (_, Some(true)) => tr!("Light or dark as your system's apps are, and high contrast while it asks for more contrast. Your system is dark now."), + (_, None) => tr!("Light or dark as your system's apps are, and high contrast while it asks for more contrast. This system doesn't say whether it is light, so it is dark."), }; form_note(ui, toggle_indent, text(Type::Caption, says)); ui.add_space(2.0); diff --git a/src/guidelines_tests.rs b/src/guidelines_tests.rs index 56ce5612..4c58e382 100644 --- a/src/guidelines_tests.rs +++ b/src/guidelines_tests.rs @@ -132,6 +132,16 @@ fn palette_failures(name: &str, t: &crate::theme::Tokens) -> Vec { need("active tool block on panel", t.active, t.panel, if t.control_outline { 3.0 } else { 1.0 }); // Stage selection is drawn over artwork, usually on a white stage. need("selection on a white stage", t.selection, egui::Color32::WHITE, 3.0); + // Marks drawn across the timeline grid while dragging frames (the drop outline, a span's new + // end) are in `text`: they must show on the cells and on the active row. + need("text (drag marks) on row_active", t.text, t.row_active, 4.5); + if !t.dark { + // Light: the white stage stands off the pasteboard by its edge line, and the pasteboard + // is a step darker than the panels so the work area reads as one region. + need("text on pasteboard", t.text, t.pasteboard, 7.0); + need("pasteboard against a white stage", t.pasteboard, egui::Color32::WHITE, 1.4); + need("selection on panel", t.selection, t.panel, 3.0); + } if t.control_outline { // High contrast: every region border and control outline is a visible line. need("border on panel", t.border, t.panel, 3.0); @@ -143,8 +153,9 @@ fn palette_failures(name: &str, t: &crate::theme::Tokens) -> Vec { #[test] fn palette_meets_contrast_and_target_minimums() { - use crate::theme::{GRAPHITE, HIGH_CONTRAST, Palette, TARGET, TOOL_BUTTON}; + use crate::theme::{GRAPHITE, HIGH_CONTRAST, LIGHT, Palette, TARGET, TOOL_BUTTON}; let mut found = palette_failures("Graphite", &GRAPHITE); + found.extend(palette_failures("Light", &LIGHT)); found.extend(palette_failures("High contrast", &HIGH_CONTRAST)); assert!(found.is_empty(), "contrast below WCAG AA:\n{}", found.join("\n")); // High contrast is stricter than AA: every text step reads at 7:1 (AAA) on its surfaces. @@ -154,8 +165,21 @@ fn palette_meets_contrast_and_target_minimums() { assert!(contrast(fg, bg) >= 7.0, "high contrast text below 7:1: {:.2}", contrast(fg, bg)); } } - // Every palette the preferences offer is checked. - assert!(Palette::ALL.iter().all(|(p, _, _)| matches!(p, Palette::Graphite | Palette::HighContrast))); + // Light is designed for light, not the dark look inverted (ADR 0077): dark text on light + // surfaces, fields the lightest of them, the frame (chrome) darker than the panels, and egui + // told it is a light look. Graphite and high contrast are the other way round. + for (name, t) in [("Graphite", GRAPHITE), ("High contrast", HIGH_CONTRAST), ("Light", LIGHT)] { + let lum = |c: egui::Color32| contrast(c, egui::Color32::BLACK); + assert_eq!(t.dark, lum(t.text) > lum(t.panel), "{name}: `dark` says which way text goes"); + } + let lum = |c: egui::Color32| contrast(c, egui::Color32::BLACK); + assert!(lum(LIGHT.field) >= lum(LIGHT.panel_alt) && lum(LIGHT.panel_alt) > lum(LIGHT.panel) && lum(LIGHT.panel) > lum(LIGHT.chrome), "light surfaces step down from fields to the frame"); + const { assert!(LIGHT.control_hairline && !GRAPHITE.control_hairline, "light controls carry a hairline") }; + // Every palette the preferences offer is checked, once each. + assert!(Palette::ALL.iter().all(|(p, _, _)| matches!(p, Palette::Graphite | Palette::HighContrast | Palette::Light))); + for p in [Palette::Graphite, Palette::Light, Palette::HighContrast] { + assert_eq!(Palette::ALL.iter().filter(|(q, _, _)| *q == p).count(), 1, "{p:?} offered once"); + } // Click targets (WCAG 2.5.8 asks for at least 24 × 24). const { assert!(TARGET >= 24.0 && TOOL_BUTTON >= TARGET) }; } diff --git a/src/main.rs b/src/main.rs index a8b131b4..386603e4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,7 @@ //! //! ```text //! anicraft [file.anicraft] [--screenshot out.png] [--renderer wgpu|gl] [--open ] -//! [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] +//! [--theme dark|light|high-contrast] [--scale ] [--lang |auto|pseudo] //! anicraft --version //! ``` //! `--screenshot` starts normally, draws ~120 frames, saves the window as PNG and exits. @@ -217,9 +217,10 @@ fn parse_args(args: impl IntoIterator) -> Result { _ => return Err("--shot-width takes a width in pixels, from 64 to 8192".into()), // i18n-exempt: a console message }, "--theme" => match args.next().as_deref() { - Some("graphite") => out.look.theme = Some(theme::Palette::Graphite), + Some("graphite" | "dark") => out.look.theme = Some(theme::Palette::Graphite), + Some("light") => out.look.theme = Some(theme::Palette::Light), Some("high-contrast") => out.look.theme = Some(theme::Palette::HighContrast), - other => return Err(format!("--theme takes graphite or high-contrast, not {}", other.unwrap_or("nothing"))), // i18n-exempt: a console message + other => return Err(format!("--theme takes dark (graphite), light or high-contrast, not {}", other.unwrap_or("nothing"))), // i18n-exempt: a console message }, "--scale" => match args.next().and_then(|s| s.trim_end_matches('%').parse::().ok()) { Some(pct) if pct.is_finite() => out.look.scale = Some(pct / 100.0), @@ -246,7 +247,7 @@ fn parse_args(args: impl IntoIterator) -> Result { /// `--help` (the console's text, in English). #[cfg(not(target_arch = "wasm32"))] // i18n-exempt: the --help console text -const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish|dock|animator|designer]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width ]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme dark|light|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish|dock|animator|designer]\n\ --renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ --shot-width scales the screenshot down to this width (the user guide's pictures)\n\ diff --git a/src/platform.rs b/src/platform.rs index 4d474bea..4d8e9e3a 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -83,15 +83,92 @@ pub fn system_high_contrast() -> Option { } } +/// What the system says about how interfaces should look (ADR 0064, ADR 0077), for Preferences › +/// Appearance › Follow system. Each part is `None` where this system doesn't say. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct SystemLook { + /// More contrast asked for ([`system_high_contrast`]). + pub high_contrast: Option, + /// Dark mode on ([`system_dark_mode`]); `Some(false)`: light. + pub dark: Option, +} + +/// Asks the system for both parts of its look. Can block for a moment: call it off the UI thread. +pub fn system_look() -> SystemLook { + SystemLook { high_contrast: system_high_contrast(), dark: system_dark_mode() } +} + +/// Whether the system's apps are set to dark (ADR 0077): Windows' "default app mode" +/// (`AppsUseLightTheme`), macOS' Appearance (`AppleInterfaceStyle`, also while it switches +/// automatically), the desktop portal's `color-scheme` on Linux (GNOME's own setting where there is +/// no portal), the browser's `prefers-color-scheme`. `None`: this system doesn't say. Can block for +/// a moment: call it off the UI thread. +pub fn system_dark_mode() -> Option { + #[cfg(windows)] + { + let key = winreg::RegKey::predef(winreg::enums::HKEY_CURRENT_USER).open_subkey(r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize").ok()?; // i18n-exempt: a registry path + let light: u32 = key.get_value("AppsUseLightTheme").ok()?; // i18n-exempt: a registry value name + Some(light == 0) + } + #[cfg(target_os = "macos")] + { + // The key exists only while the appearance is dark; `defaults` fails when it is missing. + let out = std::process::Command::new("defaults").args(["read", "-g", "AppleInterfaceStyle"]).output().ok()?; // i18n-exempt: a command line + Some(out.status.success() && String::from_utf8_lossy(&out.stdout).trim().eq_ignore_ascii_case("dark")) + } + #[cfg(target_arch = "wasm32")] + { + web_sys::window()?.match_media("(prefers-color-scheme: dark)").ok()??.matches().into() // i18n-exempt: a media query + } + #[cfg(not(any(windows, target_os = "macos", target_arch = "wasm32")))] + { + portal_color_scheme().or_else(gnome_color_scheme) + } +} + +/// The XDG desktop portal's `org.freedesktop.appearance color-scheme`: 1 prefers dark, 2 light, +/// 0 says nothing. +#[cfg(not(any(windows, target_os = "macos", target_arch = "wasm32")))] +fn portal_color_scheme() -> Option { + portal_appearance("color-scheme").and_then(scheme_from_portal) +} + +#[cfg_attr(any(windows, target_os = "macos", target_arch = "wasm32"), allow(dead_code))] +fn scheme_from_portal(v: u32) -> Option { + match v { + 1 => Some(true), + 2 => Some(false), + _ => None, + } +} + +/// GNOME's `color-scheme` (`'prefer-dark'`, `'prefer-light'`, `'default'`), for desktops without +/// the portal setting. +#[cfg(not(any(windows, target_os = "macos", target_arch = "wasm32")))] +fn gnome_color_scheme() -> Option { + let out = std::process::Command::new("gsettings").args(["get", "org.gnome.desktop.interface", "color-scheme"]).output().ok().filter(|o| o.status.success())?; // i18n-exempt: a command line + match String::from_utf8_lossy(&out.stdout).trim().trim_matches('\'') { + "prefer-dark" => Some(true), + "prefer-light" => Some(false), + _ => None, + } +} + /// 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 { + portal_appearance("contrast").map(|v| v == 1) +} + +/// One `org.freedesktop.appearance` number from the desktop portal, through `gdbus`. +#[cfg(not(any(windows, target_os = "macos", target_arch = "wasm32")))] +fn portal_appearance(key: &str) -> Option { 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 + .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", key]) // 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) + parse_portal_uint(&String::from_utf8_lossy(&out.stdout)) } /// GNOME's own switch, for desktops without the portal setting. @@ -778,12 +855,16 @@ mod tests { assert_eq!(parse_portal_uint("(,) "), Some(0)); assert_eq!(parse_portal_uint("Error: no such key"), None); + // color-scheme: 1 dark, 2 light, 0 (no preference) and anything else say nothing. + assert_eq!([0, 1, 2, 7].map(scheme_from_portal), [None, Some(true), Some(false), 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(); + let look = system_look(); + assert_eq!(look.dark, system_dark_mode()); } #[test] diff --git a/src/prefs.rs b/src/prefs.rs index 7eaabccc..7632b3f2 100644 --- a/src/prefs.rs +++ b/src/prefs.rs @@ -76,6 +76,10 @@ impl WindowBackend { } } +fn lenient_palette<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(serde_json::from_value(serde_json::Value::deserialize(d)?).unwrap_or_default()) +} + fn lenient_backend<'de, D: serde::Deserializer<'de>>(d: D) -> Result { Ok(serde_json::from_value(serde_json::Value::deserialize(d)?).unwrap_or_default()) } @@ -96,11 +100,13 @@ pub struct Prefs { pub language: String, pub ui_font: FontChoice, pub data_font: FontChoice, - /// Graphite or high contrast (ADR 0022), when chosen by hand. + /// Dark (Graphite), Light (ADR 0077) or high contrast (ADR 0022), when chosen by hand. A + /// palette this build doesn't know (a newer build's) reads as Graphite, keeping the rest. + #[serde(deserialize_with = "lenient_palette")] 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. + /// Follow the system (ADR 0064, ADR 0077): high contrast while the system asks for more + /// contrast, otherwise light or dark as its apps are. `None` (files from before): it follows, + /// unless the file chose another palette than Graphite. #[serde(skip_serializing_if = "Option::is_none")] pub theme_follows_system: Option, /// Interface scale (1.0 = 100%). @@ -254,18 +260,25 @@ pub const SCALE_RANGE: std::ops::RangeInclusive = 0.75..=2.0; pub const GAP_RANGE: std::ops::RangeInclusive = 0.0..=48.0; impl Prefs { - /// Whether the theme follows the system's contrast setting ("Follow system", the default). + /// Whether the theme follows the system ("Follow system", the default): its contrast setting + /// (ADR 0064) and its light or dark mode (ADR 0077). A file that names a palette other than + /// the default without saying whether it follows chose that palette. pub fn follows_system(&self) -> bool { - self.theme_follows_system.unwrap_or(self.theme != crate::theme::Palette::HighContrast) + self.theme_follows_system.unwrap_or(self.theme == crate::theme::Palette::Graphite) } - /// 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) -> 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, + /// The palette to draw with, given what the system says (each part `None` where it doesn't + /// say, or hasn't yet). More contrast wins over light or dark; a system that says nothing gets + /// Graphite. + pub fn palette(&self, system: crate::platform::SystemLook) -> crate::theme::Palette { + use crate::theme::Palette; + if !self.follows_system() { + return self.theme; + } + match (system.high_contrast, system.dark) { + (Some(true), _) => Palette::HighContrast, + (_, Some(false)) => Palette::Light, + _ => Palette::Graphite, } } @@ -361,21 +374,36 @@ mod tests { #[test] fn the_theme_follows_the_system_unless_one_was_chosen() { + use crate::platform::SystemLook; use crate::theme::Palette; + let look = |high_contrast, dark| SystemLook { high_contrast, dark }; // 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"); + assert_eq!(p.palette(look(Some(true), None)), Palette::HighContrast); + assert_eq!(p.palette(look(Some(true), Some(false))), Palette::HighContrast, "more contrast wins over light"); + assert_eq!(p.palette(look(Some(false), None)), Palette::Graphite); + assert_eq!(p.palette(look(Some(false), Some(false))), Palette::Light, "a light system: light (ADR 0077)"); + assert_eq!(p.palette(look(None, Some(true))), Palette::Graphite); + assert_eq!(p.palette(SystemLook::default()), 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); + assert_eq!(hc.palette(look(Some(false), Some(true))), Palette::HighContrast); + // Light chosen by hand stays light on a dark system, through a round trip. + let light = Prefs { theme: Palette::Light, theme_follows_system: Some(false), ..Prefs::default() }; + let json = serde_json::to_string(&light).unwrap_or_default(); + assert!(json.contains(r#""theme": "Light""#) || json.contains(r#""theme":"Light""#), "{json}"); + let back = Prefs::from_json(&json); + assert_eq!((back.theme, back.palette(look(Some(false), Some(true)))), (Palette::Light, Palette::Light)); + assert_eq!(Prefs::from_json(r#"{"theme": "Light"}"#).palette(look(None, Some(true))), Palette::Light, "named without the flag: chosen"); + // A palette this build doesn't know (a newer file) falls back to the defaults, not a crash. + let newer = Prefs::from_json(r#"{"theme": "Sepia", "ui_scale": 1.5}"#); + assert_eq!((newer.theme, newer.ui_scale), (Palette::Graphite, 1.5), "the other preferences stay"); // 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); + assert_eq!(manual.palette(look(Some(true), Some(false))), 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"); diff --git a/src/stage.rs b/src/stage.rs index e295899d..1630118c 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -955,7 +955,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } } } - painter.rect_stroke(stage_rect, 0.0, Stroke::new(1.0, Color32::from_black_alpha(160)), StrokeKind::Outside); + painter.rect_stroke(stage_rect, 0.0, Stroke::new(1.0, T.stage_edge), StrokeKind::Outside); // ---- overlays ------------------------------------------------------------------------- // The camera frame (or, previewing, the Camera tool's handle) comes first, under the diff --git a/src/theme.rs b/src/theme.rs index 97d1ad95..37373c39 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -1,7 +1,8 @@ //! Design tokens. Every colour, radius and target size in the shell comes from here //! (docs/ui-guidelines.md). //! -//! The look (ADR 0008): graphite neutrals, geometric controls, borders only where they separate +//! Three palettes share these roles: Graphite (dark, the default), Light (ADR 0077) and high +//! contrast (ADR 0022). The look (ADR 0008): graphite neutrals, geometric controls, borders only where they separate //! layout regions, flat buttons, and vibrant colour spent where it carries meaning (timeline //! blocks, playhead, selection). Corners follow the role of a shape, not one global value: //! structure is square, controls are softened slightly, floating surfaces are rounder. @@ -93,6 +94,20 @@ pub struct Tokens { /// Buttons and fields carry a visible `control_edge` (WCAG 1.4.11: a control's boundary at /// 3:1). Off in the graphite look, where fills and hover carry it; on in high contrast. pub control_outline: bool, + /// A light-on-dark palette (Graphite, high contrast) or dark-on-light (Light, ADR 0077): which + /// of egui's base looks the widgets start from (text cursor, scroll bars, resize grips). + pub dark: bool, + /// Buttons and fields carry a hairline in `border` at rest: the light look, where a flat grey + /// on a light panel would read as a printed box rather than a control. + pub control_hairline: bool, + /// Timeline: the tint on every fifth frame column (a whisper of light on dark, of shade on + /// light). + pub cell_tint: Color32, + /// The line around the stage, where it meets the pasteboard. + pub stage_edge: Color32, + /// Opacity of the shadow under windows and under menus and tooltips (black). + pub window_shadow: u8, + pub popup_shadow: u8, /// Corner radii by role (see `Shape` below). pub radius_control: u8, pub radius_menu: u8, @@ -160,6 +175,12 @@ pub const GRAPHITE: Tokens = Tokens { kind_movie_clip: Color32::from_rgb(0x5a, 0x8f, 0xff), kind_button: Color32::from_rgb(0xff, 0xb5, 0x3d), control_outline: false, + dark: true, + control_hairline: false, + cell_tint: Color32::from_rgba_premultiplied(6, 6, 6, 6), + stage_edge: Color32::from_black_alpha(160), + window_shadow: 150, + popup_shadow: 130, radius_control: 3, radius_menu: 6, radius_window: 10, @@ -218,6 +239,76 @@ pub const HIGH_CONTRAST: Tokens = Tokens { kind_movie_clip: Color32::from_rgb(0x85, 0xad, 0xff), kind_button: Color32::from_rgb(0xff, 0xc8, 0x5c), control_outline: true, + dark: true, + control_hairline: false, + cell_tint: Color32::from_rgba_premultiplied(6, 6, 6, 6), + stage_edge: Color32::from_black_alpha(160), + window_shadow: 150, + popup_shadow: 130, + radius_control: 3, + radius_menu: 6, + radius_window: 10, +}; + +/// The light look (ADR 0077): designed for daylight, not the dark one inverted. Cool paper greys +/// a step apart (the frame darkest, raised surfaces lightest, fields white), near-black ink for +/// text, hairlines on controls, soft shadows. Colour still goes where it means something, but in +/// deeper mid-tones: the timeline's mint, violet, amber and sky blocks sit at 3:1 against the +/// panels and keep dark marks at 4.5:1, the same rules Graphite meets. +pub const LIGHT: Tokens = Tokens { + chrome: Color32::from_rgb(0xe1, 0xe1, 0xe6), + panel: Color32::from_rgb(0xf0, 0xf0, 0xf3), + panel_alt: Color32::from_rgb(0xf8, 0xf8, 0xfa), + header: Color32::from_rgb(0xe3, 0xe3, 0xe8), + hover: Color32::from_rgb(0xd5, 0xd5, 0xdc), + active: Color32::from_rgb(0xd0, 0xdc, 0xfa), + on_active: Color32::from_rgb(0x0b, 0x1f, 0x5c), + icon: Color32::from_rgb(0x4c, 0x4c, 0x56), + icon_hot: Color32::from_rgb(0x10, 0x10, 0x14), + field: Color32::from_rgb(0xff, 0xff, 0xff), + border: Color32::from_rgb(0xc9, 0xc9, 0xd1), + control_edge: Color32::from_rgb(0x7a, 0x7a, 0x85), + separator: Color32::from_rgb(0xdf, 0xdf, 0xe5), + text: Color32::from_rgb(0x17, 0x17, 0x1b), + text_dim: Color32::from_rgb(0x44, 0x44, 0x4d), + text_faint: Color32::from_rgb(0x5c, 0x5c, 0x66), + accent: Color32::from_rgb(0x24, 0x57, 0xe0), + accent_dim: Color32::from_rgb(0xd3, 0xdf, 0xfb), + accent_text: Color32::from_rgb(0x1d, 0x4c, 0xcc), + on_fill: Color32::WHITE, + ink: Color32::from_rgb(0x10, 0x10, 0x14), + pasteboard: Color32::from_rgb(0xd2, 0xd2, 0xd9), + stage_shadow: Color32::from_black_alpha(34), + span: Color32::from_rgb(0x15, 0x95, 0x7d), + span_empty: Color32::from_rgb(0xdb, 0xdb, 0xe2), + row_active: Color32::from_rgb(0xe2, 0xe8, 0xf7), + tween: Color32::from_rgb(0x8f, 0x6c, 0xf5), + tween_shape: Color32::from_rgb(0xb9, 0x7a, 0x12), + tween_motion: Color32::from_rgb(0x2e, 0x8f, 0xcf), + waveform: Color32::from_rgb(0x1a, 0x5c, 0xa8), + tween_line: Color32::from_rgb(0x10, 0x10, 0x14), + playhead: Color32::from_rgb(0xe8, 0x46, 0x3a), + selection: Color32::from_rgb(0x24, 0x57, 0xe0), + danger: Color32::from_rgb(0xc4, 0x2e, 0x26), + error: Color32::from_rgb(0xb8, 0x26, 0x1c), + ok: Color32::from_rgb(0x12, 0x6e, 0x3e), + hint_unplaced: Color32::from_rgb(0xf0, 0x55, 0x82), + hint_start: Color32::from_rgb(0xf2, 0xa5, 0x1f), + hint_end: Color32::from_rgb(0x2f, 0xc8, 0x8c), + onion_past: Color32::from_rgb(0x2f, 0x6c, 0xe6), + onion_future: Color32::from_rgb(0x1f, 0x9a, 0x50), + slice_guide: Color32::from_rgb(0xc4, 0x2f, 0xb0), + hit_area: Color32::from_rgb(0x13, 0xb0, 0x7a), + kind_graphic: Color32::from_rgb(0x12, 0x8a, 0x74), + kind_movie_clip: Color32::from_rgb(0x2f, 0x62, 0xd8), + kind_button: Color32::from_rgb(0xb0, 0x6c, 0x08), + control_outline: false, + dark: false, + control_hairline: true, + cell_tint: Color32::from_black_alpha(9), + stage_edge: Color32::from_black_alpha(70), + window_shadow: 46, + popup_shadow: 40, radius_control: 3, radius_menu: 6, radius_window: 10, @@ -226,14 +317,19 @@ pub const HIGH_CONTRAST: Tokens = Tokens { /// Which palette the interface uses (Preferences › Appearance › Theme). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum Palette { + /// Dark (Graphite), the default look. (Saved under its old name, so older files still open.) #[default] Graphite, HighContrast, + /// Light (ADR 0077). + Light, } impl Palette { - pub const ALL: [(Palette, &'static str, &'static str); 2] = [ - (Palette::Graphite, tr_noop!("Graphite"), tr_noop!("The standard dark look: graphite panels, colour where it means something.")), + /// The palettes Preferences offers, in the order it lists them: name and a one-line note. + pub const ALL: [(Palette, &'static str, &'static str); 3] = [ + (Palette::Graphite, tr_noop!("Dark (Graphite)"), tr_noop!("The standard dark look: graphite panels, colour where it means something.")), + (Palette::Light, tr_noop!("Light"), tr_noop!("Light grey panels and dark text, for bright rooms and eyes that find dark interfaces hard.")), (Palette::HighContrast, tr_noop!("High contrast"), tr_noop!("White text on black, a yellow focus and selection colour, outlined controls.")), ]; @@ -241,16 +337,48 @@ impl Palette { match self { Palette::Graphite => &GRAPHITE, Palette::HighContrast => &HIGH_CONTRAST, + Palette::Light => &LIGHT, + } + } + + fn index(self) -> u8 { + match self { + Palette::Graphite => 0, + Palette::HighContrast => 1, + Palette::Light => 2, } } } /// The palette in use. Process-wide view state, like the interface scale: one window, one look. +#[cfg(not(test))] static ACTIVE: AtomicU8 = AtomicU8::new(0); +// Tests run side by side on threads of one process, each with its own app: each keeps its own +// palette, so switching themes in one never shows in another. +#[cfg(test)] +thread_local! { + static ACTIVE: AtomicU8 = const { AtomicU8::new(0) }; +} + +fn active() -> u8 { + #[cfg(not(test))] + return ACTIVE.load(Ordering::Relaxed); + #[cfg(test)] + return ACTIVE.with(|a| a.load(Ordering::Relaxed)); +} + +fn set_active(i: u8) { + #[cfg(not(test))] + ACTIVE.store(i, Ordering::Relaxed); + #[cfg(test)] + ACTIVE.with(|a| a.store(i, Ordering::Relaxed)); +} + pub fn palette() -> Palette { - match ACTIVE.load(Ordering::Relaxed) { + match active() { 1 => Palette::HighContrast, + 2 => Palette::Light, _ => Palette::Graphite, } } @@ -295,15 +423,9 @@ pub fn apply(ctx: &egui::Context) { /// Switches the palette and restyles every widget with it (Preferences › Theme), live. pub fn apply_palette(ctx: &egui::Context, palette: Palette) { - ACTIVE.store( - match palette { - Palette::Graphite => 0, - Palette::HighContrast => 1, - }, - Ordering::Relaxed, - ); + set_active(palette.index()); let t = *palette.tokens(); - let mut v = Visuals::dark(); + let mut v = if t.dark { Visuals::dark() } else { Visuals::light() }; v.panel_fill = t.panel; v.window_fill = t.panel_alt; v.extreme_bg_color = t.field; @@ -314,8 +436,8 @@ pub fn apply_palette(ctx: &egui::Context, palette: Palette) { v.selection.stroke = Stroke::new(2.0, t.accent); v.hyperlink_color = t.accent_text; v.window_stroke = Stroke::new(1.0, t.border); - v.window_shadow = depth(10, 28, 150); - v.popup_shadow = depth(4, 12, 130); + v.window_shadow = depth(10, 28, t.window_shadow); + v.popup_shadow = depth(4, 12, t.popup_shadow); v.window_corner_radius = CornerRadius::same(t.radius_window); v.menu_corner_radius = CornerRadius::same(t.radius_menu); for w in [&mut v.widgets.noninteractive, &mut v.widgets.inactive, &mut v.widgets.hovered, &mut v.widgets.active, &mut v.widgets.open] { @@ -327,10 +449,17 @@ pub fn apply_palette(ctx: &egui::Context, palette: Palette) { // Separators and group frames: the layout lines. v.widgets.noninteractive.bg_stroke = Stroke::new(1.0, t.border); v.widgets.noninteractive.fg_stroke = Stroke::new(1.0, t.text_dim); - // Buttons are flat fills at rest; no border on every button. + // Buttons are flat fills at rest; no border on every button (a hairline in the light look). + let rest = if t.control_outline { + Stroke::new(1.0, t.control_edge) + } else if t.control_hairline { + Stroke::new(1.0, t.border) + } else { + Stroke::NONE + }; v.widgets.inactive.weak_bg_fill = t.header; v.widgets.inactive.bg_fill = t.header; - v.widgets.inactive.bg_stroke = if t.control_outline { Stroke::new(1.0, t.control_edge) } else { Stroke::NONE }; + v.widgets.inactive.bg_stroke = rest; v.widgets.inactive.fg_stroke = Stroke::new(1.5, t.text); v.widgets.hovered.weak_bg_fill = t.hover; v.widgets.hovered.bg_fill = t.hover; @@ -343,8 +472,11 @@ pub fn apply_palette(ctx: &egui::Context, palette: Palette) { v.widgets.active.fg_stroke = Stroke::new(1.5, t.text); v.widgets.open.weak_bg_fill = t.hover; v.widgets.open.bg_fill = t.hover; - v.widgets.open.bg_stroke = if t.control_outline { Stroke::new(1.0, t.control_edge) } else { Stroke::NONE }; - // Same dark look whatever the OS theme is. + v.widgets.open.bg_stroke = rest; + // egui keeps a dark and a light style and picks one by the OS theme; both are ours, so the + // palette chosen here is the one drawn (Follow system is decided in `Prefs::palette`). Naming + // its theme keeps the window's title bar (Windows, macOS) dark or light with it. + ctx.set_theme(if t.dark { egui::Theme::Dark } else { egui::Theme::Light }); ctx.all_styles_mut(|s| { s.visuals = v.clone(); s.spacing.item_spacing = egui::vec2(8.0, 6.0); diff --git a/src/timeline.rs b/src/timeline.rs index 94b48506..18798a6c 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -747,7 +747,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { for f in first..first + visible_cols + 1 { let x = x_of(f); if (f + 1) % 5 == 0 && cell_w >= 6.0 { - cp.rect_filled(Rect::from_min_size(pos2(x, y), vec2(cell_w, rh)), 0.0, Color32::from_white_alpha(6)); + cp.rect_filled(Rect::from_min_size(pos2(x, y), vec2(cell_w, rh)), 0.0, T.cell_tint); } // Cell lines thin out with the ruler when zoomed out, so rows never turn to hatching. if (f + 1) % minor == 0 { @@ -851,7 +851,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { { let (f0, f1) = sel.frames(); let g = Rect::from_min_max(pos2(x_of(f0), y + 1.0), pos2(x_of(f1 + 1) - 1.0, y + rh - 1.0)).translate(vec2(by as f32 * cell_w, 0.0)); - cp.rect_stroke(g, SQUARE, Stroke::new(2.0, Color32::WHITE), StrokeKind::Inside); + cp.rect_stroke(g, SQUARE, Stroke::new(2.0, T.text), StrokeKind::Inside); } // Span length being dragged on this row: the new end line and its length readout. if let TlDrag::Span { layer: lid, start, end, to } = app.tl_drag @@ -862,7 +862,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let changed = Rect::from_min_max(pos2(a, y + 2.0), pos2(b - 1.0, y + rh - 2.0)); cp.rect_filled(changed, SQUARE, if to > end { T.selection.gamma_multiply(0.35) } else { Color32::from_black_alpha(120) }); let x = x_of(to); - cp.line_segment([pos2(x, y + 1.0), pos2(x, y + rh - 1.0)], Stroke::new(2.0, Color32::WHITE)); + cp.line_segment([pos2(x, y + 1.0), pos2(x, y + rh - 1.0)], Stroke::new(2.0, T.text)); let n = to - start; let secs = n as f32 / app.s.doc.stage.fps.max(1.0); let label = trn!("{n} frame · {secs} s", "{n} frames · {secs} s", n, secs = format!("{secs:.2}"));