Skip to main content

graphics/
window.rs

1use super::{icon_text::IconText, lvgl};
2use crate::{
3    Color, Error, EventKind, Key, Result,
4    event::Event,
5    event_queue::{self, EventQueue},
6};
7use core::{
8    mem::ManuallyDrop,
9    ptr::{self, NonNull},
10};
11use lvgl_rust::{DeferredClass, DeferredLink, Lvgl};
12use synchronization::{once_lock::OnceLock, waitqueue::AtomicWaker};
13
14#[repr(transparent)]
15pub struct ClassWrapper(lvgl::lv_obj_class_t);
16
17unsafe impl Send for ClassWrapper {}
18unsafe impl Sync for ClassWrapper {}
19
20static WINDOW_CLASS: OnceLock<ClassWrapper> = OnceLock::new();
21
22#[unsafe(no_mangle)]
23fn lvgl_rust_external_class_policy(
24    class: *const lvgl::lv_obj_class_t,
25) -> lvgl_rust::ExternalClassPolicy {
26    // The descriptor is initialized under the graphics lock before use. A
27    // policy lookup may only read it; initializing it calls LVGL.
28    if WINDOW_CLASS
29        .try_get()
30        .is_some_and(|window| core::ptr::eq(&window.0, class))
31    {
32        lvgl_rust::ExternalClassPolicy::ChildrenOnly
33    } else {
34        lvgl_rust::ExternalClassPolicy::Protected
35    }
36}
37
38pub(crate) fn get_window_class() -> &'static lvgl::lv_obj_class_t {
39    let class_ref = WINDOW_CLASS.get_or_init(|| {
40        let mut cls = lvgl::lv_obj_class_t {
41            base_class: unsafe { &lvgl::lv_obj_class },
42            constructor_cb: Some(window_constructor),
43            destructor_cb: Some(window_destructor),
44            event_cb: Some(window_event_callback),
45            width_def: unsafe { lvgl::lv_pct(100) },
46            height_def: unsafe { lvgl::lv_pct(100) },
47            name: c"window".as_ptr(),
48            ..Default::default()
49        };
50
51        cls.set_instance_size(size_of::<Window>() as _);
52        cls.set_group_def(lvgl::lv_obj_class_group_def_t_LV_OBJ_CLASS_GROUP_DEF_INHERIT as _);
53        cls.set_theme_inheritable(
54            lvgl::lv_obj_class_theme_inheritable_t_LV_OBJ_CLASS_THEME_INHERITABLE_TRUE as _,
55        );
56        cls.set_editable(lvgl::lv_obj_class_editable_t_LV_OBJ_CLASS_EDITABLE_INHERIT as _);
57
58        ClassWrapper(cls)
59    });
60
61    &class_ref.0
62}
63
64/// An LVGL object that queues the events of its widgets for one consumer.
65///
66/// The fixed ring has [`crate::WINDOW_EVENT_QUEUE_CAPACITY`] regular slots.
67/// A separate slot holds a pending `CloseRequested` in arrival order.
68/// Further close requests merge into it until the consumer takes it.
69///
70/// Press repeats and state changes coalesce for the same target between
71/// lifecycle events. When the ring is full, higher-priority events can evict
72/// lower-priority events. `Insert` and `Delete` are low-priority notifications.
73/// Lifecycle events stay in arrival order. The queue reserves room for the
74/// end of each accepted press. If it rejects a press, it rejects its end.
75///
76/// Losses are counted ([`Window::dropped_event_count`]) and logged at most
77/// once per second. The crate README ("Window events") details the policy.
78#[repr(C)]
79pub struct Window {
80    object: lvgl::lv_obj_t,
81    event_queue: EventQueue,
82    icon_text: IconText,
83    icon_color: Color,
84    waker: AtomicWaker,
85    deferred_delete: DeferredLink,
86}
87
88// SAFETY: only Window instances use this class. Each destructor removes its
89// link. Window operations project individual fields through raw pointers.
90static WINDOWS: DeferredClass =
91    unsafe { DeferredClass::new(core::mem::offset_of!(Window, deferred_delete)) };
92
93unsafe extern "C" fn window_constructor(
94    _class_p: *const lvgl::lv_obj_class_t,
95    object: *mut lvgl::lv_obj_t,
96) {
97    // SAFETY: LVGL holds the graphics lock and supplied a new Window allocation.
98    unsafe {
99        let window = object.cast::<Window>();
100
101        ptr::write(&raw mut (*window).event_queue, EventQueue::new());
102        ptr::write(&raw mut (*window).icon_text, IconText::new("Wi"));
103        ptr::write(&raw mut (*window).icon_color, Color::BLACK);
104        ptr::write(&raw mut (*window).waker, AtomicWaker::new());
105        ptr::write(&raw mut (*window).deferred_delete, DeferredLink::new());
106
107        lvgl::lv_obj_add_flag(object, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_EVENT_BUBBLE);
108        lvgl::lv_obj_set_style_border_width(object, 0, lvgl::LV_STATE_DEFAULT);
109        lvgl::lv_obj_set_style_radius(object, 0, lvgl::LV_STATE_DEFAULT);
110        crate::theme::set_surface(object, crate::theme::Surface::Background);
111    }
112}
113
114unsafe extern "C" fn window_destructor(
115    _class_p: *const lvgl::lv_obj_class_t,
116    obj: *mut lvgl::lv_obj_t,
117) {
118    // SAFETY: LVGL holds the graphics lock and supplied the live Window it
119    // is destroying. No owner can still access this instance.
120    unsafe {
121        WINDOWS.forget(NonNull::new_unchecked(obj));
122        ptr::drop_in_place(&raw mut (*obj.cast::<Window>()).waker);
123    }
124}
125
126/// Whether `target` is `root` or one of its descendants. Compares addresses
127/// with live objects only: `target` itself is never dereferenced.
128unsafe fn is_in_tree(root: *mut lvgl::lv_obj_t, target: *mut lvgl::lv_obj_t) -> bool {
129    unsafe {
130        root == target
131            || (0..lvgl::lv_obj_get_child_count(root) as i32)
132                .any(|index| is_in_tree(lvgl::lv_obj_get_child(root, index), target))
133    }
134}
135
136/// Null the target of every queued event whose widget is no longer below the
137/// window, and forget the presses of such widgets. Costs nothing per object
138/// and allocates nothing; the walk runs only when a descendant goes away while
139/// an event is queued or a press is followed.
140unsafe fn forget_dead_targets(window: *mut Window) {
141    unsafe {
142        let queue = &mut (*window).event_queue;
143        if queue.is_empty() && !queue.follows_presses() {
144            return;
145        }
146        let root = window as *mut lvgl::lv_obj_t;
147        queue.clear_dead_targets(|target| is_in_tree(root, target));
148    }
149}
150
151/// Whether LVGL may still send events for the current press of `device`: it
152/// is being read right now, or it still exists and is pressed. Compares
153/// addresses with live devices only: `device` itself is never dereferenced,
154/// since it may have been deleted.
155///
156/// LVGL reads one input device at a time and sends every event of a read
157/// before it returns, so a device that is released and not being read has
158/// sent the end of its press, if any. Its press is over.
159unsafe fn may_continue_press(device: event_queue::InputDevice) -> bool {
160    unsafe {
161        if ptr::eq(lvgl::lv_indev_active(), device) {
162            return true;
163        }
164        let mut input = lvgl::lv_indev_get_next(ptr::null_mut());
165        while !input.is_null() {
166            if ptr::eq(input, device) {
167                return lvgl::lv_indev_get_state(input)
168                    == lvgl::lv_indev_state_t_LV_INDEV_STATE_PRESSED;
169            }
170            input = lvgl::lv_indev_get_next(input);
171        }
172        false
173    }
174}
175
176/// Forget the presses LVGL will not end, to give their reservations back: a
177/// device released while the press belonged to another window (a keypad
178/// whose focus moved away), or deleted mid-press. Call it only with the
179/// graphics lock held.
180fn forget_ended_presses(queue: &mut EventQueue) {
181    if queue.follows_presses() {
182        queue.forget_ended_presses(|device| unsafe { may_continue_press(device) });
183    }
184}
185
186/// Log the events lost since the last report, at most once per
187/// [`crate::event_queue::LOSS_REPORT_INTERVAL`].
188fn report_losses(queue: &mut EventQueue) {
189    let now = unsafe { lvgl::lv_tick_get() };
190    if let Some(report) = queue.take_loss_report(now) {
191        log::warning!(
192            "Window event queue full: dropped {} events ({} since the window was created)",
193            report.lost,
194            report.total
195        );
196    }
197}
198
199unsafe extern "C" fn window_event_callback(
200    _class_p: *const lvgl::lv_obj_class_t,
201    event: *mut lvgl::lv_event_t,
202) {
203    // SAFETY: LVGL invokes this callback under the graphics lock, with a live
204    // event and Window. The callback borrows only the fields it accesses.
205    unsafe {
206        let res = lvgl::lv_obj_event_base(get_window_class(), event);
207
208        if res != lvgl::lv_result_t_LV_RESULT_OK {
209            return; // Not our event, ignore it
210        }
211
212        let code = lvgl::lv_event_get_code(event);
213
214        let window = lvgl::lv_event_get_current_target(event) as *mut Window;
215        let target = lvgl::lv_event_get_target(event) as *mut lvgl::lv_obj_t;
216
217        let (code, key) = match code {
218            // The window handles tree changes itself and never queues them:
219            // consumers ignore them, and building a page emits several per
220            // widget, which would fill the bounded ring and push out clicks.
221            lvgl::lv_event_code_t_LV_EVENT_CHILD_CHANGED => return,
222            lvgl::lv_event_code_t_LV_EVENT_CHILD_CREATED => {
223                let child = lvgl::lv_event_get_param(event) as *mut lvgl::lv_obj_t;
224                lvgl::lv_obj_add_flag(child, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_EVENT_BUBBLE);
225                return;
226            }
227            lvgl::lv_event_code_t_LV_EVENT_CHILD_DELETED => {
228                // A descendant was deleted or moved out. LVGL sends this to
229                // the direct parent after the object is freed, and it reaches
230                // the window by bubbling. Queued events aimed at it would
231                // otherwise match a widget created later at the same address.
232                // Remaining gap: user code that runs between the free and
233                // this event (a raw CHILD_CHANGED or scroll handler during a
234                // clean, a parent destructor, or a handler that stops
235                // bubbling) could create a widget at the freed address before
236                // the sweep, and that widget would then match a stale event.
237                forget_dead_targets(window);
238                return;
239            }
240            // The shared window queue has no subscription for hover events.
241            lvgl::lv_event_code_t_LV_EVENT_HOVER_OVER
242            | lvgl::lv_event_code_t_LV_EVENT_HOVER_LEAVE => {
243                return;
244            }
245            lvgl::lv_event_code_t_LV_EVENT_KEY => {
246                let key = lvgl::lv_indev_get_key(lvgl::lv_indev_active());
247                let key = Key::from(key);
248                (code, Some(key))
249            }
250            lvgl::lv_event_code_t_LV_EVENT_DRAW_MAIN
251            | lvgl::lv_event_code_t_LV_EVENT_DRAW_MAIN_BEGIN
252            | lvgl::lv_event_code_t_LV_EVENT_DRAW_MAIN_END
253            | lvgl::lv_event_code_t_LV_EVENT_DRAW_POST
254            | lvgl::lv_event_code_t_LV_EVENT_DRAW_POST_BEGIN
255            | lvgl::lv_event_code_t_LV_EVENT_DRAW_POST_END
256            | lvgl::lv_event_code_t_LV_EVENT_DRAW_TASK_ADDED
257            | lvgl::lv_event_code_t_LV_EVENT_REFR_EXT_DRAW_SIZE
258            | lvgl::lv_event_code_t_LV_EVENT_GET_SELF_SIZE
259            | lvgl::lv_event_code_t_LV_EVENT_COVER_CHECK
260            | lvgl::lv_event_code_t_LV_EVENT_HIT_TEST
261            | lvgl::lv_event_code_t_LV_EVENT_INVALIDATE_AREA
262            | lvgl::lv_event_code_t_LV_EVENT_LAYOUT_CHANGED => {
263                // Drawing, hit testing and layout: their parameters only live
264                // during the dispatch, and no consumer handles them.
265                return;
266            }
267            _ => (code, None),
268        };
269
270        let kind = EventKind::from_lvgl_code(code);
271        // Codes without a kind (state changes, checked/unchecked) would reach
272        // consumers as an opaque `Last` while taking a slot in the bounded ring.
273        if kind == EventKind::Last {
274            return;
275        }
276
277        let mut queued = Event::new(kind, target, key);
278        if matches!(
279            code,
280            lvgl::lv_event_code_t_LV_EVENT_PRESSED
281                | lvgl::lv_event_code_t_LV_EVENT_PRESSING
282                | lvgl::lv_event_code_t_LV_EVENT_RELEASED
283        ) {
284            let input = lvgl::lv_event_get_indev(event);
285            if !input.is_null()
286                && lvgl::lv_indev_get_type(input) == lvgl::lv_indev_type_t_LV_INDEV_TYPE_POINTER
287            {
288                let mut point = lvgl::lv_point_t::default();
289                let mut area = lvgl::lv_area_t::default();
290                lvgl::lv_indev_get_point(input, &mut point);
291                lvgl::lv_obj_get_content_coords(target, &mut area);
292                queued.pointer = Some([
293                    point.x - area.x1,
294                    point.y - area.y1,
295                    area.x2 - area.x1 + 1,
296                    area.y2 - area.y1 + 1,
297                ]);
298            }
299        }
300        // LVGL passes the input device as the parameter of every press event
301        // and of a device reset.
302        let device = if event_queue::carries_input_device(kind) {
303            lvgl::lv_event_get_param(event) as event_queue::InputDevice
304        } else {
305            ptr::null()
306        };
307        if kind == EventKind::Pressed {
308            // A new press needs room: take back what ended presses hold.
309            forget_ended_presses(&mut (*window).event_queue);
310        }
311        if (*window).event_queue.push(queued, device).lost_an_event() {
312            report_losses(&mut (*window).event_queue);
313        }
314        (*window).waker.wake();
315    }
316}
317
318impl Window {
319    /// Create a new window.
320    ///
321    /// The caller owns the new window: give it to [`OwnedWindow::from_raw`],
322    /// or delete it itself with `lv_obj_delete`, exactly once.
323    ///
324    /// # Arguments
325    ///
326    /// * `parent` - The parent object of the window.
327    ///
328    /// # Safety
329    ///
330    /// `parent` must be a live LVGL object, and the caller must hold the
331    /// graphics lock.
332    pub unsafe fn new(parent: *mut lvgl::lv_obj_t) -> Result<NonNull<Self>> {
333        // SAFETY: the caller holds the graphics lock and keeps the parent live.
334        let object = unsafe { lvgl::lv_obj_class_create_obj(get_window_class(), parent) };
335        let window = NonNull::new(object.cast()).ok_or(Error::FailedToCreateObject)?;
336        // SAFETY: the object was allocated above and the lock remains held.
337        unsafe { lvgl::lv_obj_class_init_obj(object) };
338        Ok(window)
339    }
340
341    /// Read the oldest queued event without removing it.
342    ///
343    /// # Safety
344    ///
345    /// The caller holds the graphics lock and `window` points to a live Window.
346    pub unsafe fn peek_event(window: NonNull<Self>) -> Option<Event> {
347        // SAFETY: the caller keeps this queue alive and excludes its writers.
348        unsafe { (*window.as_ptr()).event_queue.front().cloned() }
349    }
350
351    /// Take the oldest queued event. See [`Window`] for the queue policy.
352    ///
353    /// # Safety
354    ///
355    /// The caller holds the graphics lock and `window` points to a live Window.
356    pub unsafe fn pop_event(window: NonNull<Self>) -> Option<Event> {
357        // SAFETY: the caller keeps this queue alive and excludes its writers.
358        let queue = unsafe { &mut (*window.as_ptr()).event_queue };
359        if queue.has_unreported_losses() {
360            report_losses(queue);
361        }
362        forget_ended_presses(queue);
363        queue.pop_front()
364    }
365
366    /// Check whether this window has a pending close request.
367    ///
368    /// # Safety
369    ///
370    /// The caller holds the graphics lock and `window` points to a live Window.
371    pub(crate) unsafe fn has_close_request(window: NonNull<Self>) -> bool {
372        // SAFETY: the caller keeps this queue alive and excludes its writers.
373        unsafe { (*window.as_ptr()).event_queue.has_close_request() }
374    }
375
376    /// Count events lost to queue overflow since the window was created.
377    ///
378    /// # Safety
379    ///
380    /// The caller holds the graphics lock and `window` points to a live Window.
381    pub unsafe fn dropped_event_count(window: NonNull<Self>) -> u32 {
382        // SAFETY: the caller keeps this queue alive and excludes its writers.
383        unsafe { (*window.as_ptr()).event_queue.dropped() }
384    }
385
386    /// Forget queued targets before LVGL can reuse their addresses.
387    /// Retain press boundaries and close requests with a null target.
388    ///
389    /// # Safety
390    ///
391    /// The caller holds the graphics lock and `window` points to a live Window.
392    pub unsafe fn discard_events_for_target(window: NonNull<Self>, target: *mut lvgl::lv_obj_t) {
393        // SAFETY: the caller keeps this queue alive and excludes its writers.
394        unsafe { (*window.as_ptr()).event_queue.discard_target(target) };
395    }
396
397    /// Preserve event codes when a recycled address gets a new capability.
398    ///
399    /// # Safety
400    ///
401    /// The caller holds the graphics lock and `window` points to a live Window.
402    pub(crate) unsafe fn clear_event_targets_for(
403        window: NonNull<Self>,
404        target: *mut lvgl::lv_obj_t,
405    ) {
406        // SAFETY: the caller keeps this queue alive and excludes its writers.
407        unsafe { (*window.as_ptr()).event_queue.clear_target(target) };
408    }
409
410    /// Copy the icon while the window is live and the lock is held.
411    ///
412    /// # Safety
413    ///
414    /// The caller holds the graphics lock and `window` points to a live Window.
415    pub(crate) unsafe fn icon(window: NonNull<Self>) -> (IconText, Color) {
416        // SAFETY: the caller keeps these fields alive and excludes their writers.
417        unsafe { ((*window.as_ptr()).icon_text, (*window.as_ptr()).icon_color) }
418    }
419
420    /// # Safety
421    ///
422    /// The caller holds the graphics lock and `window` points to a live Window.
423    pub(crate) unsafe fn set_icon(window: NonNull<Self>, text: &str, color: Color) {
424        // SAFETY: the caller keeps these fields alive and excludes other accesses.
425        unsafe {
426            (*window.as_ptr()).icon_text = IconText::new(text);
427            (*window.as_ptr()).icon_color = color;
428        }
429    }
430
431    /// Convert a raw pointer to a window object.
432    ///
433    /// # Returns
434    ///
435    /// * `Window` - The raw pointer to the window.
436    ///
437    /// # Safety
438    ///
439    /// The caller holds the graphics lock. `window` is null or points to a
440    /// live LVGL object with the provenance of its full instance.
441    pub unsafe fn from_raw(window: *mut lvgl::lv_obj_t) -> Option<NonNull<Self>> {
442        if window.is_null() {
443            return None;
444        }
445
446        // SAFETY: the caller holds the graphics lock and the object is live.
447        let class = unsafe { lvgl::lv_obj_get_class(window) };
448
449        if class != get_window_class() {
450            return None;
451        }
452
453        NonNull::new(window as *mut Self)
454    }
455}
456
457/// The single owner of a [`Window`]: it deletes the window when dropped.
458///
459/// Nothing else deletes an owned window. The safe layer refuses to delete,
460/// clean away, own, reparent or reorder a window or an object containing one
461/// (see `lvgl_rust_external_class_policy`), raw code needs `unsafe`, and
462/// [`Window`] has no public delete. A window therefore lives exactly as long
463/// as its owner, which deletes it once.
464///
465/// LVGL can update a window while its owner waits for events. The owner
466/// exposes raw pointers for interoperation and uses a session for access.
467/// The waker is atomic and needs no session.
468///
469/// Taking ownership of a raw window requires `unsafe`:
470///
471/// ```compile_fail,E0133
472/// fn adopt(window: core::ptr::NonNull<graphics::Window>) -> graphics::OwnedWindow {
473///     graphics::OwnedWindow::from_raw(window)
474/// }
475/// ```
476///
477/// Safe code cannot borrow the window or read events without a session.
478///
479/// ```compile_fail,E0614
480/// fn borrow(window: &graphics::OwnedWindow) {
481///     let _ = &**window;
482/// }
483/// ```
484///
485/// ```compile_fail,E0061
486/// fn read(window: &graphics::OwnedWindow) {
487///     window.peek_event();
488/// }
489/// ```
490pub struct OwnedWindow(NonNull<Window>);
491
492impl OwnedWindow {
493    /// Take ownership of a raw window.
494    ///
495    /// # Safety
496    ///
497    /// `window` must point to a live window (see [`Window::new`]) that
498    /// nothing else owns or deletes. LVGL must stay initialized while the owner
499    /// exists. Every window created inside it must be deleted first.
500    pub unsafe fn from_raw(window: NonNull<Window>) -> Self {
501        Self(window)
502    }
503
504    /// Give up ownership without deleting the window. The caller becomes its
505    /// owner: it deletes the window once, under the graphics lock, or hands it
506    /// back to [`OwnedWindow::from_raw`].
507    pub fn into_raw(self) -> NonNull<Window> {
508        ManuallyDrop::new(self).0
509    }
510
511    /// Delete the window in the current session.
512    pub fn delete(self, _lvgl: &mut Lvgl) {
513        let window = self.into_raw();
514        // SAFETY: the session holds the graphics lock and this value owned the window.
515        unsafe { lvgl::lv_obj_delete(window.as_ptr().cast()) };
516    }
517
518    /// Wait for the graphics lock and delete the window.
519    pub async fn close(self) -> Result<()> {
520        crate::manager::lock_graphics()
521            .await
522            .with_lvgl(|lvgl| self.delete(lvgl))
523    }
524
525    /// The window's LVGL object, for the raw bindings.
526    pub fn as_object(&self) -> *mut lvgl::lv_obj_t {
527        self.0.as_ptr().cast()
528    }
529
530    /// The window's LVGL object, for the raw bindings.
531    pub fn as_object_mutable(&mut self) -> *mut lvgl::lv_obj_t {
532        self.as_object()
533    }
534
535    pub fn get_identifier(&self) -> usize {
536        self.as_object() as usize
537    }
538
539    pub fn peek_event(&self, _lvgl: &Lvgl) -> Option<Event> {
540        // SAFETY: the owner keeps the window live and the session excludes writers.
541        unsafe { Window::peek_event(self.0) }
542    }
543
544    /// See [`Window::pop_event`].
545    pub fn pop_event(&mut self, _lvgl: &mut Lvgl) -> Option<Event> {
546        // SAFETY: the owner keeps the window live and the session holds the lock.
547        unsafe { Window::pop_event(self.0) }
548    }
549
550    /// See [`Window::dropped_event_count`].
551    pub fn dropped_event_count(&self, _lvgl: &Lvgl) -> u32 {
552        // SAFETY: the owner keeps the window live and the session holds the lock.
553        unsafe { Window::dropped_event_count(self.0) }
554    }
555
556    /// See [`Window::discard_events_for_target`].
557    pub fn discard_events_for_target(&mut self, _lvgl: &mut Lvgl, target: *mut lvgl::lv_obj_t) {
558        // SAFETY: the owner keeps the window live and the session holds the lock.
559        let queue = unsafe { &mut (*self.0.as_ptr()).event_queue };
560        queue.discard_target(target);
561    }
562
563    pub fn get_icon<'a>(&'a self, _lvgl: &'a Lvgl) -> (&'a str, Color) {
564        // SAFETY: the owner keeps the window live. The session holds the lock,
565        // and the borrow of the owner prevents updates to its icon.
566        unsafe {
567            let window = self.0.as_ptr();
568            ((*window).icon_text.as_str(), (*window).icon_color)
569        }
570    }
571
572    /// Set the icon using up to two Unicode scalar values.
573    /// Text after a NUL is ignored.
574    pub fn set_icon(&mut self, _lvgl: &mut Lvgl, icon_string: &str, icon_color: Color) {
575        // SAFETY: the owner keeps the window live and the session holds the lock.
576        unsafe { Window::set_icon(self.0, icon_string, icon_color) };
577    }
578
579    pub fn wake_up(&self) {
580        self.waker().wake();
581    }
582
583    pub fn register_waker(&self, waker: &core::task::Waker) {
584        self.waker().register(waker);
585    }
586
587    fn waker(&self) -> &AtomicWaker {
588        // SAFETY: the owner keeps the Window live. Only the atomic waker field
589        // is borrowed, so LVGL can write the queue and its other fields.
590        unsafe { &(*self.0.as_ptr()).waker }
591    }
592}
593
594impl From<OwnedWindow> for NonNull<Window> {
595    fn from(window: OwnedWindow) -> Self {
596        window.into_raw()
597    }
598}
599
600impl Drop for OwnedWindow {
601    fn drop(&mut self) {
602        let object = self.0.cast();
603        let deleted = crate::manager::try_lock_graphics().is_some_and(|mut guard| {
604            guard
605                .with_lvgl(|_lvgl| {
606                    // SAFETY: the session holds the graphics lock. This owner
607                    // keeps the object live until it deletes it.
608                    unsafe { lvgl::lv_obj_delete(object.as_ptr()) };
609                })
610                .is_ok()
611        });
612        if !deleted {
613            // SAFETY: the Window stays live until its owner requests deletion.
614            // The destructor unlinks it if LVGL deletes it before the drain.
615            unsafe { WINDOWS.request_delete(object) };
616        }
617    }
618}