mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-21 01:52:49 +01:00
feat(a11y): follow the system's contrast setting; Preferences › Theme › Follow system (M8)
This commit is contained in:
1 parent
cb3a084388
commit
880bf0ea3c
7 files changed
+238
-8
No files matched your search
Generated
+1
@@ -239,6 +239,7 @@ dependencies = [
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"web-time",
|
||||
"winreg",
|
||||
"winresource",
|
||||
]
|
||||
|
||||
|
||||
+6
-1
@@ -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.
|
||||
|
||||
+19
-3
@@ -622,10 +622,9 @@ mod tests {
|
||||
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 the keyboard goes
|
||||
// back to the stage.
|
||||
// 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);
|
||||
let stage = focused(&ctx);
|
||||
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);
|
||||
@@ -658,6 +657,23 @@ mod tests {
|
||||
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(|_, _| {});
|
||||
|
||||
+78
-2
@@ -448,6 +448,12 @@ 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<bool>,
|
||||
/// 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).
|
||||
@@ -456,6 +462,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");
|
||||
@@ -624,6 +633,9 @@ impl App {
|
||||
tl_heard: None,
|
||||
tl_refocus: false,
|
||||
menu_keys: Default::default(),
|
||||
system_contrast: None,
|
||||
contrast_probe: None,
|
||||
contrast_asked: None,
|
||||
start: None,
|
||||
drop: Default::default(),
|
||||
thumbs: Default::default(),
|
||||
@@ -718,7 +730,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();
|
||||
@@ -758,7 +770,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);
|
||||
@@ -784,6 +799,66 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
@@ -2498,6 +2573,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);
|
||||
}
|
||||
|
||||
+18
-1
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -604,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
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user