Skip to main content

graphics/
display.rs

1use alloc::boxed::Box;
2use file_system::{ControlCommand, DirectCharacterDevice};
3use shared::AnyByLayout;
4
5use core::{ffi::c_void, ptr::null_mut, slice};
6use portable_atomic::{AtomicBool, Ordering};
7
8use crate::{
9    Area, Error, GET_BRIGHTNESS, GET_RESOLUTION, Point, RenderingColor, Result, SET_BRIGHTNESS,
10    SET_DRAWING_AREA, WAS_RESIZED, draw_buffer::Buffer,
11};
12
13use super::lvgl;
14
15fn checked_buffer_size_bytes(pixel_count: usize, bytes_per_pixel: usize) -> Option<u32> {
16    u32::try_from(pixel_count.checked_mul(bytes_per_pixel)?).ok()
17}
18
19struct UserData {
20    device: &'static dyn DirectCharacterDevice,
21}
22
23pub struct Display {
24    display: *mut lvgl::lv_display_t,
25    user_data: core::ptr::NonNull<UserData>,
26    _buffer_1: Buffer,
27    _buffer_2: Option<Buffer>,
28}
29
30unsafe impl Send for Display {}
31
32unsafe impl Sync for Display {}
33
34unsafe extern "C" fn binding_callback_function(
35    display: *mut lvgl::lv_disp_t,
36    area: *const lvgl::lv_area_t,
37    data: *mut u8,
38) {
39    let lv_area = unsafe { *area };
40    let mut area = Area::new(
41        Point::new(lv_area.x1 as i16, lv_area.y1 as i16),
42        Point::new(lv_area.x2 as i16, lv_area.y2 as i16),
43    );
44
45    let buffer_size: usize =
46        (area.get_width()) as usize * (area.get_height()) as usize * size_of::<RenderingColor>();
47
48    let buffer = unsafe { slice::from_raw_parts(data as *const u8, buffer_size) };
49
50    let user_data = unsafe { &*(lvgl::lv_display_get_user_data(display) as *const UserData) };
51
52    let device = &user_data.device;
53
54    // A failed flush drops the frame: LVGL must still learn that the flush is
55    // over, or rendering stops, and a panic here would stop the whole system.
56    let result = device
57        .control_sync(
58            SET_DRAWING_AREA::IDENTIFIER,
59            AnyByLayout::from_mutable(&mut area),
60            AnyByLayout::NONE,
61        )
62        .and_then(|()| device.write_sync(buffer, 0));
63    if let Err(error) = result
64        && !FLUSH_ERROR_REPORTED.swap(true, Ordering::Relaxed)
65    {
66        log::error!("Display flush failed, frames are dropped: {error}");
67    }
68
69    unsafe { lvgl::lv_display_flush_ready(display) };
70}
71
72fn brightness_error(error: file_system::IoErrorKind) -> Error {
73    match error {
74        file_system::IoErrorKind::Unsupported => Error::Unsupported,
75        file_system::IoErrorKind::InvalidArgument => Error::InvalidParameter,
76        _ => Error::DeviceFailure,
77    }
78}
79
80/// Whether a flush error was logged: only the first one is, so that a failing
81/// screen does not flood the log at the frame rate.
82static FLUSH_ERROR_REPORTED: AtomicBool = AtomicBool::new(false);
83
84impl Drop for Display {
85    fn drop(&mut self) {
86        // SAFETY: construction requires this display to be dropped under the
87        // graphics lock, before LVGL deinitializes.
88        unsafe {
89            lvgl::lv_display_delete(self.display);
90            drop(Box::from_raw(self.user_data.as_ptr()));
91        }
92    }
93}
94
95impl Display {
96    /// Create a display and attach its drawing buffers.
97    ///
98    /// # Safety
99    ///
100    /// LVGL must be initialized. Hold the graphics lock during creation and
101    /// while dropping the display. Drop it before LVGL deinitializes.
102    pub unsafe fn new(
103        device: &'static dyn DirectCharacterDevice,
104        buffer_size: usize,
105        double_buffered: bool,
106    ) -> Result<Self> {
107        let buffer_size_bytes =
108            checked_buffer_size_bytes(buffer_size, core::mem::size_of::<RenderingColor>())
109                .ok_or(Error::OutOfMemory)?;
110
111        // Get the resolution from the device.
112        let mut resolution = Point::new(0, 0);
113        device
114            .control_sync(
115                GET_RESOLUTION::IDENTIFIER,
116                AnyByLayout::NONE,
117                AnyByLayout::from_mutable(&mut resolution),
118            )
119            .expect("Error getting resolution");
120
121        // Create the display.
122        // SAFETY: the caller holds the lock and LVGL is initialized.
123        let lvgl_display: *mut lvgl_rust_sys::_lv_display_t = unsafe {
124            lvgl::lv_display_create(resolution.get_x() as i32, resolution.get_y() as i32)
125        };
126
127        if lvgl_display.is_null() {
128            return Err(Error::OutOfMemory);
129        }
130
131        // Set the buffer(s) and the render mode.
132        let mut buffer_1 = Buffer::new(buffer_size);
133
134        let mut buffer_2 = if double_buffered {
135            Some(Buffer::new(buffer_size))
136        } else {
137            None
138        };
139        debug_assert_eq!(buffer_1.size_in_bytes(), buffer_size_bytes as usize);
140
141        // SAFETY: the display is live under the graphics lock. The buffers
142        // have the specified size and stay allocated until display deletion.
143        unsafe {
144            lvgl::lv_display_set_buffers(
145                lvgl_display,
146                buffer_1.as_mutable_pointer() as *mut c_void,
147                buffer_2.as_mut().map_or(null_mut(), |buffer| {
148                    buffer.as_mutable_pointer() as *mut c_void
149                }),
150                buffer_size_bytes,
151                lvgl::lv_display_render_mode_t_LV_DISPLAY_RENDER_MODE_PARTIAL,
152            )
153        }
154
155        // LVGL checks the buffers, for example their alignment, and returns
156        // without registering them when a check fails: make sure it took
157        // them, rather than return a display that cannot render.
158        // SAFETY: the graphics lock protects the live display and its active buffer.
159        let registered = unsafe {
160            let active = lvgl::lv_display_get_buf_active(lvgl_display);
161            !active.is_null() && (*active).data == buffer_1.as_mutable_pointer() as *mut u8
162        };
163        if !registered {
164            // SAFETY: the new display is live and the caller still holds the lock.
165            unsafe { lvgl::lv_display_delete(lvgl_display) };
166            return Err(Error::FailedToRegister);
167        }
168
169        let user_data = core::ptr::NonNull::from(Box::leak(Box::new(UserData { device })));
170
171        // SAFETY: the display owns this allocation until after deletion.
172        unsafe { lvgl::lv_display_set_user_data(lvgl_display, user_data.as_ptr().cast()) };
173
174        // SAFETY: the display is live under the lock. Its buffers and user
175        // data stay allocated until after the last callback.
176        unsafe { lvgl::lv_display_set_flush_cb(lvgl_display, Some(binding_callback_function)) }
177
178        Ok(Self {
179            display: lvgl_display,
180            user_data,
181            _buffer_1: buffer_1,
182            _buffer_2: buffer_2,
183        })
184    }
185
186    /// Resize the LVGL display when the screen device reports a change.
187    ///
188    /// # Safety
189    ///
190    /// Hold the graphics lock.
191    pub(crate) unsafe fn check_for_resizing(&self) {
192        let mut was_resize = 0u8;
193
194        self.device()
195            .control_sync(
196                WAS_RESIZED::IDENTIFIER,
197                AnyByLayout::NONE,
198                AnyByLayout::from_mutable(&mut was_resize),
199            )
200            .expect("Error checking if display was resized");
201
202        // The payload is a flag byte; an unknown byte is not a valid flag.
203        if !bool::try_from(was_resize).expect("Invalid WAS_RESIZED payload") {
204            return;
205        }
206
207        let mut resolution = Point::new(0, 0);
208
209        self.device()
210            .control_sync(
211                GET_RESOLUTION::IDENTIFIER,
212                AnyByLayout::NONE,
213                AnyByLayout::from_mutable(&mut resolution),
214            )
215            .expect("Error getting resolution");
216
217        // SAFETY: the caller holds the lock and this display is live.
218        unsafe {
219            lvgl::lv_display_set_resolution(
220                self.display,
221                resolution.get_x() as i32,
222                resolution.get_y() as i32,
223            );
224        }
225    }
226
227    fn device(&self) -> &'static dyn DirectCharacterDevice {
228        // SAFETY: the display owns this allocation and the device never changes.
229        unsafe { self.user_data.as_ref().device }
230    }
231
232    /// Read the screen's backlight brightness, from
233    /// [`BRIGHTNESS_OFF`](crate::BRIGHTNESS_OFF) to
234    /// [`BRIGHTNESS_FULL`](crate::BRIGHTNESS_FULL).
235    ///
236    /// Returns [`Error::Unsupported`] when the screen has no brightness
237    /// control. This only talks to the screen device, not to LVGL, so it does
238    /// not need the LVGL lock.
239    pub fn get_brightness(&self) -> Result<u8> {
240        let mut level = 0u8;
241        self.device()
242            .control_sync(
243                GET_BRIGHTNESS::IDENTIFIER,
244                AnyByLayout::NONE,
245                AnyByLayout::from_mutable(&mut level),
246            )
247            .map_err(brightness_error)?;
248        Ok(level)
249    }
250
251    /// Set the screen's backlight brightness; see [`Display::get_brightness`].
252    pub fn set_brightness(&self, level: u8) -> Result<()> {
253        let mut level = level;
254        self.device()
255            .control_sync(
256                SET_BRIGHTNESS::IDENTIFIER,
257                AnyByLayout::from_mutable(&mut level),
258                AnyByLayout::NONE,
259            )
260            .map_err(brightness_error)
261    }
262
263    pub fn get_lvgl_display(&self) -> *mut lvgl::lv_display_t {
264        self.display
265    }
266
267    /// Get the active screen.
268    ///
269    /// # Safety
270    ///
271    /// Hold the graphics lock.
272    pub unsafe fn get_object(&self) -> *mut lvgl::lv_obj_t {
273        // SAFETY: the caller holds the lock and this display is live.
274        unsafe { lvgl::lv_display_get_screen_active(self.display) }
275    }
276
277    /// Get the current display resolution.
278    ///
279    /// # Safety
280    ///
281    /// Hold the graphics lock.
282    pub unsafe fn get_resolution(&self) -> Point {
283        // SAFETY: the caller holds the lock and this display is live.
284        unsafe {
285            Point::new(
286                lvgl::lv_display_get_horizontal_resolution(self.display) as i16,
287                lvgl::lv_display_get_vertical_resolution(self.display) as i16,
288            )
289        }
290    }
291
292    /// The caller holds the graphics lock.
293    pub(crate) unsafe fn capture_screen(&self) -> Result<crate::ScreenSnapshot> {
294        // SAFETY: the caller holds the lock.
295        let resolution = unsafe { self.get_resolution() };
296        if resolution.get_x() <= 0
297            || resolution.get_y() <= 0
298            || (resolution.get_x() as usize)
299                .checked_mul(resolution.get_y() as usize)
300                .is_none_or(|pixels| pixels > crate::SCREEN_SNAPSHOT_MAX_PIXELS)
301        {
302            return Err(crate::Error::InvalidParameter);
303        }
304        // SAFETY: the caller holds the lock and the display keeps the screen live.
305        let mut capture = crate::screenshot::capture_screen(unsafe { self.get_object() })?;
306        // SAFETY: the caller holds the lock and the display keeps the layers live.
307        unsafe {
308            for layer in [
309                lvgl::lv_display_get_layer_top(self.display),
310                lvgl::lv_display_get_layer_sys(self.display),
311            ] {
312                if lvgl::lv_obj_get_child_count(layer) == 0 {
313                    continue;
314                }
315                let overlay = crate::screenshot::capture_screen(layer)?;
316                crate::screenshot::composite(&mut capture, &overlay)?;
317            }
318        }
319        Ok(capture)
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    use super::checked_buffer_size_bytes;
326
327    #[test]
328    fn lvgl_buffer_size_is_in_bytes_for_supported_color_depths() {
329        assert_eq!(checked_buffer_size_bytes(800, 2), Some(1600));
330        assert_eq!(checked_buffer_size_bytes(800, 4), Some(3200));
331    }
332
333    #[test]
334    fn lvgl_buffer_size_rejects_overflow() {
335        assert_eq!(checked_buffer_size_bytes(usize::MAX, 4), None);
336        assert_eq!(checked_buffer_size_bytes(u32::MAX as usize, 2), None);
337    }
338}