Skip to main content

graphics/
theme.rs

1//! Xila's integration of the shared `lvgl_theme_shadcn` theme.
2//!
3//! The C theme owns shared styles and follows the display's lifetime. Call theme
4//! helpers while holding the graphics manager's LVGL lock.
5
6use crate::{Color, Display, Error, Result, fonts, lvgl};
7
8mod adjustments;
9
10pub use adjustments::{RenderingMode, get_rendering_mode, set_display_rendering_mode};
11
12pub(crate) fn initialize(display: &Display) -> Result<()> {
13    unsafe { initialize_display(display.get_lvgl_display()) }
14}
15
16unsafe fn initialize_display(display: *mut lvgl::lv_display_t) -> Result<()> {
17    let fonts = lvgl::lv_theme_shadcn_fonts_t {
18        small: fonts::get_font_small(),
19        normal: fonts::get_font_medium(),
20        large: fonts::get_font_large(),
21        mono: fonts::get_font_monospace_medium(),
22        // Left unset: heading fonts fall back to `large`, and a missing medium font
23        // to `normal`, so Xila keeps its single Montserrat weight and today's look.
24        h1: core::ptr::null(),
25        h2: core::ptr::null(),
26        h3: core::ptr::null(),
27        medium: core::ptr::null(),
28    };
29    // The theme copies the palette/fonts and releases its state when the display
30    // is deleted.
31    let theme = unsafe {
32        lvgl::lv_theme_shadcn_init(
33            display,
34            lvgl::lv_theme_shadcn_palette_zinc_dark(),
35            &fonts,
36            lvgl::lv_theme_shadcn_flags_t_LV_THEME_SHADCN_FLAG_NONE,
37        )
38    };
39    if theme.is_null() {
40        return Err(Error::OutOfMemory);
41    }
42    unsafe { adjustments::install(display, theme) }
43}
44
45pub(crate) fn set_rendering_mode(display: &Display, mode: RenderingMode) -> Result<()> {
46    unsafe { set_display_rendering_mode(display.get_lvgl_display(), mode) }
47}
48
49pub(crate) fn update(
50    display: &Display,
51    primary_color: Color,
52    secondary_color: Color,
53    is_dark: bool,
54) {
55    unsafe {
56        update_display(
57            display.get_lvgl_display(),
58            primary_color,
59            secondary_color,
60            is_dark,
61        )
62    }
63}
64
65unsafe fn update_display(
66    display: *mut lvgl::lv_display_t,
67    primary_color: Color,
68    secondary_color: Color,
69    is_dark: bool,
70) {
71    unsafe {
72        let mut palette = if is_dark {
73            *lvgl::lv_theme_shadcn_palette_zinc_dark()
74        } else {
75            *lvgl::lv_theme_shadcn_palette_zinc_light()
76        };
77        palette.primary = primary_color.into_lvgl_color();
78        palette.primary_fg = contrasting_foreground(primary_color).into_lvgl_color();
79        palette.ring = palette.primary;
80        palette.secondary = secondary_color.into_lvgl_color();
81        palette.secondary_fg = contrasting_foreground(secondary_color).into_lvgl_color();
82        lvgl::lv_theme_shadcn_set_palette(display, &palette);
83    }
84}
85
86fn contrasting_foreground(color: Color) -> Color {
87    let brightness = 299 * color.get_red() as u32
88        + 587 * color.get_green() as u32
89        + 114 * color.get_blue() as u32;
90    if brightness >= 128_000 {
91        Color::BLACK
92    } else {
93        Color::WHITE
94    }
95}
96
97/// A semantic container surface that follows palette changes.
98#[derive(Clone, Copy)]
99pub enum Surface {
100    Background,
101    Card,
102    Popover,
103    Muted,
104}
105
106/// Apply a shared container surface instead of a local background color.
107///
108/// # Safety
109/// `object` must be live and the caller must hold the LVGL lock.
110pub unsafe fn set_surface(object: *mut lvgl::lv_obj_t, surface: Surface) {
111    let surface = match surface {
112        Surface::Background => lvgl::lv_theme_shadcn_surface_t_LV_THEME_SHADCN_SURFACE_BACKGROUND,
113        Surface::Card => lvgl::lv_theme_shadcn_surface_t_LV_THEME_SHADCN_SURFACE_CARD,
114        Surface::Popover => lvgl::lv_theme_shadcn_surface_t_LV_THEME_SHADCN_SURFACE_POPOVER,
115        Surface::Muted => lvgl::lv_theme_shadcn_surface_t_LV_THEME_SHADCN_SURFACE_MUTED,
116    };
117    unsafe { lvgl::lv_theme_shadcn_set_surface(object, surface) };
118}
119
120/// A palette role, for drawings that LVGL styles cannot color through the theme.
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
122#[repr(usize)]
123pub enum PaletteColor {
124    Foreground,
125    MutedForeground,
126    Primary,
127    Border,
128    Input,
129}
130
131impl PaletteColor {
132    const ALL: [Self; 5] = [
133        Self::Foreground,
134        Self::MutedForeground,
135        Self::Primary,
136        Self::Border,
137        Self::Input,
138    ];
139
140    /// Inverse of `color as usize`, used to carry a role through LVGL user data.
141    pub fn from_index(index: usize) -> Self {
142        Self::ALL.get(index).copied().unwrap_or(Self::Foreground)
143    }
144}
145
146/// Current palette color of the display showing `object`, or `None` when the
147/// theme is not active there.
148///
149/// # Safety
150/// `object` must be live and the caller must hold the LVGL lock.
151pub unsafe fn get_palette_color(object: *mut lvgl::lv_obj_t, color: PaletteColor) -> Option<Color> {
152    unsafe {
153        let palette = lvgl::lv_theme_shadcn_get_palette(lvgl::lv_obj_get_display(object));
154        let palette = palette.as_ref()?;
155        let value = match color {
156            PaletteColor::Foreground => palette.foreground,
157            PaletteColor::MutedForeground => palette.muted_fg,
158            PaletteColor::Primary => palette.primary,
159            PaletteColor::Border => palette.border,
160            PaletteColor::Input => palette.input,
161        };
162        Some(Color::from_lvgl_color(value))
163    }
164}
165
166#[cfg(all(test, target_os = "linux"))]
167mod tests {
168    use super::*;
169
170    testing_support::instantiate_global_allocator!();
171
172    #[test]
173    fn palette_updates_preserve_widget_styles_and_logo_geometry() {
174        unsafe {
175            lvgl::lv_init();
176            let display = lvgl::lv_display_create(320, 240);
177            initialize_display(display).unwrap();
178            let screen = lvgl::lv_display_get_screen_active(display);
179            let logos = [1, 2, 4].map(|factor| {
180                (
181                    crate::Logo::new(screen, factor, Color::WHITE).unwrap(),
182                    factor,
183                )
184            });
185            for (logo, factor) in &logos {
186                assert_logo_geometry(logo, *factor);
187            }
188            // The desktop watermark follows the palette instead of a fixed color.
189            let themed = &logos[2].0;
190            themed.follow_palette_color(PaletteColor::Input);
191            let logo_color = |logo: &crate::Logo| {
192                lvgl::lv_obj_get_style_text_color(logo.get_inner_object(), lvgl::LV_PART_MAIN)
193            };
194            assert!(lvgl::lv_color_eq(
195                logo_color(themed),
196                (*lvgl::lv_theme_shadcn_get_palette(display)).input
197            ));
198            let button = lvgl::lv_button_create(screen);
199            let surface = lvgl::lv_obj_create(screen);
200            set_surface(surface, Surface::Muted);
201            let dark = *lvgl::lv_theme_shadcn_get_palette(display);
202            assert!(dark.dark);
203            assert!(lvgl::lv_color_eq(
204                lvgl::lv_obj_get_style_bg_color(button, 0),
205                dark.primary
206            ));
207            assert!(lvgl::lv_color_eq(
208                lvgl::lv_obj_get_style_bg_color(surface, 0),
209                dark.muted
210            ));
211
212            let primary = Color::new(0x25, 0x63, 0xeb);
213            let secondary = Color::new(0xf4, 0xf4, 0xf5);
214            update_display(display, primary, secondary, false);
215            let light = *lvgl::lv_theme_shadcn_get_palette(display);
216            assert!(!light.dark);
217            assert!(lvgl::lv_color_eq(light.primary, primary.into_lvgl_color()));
218            assert!(lvgl::lv_color_eq(
219                light.secondary,
220                secondary.into_lvgl_color()
221            ));
222            assert!(lvgl::lv_color_eq(
223                light.primary_fg,
224                Color::WHITE.into_lvgl_color()
225            ));
226            assert!(lvgl::lv_color_eq(
227                light.secondary_fg,
228                Color::BLACK.into_lvgl_color()
229            ));
230            assert!(lvgl::lv_color_eq(
231                lvgl::lv_obj_get_style_bg_color(button, 0),
232                light.primary
233            ));
234            assert!(lvgl::lv_color_eq(
235                lvgl::lv_obj_get_style_bg_color(surface, 0),
236                light.muted
237            ));
238
239            assert!(lvgl::lv_color_eq(logo_color(&logos[2].0), light.input));
240            assert!(!lvgl::lv_color_eq(logo_color(&logos[2].0), dark.input));
241            // Fixed-color logos keep their color.
242            assert!(lvgl::lv_color_eq(
243                logo_color(&logos[0].0),
244                Color::WHITE.into_lvgl_color()
245            ));
246            themed.follow_palette_color(PaletteColor::Border);
247            assert!(lvgl::lv_color_eq(logo_color(themed), light.border));
248            themed.set_color(Color::WHITE);
249            update_display(display, primary, secondary, true);
250            assert!(lvgl::lv_color_eq(
251                logo_color(themed),
252                Color::WHITE.into_lvgl_color()
253            ));
254            for (logo, factor) in &logos {
255                assert_logo_geometry(logo, *factor);
256            }
257            drop(logos);
258            lvgl::lv_display_delete(display);
259            // Theme state must be gone before display storage can be reused.
260            assert!(!lvgl::lv_theme_shadcn_is_active(display));
261            lvgl::lv_deinit();
262        }
263    }
264    unsafe fn assert_logo_geometry(logo: &crate::Logo, factor: u8) {
265        unsafe {
266            let object = logo.get_inner_object();
267            let size = 32 * i32::from(factor);
268            lvgl::lv_obj_update_layout(object);
269            assert_eq!(lvgl::lv_obj_get_width(object), size);
270            assert_eq!(lvgl::lv_obj_get_height(object), size);
271            assert_eq!(lvgl::lv_obj_get_child_count(object), 0);
272        }
273    }
274}