Skip to main content

graphics/
manager.rs

1use alloc::{
2    boxed::Box,
3    string::{String, ToString},
4    vec,
5    vec::Vec,
6};
7use file_system::DirectCharacterDevice;
8use lvgl_rust::Lvgl;
9use synchronization::blocking_mutex::raw::CriticalSectionRawMutex;
10use synchronization::mutex::{Mutex, MutexGuard};
11use synchronization::rwlock::RwLock;
12use task::block_on;
13
14use core::{cell::Cell, future::Future, marker::PhantomData};
15use portable_atomic::{AtomicPtr, Ordering};
16
17use core::time::Duration;
18
19use super::lvgl;
20
21use crate::input::InputQueue;
22use crate::on_screen_keyboard::OnScreenKeyboard;
23use crate::window::Window;
24use crate::{Color, theme};
25use crate::{Display, OwnedWindow};
26use crate::{Error, Result};
27use crate::{Input, InputKind, Key, State};
28
29static GRAPHICS_LOCK: Mutex<CriticalSectionRawMutex, ()> = Mutex::new(());
30static TICK_TIME_MANAGER: AtomicPtr<time::Manager<'static>> = AtomicPtr::new(core::ptr::null_mut());
31static FFI_GRAPHICS_MANAGER: AtomicPtr<Manager> = AtomicPtr::new(core::ptr::null_mut());
32
33/// Register the manager used by C/wasm callbacks that cannot carry Rust references.
34pub fn set_ffi_manager(manager: &'static Manager) {
35    FFI_GRAPHICS_MANAGER.store(manager as *const _ as *mut _, Ordering::Release);
36}
37
38/// Resolve the graphics capability at an FFI callback boundary.
39pub fn ffi_manager() -> &'static Manager {
40    let manager = FFI_GRAPHICS_MANAGER.load(Ordering::Acquire);
41    assert!(!manager.is_null(), "FFI graphics manager not initialized");
42    unsafe { &*manager }
43}
44
45/// Return the graphics capability when initialized, without panicking during startup.
46pub fn try_ffi_manager() -> Option<&'static Manager> {
47    let manager = FFI_GRAPHICS_MANAGER.load(Ordering::Acquire);
48    if manager.is_null() {
49        None
50    } else {
51        Some(unsafe { &*manager })
52    }
53}
54
55pub async fn initialize(
56    time_manager: &'static time::Manager<'static>,
57    screen_device: &'static dyn DirectCharacterDevice,
58    input_device: &'static dyn DirectCharacterDevice,
59    input_device_type: InputKind,
60    buffer_size: usize,
61    double_buffered: bool,
62) -> Manager {
63    let input_devices = [(input_device, input_device_type)];
64    initialize_with_input_devices(
65        time_manager,
66        screen_device,
67        &input_devices,
68        buffer_size,
69        double_buffered,
70    )
71    .await
72}
73
74/// Initialize graphics with zero or more physical input devices. Graphics-owned
75/// virtual pointer and keypad devices are always installed for subsystem input.
76pub async fn initialize_with_input_devices(
77    time_manager: &'static time::Manager<'static>,
78    screen_device: &'static dyn DirectCharacterDevice,
79    input_devices: &[(&'static dyn DirectCharacterDevice, InputKind)],
80    buffer_size: usize,
81    double_buffered: bool,
82) -> Manager {
83    Manager::new(
84        time_manager,
85        screen_device,
86        input_devices,
87        buffer_size,
88        double_buffered,
89    )
90    .expect("Failed to create manager instance")
91}
92
93struct Inner {
94    _inputs: Vec<Input>,
95    displays: Vec<Display>,
96    // Drop displays first because LVGL callbacks borrow the keyboard state.
97    on_screen_keyboard: Option<Box<OnScreenKeyboard>>,
98}
99
100pub struct Manager {
101    inner: RwLock<CriticalSectionRawMutex, Inner>,
102    window_parent: AtomicPtr<lvgl::lv_obj_t>,
103    injected_inputs: synchronization::Arc<InputQueue>,
104}
105
106/// Bounds for UI tree snapshots. These limits keep diagnostics safe on small targets.
107pub const UI_TREE_MAX_ELEMENTS: usize = 256;
108pub const UI_TREE_MAX_DEPTH: usize = 24;
109use crate::UiTreeSnapshot;
110use crate::inspection::inspect_children;
111#[cfg(test)]
112use crate::inspection::semantic_role;
113
114impl Manager {
115    /// Snapshot a bounded depth-first view of the currently mounted UI tree.
116    ///
117    /// Element IDs are indexes into this snapshot and must not be retained across
118    /// snapshots. No LVGL pointer is returned to the caller.
119    pub async fn inspect_ui_tree(
120        &self,
121        max_elements: usize,
122        max_depth: usize,
123    ) -> Result<UiTreeSnapshot> {
124        validate_ui_tree_limits(max_elements, max_depth)?;
125
126        let mut guard = self.lock().await;
127        guard.with_lvgl(|_| ())?;
128        let inner = self.inner.read().await;
129        if inner.displays.is_empty() {
130            return Err(Error::NotAvailable);
131        }
132
133        let mut elements = Vec::with_capacity(max_elements);
134        let mut truncated = false;
135        // SAFETY: the lock covers traversal and the manager owns the display.
136        unsafe {
137            let screen = inner.displays[0].get_object();
138            let display = lvgl::lv_obj_get_display(screen);
139            for (root, layer) in [
140                (screen, "screen"),
141                (lvgl::lv_display_get_layer_top(display), "top"),
142                (lvgl::lv_display_get_layer_sys(display), "system"),
143            ] {
144                lvgl::lv_obj_update_layout(root);
145                inspect_children(
146                    root,
147                    None,
148                    0,
149                    (max_depth, max_elements),
150                    &mut elements,
151                    &mut truncated,
152                    layer,
153                );
154            }
155        }
156        Ok(UiTreeSnapshot {
157            elements,
158            truncated,
159        })
160    }
161
162    /// Resolve and hit-test a unique control while holding the graphics lock.
163    /// Coordinates and raw object pointers never survive the operation.
164    pub async fn click_ui(
165        &self,
166        role: Option<&str>,
167        name: Option<&str>,
168        text: Option<&str>,
169        button: Option<&str>,
170    ) -> core::result::Result<(i32, i32), &'static str> {
171        if [role, name, text, button].iter().all(Option::is_none) {
172            return Err("invalid_selector");
173        }
174        let mut guard = self.lock().await;
175        guard.with_lvgl(|_| ()).map_err(|_| "not_available")?;
176        let inner = self.inner.read().await;
177        let display = inner.displays.first().ok_or("not_available")?;
178        // SAFETY: the graphics lock is held and the manager owns the display.
179        let screen = unsafe { display.get_object() };
180        let display = display.get_lvgl_display();
181        // SAFETY: the display stays live and the graphics lock protects its layers.
182        let roots = unsafe {
183            [
184                (screen, "screen"),
185                (lvgl::lv_display_get_layer_top(display), "top"),
186                (lvgl::lv_display_get_layer_sys(display), "system"),
187            ]
188        };
189        let mut elements = Vec::with_capacity(UI_TREE_MAX_ELEMENTS);
190        let mut truncated = false;
191        for (root, layer) in roots {
192            // SAFETY: the graphics lock covers layout and traversal of the live root.
193            unsafe {
194                lvgl::lv_obj_update_layout(root);
195                inspect_children(
196                    root,
197                    None,
198                    0,
199                    (UI_TREE_MAX_DEPTH, UI_TREE_MAX_ELEMENTS),
200                    &mut elements,
201                    &mut truncated,
202                    layer,
203                );
204            }
205        }
206        if truncated {
207            return Err("tree_truncated");
208        }
209        let mut found = None;
210        for e in &elements {
211            if !e.visible
212                || e.disabled
213                || role.is_some_and(|r| e.role != r && e.semantic_role != Some(r))
214            {
215                continue;
216            }
217            // A capped prefix may conceal another exact match. Refuse to claim
218            // uniqueness rather than silently skipping that possible target.
219            if name.is_some_and(|n| {
220                e.name_truncated
221                    && e.name
222                        .as_deref()
223                        .is_some_and(|prefix| n.starts_with(prefix))
224            }) || text.is_some_and(|t| {
225                e.text_truncated
226                    && e.text
227                        .as_deref()
228                        .is_some_and(|prefix| t.starts_with(prefix))
229            }) {
230                return Err("text_truncated");
231            }
232            if name.is_some_and(|n| e.name.as_deref() != Some(n))
233                || text.is_some_and(|t| e.text.as_deref() != Some(t))
234            {
235                continue;
236            }
237            let candidates: Vec<_> = if let Some(label) = button {
238                if e.buttons_truncated {
239                    return Err("buttons_truncated");
240                }
241                if e.buttons.iter().any(|b| {
242                    b.text_truncated
243                        && b.text
244                            .as_deref()
245                            .is_some_and(|prefix| label.starts_with(prefix))
246                }) {
247                    return Err("text_truncated");
248                }
249
250                e.buttons
251                    .iter()
252                    .filter(|b| {
253                        !b.hidden
254                            && !b.disabled
255                            && !b.text_truncated
256                            && b.text.as_deref() == Some(label)
257                    })
258                    .map(|b| b.bounds)
259                    .collect()
260            } else {
261                if !e.clickable {
262                    continue;
263                }
264                e.clipped_bounds.into_iter().collect()
265            };
266            for bounds in candidates {
267                if found.is_some() {
268                    return Err("ambiguous_target");
269                }
270                let Some(clip) = e.clipped_bounds else {
271                    continue;
272                };
273                let bounds = (
274                    bounds.0.max(clip.0),
275                    bounds.1.max(clip.1),
276                    bounds.2.min(clip.2),
277                    bounds.3.min(clip.3),
278                );
279                if bounds.0 > bounds.2 || bounds.1 > bounds.3 {
280                    continue;
281                }
282                found = Some((e.id, ((bounds.0 + bounds.2) / 2, (bounds.1 + bounds.3) / 2)));
283            }
284        }
285        let (identifier, (x, y)) = found.ok_or("target_not_found")?;
286        let mut remaining = identifier;
287        let mut target = None;
288        for (root, _) in roots {
289            // SAFETY: the graphics lock covers traversal of the live root.
290            if let Some(obj) = unsafe { crate::inspection::object_at(root, &mut remaining, 0) } {
291                target = Some(obj);
292                break;
293            }
294        }
295        let target = target.ok_or("target_not_found")?;
296        let mut point = lvgl::lv_point_t { x, y };
297        let mut hit = core::ptr::null_mut();
298        for (root, _) in roots.into_iter().rev() {
299            // SAFETY: the root is live under the graphics lock and point is writable.
300            hit = unsafe { lvgl::lv_indev_search_obj(root, &mut point) };
301            if !hit.is_null() {
302                break;
303            }
304        }
305        // A labelled child may receive the pointer. Require it to belong to the target.
306        let mut owner = hit;
307        while !owner.is_null() && owner != target {
308            // SAFETY: hit testing returned a live object and the lock protects its ancestors.
309            owner = unsafe { lvgl::lv_obj_get_parent(owner) };
310        }
311        if owner != target {
312            return Err("target_obscured");
313        }
314        let point = crate::Point::new(
315            i16::try_from(x).map_err(|_| "invalid_coordinates")?,
316            i16::try_from(y).map_err(|_| "invalid_coordinates")?,
317        );
318        // SAFETY: the graphics lock is held and the manager owns the display.
319        validate_pointer_point(point, unsafe { inner.displays[0].get_resolution() })
320            .map_err(|_| "invalid_coordinates")?;
321        self.injected_inputs
322            .pointer_click(point)
323            .map_err(|_| "busy")?;
324        Ok((x, y))
325    }
326
327    /// Capture the active LVGL screen into an owned, bounded RGBA8888 buffer.
328    pub async fn capture_screen(&self) -> Result<crate::ScreenSnapshot> {
329        let mut guard = self.lock().await;
330        guard.with_lvgl(|_| ())?;
331        let inner = self.inner.read().await;
332        let display = inner.displays.first().ok_or(Error::NotAvailable)?;
333        // SAFETY: the graphics lock is held and the manager owns the display.
334        unsafe { display.capture_screen() }
335    }
336
337    /// Return the current active LVGL display resolution.
338    pub async fn get_resolution(&self) -> Result<crate::Point> {
339        let _lock = self.lock().await;
340        let inner = self.inner.read().await;
341        let display = inner.displays.first().ok_or(Error::NotAvailable)?;
342        // SAFETY: the graphics lock is held and the manager owns the display.
343        Ok(unsafe { display.get_resolution() })
344    }
345
346    /// Read the backlight brightness of the main screen, from
347    /// [`BRIGHTNESS_OFF`](crate::BRIGHTNESS_OFF) to
348    /// [`BRIGHTNESS_FULL`](crate::BRIGHTNESS_FULL).
349    ///
350    /// Returns [`Error::Unsupported`] when the screen has no brightness
351    /// control. Brightness does not touch LVGL: callers may hold the LVGL lock
352    /// or not.
353    pub async fn get_brightness(&self) -> Result<u8> {
354        let inner = self.inner.read().await;
355        inner
356            .displays
357            .first()
358            .ok_or(Error::NotAvailable)?
359            .get_brightness()
360    }
361
362    /// Set the backlight brightness of the main screen; see
363    /// [`Manager::get_brightness`]. Level [`BRIGHTNESS_OFF`](crate::BRIGHTNESS_OFF)
364    /// turns the backlight off.
365    pub async fn set_brightness(&self, level: u8) -> Result<()> {
366        let inner = self.inner.read().await;
367        inner
368            .displays
369            .first()
370            .ok_or(Error::NotAvailable)?
371            .set_brightness(level)
372    }
373
374    /// Queue a pointer move for the graphics-owned LVGL pointer input.
375    pub async fn inject_pointer_move(&self, point: crate::Point) -> Result<()> {
376        let _lock = self.lock().await;
377        let inner = self.inner.read().await;
378        let display = inner.displays.first().ok_or(Error::NotAvailable)?;
379        // SAFETY: the graphics lock is held and the manager owns the display.
380        let resolution = unsafe { display.get_resolution() };
381        validate_pointer_point(point, resolution)?;
382        self.injected_inputs.pointer_move(point)
383    }
384
385    /// Atomically queue a pointer move and complete click at a valid display point.
386    pub async fn inject_pointer_click(&self, point: crate::Point) -> Result<()> {
387        let _lock = self.lock().await;
388        let inner = self.inner.read().await;
389        let display = inner.displays.first().ok_or(Error::NotAvailable)?;
390        // SAFETY: the graphics lock is held and the manager owns the display.
391        let resolution = unsafe { display.get_resolution() };
392        validate_pointer_point(point, resolution)?;
393        self.injected_inputs.pointer_click(point)
394    }
395
396    /// Queue a pointer button state at the most recently injected pointer point.
397    pub async fn inject_pointer_button(&self, state: State) -> Result<()> {
398        let _lock = self.lock().await;
399        self.injected_inputs.pointer_button(state)
400    }
401
402    /// Queue one keyboard key transition for the graphics-owned LVGL keypad.
403    pub async fn inject_key(&self, key: Key, state: State) -> Result<()> {
404        let _lock = self.lock().await;
405        self.injected_inputs.key(key, state)
406    }
407
408    /// Queue a complete key press and release, or leave the queue unchanged.
409    pub async fn inject_key_press(&self, key: Key) -> Result<()> {
410        let _lock = self.lock().await;
411        self.injected_inputs.key_press(key)
412    }
413
414    /// Queue printable ASCII text as ordered key press and release events.
415    pub async fn inject_text(&self, text: &str) -> Result<usize> {
416        let _lock = self.lock().await;
417        self.injected_inputs.text(text)
418    }
419
420    /// Queue a bounded prefix of printable Unicode text, returning the accepted byte count.
421    /// A queue-full error never enqueues a partial press/release pair.
422    pub async fn inject_text_chunk(&self, text: &str) -> Result<usize> {
423        let _lock = self.lock().await;
424        self.injected_inputs.text_chunk(text)
425    }
426
427    pub fn lock_function_sync<T>(&self, function: impl FnOnce() -> Result<T>) -> Result<T> {
428        task::block_on(self.lock_function(function))
429    }
430}
431
432fn validate_pointer_point(point: crate::Point, resolution: crate::Point) -> Result<()> {
433    if point.get_x() < 0
434        || point.get_y() < 0
435        || point.get_x() >= resolution.get_x()
436        || point.get_y() >= resolution.get_y()
437    {
438        Err(Error::InvalidParameter)
439    } else {
440        Ok(())
441    }
442}
443
444fn validate_ui_tree_limits(max_elements: usize, max_depth: usize) -> Result<()> {
445    if max_elements == 0
446        || max_elements > UI_TREE_MAX_ELEMENTS
447        || max_depth == 0
448        || max_depth > UI_TREE_MAX_DEPTH
449    {
450        Err(Error::InvalidParameter)
451    } else {
452        Ok(())
453    }
454}
455
456#[cfg(test)]
457mod ui_tree_tests {
458    use super::*;
459
460    #[test]
461    fn semantic_roles_cover_common_widgets_and_preserve_unknown_classes() {
462        assert_eq!(semantic_role("lv_button"), Some("button"));
463        assert_eq!(semantic_role("lv_textarea"), Some("textbox"));
464        assert_eq!(semantic_role("lv_checkbox"), Some("checkbox"));
465        assert_eq!(semantic_role("lv_switch"), Some("switch"));
466        assert_eq!(semantic_role("lv_slider"), Some("slider"));
467        assert_eq!(semantic_role("lv_dropdown"), Some("combobox"));
468        assert_eq!(semantic_role("lv_label"), Some("text"));
469        assert_eq!(semantic_role("my_custom_widget"), None);
470    }
471
472    #[test]
473    fn tree_limits_are_bounded() {
474        assert_eq!(validate_ui_tree_limits(1, 1), Ok(()));
475        assert_eq!(
476            validate_ui_tree_limits(UI_TREE_MAX_ELEMENTS + 1, 1),
477            Err(Error::InvalidParameter)
478        );
479        assert_eq!(
480            validate_ui_tree_limits(1, UI_TREE_MAX_DEPTH + 1),
481            Err(Error::InvalidParameter)
482        );
483        assert_eq!(validate_ui_tree_limits(0, 1), Err(Error::InvalidParameter));
484    }
485}
486
487#[cfg(test)]
488mod injected_input_tests {
489    use super::*;
490
491    #[test]
492    fn injected_pointer_rejects_right_and_bottom_edges() {
493        let resolution = crate::Point::new(640, 480);
494        assert_eq!(
495            validate_pointer_point(crate::Point::new(639, 479), resolution),
496            Ok(())
497        );
498        assert_eq!(
499            validate_pointer_point(crate::Point::new(640, 10), resolution),
500            Err(Error::InvalidParameter)
501        );
502        assert_eq!(
503            validate_pointer_point(crate::Point::new(10, 480), resolution),
504            Err(Error::InvalidParameter)
505        );
506    }
507}
508
509impl Drop for Manager {
510    fn drop(&mut self) {
511        let mut guard = block_on(lock_graphics());
512        let inner = self.inner.get_mut();
513        inner._inputs.clear();
514        inner.displays.clear();
515        let _ = guard
516            .access
517            .session()
518            .and_then(|session| Lvgl::deinit(session).map_err(Error::from));
519    }
520}
521
522/// Holds the process-wide graphics lock. Use [`Self::with_lvgl`] to run
523/// operations that need a session. A guard can move between threads, and
524/// only one thread can use it at a time.
525///
526/// ```compile_fail,E0277
527/// fn require_sync<T: Sync>() {}
528/// require_sync::<graphics::GraphicsGuard<'static>>();
529/// ```
530#[must_use = "Dropping the guard releases the graphics lock"]
531pub struct GraphicsGuard<'a> {
532    access: LvglGuard<'a>,
533    not_sync: PhantomData<Cell<()>>,
534}
535
536impl GraphicsGuard<'_> {
537    /// Run a synchronous operation in an LVGL session. The session token
538    /// cannot escape the operation.
539    ///
540    /// ```compile_fail
541    /// fn escape(guard: &mut graphics::GraphicsGuard<'_>) {
542    ///     let _ = guard.with_lvgl(|lvgl| lvgl);
543    /// }
544    /// ```
545    pub fn with_lvgl<T>(&mut self, function: impl FnOnce(&mut Lvgl) -> T) -> Result<T> {
546        let mut session = self.access.session()?;
547        crate::call::drain_retired_states(&mut session);
548        Ok(function(&mut session))
549    }
550}
551
552struct LvglGuard<'a> {
553    _lock: MutexGuard<'a, CriticalSectionRawMutex, ()>,
554}
555
556// SAFETY: constructed only from GRAPHICS_LOCK, which serializes LVGL access
557// and orders it between threads. The private guard is borrowed for sessions
558// within this module. No borrow can escape with a 'static lifetime.
559unsafe impl lvgl_rust::LvglAccess for LvglGuard<'_> {}
560
561impl LvglGuard<'_> {
562    fn session(&mut self) -> Result<lvgl_rust::Session<'_>> {
563        Lvgl::enter(self).map_err(Error::from)
564    }
565}
566
567pub(crate) async fn lock_graphics() -> GraphicsGuard<'static> {
568    GraphicsGuard {
569        access: LvglGuard {
570            _lock: GRAPHICS_LOCK.lock().await,
571        },
572        not_sync: PhantomData,
573    }
574}
575
576pub(crate) fn try_lock_graphics() -> Option<GraphicsGuard<'static>> {
577    GRAPHICS_LOCK.try_lock().ok().map(|lock| GraphicsGuard {
578        access: LvglGuard { _lock: lock },
579        not_sync: PhantomData,
580    })
581}
582
583extern "C" fn binding_tick_callback_function() -> u32 {
584    let manager = TICK_TIME_MANAGER.load(Ordering::Acquire);
585    assert!(!manager.is_null(), "Graphics time manager not initialized");
586    // SAFETY: initialization publishes a static time manager before it sets this callback.
587    unsafe { &*manager }.monotonic_milliseconds_wrapping()
588}
589
590// SAFETY: Manager owns its devices, and all access is through synchronized fields.
591unsafe impl Send for Manager {}
592
593// SAFETY: LVGL calls use GRAPHICS_LOCK, and Inner uses the reader-writer lock.
594unsafe impl Sync for Manager {}
595
596impl Manager {
597    fn new(
598        time_manager: &'static time::Manager<'static>,
599        screen_device: &'static dyn DirectCharacterDevice,
600        input_devices: &[(&'static dyn DirectCharacterDevice, InputKind)],
601        buffer_size: usize,
602        double_buffered: bool,
603    ) -> Result<Self> {
604        let injected_inputs = InputQueue::new()?;
605        // Keep the lock until initialization and device registration complete.
606        let mut guard = try_lock_graphics().ok_or(Error::AlreadyInitialized)?;
607        let mut session = lvgl_rust::init(&mut guard.access).map_err(Error::from)?;
608        TICK_TIME_MANAGER.store(time_manager as *const _ as *mut _, Ordering::Release);
609        session.set_tick_cb(binding_tick_callback_function);
610        crate::window::get_window_class();
611        // SAFETY: the session holds the lock. The default group must exist
612        // before input registration so keypads can join it.
613        unsafe {
614            let group = lvgl::lv_group_create();
615            lvgl::lv_group_set_default(group);
616        }
617
618        let (display, inputs) = Self::create_display(
619            screen_device,
620            input_devices,
621            buffer_size,
622            double_buffered,
623            injected_inputs.clone(),
624        )?;
625        theme::initialize(&display)?;
626
627        Ok(Self {
628            inner: RwLock::new(Inner {
629                _inputs: inputs,
630                displays: vec![display],
631                on_screen_keyboard: None,
632            }),
633            window_parent: AtomicPtr::new(core::ptr::null_mut()),
634            injected_inputs,
635        })
636    }
637
638    /// Enable the system on-screen keyboard on the first display.
639    ///
640    /// Call during platform setup on touch-only devices, before creating any
641    /// file pickers. A picker chooses its keyboard when it is created.
642    /// Tapping a text area on the active screen opens the keyboard.
643    pub async fn enable_on_screen_keyboard(&self) {
644        let _guard = self.lock().await;
645        let mut inner = self.inner.write().await;
646        if inner.on_screen_keyboard.is_none() {
647            let keyboard = Box::new(OnScreenKeyboard::new());
648            // SAFETY: the display is live under the graphics lock. The box keeps
649            // the keyboard state at a fixed address until display teardown.
650            unsafe { keyboard.observe(inner.displays[0].get_lvgl_display()) };
651            inner.on_screen_keyboard = Some(keyboard);
652        }
653    }
654
655    pub async fn r#loop<F>(&self, sleep: impl Fn(Duration) -> F + Send + 'static) -> Result<()>
656    where
657        F: Future<Output = ()> + Send + 'static,
658    {
659        let mut call_count: u8 = 0;
660
661        loop {
662            let time_until_next = {
663                let mut guard = self.lock().await;
664                let inner = self.inner.read().await;
665
666                // Through the session: requests recorded by the safe layer
667                // (dropped `Owned` values, `delete_later`) run right after.
668                // One timer handler can drain up to 512 events per input device.
669                // Draining a large paste therefore holds the graphics lock longer than an
670                // ordinary frame; how long has not been measured on ESP32.
671                let time_until_next = guard.with_lvgl(Lvgl::timer_handler)?;
672                if let Some(keyboard) = &inner.on_screen_keyboard {
673                    // SAFETY: the graphics lock protects the live display and keyboard.
674                    unsafe { keyboard.update(inner.displays[0].get_lvgl_display()) };
675                }
676
677                if call_count >= 30 {
678                    for display in &inner.displays {
679                        // SAFETY: the graphics guard is still held.
680                        unsafe { display.check_for_resizing() };
681                    }
682                    call_count = 0;
683                }
684                call_count = call_count.saturating_add(1);
685
686                time_until_next
687            };
688
689            sleep(Duration::from_millis(time_until_next as u64)).await;
690        }
691    }
692
693    /// Create the next windows inside `window_parent` instead of the screen.
694    ///
695    /// # Safety
696    ///
697    /// `window_parent` must be a live LVGL object that stays alive while it
698    /// is the window parent and holds windows. It must not be inside a window.
699    pub unsafe fn set_window_parent(&self, _lvgl: &mut Lvgl, window_parent: *mut lvgl::lv_obj_t) {
700        self.window_parent.store(window_parent, Ordering::Relaxed);
701    }
702
703    fn window_parent(&self, lvgl: &Lvgl) -> Result<*mut lvgl::lv_obj_t> {
704        let parent = self.window_parent.load(Ordering::Relaxed);
705        if parent.is_null() {
706            // The safe API can replace and delete the screen between sessions.
707            self.get_current_screen(lvgl)
708        } else {
709            Ok(parent)
710        }
711    }
712
713    /// Create a window inside the window parent. By default this is the
714    /// active screen. Returns [`Error::AlreadyInUse`] if a pending screen
715    /// transition can delete the parent. The manager must outlive the owner.
716    ///
717    /// ```compile_fail,E0061
718    /// fn create(manager: &'static graphics::Manager) {
719    ///     let _ = manager.create_window();
720    /// }
721    /// ```
722    pub fn create_window(&'static self, lvgl: &mut Lvgl) -> Result<OwnedWindow> {
723        let parent = self.window_parent(lvgl)?;
724        // SAFETY: the session holds the graphics lock. The parent is the live
725        // active screen or satisfies the set_window_parent lifetime contract.
726        let can_be_deleted = unsafe {
727            let screen = lvgl::lv_obj_get_screen(parent);
728            let display = lvgl::lv_obj_get_display(parent);
729            screen == lvgl::lv_display_get_screen_prev(display)
730                || (screen == lvgl::lv_display_get_screen_active(display)
731                    && !lvgl::lv_display_get_screen_loading(display).is_null())
732        };
733        if can_be_deleted {
734            return Err(Error::AlreadyInUse);
735        }
736
737        // SAFETY: the session still holds the lock and the live parent is
738        // outside the screens that the pending transition can delete.
739        let window = unsafe { Window::new(parent)? };
740        // SAFETY: the window was just created and the static manager keeps LVGL live.
741        Ok(unsafe { OwnedWindow::from_raw(window) })
742    }
743
744    /// Register a physical input device under the graphics lock.
745    pub async fn add_input_device(
746        &self,
747        input_device: &'static dyn DirectCharacterDevice,
748        input_type: InputKind,
749    ) -> Result<()> {
750        let _guard = self.lock().await;
751        let mut inner = self.inner.write().await;
752        // SAFETY: LVGL is initialized and the lock covers registration.
753        // The manager also holds the lock when it drops the input.
754        let input = unsafe { Input::new(input_device, input_type)? };
755        inner._inputs.push(input);
756        Ok(())
757    }
758
759    fn create_display(
760        screen_device: &'static dyn DirectCharacterDevice,
761        input_devices: &[(&'static dyn DirectCharacterDevice, InputKind)],
762        buffer_size: usize,
763        double_buffered: bool,
764        injected_inputs: synchronization::Arc<InputQueue>,
765    ) -> Result<(Display, Vec<Input>)> {
766        // SAFETY: initialization holds the lock and the manager drops the
767        // display under the lock before deinitializing LVGL.
768        let display = unsafe { Display::new(screen_device, buffer_size, double_buffered)? };
769        // SAFETY: initialization holds the graphics lock, including on
770        // failure. The manager holds it when dropping the returned inputs.
771        let mut inputs = unsafe {
772            vec![
773                Input::new_virtual(injected_inputs.clone(), InputKind::Pointer)?,
774                Input::new_virtual(injected_inputs, InputKind::Keypad)?,
775            ]
776        };
777        for (device, kind) in input_devices {
778            // SAFETY: initialization holds the graphics lock and the manager
779            // also holds it when dropping inputs.
780            inputs.push(unsafe { Input::new(*device, *kind)? });
781        }
782        Ok((display, inputs))
783    }
784
785    pub fn get_window_count(&self, lvgl: &Lvgl) -> Result<usize> {
786        let parent = self.window_parent(lvgl)?;
787        // SAFETY: the parent stays live and the session holds the lock.
788        Ok(unsafe { lvgl::lv_obj_get_child_count(parent) } as usize)
789    }
790
791    pub fn get_window_icon(&self, lvgl: &Lvgl, index: usize) -> Result<(String, Color)> {
792        let index = i32::try_from(index).map_err(|_| Error::InvalidWindowIdentifier)?;
793        let parent = self.window_parent(lvgl)?;
794        // SAFETY: the parent stays live and the session excludes changes to
795        // the tree and icon fields throughout this operation.
796        let (text, color) = unsafe {
797            let child = lvgl::lv_obj_get_child(parent, index);
798            let window = Window::from_raw(child).ok_or(Error::InvalidWindowIdentifier)?;
799            Window::icon(window)
800        };
801        Ok((text.as_str().to_string(), color))
802    }
803
804    pub fn get_window_identifier(&self, lvgl: &Lvgl, index: usize) -> Result<usize> {
805        let index = i32::try_from(index).map_err(|_| Error::InvalidWindowIdentifier)?;
806        let parent = self.window_parent(lvgl)?;
807        // SAFETY: the parent stays live and the session holds the lock.
808        Ok(unsafe { lvgl::lv_obj_get_child(parent, index) } as usize)
809    }
810
811    fn find_window(&self, lvgl: &Lvgl, identifier: usize) -> Result<*mut lvgl::lv_obj_t> {
812        let parent = self.window_parent(lvgl)?;
813        // SAFETY: the parent stays live and the session excludes changes to its children.
814        unsafe {
815            (0..lvgl::lv_obj_get_child_count(parent) as i32)
816                .map(|index| lvgl::lv_obj_get_child(parent, index))
817                .find(|child| *child as usize == identifier)
818                .ok_or(Error::InvalidWindowIdentifier)
819        }
820    }
821
822    pub fn maximize_window(&self, lvgl: &mut Lvgl, identifier: usize) -> Result<()> {
823        let window = self.find_window(lvgl, identifier)?;
824        // SAFETY: find_window resolved a live child and the session still
825        // holds the graphics lock.
826        unsafe { lvgl::lv_obj_move_foreground(window) };
827        Ok(())
828    }
829
830    /// Request that a window close. A pending request satisfies later calls
831    /// until the window consumes it.
832    ///
833    /// Returns `InvalidWindowIdentifier` if the identifier does not identify
834    /// a window, or `NotAvailable` if dispatch fails or leaves no pending request.
835    pub fn send_window_close_request(&self, lvgl: &mut Lvgl, identifier: usize) -> Result<()> {
836        let object = self.find_window(lvgl, identifier)?;
837        // SAFETY: the session keeps the live child stable during lookup.
838        let window = unsafe { Window::from_raw(object) }.ok_or(Error::InvalidWindowIdentifier)?;
839        // SAFETY: the session excludes other tasks through dispatch. LVGL
840        // returns INVALID if a handler deletes the object during dispatch.
841        let result = unsafe {
842            lvgl::lv_obj_send_event(
843                object,
844                crate::EventKind::CloseRequested.into_lvgl_code(),
845                core::ptr::null_mut(),
846            )
847        };
848        // A preprocessing handler can stop dispatch without returning INVALID.
849        if result != lvgl::lv_result_t_LV_RESULT_OK || !unsafe { Window::has_close_request(window) }
850        {
851            return Err(Error::NotAvailable);
852        }
853        Ok(())
854    }
855
856    pub async fn lock_function<T>(&self, function: impl FnOnce() -> Result<T>) -> Result<T> {
857        let _lock = self.lock().await;
858        function()
859    }
860
861    pub async fn lock(&self) -> GraphicsGuard<'_> {
862        lock_graphics().await
863    }
864
865    pub fn synchronous_lock(&self) -> GraphicsGuard<'_> {
866        block_on(self.lock())
867    }
868
869    pub fn try_lock(&self) -> Option<GraphicsGuard<'_>> {
870        try_lock_graphics()
871    }
872
873    /// Run a synchronous operation under the graphics lock, in an LVGL
874    /// session. Use the existing guard if the lock is already held.
875    pub async fn with_lvgl<T>(&self, function: impl FnOnce(&mut Lvgl) -> Result<T>) -> Result<T> {
876        self.lock().await.with_lvgl(function)?
877    }
878
879    /// [`Manager::with_lvgl`] from synchronous code.
880    pub fn with_lvgl_sync<T>(&self, function: impl FnOnce(&mut Lvgl) -> Result<T>) -> Result<T> {
881        block_on(self.with_lvgl(function))
882    }
883
884    pub fn get_current_screen(&self, _lvgl: &Lvgl) -> Result<*mut lvgl::lv_obj_t> {
885        // SAFETY: the session holds the graphics lock.
886        let screen = unsafe { lvgl::lv_screen_active() };
887        core::ptr::NonNull::new(screen)
888            .map(|screen| screen.as_ptr())
889            .ok_or(Error::NotAvailable)
890    }
891
892    pub async fn update_theme(
893        &self,
894        primary_color: Color,
895        secondary_color: Color,
896        is_dark: bool,
897    ) -> Result<()> {
898        let mut guard = self.lock().await;
899        self.update_theme_locked(&mut guard, primary_color, secondary_color, is_dark)
900            .await
901    }
902
903    pub(crate) async fn update_theme_locked(
904        &self,
905        _guard: &mut GraphicsGuard<'_>,
906        primary_color: Color,
907        secondary_color: Color,
908        is_dark: bool,
909    ) -> Result<()> {
910        let displays = &self.inner.read().await.displays;
911
912        for display in displays {
913            theme::update(display, primary_color, secondary_color, is_dark);
914        }
915
916        Ok(())
917    }
918
919    /// Select how much the theme may spend on rendering, on every display.
920    ///
921    /// The mode is [`theme::RenderingMode::Default`] until a platform selects
922    /// another one for a slow display, ideally before it creates the interface.
923    pub async fn set_rendering_mode(&self, mode: theme::RenderingMode) -> Result<()> {
924        let _lock = self.lock().await;
925        for display in &self.inner.read().await.displays {
926            theme::set_rendering_mode(display, mode)?;
927        }
928        Ok(())
929    }
930
931    /// The rendering mode in use.
932    pub fn get_rendering_mode(&self) -> theme::RenderingMode {
933        theme::get_rendering_mode()
934    }
935}