Skip to main content

graphics/
headless_screen.rs

1//! A screen device that validates flushes without presenting pixels.
2
3use core::fmt;
4
5use crate::{
6    Area, GET_RESOLUTION, Point, RenderingColor, SCREEN_SNAPSHOT_MAX_PIXELS, SET_DRAWING_AREA,
7    WAS_RESIZED,
8};
9use file_system::{
10    ControlCommand, ControlCommandIdentifier, DirectBaseOperations, DirectCharacterDevice,
11    MountOperations, Size,
12};
13use shared::{AnyByLayout, align_slice_to};
14use std::sync::Mutex;
15
16/// Error returned when creating a [`HeadlessScreenDevice`].
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum HeadlessError {
19    /// The requested width or height is non-positive, or the total pixel count
20    /// exceeds the supported snapshot limit.
21    InvalidResolution,
22}
23
24impl fmt::Display for HeadlessError {
25    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            Self::InvalidResolution => formatter.write_str("invalid headless resolution"),
28        }
29    }
30}
31
32/// Character device implementing a headless display for host drivers and tests.
33///
34/// Tracks the active drawing area and validates flush buffer alignment and
35/// byte counts against the configured resolution without presenting pixels.
36pub struct HeadlessScreenDevice {
37    resolution: Point,
38    drawing_area: Mutex<Area>,
39}
40
41impl HeadlessScreenDevice {
42    /// Create a headless screen device for the given pixel `resolution`.
43    pub fn new(resolution: Point) -> Result<Self, HeadlessError> {
44        validate_resolution(resolution).map_err(|_| HeadlessError::InvalidResolution)?;
45        Ok(Self {
46            resolution,
47            drawing_area: Mutex::new(Area::default()),
48        })
49    }
50}
51
52impl DirectBaseOperations for HeadlessScreenDevice {
53    fn read(
54        &self,
55        _context: &mut core::task::Context<'_>,
56        _: &mut [u8],
57        _: Size,
58    ) -> core::task::Poll<file_system::Result<usize>> {
59        file_system::ready(|| Err(file_system::IoErrorKind::Unsupported))
60    }
61
62    fn write(
63        &self,
64        _context: &mut core::task::Context<'_>,
65        buffer: &[u8],
66        _: Size,
67    ) -> core::task::Poll<file_system::Result<usize>> {
68        file_system::ready(|| {
69            let pixels: &[RenderingColor] =
70                align_slice_to(buffer).ok_or(file_system::IoErrorKind::InvalidArgument)?;
71            let expected = self
72                .drawing_area
73                .lock()
74                .map_err(|_| file_system::IoErrorKind::InputOutput)
75                .and_then(|area| {
76                    validate_flush(self.resolution, *area, size_of::<RenderingColor>())
77                        .map_err(|_| file_system::IoErrorKind::InvalidArgument)
78                })?;
79            if pixels.len().checked_mul(size_of::<RenderingColor>()) != Some(expected)
80                || buffer.len() != expected
81            {
82                return Err(file_system::IoErrorKind::InvalidArgument);
83            }
84            Ok(buffer.len())
85        })
86    }
87
88    fn control(
89        &self,
90        _context: &mut core::task::Context<'_>,
91        command: ControlCommandIdentifier,
92        input: &AnyByLayout,
93        output: &mut AnyByLayout,
94    ) -> core::task::Poll<file_system::Result<()>> {
95        file_system::ready(|| {
96            match command {
97                SET_DRAWING_AREA::IDENTIFIER => {
98                    let area = *SET_DRAWING_AREA::cast_input(input)?;
99                    *self
100                        .drawing_area
101                        .lock()
102                        .map_err(|_| file_system::IoErrorKind::InputOutput)? = area;
103                }
104                GET_RESOLUTION::IDENTIFIER => {
105                    *GET_RESOLUTION::cast_output(output)? = self.resolution;
106                }
107                WAS_RESIZED::IDENTIFIER => {
108                    *WAS_RESIZED::cast_output(output)? = 0;
109                }
110                _ => return Err(file_system::IoErrorKind::Unsupported),
111            }
112            Ok(())
113        })
114    }
115}
116
117impl MountOperations for HeadlessScreenDevice {}
118impl DirectCharacterDevice for HeadlessScreenDevice {}
119
120fn validate_resolution(resolution: Point) -> Result<(), ()> {
121    let width = usize::try_from(resolution.get_x()).map_err(|_| ())?;
122    let height = usize::try_from(resolution.get_y()).map_err(|_| ())?;
123    if width == 0
124        || height == 0
125        || width
126            .checked_mul(height)
127            .is_none_or(|pixels| pixels > SCREEN_SNAPSHOT_MAX_PIXELS)
128    {
129        Err(())
130    } else {
131        Ok(())
132    }
133}
134
135fn validate_flush(resolution: Point, area: Area, bytes_per_pixel: usize) -> Result<usize, ()> {
136    let first = area.get_point_1();
137    let second = area.get_point_2();
138    let (x1, y1, x2, y2) = (
139        i32::from(first.get_x()),
140        i32::from(first.get_y()),
141        i32::from(second.get_x()),
142        i32::from(second.get_y()),
143    );
144    let width = i32::from(resolution.get_x());
145    let height = i32::from(resolution.get_y());
146    if x1 < 0 || y1 < 0 || x2 < x1 || y2 < y1 || x2 >= width || y2 >= height {
147        return Err(());
148    }
149    let pixels = usize::try_from(x2 - x1 + 1)
150        .ok()
151        .and_then(|flush_width| {
152            usize::try_from(y2 - y1 + 1)
153                .ok()
154                .and_then(|flush_height| flush_width.checked_mul(flush_height))
155        })
156        .ok_or(())?;
157    pixels.checked_mul(bytes_per_pixel).ok_or(())
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn headless_screen_accepts_valid_flush() {
166        let resolution = Point::new(640, 480);
167        let area = Area::new(Point::new(4, 8), Point::new(15, 19));
168        assert_eq!(validate_flush(resolution, area, 4), Ok(12 * 12 * 4));
169    }
170
171    #[test]
172    fn headless_screen_rejects_invalid_dimensions() {
173        assert_eq!(validate_resolution(Point::new(0, 480)), Err(()));
174        assert_eq!(validate_resolution(Point::new(1920, 1081)), Err(()));
175    }
176
177    #[test]
178    fn headless_screen_rejects_out_of_bounds_flush() {
179        let area = Area::new(Point::new(639, 0), Point::new(640, 1));
180        assert_eq!(validate_flush(Point::new(640, 480), area, 4), Err(()));
181    }
182}