use crate::color::Color;
use crate::theme::{Contrast, Theme};
use crate::ui::Ui;
use std::cell::Cell;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Wishes {
pub dark: bool,
pub accent: Option<Color>,
pub contrast: Option<Contrast>,
pub still: bool,
pub text: f32,
}
impl Default for Wishes {
fn default() -> Self {
Wishes { dark: false, accent: None, contrast: None, still: false, text: 1.0 }
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct Wished {
pub(crate) wishes: Wishes,
theme: Cell<Option<Theme>>,
}
impl Ui {
pub fn set_wishes(&mut self, wishes: Wishes) -> bool {
if wishes == self.wished.wishes {
return false;
}
self.wished = Wished { wishes, theme: Cell::new(None) };
true
}
pub fn system_dark(&self) -> bool {
self.wished.wishes.dark
}
pub fn system_accent(&self) -> Option<Color> {
self.wished.wishes.accent
}
pub fn high_contrast(&self) -> bool {
self.wished.wishes.contrast.is_some()
}
pub fn reduced_motion(&self) -> bool {
self.wished.wishes.still
}
pub fn text_scale(&self) -> f32 {
self.wished.wishes.text
}
pub fn system_theme(&self) -> Theme {
let theme = self.wished.theme.get().unwrap_or_else(|| Theme::following(&self.wished.wishes));
self.wished.theme.set(Some(theme));
theme
}
}
#[cfg(windows)]
pub(crate) fn of_windows() -> Wishes {
#[cfg(test)]
if let Some(wishes) = tests::PRETENDED.get() {
return wishes;
}
let mut wishes = Wishes { dark: number("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", "AppsUseLightTheme") == Some(0), ..Wishes::default() };
wishes.text = number("Software\\Microsoft\\Accessibility", "TextScaleFactor").map_or(1.0, |percent| percent.clamp(100, 225) as f32 / 100.0);
let mut palette = [0u8; 32];
let read = registry("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Accent", "AccentPalette", 0x08, &mut palette) == Some(32);
wishes.accent = read.then(|| Color::rgb(u32::from_be_bytes([0, palette[12], palette[13], palette[14]])));
let (mut moves, mut contrast) = (1i32, [0u32; 4]);
unsafe {
wishes.still = sys::SystemParametersInfoW(SPI_GETCLIENTAREAANIMATION, 0, (&raw mut moves).cast(), 0) != 0 && moves == 0;
contrast[0] = 16;
let read = sys::SystemParametersInfoW(SPI_GETHIGHCONTRAST, 16, contrast.as_mut_ptr().cast(), 0) != 0;
wishes.contrast = (read && contrast[1] & HCF_HIGHCONTRASTON != 0).then(system_colors);
}
wishes
}
#[cfg(windows)]
const SPI_GETCLIENTAREAANIMATION: u32 = 0x1042;
#[cfg(windows)]
const SPI_GETHIGHCONTRAST: u32 = 0x0042;
#[cfg(windows)]
const HCF_HIGHCONTRASTON: u32 = 1;
#[cfg(windows)]
fn system_colors() -> Contrast {
let color = |index: i32| {
let bgr = unsafe { sys::GetSysColor(index) };
Color::rgb((bgr & 0xff) << 16 | (bgr & 0xff00) | (bgr >> 16 & 0xff))
};
Contrast { ground: color(5), text: color(8), link: color(26), off: color(17), picked: color(13), on_picked: color(14), button: color(15), button_text: color(18) }
}
#[cfg(windows)]
fn number(key: &str, name: &str) -> Option<u32> {
let mut value = [0u8; 4];
registry(key, name, 0x10, &mut value).filter(|bytes| *bytes == 4).map(|_| u32::from_le_bytes(value))
}
#[cfg(windows)]
fn registry(key: &str, name: &str, kinds: u32, value: &mut [u8]) -> Option<u32> {
let wide = |text: &str| text.encode_utf16().chain([0]).collect::<Vec<u16>>();
let (key, name, mut bytes) = (wide(key), wide(name), value.len() as u32);
let read = unsafe { sys::RegGetValueW(0x8000_0001u32 as i32 as isize, key.as_ptr(), name.as_ptr(), kinds, std::ptr::null_mut(), value.as_mut_ptr(), &mut bytes) };
(read == 0).then_some(bytes)
}
#[cfg(windows)]
#[allow(non_snake_case)]
mod sys {
#[link(name = "user32")]
unsafe extern "system" {
pub fn SystemParametersInfoW(action: u32, number: u32, value: *mut core::ffi::c_void, change: u32) -> i32;
pub fn GetSysColor(index: i32) -> u32;
}
#[link(name = "advapi32")]
unsafe extern "system" {
pub fn RegGetValueW(key: isize, under: *const u16, name: *const u16, kinds: u32, kind: *mut u32, value: *mut u8, bytes: *mut u32) -> i32;
}
}
#[cfg(all(unix, not(target_os = "macos")))]
pub(crate) fn of_x_settings(settings: &[u8]) -> Option<Wishes> {
let ends_first = *settings.first()? == 0;
let number = |at: usize, len: usize| {
let mut bytes = [0; 4];
bytes[..len].copy_from_slice(settings.get(at..at.checked_add(len)?)?);
Some(if ends_first { u32::from_le_bytes(bytes) } else { u32::from_be_bytes(bytes) >> (32 - 8 * len) } as usize)
};
let (mut at, mut wishes, mut theme) = (12, Wishes::default(), &b""[..]);
for _ in 0..number(8, 4)? {
let (kind, named) = (*settings.get(at)?, number(at + 2, 2)?);
let (name, value) = (settings.get(at + 4..at + 4 + named)?, (at + 4 + named).next_multiple_of(4) + 4);
let long = match kind {
0 => 4,
1 => number(value, 4)?.checked_next_multiple_of(4)?.checked_add(4)?,
_ => 8,
};
let held = settings.get(value..value.checked_add(long)?)?;
match (kind, name) {
(0, b"Gtk/ApplicationPreferDarkTheme") => wishes.dark |= number(value, 4)? == 1,
(0, b"Gtk/EnableAnimations") => wishes.still = number(value, 4)? == 0,
(1, b"Net/ThemeName") => theme = &held[4..][..number(value, 4)?],
_ => {}
}
at = value + long;
}
let named = |start: &[u8], end: &[u8]| theme.len() >= start.len().max(end.len()) && theme[..start.len()].eq_ignore_ascii_case(start) && theme[theme.len() - end.len()..].eq_ignore_ascii_case(end);
wishes.dark |= named(b"", b"-dark") || named(b"HighContrastInverse", b"");
wishes.contrast = named(b"HighContrast", b"").then_some(if wishes.dark { Contrast::DARK } else { Contrast::LIGHT });
Some(wishes)
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::color::Color;
std::thread_local! {
pub(crate) static PRETENDED: std::cell::Cell<Option<Wishes>> = const { std::cell::Cell::new(None) };
}
#[test]
fn an_interface_hears_what_the_person_asked_for_once() {
let mut ui = Ui::new(Box::new(crate::text::BuiltInFont), Box::new(crate::platform::LocalClipboard::default()));
assert!(!ui.system_dark() && ui.system_accent().is_none() && !ui.high_contrast() && !ui.reduced_motion() && ui.text_scale() == 1.0);
assert_eq!(ui.system_theme(), Theme::light());
let wishes = Wishes { dark: true, accent: Some(Color::rgb(0x0078d4)), contrast: None, still: true, text: 1.25 };
assert!(ui.set_wishes(wishes) && !ui.set_wishes(wishes));
assert!(ui.system_dark() && ui.system_accent() == Some(Color::rgb(0x0078d4)) && ui.reduced_motion() && ui.text_scale() == 1.25);
assert_eq!(ui.system_theme(), Theme::following(&wishes));
assert!(ui.set_wishes(Wishes { contrast: Some(Contrast::DARK), ..wishes }) && ui.high_contrast());
assert_eq!(ui.system_theme(), Theme::high_contrast(Contrast::DARK).text_scaled(1.25));
}
#[test]
fn nothing_moves_by_itself_for_a_person_who_asked_for_less_movement() {
let mut ui = Ui::new(Box::new(crate::text::BuiltInFont), Box::new(crate::platform::LocalClipboard::default()));
ui.resize(crate::geom::Size { w: 40.0, h: 40.0 }, 1.0);
let over = std::time::Duration::from_millis(120);
let glided = |ui: &mut Ui, target: f32| {
let mut value = f32::NAN;
ui.run(&mut |ui| value = ui.glide(7, target, over));
(value, ui.wake_in())
};
assert_eq!(glided(&mut ui, 0.0), (0.0, None));
assert_eq!(glided(&mut ui, 1.0), (0.0, Some(crate::ui::FRAME)));
ui.set_wishes(Wishes { still: true, ..Wishes::default() });
assert_eq!(glided(&mut ui, 1.0), (1.0, None));
assert_eq!(glided(&mut ui, 0.0), (0.0, None));
let spun = |ui: &mut Ui, at: u64| {
ui.set_time(std::time::Duration::from_millis(at));
ui.run(&mut |ui| _ = ui.spinner());
let drawn = crate::Surface::draw(ui, 64).pixels;
(drawn.iter().map(|pixel| *pixel != drawn[0]).collect::<Vec<bool>>(), drawn, ui.wake_in())
};
let (first, later) = (spun(&mut ui, 500), spun(&mut ui, 1500));
assert!(first.1 == later.1 && spun(&mut ui, 0).1 != first.1, "standing where it was, and fading");
assert_eq!((first.2, later.2), (Some(crate::ui::FRAME * 3), Some(crate::ui::FRAME * 3)));
ui.set_wishes(Wishes::default());
let (first, later) = (spun(&mut ui, 1000), spun(&mut ui, 1250));
assert!(first.0 != later.0 && first.2 == Some(crate::ui::FRAME), "turned a quarter of the way round");
}
#[cfg(windows)]
#[test]
fn what_windows_keeps_is_read() {
let wishes = of_windows();
assert_eq!(of_windows(), wishes);
assert!((1.0..=2.25).contains(&wishes.text), "{wishes:?}");
assert!(wishes.accent.is_some_and(|accent| accent.a() == 255), "{wishes:?}");
let pretend = Wishes { dark: !wishes.dark, still: true, text: 2.0, ..Wishes::default() };
PRETENDED.set(Some(pretend));
assert_eq!((of_windows(), std::thread::spawn(of_windows).join().unwrap()), (pretend, wishes));
PRETENDED.set(None);
assert_eq!(of_windows(), wishes);
}
#[cfg(all(unix, not(target_os = "macos")))]
pub(crate) enum Kept<'a> {
Number(u32),
Text(&'a str),
Colour,
}
#[cfg(all(unix, not(target_os = "macos")))]
pub(crate) fn settings_of(ends_first: bool, list: &[(&str, Kept)]) -> Vec<u8> {
let number = |value: u32, len: usize| if ends_first { value.to_le_bytes()[..len].to_vec() } else { value.to_be_bytes()[4 - len..].to_vec() };
let mut bytes = vec![!ends_first as u8, 0, 0, 0];
bytes.extend([number(7, 4), number(list.len() as u32, 4)].concat());
for (name, kept) in list {
let (kind, value) = match kept {
Kept::Number(value) => (0, number(*value, 4)),
Kept::Text(text) => (1, [&number(text.len() as u32, 4), text.as_bytes(), &[0u8; 3][..text.len().next_multiple_of(4) - text.len()]].concat()),
Kept::Colour => (2, vec![0xff; 8]),
};
bytes.extend([&[kind, 0][..], &number(name.len() as u32, 2), name.as_bytes()].concat());
bytes.resize(bytes.len().next_multiple_of(4), 0);
bytes.extend([number(1, 4), value].concat());
}
bytes
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn the_desktops_settings_say_what_the_person_asked_for() {
use Kept::{Colour, Number, Text};
let read = |list: &[(&str, Kept)]| [true, false].map(|ends_first| of_x_settings(&settings_of(ends_first, list)));
let dark = |list: &[(&str, Kept)]| read(list).map(|wishes| wishes.map(|wishes| wishes.dark));
assert_eq!(dark(&[("Net/ThemeName", Text("Adwaita-dark"))]), [Some(true); 2]);
let many = [("Xft/DPI", Number(98_304)), ("Gtk/ColorPalette", Colour), ("Net/IconThemeName", Text("Papirus")), ("Net/ThemeName", Text("Breeze-Dark")), ("Gtk/FontName", Text("Sans 10"))];
assert_eq!(dark(&many), [Some(true); 2]);
for light in ["Adwaita", "Arc-Darker", "Materia-dark-compact", "dark", ""] {
assert_eq!(dark(&[("Net/ThemeName", Text(light)), ("Net/IconThemeName", Text("Papirus-dark"))]), [Some(false); 2], "{light:?}");
}
assert_eq!(dark(&[("Net/ThemeName", Text("Adwaita")), ("Gtk/ApplicationPreferDarkTheme", Number(1))]), [Some(true); 2]);
assert_eq!(dark(&[("Gtk/ApplicationPreferDarkTheme", Number(0)), ("Net/ThemeName", Text("Adwaita"))]), [Some(false); 2]);
assert_eq!(dark(&[("Gtk/ApplicationPreferDarkTheme", Text("1")), ("Net/ThemeName", Number(1))]), [Some(false); 2]);
assert_eq!(read(&[]), [Some(Wishes::default()); 2]);
let contrast = |name: &'static str| read(&[("Net/ThemeName", Text(name))]).map(|wishes| wishes.map(|wishes| (wishes.dark, wishes.contrast)));
assert_eq!(contrast("HighContrast"), [Some((false, Some(Contrast::LIGHT))); 2]);
assert_eq!(contrast("HighContrastInverse"), [Some((true, Some(Contrast::DARK))); 2]);
assert_eq!(contrast("highcontrast"), [Some((false, Some(Contrast::LIGHT))); 2]);
assert_eq!(contrast("Adwaita-HighContrast-ish"), [Some((false, None)); 2]);
let still = |list: &[(&str, Kept)]| read(list).map(|wishes| wishes.map(|wishes| wishes.still));
assert_eq!([still(&[("Gtk/EnableAnimations", Number(0))]), still(&[("Gtk/EnableAnimations", Number(1))])], [[Some(true); 2], [Some(false); 2]]);
assert_eq!(still(&[("Gtk/EnableAnimations", Text("0"))]), [Some(false); 2]);
let whole = settings_of(true, &[("Gtk/EnableAnimations", Number(0)), ("Net/ThemeName", Text("HighContrast"))]);
(0..whole.len()).for_each(|len| assert_eq!(of_x_settings(&whole[..len]), None, "cut short after {len} bytes"));
let whole = settings_of(true, &many);
(0..whole.len()).for_each(|len| assert_eq!(of_x_settings(&whole[..len]), None, "cut short after {len} bytes"));
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
let mut chance = |below: usize| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % below as u64) as usize
};
for _ in 0..50_000 {
let mut scrambled = whole.clone();
for _ in 0..1 + chance(4) {
let at = chance(scrambled.len());
scrambled[at] = chance(256) as u8;
}
std::hint::black_box(of_x_settings(&scrambled));
}
}
}