Skip to main content

graphics/
appearance.rs

1//! Per-user appearance preferences: theme and screen brightness. Record
2//! layouts and preset IDs are stable on disk; version 1 records, which have no
3//! brightness, still load at full brightness, and a saved brightness outside
4//! the allowed range is clamped on load instead of rejecting the record.
5use crate as graphics;
6use crate::{BRIGHTNESS_FULL, Color, Error, lvgl};
7use file_system::{AccessFlags, CreateFlags, Flags, Permissions};
8use task::TaskIdentifier;
9use virtual_file_system::ResultExt as _;
10use virtual_file_system::{self, File, VirtualFileSystem};
11
12const RECORD_1_SIZE: usize = 11;
13const RECORD_SIZE: usize = 12;
14pub const PRESET_COUNT: u8 = 6;
15
16/// Lowest brightness a saved appearance can hold, about 10 %, so that a
17/// preference can never leave the screen dark at start-up or login.
18pub const MINIMUM_BRIGHTNESS: u8 = 26;
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub struct Appearance {
22    pub is_dark: bool,
23    /// Zero selects the zinc palette's mode-dependent color.
24    pub primary: u8,
25    pub secondary: u8,
26    /// Screen backlight level, from [`MINIMUM_BRIGHTNESS`] to
27    /// [`BRIGHTNESS_FULL`]. Ignored on screens without brightness control.
28    pub brightness: u8,
29}
30
31impl Default for Appearance {
32    fn default() -> Self {
33        Self {
34            is_dark: true,
35            primary: 0,
36            secondary: 0,
37            brightness: BRIGHTNESS_FULL,
38        }
39    }
40}
41
42impl Appearance {
43    pub fn colors(self) -> (Color, Color) {
44        // These palette accessors return immutable static data; no LVGL objects
45        // are accessed, and they can be read before graphics initialization.
46        let palette = unsafe {
47            if self.is_dark {
48                *lvgl::lv_theme_shadcn_palette_zinc_dark()
49            } else {
50                *lvgl::lv_theme_shadcn_palette_zinc_light()
51            }
52        };
53        let preset = |index, automatic| match index {
54            1 => Color::new(0x25, 0x63, 0xeb),
55            2 => Color::new(0x16, 0xa3, 0x4a),
56            3 => Color::new(0xea, 0x58, 0x0c),
57            4 => Color::new(0xe1, 0x1d, 0x48),
58            5 => Color::new(0x7c, 0x3a, 0xed),
59            _ => Color::from_lvgl_color(automatic),
60        };
61        (
62            preset(self.primary, palette.primary),
63            preset(self.secondary, palette.secondary),
64        )
65    }
66
67    /// Apply the theme and the screen brightness. Screens without brightness
68    /// control keep their level.
69    pub async fn apply(
70        self,
71        manager: &graphics::Manager,
72        guard: &mut graphics::GraphicsGuard<'_>,
73    ) -> graphics::Result<()> {
74        let (primary, secondary) = self.colors();
75        manager
76            .update_theme_locked(guard, primary, secondary, self.is_dark)
77            .await?;
78        self.apply_brightness(manager).await
79    }
80
81    /// Apply only the screen brightness, raised to [`MINIMUM_BRIGHTNESS`].
82    /// Screens without brightness control keep their level. The LVGL lock may
83    /// be held or not.
84    pub async fn apply_brightness(self, manager: &graphics::Manager) -> graphics::Result<()> {
85        match manager
86            .set_brightness(self.brightness.max(MINIMUM_BRIGHTNESS))
87            .await
88        {
89            Err(Error::Unsupported | Error::NotAvailable) => Ok(()),
90            result => result,
91        }
92    }
93
94    fn encode(self) -> [u8; RECORD_SIZE] {
95        let mut bytes = [0; RECORD_SIZE];
96        bytes[..4].copy_from_slice(b"XAP2");
97        bytes[4] = u8::from(self.is_dark);
98        bytes[5] = self.primary;
99        bytes[6] = self.secondary;
100        bytes[7] = self.brightness;
101        let checksum = checksum(&bytes[..8]);
102        bytes[8..].copy_from_slice(&checksum.to_le_bytes());
103        bytes
104    }
105
106    fn decode(bytes: &[u8]) -> Option<Self> {
107        // Version 1 records end before the brightness byte.
108        let (brightness, body) = match (bytes.len(), bytes.get(..4)?) {
109            (RECORD_1_SIZE, b"XAP1") => (BRIGHTNESS_FULL, 7),
110            (RECORD_SIZE, b"XAP2") => (bytes[7], 8),
111            _ => return None,
112        };
113        if bytes[4] > 1
114            || bytes[5] >= PRESET_COUNT
115            || bytes[6] >= PRESET_COUNT
116            || checksum(&bytes[..body]) != u32::from_le_bytes(bytes[body..].try_into().ok()?)
117        {
118            return None;
119        }
120        Some(Self {
121            is_dark: bytes[4] != 0,
122            primary: bytes[5],
123            secondary: bytes[6],
124            // Clamp instead of rejecting: the checksum already guards against
125            // corruption, and a level saved below the current minimum (raised
126            // after the record was written) must not discard the theme.
127            brightness: brightness.clamp(MINIMUM_BRIGHTNESS, BRIGHTNESS_FULL),
128        })
129    }
130
131    pub async fn load(
132        vfs: &VirtualFileSystem,
133        task: TaskIdentifier,
134    ) -> virtual_file_system::Result<Self> {
135        let user = vfs.task_manager().get_user(task).await.map_io_error()?;
136        let path = vfs
137            .get_user_home(user)
138            .await?
139            .append(".appearance")
140            .ok_or(virtual_file_system::IoErrorKind::InvalidPath)?;
141        let mut file = match File::open(vfs, task, &path, AccessFlags::Read.into()).await {
142            Ok(file) => file,
143            Err(file_system::IoErrorKind::NotFound) => {
144                return Ok(Self::default());
145            }
146            Err(error) => return Err(error),
147        };
148        // One extra byte rejects oversized files without allocating for their contents.
149        let mut bytes = [0; RECORD_SIZE + 1];
150        let mut length = 0;
151        while length < bytes.len() {
152            let read = file.read(&mut bytes[length..]).await?;
153            if read == 0 {
154                break;
155            }
156            length += read;
157        }
158        file.close(vfs).await?;
159        Self::decode(&bytes[..length]).ok_or(virtual_file_system::IoErrorKind::InvalidArgument)
160    }
161
162    /// Persist this user's choices. Callers must serialize saves for that user;
163    /// Settings does so with the LVGL lock held during event dispatch.
164    pub async fn save(
165        self,
166        vfs: &VirtualFileSystem,
167        task: TaskIdentifier,
168    ) -> virtual_file_system::Result<()> {
169        let user = vfs.task_manager().get_user(task).await.map_io_error()?;
170        let home = vfs.ensure_user_home(task, user).await?;
171        let path = home
172            .clone()
173            .append(".appearance")
174            .ok_or(virtual_file_system::IoErrorKind::InvalidPath)?;
175        let temporary = home
176            .append(".appearance.tmp")
177            .ok_or(virtual_file_system::IoErrorKind::InvalidPath)?;
178        // The graphics lock serializes Settings writers. Remove any temporary
179        // file left by an interrupted save.
180        match vfs.remove(task, &temporary).await {
181            Ok(()) | Err(file_system::IoErrorKind::NotFound) => {}
182            Err(error) => return Err(error),
183        }
184        let mut file = File::open(
185            vfs,
186            task,
187            &temporary,
188            Flags::new(AccessFlags::Write, Some(CreateFlags::CREATE_TRUNCATE), None),
189        )
190        .await?;
191        let bytes = self.encode();
192        if Self::decode(&bytes).is_none() {
193            return Err(virtual_file_system::IoErrorKind::InvalidArgument);
194        }
195        file.set_permissions(Permissions::USER_READ_WRITE).await?;
196        let mut written = 0;
197        while written < bytes.len() {
198            let count = file.write(&bytes[written..]).await?;
199            if count == 0 {
200                return Err(virtual_file_system::IoErrorKind::WriteZero);
201            }
202            written += count;
203        }
204        file.flush().await?;
205        file.close(vfs).await?;
206        vfs.rename(task, &temporary, &path).await
207    }
208}
209
210fn checksum(bytes: &[u8]) -> u32 {
211    bytes.iter().fold(0x811c9dc5u32, |hash, byte| {
212        (hash ^ u32::from(*byte)).wrapping_mul(0x01000193)
213    })
214}
215
216/// Restore the current user's appearance at login, before opening application
217/// windows. This acquires the LVGL lock; callers must not already hold it.
218/// Invalid preferences leave the existing theme intact.
219pub async fn restore_appearance(
220    manager: &graphics::Manager,
221    vfs: &VirtualFileSystem,
222    task: TaskIdentifier,
223) {
224    if let Ok(user) = vfs.task_manager().get_user(task).await
225        && let Err(error) = vfs.ensure_user_home(task, user).await
226    {
227        log::warning!("Could not prepare user home: {}", error);
228    }
229    match Appearance::load(vfs, task).await {
230        Ok(appearance) => {
231            let mut guard = manager.lock().await;
232            if let Err(error) = appearance.apply(manager, &mut guard).await {
233                log::warning!("Could not restore appearance: {}", error);
234            }
235        }
236        Err(error) => log::warning!("Could not read appearance preferences: {}", error),
237    }
238}
239
240#[cfg(all(test, target_os = "linux"))]
241mod tests {
242    use super::*;
243    #[test]
244    fn records_round_trip_and_reject_damaged_or_unknown_choices() {
245        for is_dark in [false, true] {
246            for primary in 0..PRESET_COUNT {
247                for secondary in 0..PRESET_COUNT {
248                    for brightness in [MINIMUM_BRIGHTNESS, 128, BRIGHTNESS_FULL] {
249                        let appearance = Appearance {
250                            is_dark,
251                            primary,
252                            secondary,
253                            brightness,
254                        };
255                        assert_eq!(Appearance::decode(&appearance.encode()), Some(appearance));
256                    }
257                }
258            }
259        }
260        let bytes = Appearance::default().encode();
261        for index in 0..bytes.len() {
262            let mut damaged = bytes;
263            damaged[index] ^= 1;
264            assert_eq!(Appearance::decode(&damaged), None);
265        }
266        for length in 0..bytes.len() {
267            assert_eq!(Appearance::decode(&bytes[..length]), None);
268        }
269        assert_eq!(Appearance::decode(&[0; RECORD_SIZE + 1]), None);
270        for invalid in [
271            Appearance {
272                primary: PRESET_COUNT,
273                ..Appearance::default()
274            },
275            Appearance {
276                secondary: PRESET_COUNT,
277                ..Appearance::default()
278            },
279        ] {
280            assert_eq!(Appearance::decode(&invalid.encode()), None);
281        }
282    }
283
284    #[test]
285    fn brightness_below_the_minimum_is_clamped_and_the_theme_kept() {
286        // A record saved before the minimum was raised keeps its theme and
287        // loads with the brightness clamped to the allowed range.
288        for brightness in [0, 1, MINIMUM_BRIGHTNESS - 1] {
289            let saved = Appearance {
290                is_dark: false,
291                primary: 3,
292                secondary: 5,
293                brightness,
294            };
295            assert_eq!(
296                Appearance::decode(&saved.encode()),
297                Some(Appearance {
298                    brightness: MINIMUM_BRIGHTNESS,
299                    ..saved
300                })
301            );
302        }
303    }
304
305    #[test]
306    fn version_1_records_load_at_full_brightness() {
307        let mut bytes = [0; RECORD_1_SIZE];
308        bytes[..4].copy_from_slice(b"XAP1");
309        bytes[4..7].copy_from_slice(&[0, 3, 5]);
310        let checksum = checksum(&bytes[..7]);
311        bytes[7..].copy_from_slice(&checksum.to_le_bytes());
312        assert_eq!(
313            Appearance::decode(&bytes),
314            Some(Appearance {
315                is_dark: false,
316                primary: 3,
317                secondary: 5,
318                brightness: BRIGHTNESS_FULL,
319            })
320        );
321        // A version 1 tag on a version 2 length, and the reverse, are damaged.
322        let mut current = Appearance::default().encode();
323        current[..4].copy_from_slice(b"XAP1");
324        assert_eq!(Appearance::decode(&current), None);
325        bytes[..4].copy_from_slice(b"XAP2");
326        assert_eq!(Appearance::decode(&bytes), None);
327    }
328
329    #[test]
330    fn automatic_colors_follow_zinc_mode_and_presets_survive_mode_changes() {
331        let mut appearance = Appearance::default();
332        assert!(appearance.is_dark);
333        assert_eq!(
334            appearance.colors(),
335            (Color::new(228, 228, 231), Color::new(39, 39, 42))
336        );
337        appearance.is_dark = false;
338        assert_eq!(
339            appearance.colors(),
340            (Color::new(24, 24, 27), Color::new(244, 244, 245))
341        );
342        appearance.primary = 1;
343        appearance.secondary = 2;
344        let colors = appearance.colors();
345        assert_ne!(colors.0, colors.1);
346        appearance.is_dark = true;
347        assert_eq!(appearance.colors(), colors);
348    }
349}