BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / appearance.rs

appearance.rs

appearance.rs 11.9 KiB Download Raw
1use store::Store;
2
3use crate::theme::{self, ColorScheme, Shade};
4
5const META_KEY: &str = "appearance.settings";
6const COLOR_SCHEME_KEY: &str = "color_scheme";
7const APP_ICON_KEY: &str = "app_icon";
8const THEME_KEY: &str = "theme";
9const ZOOM_KEY: &str = "zoom";
10pub const ZOOM_STEPS: [f32; 14] = [
11 0.5, 0.67, 0.75, 0.8, 0.9, 1., 1.1, 1.25, 1.5, 1.75, 2., 2.5, 3., 4.,
12];
13pub const DEFAULT_ZOOM: f32 = 1.;
14/// Look of a fresh install: the KVT scheme in its light shade (house style: logo on white).
15/// `ThemeChoice::default()` stays dark: it is what settings saved without a theme key meant.
16const DEFAULT_THEME: ThemeChoice = ThemeChoice::Light;
17/// Scheme of settings saved without a `color_scheme` key (before the KVT scheme existed).
18const LEGACY_COLOR_SCHEME: &str = "rusty-teams";
19const RUSTY_TEAMS_ICON_PNG: &[u8] = include_bytes!("../../app/assets/icon/teams-fast-256.png");
20const MICROSOFT_TEAMS_ICON_PNG: &[u8] =
21 include_bytes!("../../app/assets/icon/microsoft-teams-256.png");
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum AppIcon {
25 #[default]
26 RustyTeams,
27 MicrosoftTeams,
28}
29
30impl AppIcon {
31 pub const ALL: [AppIcon; 2] = [AppIcon::RustyTeams, AppIcon::MicrosoftTeams];
32
33 pub fn key(self) -> &'static str {
34 match self {
35 AppIcon::RustyTeams => "rusty-teams",
36 AppIcon::MicrosoftTeams => "microsoft-teams",
37 }
38 }
39
40 pub fn from_key(key: &str) -> Option<AppIcon> {
41 AppIcon::ALL.into_iter().find(|icon| icon.key() == key)
42 }
43
44 pub fn label(self) -> &'static str {
45 match self {
46 AppIcon::RustyTeams => "Rusty Teams",
47 AppIcon::MicrosoftTeams => "Microsoft Teams",
48 }
49 }
50
51 pub fn png(self) -> &'static [u8] {
52 match self {
53 AppIcon::RustyTeams => RUSTY_TEAMS_ICON_PNG,
54 AppIcon::MicrosoftTeams => MICROSOFT_TEAMS_ICON_PNG,
55 }
56 }
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub enum ThemeChoice {
61 FollowOperatingSystem,
62 Light,
63 #[default]
64 Dark,
65 HighContrast,
66}
67
68impl ThemeChoice {
69 pub const ALL: [ThemeChoice; 4] = [
70 ThemeChoice::FollowOperatingSystem,
71 ThemeChoice::Light,
72 ThemeChoice::Dark,
73 ThemeChoice::HighContrast,
74 ];
75
76 pub fn key(self) -> &'static str {
77 match self {
78 ThemeChoice::FollowOperatingSystem => "followOsTheme",
79 ThemeChoice::Light => "light",
80 ThemeChoice::Dark => "dark",
81 ThemeChoice::HighContrast => "contrast",
82 }
83 }
84
85 pub fn from_key(key: &str) -> Option<ThemeChoice> {
86 ThemeChoice::ALL
87 .into_iter()
88 .find(|choice| choice.key() == key)
89 }
90
91 pub fn label(self) -> &'static str {
92 match self {
93 ThemeChoice::FollowOperatingSystem => "Follow operating system theme",
94 ThemeChoice::Light => "Light",
95 ThemeChoice::Dark => "Dark",
96 ThemeChoice::HighContrast => "High contrast",
97 }
98 }
99
100 pub fn shade(self, system: SystemTheme) -> Shade {
101 match self {
102 ThemeChoice::Light => Shade::Light,
103 ThemeChoice::Dark => Shade::Dark,
104 ThemeChoice::HighContrast => Shade::HighContrast,
105 ThemeChoice::FollowOperatingSystem if system.high_contrast => Shade::HighContrast,
106 ThemeChoice::FollowOperatingSystem if system.dark => Shade::Dark,
107 ThemeChoice::FollowOperatingSystem => Shade::Light,
108 }
109 }
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
113pub struct SystemTheme {
114 pub dark: bool,
115 pub high_contrast: bool,
116}
117
118#[derive(Debug, Clone, Copy, PartialEq)]
119pub struct AppearanceSettings {
120 pub color_scheme: &'static ColorScheme,
121 pub app_icon: AppIcon,
122 pub theme: ThemeChoice,
123 pub zoom: f32,
124}
125
126impl Default for AppearanceSettings {
127 fn default() -> Self {
128 AppearanceSettings {
129 color_scheme: theme::default_scheme(),
130 app_icon: AppIcon::default(),
131 theme: DEFAULT_THEME,
132 zoom: DEFAULT_ZOOM,
133 }
134 }
135}
136
137pub fn nearest_zoom_step(zoom: f32) -> f32 {
138 ZOOM_STEPS
139 .into_iter()
140 .min_by(|first, second| (first - zoom).abs().total_cmp(&(second - zoom).abs()))
141 .unwrap_or(DEFAULT_ZOOM)
142}
143
144pub fn zoom_in(zoom: f32) -> f32 {
145 ZOOM_STEPS
146 .into_iter()
147 .find(|step| *step > zoom + f32::EPSILON)
148 .unwrap_or(ZOOM_STEPS[ZOOM_STEPS.len() - 1])
149}
150
151pub fn zoom_out(zoom: f32) -> f32 {
152 ZOOM_STEPS
153 .into_iter()
154 .rev()
155 .find(|step| *step < zoom - f32::EPSILON)
156 .unwrap_or(ZOOM_STEPS[0])
157}
158
159pub fn zoom_percent(zoom: f32) -> u32 {
160 (zoom * 100. - 0.001).ceil().max(0.) as u32
161}
162
163#[cfg(windows)]
164pub fn system_high_contrast() -> bool {
165 use windows::Win32::UI::Accessibility::{HCF_HIGHCONTRASTON, HIGHCONTRASTW};
166 use windows::Win32::UI::WindowsAndMessaging::{
167 SPI_GETHIGHCONTRAST, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,
168 };
169 let mut info = HIGHCONTRASTW {
170 cbSize: std::mem::size_of::<HIGHCONTRASTW>() as u32,
171 ..Default::default()
172 };
173 let read = unsafe {
174 SystemParametersInfoW(
175 SPI_GETHIGHCONTRAST,
176 info.cbSize,
177 Some(std::ptr::from_mut(&mut info).cast()),
178 SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
179 )
180 };
181 read.is_ok() && info.dwFlags.0 & HCF_HIGHCONTRASTON.0 != 0
182}
183
184#[cfg(not(windows))]
185pub fn system_high_contrast() -> bool {
186 false
187}
188
189pub fn load(store: &Store) -> AppearanceSettings {
190 store
191 .meta(META_KEY)
192 .ok()
193 .flatten()
194 .map(|text| parse(&text))
195 .unwrap_or_default()
196}
197
198pub fn save(store: &Store, settings: &AppearanceSettings) {
199 let _ = store.set_meta(META_KEY, &serialize(settings));
200}
201
202fn serialize(settings: &AppearanceSettings) -> String {
203 format!(
204 "{COLOR_SCHEME_KEY}={}\n{APP_ICON_KEY}={}\n{THEME_KEY}={}\n{ZOOM_KEY}={}",
205 settings.color_scheme.id,
206 settings.app_icon.key(),
207 settings.theme.key(),
208 settings.zoom
209 )
210}
211
212fn parse(text: &str) -> AppearanceSettings {
213 let mut settings = AppearanceSettings::default();
214 let has_key = |key: &str| {
215 text.lines()
216 .any(|line| line.split_once('=').is_some_and(|(name, _)| name == key))
217 };
218 // Settings saved before the KVT default existed may lack a key. That user never picked
219 // one and keeps the look the app had then, instead of switching to the new default.
220 if !has_key(COLOR_SCHEME_KEY) && !text.trim().is_empty() {
221 if let Some(scheme) = theme::scheme_by_id(LEGACY_COLOR_SCHEME) {
222 settings.color_scheme = scheme;
223 }
224 }
225 if !has_key(THEME_KEY) && !text.trim().is_empty() {
226 settings.theme = ThemeChoice::default();
227 }
228 for line in text.lines() {
229 match line.split_once('=') {
230 Some((COLOR_SCHEME_KEY, value)) => {
231 if let Some(scheme) = theme::scheme_by_id(value) {
232 settings.color_scheme = scheme;
233 }
234 }
235 Some((APP_ICON_KEY, value)) => {
236 if let Some(icon) = AppIcon::from_key(value) {
237 settings.app_icon = icon;
238 }
239 }
240 Some((THEME_KEY, value)) => {
241 if let Some(choice) = ThemeChoice::from_key(value) {
242 settings.theme = choice;
243 }
244 }
245 Some((ZOOM_KEY, value)) => {
246 if let Ok(zoom) = value.parse::<f32>() {
247 settings.zoom = nearest_zoom_step(zoom);
248 }
249 }
250 _ => {}
251 }
252 }
253 settings
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259
260 #[test]
261 fn defaults_are_the_koninklijke_van_twist_look() {
262 let settings = AppearanceSettings::default();
263 assert_eq!(settings.color_scheme.id, "koninklijke-van-twist");
264 assert_eq!(settings.app_icon, AppIcon::RustyTeams);
265 assert_eq!(settings.theme, ThemeChoice::Light);
266 assert_eq!(settings.zoom, 1.);
267 }
268
269 #[test]
270 fn round_trips_every_field() {
271 let settings = AppearanceSettings {
272 color_scheme: theme::scheme_by_id("teams").unwrap(),
273 app_icon: AppIcon::MicrosoftTeams,
274 theme: ThemeChoice::FollowOperatingSystem,
275 zoom: 1.25,
276 };
277 assert_eq!(parse(&serialize(&settings)), settings);
278 }
279
280 #[test]
281 fn unknown_values_fall_back_to_defaults() {
282 assert_eq!(parse(""), AppearanceSettings::default());
283 assert_eq!(
284 parse("color_scheme=solarized\napp_icon=clippy\ntheme=sepia\nzoom=big\njunk"),
285 AppearanceSettings::default()
286 );
287 }
288
289 #[test]
290 fn persists_in_store() {
291 let store = Store::open_in_memory().unwrap();
292 assert_eq!(load(&store), AppearanceSettings::default());
293 let changed = AppearanceSettings {
294 color_scheme: theme::scheme_by_id("teams").unwrap(),
295 app_icon: AppIcon::MicrosoftTeams,
296 theme: ThemeChoice::Light,
297 zoom: 0.9,
298 };
299 save(&store, &changed);
300 assert_eq!(load(&store), changed);
301 }
302
303 #[test]
304 fn older_settings_without_theme_and_zoom_keep_the_dark_default() {
305 let settings = parse("color_scheme=teams\napp_icon=rusty-teams");
306 assert_eq!(settings.theme, ThemeChoice::Dark);
307 assert_eq!(settings.zoom, DEFAULT_ZOOM);
308 assert_eq!(parse("zoom=1.3").zoom, 1.25);
309 }
310
311 #[test]
312 fn an_explicit_choice_survives_the_new_default() {
313 for scheme in theme::SCHEMES {
314 for choice in ThemeChoice::ALL {
315 let settings = AppearanceSettings {
316 color_scheme: scheme,
317 theme: choice,
318 ..AppearanceSettings::default()
319 };
320 assert_eq!(parse(&serialize(&settings)), settings);
321 }
322 }
323 // The look the app had before the KVT scheme, saved explicitly, stays as it is.
324 let before = parse("color_scheme=rusty-teams\napp_icon=rusty-teams\ntheme=dark\nzoom=1");
325 assert_eq!(before.color_scheme.id, "rusty-teams");
326 assert_eq!(before.theme, ThemeChoice::Dark);
327 }
328
329 #[test]
330 fn settings_saved_without_a_scheme_or_theme_keep_the_old_look() {
331 let settings = parse("zoom=1.25");
332 assert_eq!(settings.color_scheme.id, "rusty-teams");
333 assert_eq!(settings.theme, ThemeChoice::Dark);
334 assert_eq!(settings.zoom, 1.25);
335 assert_eq!(parse(" \n"), AppearanceSettings::default());
336 }
337
338 #[test]
339 fn follow_os_takes_dark_light_and_forced_contrast_from_the_system() {
340 let follow = ThemeChoice::FollowOperatingSystem;
341 let dark = SystemTheme {
342 dark: true,
343 high_contrast: false,
344 };
345 assert_eq!(follow.shade(dark), Shade::Dark);
346 assert_eq!(follow.shade(SystemTheme::default()), Shade::Light);
347 let forced = SystemTheme {
348 dark: false,
349 high_contrast: true,
350 };
351 assert_eq!(follow.shade(forced), Shade::HighContrast);
352 assert_eq!(ThemeChoice::Light.shade(dark), Shade::Light);
353 assert_eq!(ThemeChoice::HighContrast.shade(dark), Shade::HighContrast);
354 }
355
356 #[test]
357 fn theme_keys_are_the_teams_option_keys() {
358 let keys: Vec<_> = ThemeChoice::ALL.iter().map(|choice| choice.key()).collect();
359 assert_eq!(keys, ["followOsTheme", "light", "dark", "contrast"]);
360 }
361
362 #[test]
363 fn zoom_walks_the_steps_and_stops_at_both_ends() {
364 assert_eq!(zoom_in(1.), 1.1);
365 assert_eq!(zoom_out(1.), 0.9);
366 assert_eq!(zoom_in(4.), 4.);
367 assert_eq!(zoom_out(0.5), 0.5);
368 assert_eq!(zoom_out(zoom_in(1.25)), 1.25);
369 assert_eq!(zoom_percent(0.67), 67);
370 assert_eq!(zoom_percent(1.1), 110);
371 assert_eq!(zoom_percent(1.), 100);
372 }
373
374 #[test]
375 fn both_icons_are_png() {
376 for icon in AppIcon::ALL {
377 assert!(icon.png().starts_with(b"\x89PNG"), "{}", icon.key());
378 }
379 }
380}