1use alloc::vec::Vec;
2
3use crate::{Error, Result, lvgl};
4
5pub const SCREEN_SNAPSHOT_MAX_PIXELS: usize = 2_073_600;
7
8#[derive(Clone, Debug, PartialEq, Eq)]
10pub struct ScreenSnapshot {
11 pub width: u16,
12 pub height: u16,
13 pub pixels_rgba: Vec<u8>,
14}
15
16fn copy_strided_bgra_to_rgba(
17 width: usize,
18 height: usize,
19 stride: usize,
20 source: &[u8],
21) -> Result<Vec<u8>> {
22 let pixel_count = width.checked_mul(height).ok_or(Error::InvalidParameter)?;
23 let row_bytes = width.checked_mul(4).ok_or(Error::InvalidParameter)?;
24 let source_len = stride.checked_mul(height).ok_or(Error::InvalidParameter)?;
25 if width == 0
26 || height == 0
27 || pixel_count > SCREEN_SNAPSHOT_MAX_PIXELS
28 || stride < row_bytes
29 || source.len() < source_len
30 {
31 return Err(Error::InvalidParameter);
32 }
33
34 let output_len = pixel_count.checked_mul(4).ok_or(Error::InvalidParameter)?;
35 let mut pixels_rgba = Vec::new();
36 pixels_rgba
37 .try_reserve_exact(output_len)
38 .map_err(|_| Error::OutOfMemory)?;
39 for row in 0..height {
40 let row_start = row * stride;
41 let (row_pixels, _) = source[row_start..row_start + row_bytes].as_chunks::<4>();
42 for pixel in row_pixels {
43 pixels_rgba.extend_from_slice(&[pixel[2], pixel[1], pixel[0], pixel[3]]);
46 }
47 }
48 Ok(pixels_rgba)
49}
50
51struct DrawBuffer(*mut lvgl::lv_draw_buf_t);
52
53impl Drop for DrawBuffer {
54 fn drop(&mut self) {
55 unsafe { lvgl::lv_draw_buf_destroy(self.0) };
56 }
57}
58
59pub(crate) fn capture_screen(object: *mut lvgl::lv_obj_t) -> Result<ScreenSnapshot> {
60 if object.is_null() {
61 return Err(Error::NotAvailable);
62 }
63
64 let (expected_width, expected_height) = unsafe {
68 lvgl::lv_obj_update_layout(object);
69 let width = lvgl::lv_obj_get_width(object);
70 let height = lvgl::lv_obj_get_height(object);
71 let ext = lvgl::lv_obj_get_ext_draw_size(object);
72 let twice_ext = ext.checked_mul(2).ok_or(Error::InvalidParameter)?;
73 (
74 width
75 .checked_add(twice_ext)
76 .ok_or(Error::InvalidParameter)?,
77 height
78 .checked_add(twice_ext)
79 .ok_or(Error::InvalidParameter)?,
80 )
81 };
82 if expected_width <= 0
83 || expected_height <= 0
84 || (expected_width as usize)
85 .checked_mul(expected_height as usize)
86 .is_none_or(|area| area > SCREEN_SNAPSHOT_MAX_PIXELS)
87 {
88 return Err(Error::InvalidParameter);
89 }
90
91 let draw_buf =
92 unsafe { lvgl::snapshot_take(object, lvgl::lv_color_format_t_LV_COLOR_FORMAT_ARGB8888) };
93 if draw_buf.is_null() {
94 return Err(Error::OutOfMemory);
95 }
96 let draw_buf = DrawBuffer(draw_buf);
97
98 let header = unsafe { &(*draw_buf.0).header };
99 let width = header.w() as usize;
100 let height = header.h() as usize;
101 let pixel_count = width.checked_mul(height).ok_or(Error::InvalidParameter)?;
102 if width == 0 || height == 0 || pixel_count > SCREEN_SNAPSHOT_MAX_PIXELS {
103 return Err(Error::InvalidParameter);
104 }
105
106 let width_u16 = u16::try_from(width).map_err(|_| Error::InvalidParameter)?;
107 let height_u16 = u16::try_from(height).map_err(|_| Error::InvalidParameter)?;
108 let row_bytes = width.checked_mul(4).ok_or(Error::InvalidParameter)?;
109 let stride = header.stride() as usize;
110 let source_len = stride.checked_mul(height).ok_or(Error::InvalidParameter)?;
111 let source = unsafe { &*draw_buf.0 };
112 if header.cf() != lvgl::lv_color_format_t_LV_COLOR_FORMAT_ARGB8888
113 || stride < row_bytes
114 || source.data.is_null()
115 || (source.data_size as usize) < source_len
116 {
117 return Err(Error::InvalidParameter);
118 }
119
120 let source_bytes = unsafe { core::slice::from_raw_parts(source.data, source_len) };
121 let pixels_rgba = copy_strided_bgra_to_rgba(width, height, stride, source_bytes)?;
122
123 Ok(ScreenSnapshot {
124 width: width_u16,
125 height: height_u16,
126 pixels_rgba,
127 })
128}
129
130pub(crate) fn composite(base: &mut ScreenSnapshot, overlay: &ScreenSnapshot) -> Result<()> {
132 if base.width != overlay.width
133 || base.height != overlay.height
134 || base.pixels_rgba.len() != overlay.pixels_rgba.len()
135 {
136 return Err(Error::InvalidParameter);
137 }
138 for (dst, src) in base
139 .pixels_rgba
140 .as_chunks_mut::<4>()
141 .0
142 .iter_mut()
143 .zip(overlay.pixels_rgba.as_chunks::<4>().0.iter())
144 {
145 let sa = u32::from(src[3]);
146 let da = u32::from(dst[3]);
147 let alpha = sa * 255 + da * (255 - sa);
148 if alpha == 0 {
149 dst.fill(0);
150 continue;
151 }
152 for channel in 0..3 {
153 dst[channel] = ((u32::from(src[channel]) * sa * 255
154 + u32::from(dst[channel]) * da * (255 - sa)
155 + alpha / 2)
156 / alpha) as u8;
157 }
158 dst[3] = ((alpha + 127) / 255) as u8;
159 }
160 Ok(())
161}
162
163#[cfg(test)]
164mod tests {
165 use alloc::vec;
166
167 use super::*;
168
169 #[test]
170 fn screen_snapshot_copies_strided_rgba_pixels() {
171 let source = [3, 2, 1, 4, 0, 0, 0, 0, 30, 20, 10, 40, 0, 0, 0, 0];
172 assert_eq!(
173 copy_strided_bgra_to_rgba(1, 2, 8, &source),
174 Ok(vec![1, 2, 3, 4, 10, 20, 30, 40])
175 );
176 }
177
178 #[test]
179 fn screen_snapshot_rejects_malformed_draw_buffer() {
180 assert_eq!(
181 copy_strided_bgra_to_rgba(2, 1, 7, &[0; 8]),
182 Err(Error::InvalidParameter)
183 );
184 assert_eq!(
185 copy_strided_bgra_to_rgba(2, 1, 8, &[0; 7]),
186 Err(Error::InvalidParameter)
187 );
188 }
189
190 #[test]
191 fn screen_snapshot_rejects_dimensions_over_limit() {
192 assert_eq!(
193 copy_strided_bgra_to_rgba(SCREEN_SNAPSHOT_MAX_PIXELS + 1, 1, 0, &[]),
194 Err(Error::InvalidParameter)
195 );
196 }
197}