denise 0.13.0

Direct-rendering UI toolkit for embedded Linux and systems without a desktop environment.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! The pixel buffer contract every backend implements.

use alloc::boxed::Box;

use crate::geom::{Rect, Size};

/// Layout of one `u32` in a [`Frame`]'s pixel slice.
///
/// The word is always `0xAARRGGBB` in *native* endianness. On little-endian targets
/// that is byte order `B, G, R, A`, which is what DRM's `ARGB8888`/`XRGB8888`
/// fourccs and Win32 `BI_RGB` DIB sections both mean. It is deliberately *not*
/// tiny-skia's `Pixmap` layout, which is `R, G, B, A` in byte order; anything
/// bridging the two owes a swizzle.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PixelFormat {
    /// `0xAARRGGBB`. The alpha byte is meaningful.
    Argb8888,
    /// `0xXXRRGGBB`. The high byte is ignored by the scanout hardware.
    Xrgb8888,
}

impl PixelFormat {
    /// Bytes per pixel.
    #[inline]
    pub const fn bytes_per_pixel(self) -> usize {
        4
    }

    /// Returns `true` if the high byte is honoured on present.
    #[inline]
    pub const fn has_alpha(self) -> bool {
        matches!(self, PixelFormat::Argb8888)
    }
}

/// How stale the contents of the buffer just acquired are.
///
/// Modelled on `EGL_EXT_buffer_age`. With N-buffering the buffer handed back holds
/// the contents of frame `current - age`, so a correct incremental repaint must
/// cover the union of the last `age` frames' damage — not just this frame's.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BufferAge {
    /// Contents are undefined. Repaint everything.
    ///
    /// Returned after a resize, on the first frame, and by backends that cannot
    /// track age (most compositor-mediated ones).
    Undefined,
    /// Contents are those of the frame `n` presents ago. `1` means the buffer we
    /// most recently presented, i.e. single buffering or a persistent shadow.
    Frames(u32),
}

/// A borrowed, writable pixel buffer for exactly one frame.
///
/// Obtained from [`Surface::acquire`] and released by dropping it, after which the
/// same surface must be told what changed via [`Surface::present`].
///
/// `stride` is in **pixels**, not bytes, and may exceed `size.width`: DRM
/// framebuffers are pitch-aligned (64 bytes on vc4, more elsewhere) and fbdev has
/// its own `line_length`. Never assume `stride == width` — index rows through
/// [`Frame::row_mut`] or [`Frame::rows_mut`].
#[derive(Debug)]
#[must_use = "a Frame must be drawn into and dropped before Surface::present"]
pub struct Frame<'a> {
    pixels: &'a mut [u32],
    size: Size,
    stride: u32,
    format: PixelFormat,
    age: BufferAge,
}

/// How many words a buffer must hold to cover `size` at `stride`.
///
/// `u64`, and deliberately not `usize`. Both inputs are `u32` and both come from
/// a caller who may be wrong about them, and on a 32-bit target — `armv7` is one
/// of this project's — `stride * (height - 1)` overflows a `usize` and wraps: a
/// geometry needing 4 550 000 000 words then validates happily against a
/// 255 032 704-word buffer, and the paint path indexes past the end of it. The
/// product of two `u32`s cannot overflow a `u64`, so this answer is the same on
/// every target.
///
/// Zero for an empty size, which no caller should be asking about.
#[inline]
pub const fn required_words(size: Size, stride: u32) -> u64 {
    if size.is_empty() {
        return 0;
    }
    stride as u64 * (size.height as u64 - 1) + size.width as u64
}

impl<'a> Frame<'a> {
    /// Wraps a backend buffer.
    ///
    /// Returns [`SurfaceError::BufferTooSmall`] unless `stride >= size.width` and
    /// `pixels` covers `stride * (height - 1) + width` words.
    pub fn new(
        pixels: &'a mut [u32],
        size: Size,
        stride: u32,
        format: PixelFormat,
        age: BufferAge,
    ) -> Result<Self, SurfaceError> {
        if size.is_empty() {
            return Err(SurfaceError::NotReady);
        }
        if stride < size.width {
            return Err(SurfaceError::BufferTooSmall {
                required: size.width as usize,
                actual: stride as usize,
            });
        }
        let required = required_words(size, stride);
        if (pixels.len() as u64) < required {
            return Err(SurfaceError::BufferTooSmall {
                // Saturated only in the case that cannot fit the machine anyway,
                // where the number's job is to appear in a message.
                required: usize::try_from(required).unwrap_or(usize::MAX),
                actual: pixels.len(),
            });
        }
        Ok(Self {
            pixels,
            size,
            stride,
            format,
            age,
        })
    }

    /// Visible extent in physical pixels.
    #[inline]
    pub const fn size(&self) -> Size {
        self.size
    }

    /// Distance between the starts of consecutive rows, in pixels.
    #[inline]
    pub const fn stride(&self) -> u32 {
        self.stride
    }

    /// Word layout of the buffer.
    #[inline]
    pub const fn format(&self) -> PixelFormat {
        self.format
    }

    /// How stale these contents are. Feed to [`crate::DamageTracker::resolve`].
    #[inline]
    pub const fn age(&self) -> BufferAge {
        self.age
    }

    /// Full backing slice, including any inter-row padding.
    #[inline]
    pub fn pixels(&self) -> &[u32] {
        self.pixels
    }

    /// Full backing slice, including any inter-row padding.
    #[inline]
    pub fn pixels_mut(&mut self) -> &mut [u32] {
        self.pixels
    }

    /// One row, trimmed to the visible width. Returns `None` past the bottom edge.
    #[inline]
    pub fn row(&self, y: u32) -> Option<&[u32]> {
        if y >= self.size.height {
            return None;
        }
        let start = y as usize * self.stride as usize;
        Some(&self.pixels[start..start + self.size.width as usize])
    }

    /// One row, trimmed to the visible width. Returns `None` past the bottom edge.
    #[inline]
    pub fn row_mut(&mut self, y: u32) -> Option<&mut [u32]> {
        if y >= self.size.height {
            return None;
        }
        let start = y as usize * self.stride as usize;
        Some(&mut self.pixels[start..start + self.size.width as usize])
    }

    /// Every visible row, top to bottom, each trimmed to the visible width.
    #[inline]
    pub fn rows_mut(&mut self) -> impl Iterator<Item = &mut [u32]> {
        let width = self.size.width as usize;
        let height = self.size.height as usize;
        self.pixels
            .chunks_mut(self.stride as usize)
            .take(height)
            .map(move |row| &mut row[..width])
    }
}

/// A backend that owns a presentable pixel buffer.
///
/// The contract is strictly alternating: [`acquire`](Surface::acquire), draw, drop
/// the frame, [`present`](Surface::present). Implementations should return
/// [`SurfaceError::FrameInFlight`] or [`SurfaceError::NoFrame`] rather than
/// silently tolerating a violation.
pub trait Surface {
    /// Visible extent in physical pixels.
    fn size(&self) -> Size;

    /// Physical pixels per logical pixel. `1.0` on a typical panel.
    fn scale_factor(&self) -> f32;

    /// Word layout the backend will scan out.
    fn format(&self) -> PixelFormat;

    /// Takes the next drawable buffer.
    fn acquire(&mut self) -> Result<Frame<'_>, SurfaceError>;

    /// Publishes the frame, telling the backend which regions changed.
    ///
    /// `damage` must be in physical pixels relative to the surface origin, and
    /// should already be clipped to [`size`](Surface::size). An empty slice means
    /// nothing changed; a backend may still be obliged to flip.
    ///
    /// How much this buys varies enormously. `BitBlt`, X11 and Wayland genuinely
    /// upload only the listed regions. A DRM page flip swaps whole buffers and will
    /// ignore the damage unless the driver honours `FB_DAMAGE_CLIPS`; there the win
    /// is upstream, in not rasterising the untouched pixels at all.
    fn present(&mut self, damage: &[Rect]) -> Result<(), SurfaceError>;
}

/// Failures from [`Surface`].
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SurfaceError {
    /// The surface has no valid size yet, or is not currently displayable.
    #[error("surface is not ready to render")]
    NotReady,

    /// [`Surface::acquire`] was called twice without an intervening present.
    #[error("a frame is already in flight; present it before acquiring another")]
    FrameInFlight,

    /// [`Surface::present`] was called without a preceding acquire.
    #[error("no frame has been acquired")]
    NoFrame,

    /// The backend handed over a buffer too small for the geometry it declared.
    #[error("buffer too small: need {required} pixels, got {actual}")]
    BufferTooSmall {
        /// Words the declared geometry requires.
        required: usize,
        /// Words actually available.
        actual: usize,
    },

    /// A cursor sprite larger than the plane can hold.
    ///
    /// Cursor planes are fixed-size, so this is a limit rather than a shortage.
    /// Refused rather than cropped: a pointer missing its lower half reads as a
    /// rendering bug, not as a hardware constraint.
    #[error(
        "cursor sprite is {}x{} but the plane holds at most {}x{}",
        requested.width, requested.height, limit.width, limit.height
    )]
    CursorTooLarge {
        /// The largest sprite the hardware accepts.
        limit: crate::geom::Size,
        /// The sprite that was offered.
        requested: crate::geom::Size,
    },

    /// A platform-specific failure.
    #[error("backend error: {0}")]
    Backend(Box<dyn core::error::Error + Send + Sync + 'static>),
}

impl SurfaceError {
    /// Wraps a platform error without leaking its type into the core.
    pub fn backend<E: core::error::Error + Send + Sync + 'static>(err: E) -> Self {
        SurfaceError::Backend(Box::new(err))
    }

    /// Wraps a platform error that is not `Send + Sync`, keeping only its message.
    ///
    /// [`SurfaceError`] is deliberately thread-safe so applications can put it in
    /// an `anyhow::Error` or return it from `main`. Some platform errors are not —
    /// softbuffer's, for one — so they get flattened to text here rather than
    /// infecting every caller.
    pub fn backend_msg(err: impl core::fmt::Display) -> Self {
        use alloc::string::ToString;
        SurfaceError::Backend(Box::new(BackendMessage(err.to_string())))
    }
}

/// A platform error reduced to its message.
#[derive(Debug)]
struct BackendMessage(alloc::string::String);

impl core::fmt::Display for BackendMessage {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.0)
    }
}

impl core::error::Error for BackendMessage {}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    /// The geometry that used to slip through the buffer check on a 32-bit
    /// target. `required_words` answers in `u64`, so the number is the same on
    /// the machine running this test and on an `armv7` panel.
    ///
    /// 70 000 × 65 000 at stride 70 000 needs 4 550 000 000 words. In `usize`
    /// arithmetic on 32 bits that wraps to 255 032 704 — small enough that a
    /// quarter-gigaword buffer would have been accepted for it, after which
    /// `Canvas::row_span` indexes past the end and panics.
    #[test]
    fn a_geometry_that_overflows_32_bit_arithmetic_is_still_measured_honestly() {
        let size = Size::new(70_000, 65_000);
        assert_eq!(required_words(size, 70_000), 4_550_000_000);
        // What the old expression produced once truncated to 32 bits.
        assert_ne!(4_550_000_000_u64 & 0xFFFF_FFFF, 4_550_000_000);

        // And the check that consumes it rejects a buffer of the wrapped size.
        let mut buf = vec![0u32; 1024];
        assert!(
            Frame::new(
                &mut buf,
                size,
                70_000,
                PixelFormat::Xrgb8888,
                BufferAge::Undefined,
            )
            .is_err()
        );
    }

    #[test]
    fn rejects_stride_below_width() {
        let mut buf = vec![0u32; 64];
        let err = Frame::new(
            &mut buf,
            Size::new(8, 8),
            4,
            PixelFormat::Xrgb8888,
            BufferAge::Undefined,
        );
        assert!(matches!(err, Err(SurfaceError::BufferTooSmall { .. })));
    }

    #[test]
    fn rejects_short_buffer() {
        let mut buf = vec![0u32; 10];
        let err = Frame::new(
            &mut buf,
            Size::new(8, 8),
            8,
            PixelFormat::Xrgb8888,
            BufferAge::Undefined,
        );
        assert!(matches!(err, Err(SurfaceError::BufferTooSmall { .. })));
    }

    #[test]
    fn accepts_exactly_sized_padded_buffer() {
        // 4 rows of stride 10, but the last row only needs its 6 visible pixels.
        let mut buf = vec![0u32; 10 * 3 + 6];
        let mut frame = Frame::new(
            &mut buf,
            Size::new(6, 4),
            10,
            PixelFormat::Xrgb8888,
            BufferAge::Frames(1),
        )
        .expect("geometry fits");
        assert_eq!(frame.rows_mut().count(), 4);
        assert!(frame.rows_mut().all(|r| r.len() == 6));
    }

    #[test]
    fn rows_skip_padding() {
        let mut buf = vec![0u32; 10 * 3];
        let mut frame = Frame::new(
            &mut buf,
            Size::new(6, 3),
            10,
            PixelFormat::Xrgb8888,
            BufferAge::Undefined,
        )
        .expect("geometry fits");
        for row in frame.rows_mut() {
            row.fill(0xFFFF_FFFF);
        }
        // Padding words 6..10 of each row must be untouched.
        assert!(buf.chunks(10).all(|c| c[6..].iter().all(|&p| p == 0)));
    }

    #[test]
    fn zero_size_is_not_ready() {
        let mut buf = vec![0u32; 4];
        assert!(matches!(
            Frame::new(
                &mut buf,
                Size::ZERO,
                0,
                PixelFormat::Xrgb8888,
                BufferAge::Undefined
            ),
            Err(SurfaceError::NotReady)
        ));
    }
}