Skip to main content

fbsurface/
view.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Read-only surfaces, and the sealed source trait used by bulk copies.
24//!
25//! [`View`] is the immutable counterpart of [`Canvas`](crate::Canvas): it
26//! borrows a `&[u8]` (or points at shared memory) and can only be read.
27//! This is what lets a caller blit directly from a client buffer, a mapped
28//! frame or a wire payload without copying it into a mutable surface first.
29//!
30//! [`Source`] is deliberately an `unsafe trait`: it hands out a raw row
31//! pointer to the crate's copy loops, so a bad implementation would turn a
32//! safe `blit` into undefined behaviour. It is implemented only for
33//! [`Canvas`](crate::Canvas) and [`View`], and cannot be implemented outside
34//! this crate without an explicit `unsafe impl`.
35
36use core::marker::PhantomData;
37
38use crate::{
39    canvas::{validate, validate_alignment, Canvas, Error},
40    format::{Format, Packed},
41    geom::{Dims, Rect},
42};
43
44/// A surface that a [`Canvas`](crate::Canvas) can copy from.
45///
46/// # Safety
47///
48/// Implementors must guarantee that, for every `y < dims().h`, [`Self::row_ptr`]
49/// returns a pointer to at least `dims().w * format().bytes_per_pixel()`
50/// readable bytes, and that the pointer stays valid for as long as `self` is
51/// borrowed.
52pub unsafe trait Source {
53    fn dims(&self) -> Dims;
54    fn format(&self) -> Format;
55
56    /// Bytes per row.
57    ///
58    /// Safe to call on its own: it is only used to detect a contiguous
59    /// buffer for the multi-row fast path, never to index memory.
60    fn pitch(&self) -> usize;
61
62    /// Pointer to the first pixel of row `y`.
63    ///
64    /// # Safety
65    ///
66    /// `y` must be in `0..dims().h`.
67    unsafe fn row_ptr(&self, y: u32) -> *const u8;
68
69    /// Read one pixel with no volatile semantics.
70    ///
71    /// Defaulted so both `Canvas` and `View` share the exact same decoding
72    /// rules.
73    ///
74    /// # Safety
75    ///
76    /// `x` and `y` must be inside the surface.
77    #[inline]
78    unsafe fn read_raw(&self, x: u32, y: u32) -> u32 {
79        // SAFETY: forwarded from the caller.
80        let ptr = unsafe { self.row_ptr(y) };
81        let format = self.format();
82        // SAFETY: the trait contract guarantees the row is readable and
83        // `x` is in bounds; 32 bpp surfaces are 4-byte aligned by
84        // construction, 24 bpp uses byte reads.
85        unsafe {
86            match format.bytes_per_pixel() {
87                4 => (ptr.add(x as usize * 4) as *const u32).read_unaligned(),
88                3 => {
89                    let p = ptr.add(x as usize * 3);
90                    p.read() as u32 | (p.add(1).read() as u32) << 8 | (p.add(2).read() as u32) << 16
91                }
92                _ => 0,
93            }
94        }
95    }
96}
97
98// SAFETY: `Canvas::row_ptr` is the validated surface geometry from
99// `canvas.rs`; the pointer stays valid for the borrow of the canvas.
100unsafe impl<O: crate::ops::PixelOps> Source for Canvas<'_, O> {
101    #[inline]
102    fn dims(&self) -> Dims {
103        Canvas::dims(self)
104    }
105
106    #[inline]
107    fn format(&self) -> Format {
108        Canvas::format(self)
109    }
110
111    #[inline]
112    fn pitch(&self) -> usize {
113        Canvas::pitch(self)
114    }
115
116    #[inline]
117    unsafe fn row_ptr(&self, y: u32) -> *const u8 {
118        // `y` is in bounds per the trait contract; the canvas row pointer is
119        // valid for the borrow.
120        Canvas::row_ptr(self, y) as *const u8
121    }
122}
123
124/// An immutable rectangle of pixels.
125///
126/// Created from a borrowed slice or from raw memory (MMIO, shared mapping).
127/// It records no damage and cannot be drawn into.
128pub struct View<'a> {
129    base: *const u8,
130    pitch: usize,
131    dims: Dims,
132    format: Format,
133    _borrow: PhantomData<&'a [u8]>,
134}
135
136// A `View` only reads, so sharing it cannot tear a pixel. `View::from_raw`
137// requires the backing memory to be safe to read from any CPU the view is
138// sent to; a thread-local or per-CPU mapping must not be wrapped in a `View`.
139unsafe impl Send for View<'_> {}
140unsafe impl Sync for View<'_> {}
141
142impl core::fmt::Debug for View<'_> {
143    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
144        f.debug_struct("View")
145            .field("dims", &self.dims)
146            .field("pitch", &self.pitch)
147            .field("format", &self.format)
148            .finish_non_exhaustive()
149    }
150}
151
152impl<'a> View<'a> {
153    /// Build a view over a borrowed buffer.
154    ///
155    /// `pitch` is a byte count, not a pixel count.
156    pub fn new(buf: &'a [u8], dims: Dims, pitch: usize, format: Format) -> Result<Self, Error> {
157        validate(dims, pitch, format)?;
158        validate_alignment(buf.as_ptr() as usize, format)?;
159        let required = pitch.checked_mul(dims.h as usize).ok_or(Error::Overflow)?;
160        if buf.len() < required {
161            return Err(Error::BufferTooSmall {
162                len: buf.len(),
163                required,
164            });
165        }
166        // SAFETY: validated above; the borrow ties the view to `buf`.
167        unsafe { Self::from_raw(buf.as_ptr(), dims, pitch, format) }
168    }
169
170    /// Build a view over raw memory.
171    ///
172    /// # Safety
173    ///
174    /// `base` must be readable for `pitch * height` bytes for the whole
175    /// lifetime `'a`, and the memory must stay valid if the view is sent to
176    /// another CPU (`View` is `Send + Sync`).
177    pub unsafe fn from_raw(
178        base: *const u8,
179        dims: Dims,
180        pitch: usize,
181        format: Format,
182    ) -> Result<Self, Error> {
183        validate(dims, pitch, format)?;
184        validate_alignment(base as usize, format)?;
185        pitch.checked_mul(dims.h as usize).ok_or(Error::Overflow)?;
186        Ok(Self {
187            base,
188            pitch,
189            dims,
190            format,
191            _borrow: PhantomData,
192        })
193    }
194
195    #[inline]
196    pub fn dims(&self) -> Dims {
197        self.dims
198    }
199
200    #[inline]
201    pub fn format(&self) -> Format {
202        self.format
203    }
204
205    #[inline]
206    pub fn pitch(&self) -> usize {
207        self.pitch
208    }
209
210    #[inline]
211    pub fn bytes_per_pixel(&self) -> usize {
212        self.format.bytes_per_pixel()
213    }
214
215    #[inline]
216    pub fn bounds(&self) -> Rect {
217        Rect::new(0, 0, self.dims.w, self.dims.h)
218    }
219
220    #[inline]
221    pub fn clip(&self, rect: Rect) -> Option<Rect> {
222        let clipped = rect.intersect(self.bounds());
223        if clipped.is_empty() {
224            None
225        } else {
226            Some(clipped)
227        }
228    }
229
230    /// Read one pixel. Volatile, because the backing memory may be MMIO or
231    /// a shared mapping that a device updates.
232    pub fn read_pixel(&self, x: u32, y: u32) -> Option<Packed> {
233        if x >= self.dims.w || y >= self.dims.h {
234            return None;
235        }
236        let ptr = unsafe { self.base.add(y as usize * self.pitch) };
237        let value = match self.format.bytes_per_pixel() {
238            4 => {
239                // SAFETY: in bounds and aligned.
240                unsafe { core::ptr::read_volatile(ptr.add(x as usize * 4) as *const u32) }
241            }
242            3 => {
243                // SAFETY: in bounds.
244                unsafe {
245                    let p = ptr.add(x as usize * 3);
246                    core::ptr::read_volatile(p) as u32
247                        | (core::ptr::read_volatile(p.add(1)) as u32) << 8
248                        | (core::ptr::read_volatile(p.add(2)) as u32) << 16
249                }
250            }
251            _ => return None,
252        };
253        Some(Packed::raw(value))
254    }
255}
256
257// SAFETY: the geometry was validated at construction, and the pointer is
258// valid for `pitch * height` bytes for `'a`.
259unsafe impl Source for View<'_> {
260    #[inline]
261    fn dims(&self) -> Dims {
262        self.dims
263    }
264
265    #[inline]
266    fn format(&self) -> Format {
267        self.format
268    }
269
270    #[inline]
271    fn pitch(&self) -> usize {
272        self.pitch
273    }
274
275    #[inline]
276    unsafe fn row_ptr(&self, y: u32) -> *const u8 {
277        // SAFETY: `y < height` by the trait contract, and the backing store
278        // holds `pitch * height` bytes.
279        unsafe { self.base.add(y as usize * self.pitch) }
280    }
281}
282
283impl<'a, O: crate::ops::PixelOps> Canvas<'a, O> {
284    /// Borrow this canvas as an immutable view.
285    ///
286    /// Useful to keep a source alive while the destination is drawn through
287    /// a different alias, or to pass a canvas to code that only reads.
288    pub fn view(&self) -> View<'_> {
289        // SAFETY: the canvas geometry was validated at construction and the
290        // view borrows it for `'_`.
291        unsafe {
292            View::from_raw(
293                Canvas::row_ptr(self, 0) as *const u8,
294                self.dims(),
295                self.pitch(),
296                self.format(),
297            )
298            .expect("a validated canvas is a valid view")
299        }
300    }
301}
302
303#[cfg(test)]
304mod tests {
305    extern crate alloc;
306
307    use super::*;
308    use crate::geom::Rect;
309
310    #[test]
311    fn view_reads_the_underlying_bytes() {
312        let words = [0x0011_2233u32, 0x0044_5566];
313        // SAFETY: `u32` has no padding.
314        let bytes =
315            unsafe { core::slice::from_raw_parts(words.as_ptr() as *const u8, words.len() * 4) };
316        let view = View::new(bytes, Dims::new(2, 1), 8, Format::XRGB8888).unwrap();
317        assert_eq!(view.read_pixel(0, 0), Some(Packed::raw(0x0011_2233)));
318        assert_eq!(view.read_pixel(1, 0), Some(Packed::raw(0x0044_5566)));
319        assert_eq!(view.read_pixel(2, 0), None);
320    }
321
322    #[test]
323    fn view_rejects_inconsistent_geometry() {
324        let bytes = [0u8; 16];
325        assert!(View::new(&bytes, Dims::new(4, 4), 16, Format::XRGB8888).is_err());
326        assert!(View::new(&bytes[1..], Dims::new(1, 1), 4, Format::XRGB8888).is_err());
327    }
328
329    #[test]
330    fn view_clip_matches_canvas_clip() {
331        let bytes = [0u8; 64];
332        let view = View::new(&bytes, Dims::new(4, 4), 16, Format::XRGB8888).unwrap();
333        assert_eq!(
334            view.clip(Rect::new(2, 2, 8, 8)),
335            Some(Rect::new(2, 2, 2, 2))
336        );
337        assert_eq!(view.clip(Rect::new(9, 0, 1, 1)), None);
338    }
339}