Skip to main content

graphics/theme/
adjustments.rs

1//! What Xila changes in the shadcn theme: invalidation fixes for every display,
2//! and the light rendering mode.
3//!
4//! The theme exposes its palette, radius scale and a flag that only stops the
5//! skeleton pulse, so the rest is done here: a callback chained after the theme's
6//! own removes or overrides a few of its styles on each new object. The override
7//! styles are constant and shared, so an object pays one style slot for each and
8//! nothing has to be released.
9//!
10//! The theme has no shadows or gradients to remove, and its remaining blending
11//! is cheap: a disabled control scales the opacity of what it draws, without an
12//! intermediate layer, and a scrollbar is a few pixels wide.
13
14use core::{cell::UnsafeCell, ffi::c_void, ptr};
15
16use portable_atomic::{AtomicBool, Ordering};
17
18use crate::{Error, Result, lvgl};
19
20/// How much the theme may spend on rendering.
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
22pub enum RenderingMode {
23    /// The full theme: animated state changes and scrolling, dimmed modal
24    /// backdrops, clipped rounded corners.
25    #[default]
26    Default,
27    /// For slow display buses and processors. State changes and the scrolls
28    /// that LVGL animates take one frame, the momentum of a scroll takes half
29    /// as many, modal backdrops are not blended, lists and tables do not clip
30    /// their children to their rounded corners, and ending a scroll does not
31    /// redraw the scrolled object.
32    Light,
33}
34
35/// Light rendering is on. Read and written under the LVGL lock.
36static LIGHT: AtomicBool = AtomicBool::new(false);
37
38/// Static data that LVGL reads, and that only changes under the LVGL lock.
39#[repr(transparent)]
40struct Shared<T>(UnsafeCell<T>);
41
42// SAFETY: every access happens under the LVGL lock.
43unsafe impl<T> Sync for Shared<T> {}
44
45impl<T> Shared<T> {
46    const fn new(value: T) -> Self {
47        Self(UnsafeCell::new(value))
48    }
49
50    const fn get(&self) -> *mut T {
51        self.0.get()
52    }
53}
54
55const fn number(property: u32, value: i32) -> lvgl::lv_style_const_prop_t {
56    lvgl::lv_style_const_prop_t {
57        prop: property as lvgl::lv_style_prop_t,
58        value: lvgl::lv_style_value_t { num: value },
59    }
60}
61
62/// Ends a constant style's property list.
63const END: lvgl::lv_style_const_prop_t = number(lvgl::_lv_style_id_t_LV_STYLE_PROP_INV, 0);
64
65/// A style in LVGL's constant layout (`LV_STYLE_CONST_INIT`): its properties are
66/// a static list instead of memory from LVGL's heap.
67const fn constant_style(properties: *mut lvgl::lv_style_const_prop_t) -> lvgl::lv_style_t {
68    lvgl::lv_style_t {
69        values_and_props: properties.cast(),
70        has_group: u32::MAX,
71        prop_cnt: 255,
72    }
73}
74
75/// The properties the theme animates on a state change.
76static TRANSITION_PROPERTIES: [lvgl::lv_style_prop_t; 4] = [
77    lvgl::_lv_style_id_t_LV_STYLE_BG_COLOR as lvgl::lv_style_prop_t,
78    lvgl::_lv_style_id_t_LV_STYLE_BORDER_COLOR as lvgl::lv_style_prop_t,
79    lvgl::_lv_style_id_t_LV_STYLE_OPA as lvgl::lv_style_prop_t,
80    lvgl::_lv_style_id_t_LV_STYLE_PROP_INV as lvgl::lv_style_prop_t,
81];
82
83static INSTANT_TRANSITION: Shared<lvgl::lv_style_transition_dsc_t> =
84    Shared::new(lvgl::lv_style_transition_dsc_t {
85        props: TRANSITION_PROPERTIES.as_ptr(),
86        user_data: ptr::null_mut(),
87        path_xcb: Some(lvgl::lv_anim_path_step),
88        time: 0,
89        delay: 0,
90    });
91
92static INSTANT_TRANSITION_PROPERTIES: Shared<[lvgl::lv_style_const_prop_t; 2]> = Shared::new([
93    lvgl::lv_style_const_prop_t {
94        prop: lvgl::_lv_style_id_t_LV_STYLE_TRANSITION as lvgl::lv_style_prop_t,
95        value: lvgl::lv_style_value_t {
96            ptr: INSTANT_TRANSITION.get() as *const c_void,
97        },
98    },
99    END,
100]);
101
102/// Replaces the theme's 150 ms transition: the new state shows in one frame.
103static INSTANT: Shared<lvgl::lv_style_t> =
104    Shared::new(constant_style(INSTANT_TRANSITION_PROPERTIES.get().cast()));
105
106static UNBLENDED_PROPERTIES: Shared<[lvgl::lv_style_const_prop_t; 2]> = Shared::new([
107    number(
108        lvgl::_lv_style_id_t_LV_STYLE_BG_OPA,
109        lvgl::LV_OPA_TRANSP as i32,
110    ),
111    END,
112]);
113
114/// Replaces the half-transparent black of a modal backdrop: blending it costs a
115/// pass over the whole screen.
116static UNBLENDED: Shared<lvgl::lv_style_t> =
117    Shared::new(constant_style(UNBLENDED_PROPERTIES.get().cast()));
118
119static UNCLIPPED_PROPERTIES: Shared<[lvgl::lv_style_const_prop_t; 2]> =
120    Shared::new([number(lvgl::_lv_style_id_t_LV_STYLE_CLIP_CORNER, 0), END]);
121
122/// Stops clipping children to rounded corners, which LVGL does by rendering the
123/// top and bottom bands of the object into layers.
124static UNCLIPPED: Shared<lvgl::lv_style_t> =
125    Shared::new(constant_style(UNCLIPPED_PROPERTIES.get().cast()));
126
127const MAIN: lvgl::lv_style_selector_t = lvgl::LV_PART_MAIN;
128const ITEMS: lvgl::lv_style_selector_t = lvgl::LV_PART_ITEMS;
129const SCROLLBAR: lvgl::lv_style_selector_t = lvgl::lv_part_t_LV_PART_SCROLLBAR;
130const PRESSED: lvgl::lv_style_selector_t = lvgl::LV_STATE_PRESSED;
131const SCROLLED: lvgl::lv_style_selector_t = lvgl::lv_state_t_LV_STATE_SCROLLED;
132const ANY: lvgl::lv_style_selector_t = lvgl::lv_part_t_LV_PART_ANY | lvgl::lv_state_t_LV_STATE_ANY;
133
134/// Share of the foreground that the theme mixes into a pressed key
135/// (`LV_THEME_SHADCN_PRESS_MIX`).
136const KEY_PRESS_MIX: u8 = 26;
137
138/// What an object needs, from what the theme gives its class.
139#[derive(Clone, Copy, PartialEq, Eq)]
140enum Kind {
141    /// Nothing to adjust.
142    Untouched,
143    /// Looks different while pressed: buttons, list and menu entries.
144    Pressable,
145    /// Reacts to presses without a pressed look: inputs, toggles, sliders.
146    Control,
147    /// A plain object: a card or a layout container, which may scroll.
148    Container,
149    /// A text input, which is a control that scrolls its text.
150    TextInput,
151    /// Scrolls, and has no interaction styles of its own.
152    Scrollable,
153    /// A list or a table: scrolls, and clips its children to its corners.
154    Collection,
155    /// The on-screen keyboard.
156    Keyboard,
157    /// The dimmed area behind a message box.
158    Backdrop,
159}
160
161fn kind_of(class: *const lvgl::lv_obj_class_t) -> Option<Kind> {
162    let classes: [(*const lvgl::lv_obj_class_t, Kind); 25] = {
163        [
164            (&raw const lvgl::lv_label_class, Kind::Untouched),
165            (&raw const lvgl::lv_obj_class, Kind::Container),
166            (&raw const lvgl::lv_button_class, Kind::Pressable),
167            (&raw const lvgl::lv_list_button_class, Kind::Pressable),
168            (&raw const lvgl::lv_menu_cont_class, Kind::Pressable),
169            (
170                &raw const lvgl::lv_msgbox_footer_button_class,
171                Kind::Pressable,
172            ),
173            (
174                &raw const lvgl::lv_msgbox_header_button_class,
175                Kind::Pressable,
176            ),
177            (&raw const lvgl::lv_textarea_class, Kind::TextInput),
178            (&raw const lvgl::lv_spinbox_class, Kind::TextInput),
179            (&raw const lvgl::lv_dropdown_class, Kind::Control),
180            (&raw const lvgl::lv_roller_class, Kind::Control),
181            (&raw const lvgl::lv_switch_class, Kind::Control),
182            (&raw const lvgl::lv_checkbox_class, Kind::Control),
183            (&raw const lvgl::lv_slider_class, Kind::Control),
184            (&raw const lvgl::lv_arc_class, Kind::Control),
185            (&raw const lvgl::lv_imagebutton_class, Kind::Control),
186            (&raw const lvgl::lv_list_class, Kind::Collection),
187            (&raw const lvgl::lv_table_class, Kind::Collection),
188            (&raw const lvgl::lv_tileview_class, Kind::Scrollable),
189            (&raw const lvgl::lv_tileview_tile_class, Kind::Scrollable),
190            (&raw const lvgl::lv_menu_page_class, Kind::Scrollable),
191            (&raw const lvgl::lv_dropdownlist_class, Kind::Scrollable),
192            (&raw const lvgl::lv_msgbox_content_class, Kind::Scrollable),
193            (&raw const lvgl::lv_keyboard_class, Kind::Keyboard),
194            (&raw const lvgl::lv_msgbox_backdrop_class, Kind::Backdrop),
195        ]
196    };
197    classes
198        .iter()
199        .find(|(known, _)| ptr::eq(*known, class))
200        .map(|(_, kind)| *kind)
201}
202
203/// Adjusts `object` as an instance of `class`.
204///
205/// Safe to repeat on an object: styles and callbacks are added once.
206unsafe fn adjust(object: *mut lvgl::lv_obj_t, class: *const lvgl::lv_obj_class_t) {
207    let Some(kind) = kind_of(class) else {
208        return;
209    };
210    let light = LIGHT.load(Ordering::Relaxed);
211
212    unsafe {
213        // The theme adds its transition a second time for the pressed state. On
214        // an object that does not look different pressed, that style only makes
215        // LVGL redraw the whole object on every press and release: for a window
216        // or a card, most of the screen. The copy for the default state already
217        // covers both directions.
218        if matches!(kind, Kind::Container | Kind::Control | Kind::TextInput) {
219            lvgl::lv_obj_remove_theme(object, MAIN | PRESSED);
220        }
221
222        if kind == Kind::Keyboard {
223            // Likewise, a style for pressed keys makes LVGL redraw the whole
224            // keyboard for each key. The button matrix already redraws the one
225            // key; `color_pressed_key` gives it the pressed color.
226            lvgl::lv_obj_remove_theme(object, ITEMS | PRESSED);
227            add_event_callback(
228                object,
229                color_pressed_key,
230                lvgl::lv_event_code_t_LV_EVENT_DRAW_TASK_ADDED,
231            );
232            lvgl::lv_obj_set_send_draw_task_events(object, true);
233        }
234
235        if !light {
236            return;
237        }
238
239        match kind {
240            Kind::Pressable => {
241                add_style(object, INSTANT.get(), MAIN);
242                add_style(object, INSTANT.get(), MAIN | PRESSED);
243            }
244            Kind::Control | Kind::TextInput | Kind::Container => {
245                add_style(object, INSTANT.get(), MAIN);
246            }
247            Kind::Collection => add_style(object, UNCLIPPED.get(), MAIN),
248            Kind::Backdrop => add_style(object, UNBLENDED.get(), MAIN),
249            Kind::Scrollable | Kind::Keyboard | Kind::Untouched => {}
250        }
251
252        if matches!(
253            kind,
254            Kind::Container | Kind::TextInput | Kind::Scrollable | Kind::Collection
255        ) {
256            adjust_scrolling(object);
257        }
258    }
259}
260
261/// Light rendering for an object that may scroll.
262unsafe fn adjust_scrolling(object: *mut lvgl::lv_obj_t) {
263    if unsafe { find_event_callback(object, finish_scroll_at_once) }.is_some() {
264        return;
265    }
266    unsafe {
267        // The theme makes the scrollbar more opaque during a scroll. LVGL
268        // redraws the whole object when a style for a state comes or goes, so
269        // that costs a full redraw of the scrolled object when the scroll ends.
270        // The callback keeps the theme's style, which `restore_existing` gives
271        // back.
272        let style = find_theme_style(object, SCROLLBAR | SCROLLED);
273        if !style.is_null() {
274            lvgl::lv_obj_remove_style(object, style, SCROLLBAR | SCROLLED);
275        }
276        lvgl::lv_obj_add_event_cb(
277            object,
278            Some(finish_scroll_at_once),
279            lvgl::lv_event_code_t_LV_EVENT_SCROLL_BEGIN,
280            style.cast_mut().cast(),
281        );
282    }
283}
284
285/// The style that the theme gave `object` for `selector`, or null.
286unsafe fn find_theme_style(
287    object: *mut lvgl::lv_obj_t,
288    selector: lvgl::lv_style_selector_t,
289) -> *const lvgl::lv_style_t {
290    unsafe {
291        let count = (*object).style_cnt() as usize;
292        if count == 0 {
293            return ptr::null();
294        }
295        core::slice::from_raw_parts((*object).styles, count)
296            .iter()
297            .find(|style| style.is_theme() != 0 && style.selector() == selector)
298            .map_or(ptr::null(), |style| style.style)
299    }
300}
301
302/// Adds back a style that [`find_theme_style`] found, as the theme's own.
303unsafe fn restore_theme_style(
304    object: *mut lvgl::lv_obj_t,
305    style: *const lvgl::lv_style_t,
306    selector: lvgl::lv_style_selector_t,
307) {
308    unsafe {
309        lvgl::lv_obj_add_style(object, style, selector);
310        // As LVGL marks the styles that a theme adds, so that removing the
311        // theme's styles, as `adjust_scrolling` does again, finds it.
312        let count = (*object).style_cnt() as usize;
313        if let Some(entry) = core::slice::from_raw_parts_mut((*object).styles, count)
314            .iter_mut()
315            .find(|entry| ptr::eq(entry.style, style) && entry.selector() == selector)
316        {
317            entry.set_is_theme(1);
318        }
319    }
320}
321
322/// The descriptor of `callback` on `object`, if it was added.
323unsafe fn find_event_callback(
324    object: *mut lvgl::lv_obj_t,
325    callback: unsafe extern "C" fn(*mut lvgl::lv_event_t),
326) -> Option<*mut lvgl::lv_event_dsc_t> {
327    unsafe {
328        (0..lvgl::lv_obj_get_event_count(object))
329            .map(|index| lvgl::lv_obj_get_event_dsc(object, index))
330            .find(|descriptor| {
331                lvgl::lv_event_dsc_get_cb(*descriptor)
332                    .is_some_and(|added| ptr::fn_addr_eq(added, callback))
333            })
334    }
335}
336
337unsafe fn add_style(
338    object: *mut lvgl::lv_obj_t,
339    style: *const lvgl::lv_style_t,
340    selector: lvgl::lv_style_selector_t,
341) {
342    // Adding a style that is already there with this selector moves it to the
343    // top instead of adding it again.
344    unsafe { lvgl::lv_obj_add_style(object, style, selector) };
345}
346
347unsafe fn add_event_callback(
348    object: *mut lvgl::lv_obj_t,
349    callback: unsafe extern "C" fn(*mut lvgl::lv_event_t),
350    code: lvgl::lv_event_code_t,
351) {
352    unsafe {
353        lvgl::lv_obj_remove_event_cb(object, Some(callback));
354        lvgl::lv_obj_add_event_cb(object, Some(callback), code, ptr::null_mut());
355    }
356}
357
358/// Snaps the scrolls that LVGL animates: scrolling to a position or an object,
359/// settling on a snap point, returning from an overscroll. Each frame of such
360/// an animation redraws the whole scrolled object. Scrolling under the finger
361/// and its momentum do not come through here, and stay.
362unsafe extern "C" fn finish_scroll_at_once(event: *mut lvgl::lv_event_t) {
363    unsafe {
364        // LVGL passes the animation it is about to start, or null for a scroll
365        // without one.
366        let animation = lvgl::lv_event_get_param(event).cast::<lvgl::lv_anim_t>();
367        if !animation.is_null() {
368            lvgl::lv_anim_set_duration(animation, 0);
369            // LVGL's easing paths return the start value for a zero duration.
370            lvgl::lv_anim_set_path_cb(animation, Some(lvgl::lv_anim_path_step));
371        }
372    }
373}
374
375/// Gives the pressed key of a keyboard the theme's pressed color.
376unsafe extern "C" fn color_pressed_key(event: *mut lvgl::lv_event_t) {
377    unsafe {
378        let keyboard = lvgl::lv_event_get_current_target_obj(event);
379        if !lvgl::lv_obj_has_state(keyboard, lvgl::LV_STATE_PRESSED as lvgl::lv_state_t) {
380            return;
381        }
382        let task = lvgl::lv_event_get_draw_task(event);
383        let fill = lvgl::lv_draw_task_get_fill_dsc(task);
384        if fill.is_null()
385            || (*fill).base.part != ITEMS
386            || (*fill).base.id1 != lvgl::lv_buttonmatrix_get_selected_button(keyboard)
387        {
388            return;
389        }
390        let palette = lvgl::lv_theme_shadcn_get_palette(lvgl::lv_obj_get_display(keyboard));
391        if let Some(palette) = palette.as_ref() {
392            (*fill).color =
393                lvgl::lv_color_mix(palette.secondary_fg, palette.secondary, KEY_PRESS_MIX);
394        }
395    }
396}
397
398/// Runs after the theme has styled a new object.
399unsafe extern "C" fn apply_callback(_theme: *mut lvgl::lv_theme_t, object: *mut lvgl::lv_obj_t) {
400    // For a class that inherits its base class's theme, LVGL calls the theme
401    // once for each class with the object's class set to it.
402    unsafe { adjust(object, lvgl::lv_obj_get_class(object)) };
403}
404
405/// Runs the animations before a frame is rendered, in light mode.
406///
407/// LVGL starts a transition on a state change and leaves even the only step of
408/// [`INSTANT`] to the animation timer, which runs after the display's: each
409/// state change would first be drawn once more with the old colors.
410///
411/// This also advances the momentum of a scroll, which LVGL slows down once for
412/// each run of the animations instead of over time. On a display that renders
413/// slower than the animation timer runs, a fling then covers the same distance
414/// in half the frames.
415unsafe extern "C" fn settle_transitions(_: *mut lvgl::lv_event_t) {
416    if LIGHT.load(Ordering::Relaxed) {
417        unsafe { lvgl::lv_anim_refr_now() };
418    }
419}
420
421unsafe extern "C" fn delete_theme(event: *mut lvgl::lv_event_t) {
422    unsafe { lvgl::lv_theme_delete(lvgl::lv_event_get_user_data(event).cast()) };
423}
424
425/// Chains [`apply_callback`] after the theme's own callback, once for a display.
426///
427/// The theme's helpers only act while the display's theme is the one the theme
428/// created, so another theme cannot be put on top of it. Instead that theme
429/// becomes the hook, and a copy that keeps its callback runs first as its parent.
430pub(super) unsafe fn install(
431    display: *mut lvgl::lv_display_t,
432    theme: *mut lvgl::lv_theme_t,
433) -> Result<()> {
434    unsafe {
435        let original = lvgl::lv_theme_create();
436        if original.is_null() {
437            return Err(Error::OutOfMemory);
438        }
439        lvgl::lv_theme_copy(original, theme);
440        lvgl::lv_theme_set_parent(theme, original);
441        lvgl::lv_theme_set_apply_cb(theme, Some(apply_callback));
442        lvgl::lv_display_add_event_cb(
443            display,
444            Some(settle_transitions),
445            lvgl::lv_event_code_t_LV_EVENT_REFR_START,
446            ptr::null_mut(),
447        );
448        // The theme frees itself with the display, but not the copy.
449        lvgl::lv_display_add_event_cb(
450            display,
451            Some(delete_theme),
452            lvgl::lv_event_code_t_LV_EVENT_DELETE,
453            original.cast(),
454        );
455    }
456    Ok(())
457}
458
459unsafe extern "C" fn adjust_existing(
460    object: *mut lvgl::lv_obj_t,
461    _: *mut c_void,
462) -> lvgl::lv_obj_tree_walk_res_t {
463    unsafe {
464        // Outside the theme's own pass, adjust the object for the classes LVGL
465        // applied the theme for: its own and, as long as a class lets the
466        // classes derived from it inherit its theme, the one it derives from.
467        let mut class = lvgl::lv_obj_get_class(object);
468        while !class.is_null() {
469            adjust(object, class);
470            if (*class).theme_inheritable()
471                != lvgl::lv_obj_class_theme_inheritable_t_LV_OBJ_CLASS_THEME_INHERITABLE_TRUE
472            {
473                break;
474            }
475            class = (*class).base_class;
476        }
477    }
478    lvgl::lv_obj_tree_walk_res_t_LV_OBJ_TREE_WALK_NEXT
479}
480
481unsafe extern "C" fn restore_existing(
482    object: *mut lvgl::lv_obj_t,
483    _: *mut c_void,
484) -> lvgl::lv_obj_tree_walk_res_t {
485    unsafe {
486        for style in [INSTANT.get(), UNBLENDED.get(), UNCLIPPED.get()] {
487            lvgl::lv_obj_remove_style(object, style, ANY);
488        }
489        if let Some(descriptor) = find_event_callback(object, finish_scroll_at_once) {
490            // The style the theme gave the scrollbar during a scroll, which
491            // `adjust_scrolling` kept. The theme's styles live as long as the
492            // display, and Xila never deinitializes the theme.
493            let style = lvgl::lv_event_dsc_get_user_data(descriptor)
494                .cast::<lvgl::lv_style_t>()
495                .cast_const();
496            lvgl::lv_obj_remove_event_cb(object, Some(finish_scroll_at_once));
497            if !style.is_null() {
498                restore_theme_style(object, style, SCROLLBAR | SCROLLED);
499            }
500        }
501    }
502    lvgl::lv_obj_tree_walk_res_t_LV_OBJ_TREE_WALK_NEXT
503}
504
505/// Select the rendering mode of the theme on `display`.
506///
507/// The mode is shared by every display. Objects created from now on follow it,
508/// and so do the objects that `display` already shows: leaving light mode gives
509/// them back the theme's look.
510///
511/// # Safety
512/// `display` must be live and the caller must hold the LVGL lock.
513pub unsafe fn set_display_rendering_mode(
514    display: *mut lvgl::lv_display_t,
515    mode: RenderingMode,
516) -> Result<()> {
517    unsafe {
518        if !lvgl::lv_theme_shadcn_is_active(display) {
519            return Err(Error::NotAvailable);
520        }
521        let light = mode == RenderingMode::Light;
522        LIGHT.store(light, Ordering::Relaxed);
523
524        let callback: lvgl::lv_obj_tree_walk_cb_t = if light {
525            Some(adjust_existing)
526        } else {
527            Some(restore_existing)
528        };
529        for root in [
530            lvgl::lv_display_get_screen_active(display),
531            lvgl::lv_display_get_layer_top(display),
532            lvgl::lv_display_get_layer_sys(display),
533            lvgl::lv_display_get_layer_bottom(display),
534        ] {
535            if !root.is_null() {
536                lvgl::lv_obj_tree_walk(root, callback, ptr::null_mut());
537            }
538        }
539    }
540    Ok(())
541}
542
543/// The rendering mode that [`set_display_rendering_mode`] last selected.
544pub fn get_rendering_mode() -> RenderingMode {
545    if LIGHT.load(Ordering::Relaxed) {
546        RenderingMode::Light
547    } else {
548        RenderingMode::Default
549    }
550}
551
552#[cfg(all(test, target_os = "linux"))]
553mod tests;