Skip to main content

fbsurface/
owned.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//! Heap-backed surfaces.
24//!
25//! [`OwnedSurface`] is the double-buffer half of the API: a 32 bpp surface
26//! that owns its pixels (`Vec<u32>`, so the base is 4-byte aligned) and keeps
27//! its own damage set across drawing calls.
28//!
29//! It is the replacement for `CanvasBuffer`'s `back_buffer` field, with the
30//! lifetime problem removed: instead of storing a `Canvas` next to the
31//! `Vec`, it builds a short-lived `Canvas` on demand and merges the damage
32//! back into the owner. That keeps the borrow checker in charge and makes a
33//! dangling surface pointer impossible.
34//!
35//! ```
36//! use fbsurface::{Dims, Format, OwnedSurface, Rect};
37//!
38//! let mut back = OwnedSurface::new(Dims::new(8, 8), Format::XRGB8888).unwrap();
39//! back.fill_rect(Rect::new(2, 2, 3, 3), Format::XRGB8888.white());
40//! assert_eq!(back.dirty().len(), 1);
41//! ```
42
43use alloc::{vec, vec::Vec};
44
45use crate::{
46    canvas::{Canvas, Error},
47    format::{Format, Packed},
48    geom::{Dims, Rect, RectSet, DEFAULT_SET_CAPACITY},
49    ops::{PixelOps, ScalarOps},
50    view::{Source, View},
51};
52
53/// A heap-backed, 32 bpp surface with damage tracking.
54///
55/// The pitch is always `width * 4` (no padding), which is what a compositor
56/// or a console back buffer wants. Use [`Canvas`](crate::Canvas) directly
57/// when the backing store has a driver-provided pitch (scanout, client
58/// buffer).
59pub struct OwnedSurface<O: PixelOps = ScalarOps> {
60    words: Vec<u32>,
61    dims: Dims,
62    format: Format,
63    ops: O,
64    dirty: RectSet<DEFAULT_SET_CAPACITY>,
65    track_dirty: bool,
66}
67
68impl<O: PixelOps> core::fmt::Debug for OwnedSurface<O> {
69    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
70        f.debug_struct("OwnedSurface")
71            .field("dims", &self.dims)
72            .field("format", &self.format)
73            .field("dirty", &self.dirty)
74            .field("track_dirty", &self.track_dirty)
75            .finish_non_exhaustive()
76    }
77}
78
79impl<O: PixelOps + Copy> OwnedSurface<O> {
80    /// Allocate a zeroed surface.
81    ///
82    /// Only 32 bpp layouts are accepted: a heap surface is a drawing target,
83    /// not a 24 bpp scanout, and `Vec<u32>` gives the alignment the pixel
84    /// backends expect.
85    pub fn with_ops(dims: Dims, format: Format, ops: O) -> Result<Self, Error> {
86        if dims.is_empty() {
87            return Err(Error::EmptySurface);
88        }
89        if format.bits_per_pixel() != 32 {
90            return Err(Error::UnsupportedFormat {
91                bits_per_pixel: format.bits_per_pixel(),
92            });
93        }
94        if !format.is_valid() {
95            return Err(Error::InvalidFormat);
96        }
97        let area = (dims.w as usize)
98            .checked_mul(dims.h as usize)
99            .ok_or(Error::Overflow)?;
100        Ok(Self {
101            words: vec![0u32; area],
102            dims,
103            format,
104            ops,
105            dirty: RectSet::empty(),
106            track_dirty: true,
107        })
108    }
109
110    /// Wrap an existing word buffer.
111    ///
112    /// The buffer must hold at least `dims.w * dims.h` pixels; extra words
113    /// are ignored.
114    pub fn from_words(words: Vec<u32>, dims: Dims, format: Format, ops: O) -> Result<Self, Error> {
115        if dims.is_empty() {
116            return Err(Error::EmptySurface);
117        }
118        if format.bits_per_pixel() != 32 {
119            return Err(Error::UnsupportedFormat {
120                bits_per_pixel: format.bits_per_pixel(),
121            });
122        }
123        if !format.is_valid() {
124            return Err(Error::InvalidFormat);
125        }
126        let area = (dims.w as usize)
127            .checked_mul(dims.h as usize)
128            .ok_or(Error::Overflow)?;
129        if words.len() < area {
130            return Err(Error::BufferTooSmall {
131                len: words.len() * 4,
132                required: area * 4,
133            });
134        }
135        Ok(Self {
136            words,
137            dims,
138            format,
139            ops,
140            dirty: RectSet::empty(),
141            track_dirty: true,
142        })
143    }
144
145    #[inline]
146    pub fn dims(&self) -> Dims {
147        self.dims
148    }
149
150    #[inline]
151    pub fn format(&self) -> Format {
152        self.format
153    }
154
155    /// Bytes per row (always `width * 4`).
156    #[inline]
157    pub fn pitch(&self) -> usize {
158        self.dims.w as usize * 4
159    }
160
161    #[inline]
162    pub fn bounds(&self) -> Rect {
163        Rect::new(0, 0, self.dims.w, self.dims.h)
164    }
165
166    /// Raw pixels. Bypasses damage tracking; call [`Self::mark_dirty`] if
167    /// the caller wrote through this slice.
168    #[inline]
169    pub fn words(&self) -> &[u32] {
170        &self.words
171    }
172
173    /// Mutable raw pixels. See [`Self::words`].
174    #[inline]
175    pub fn words_mut(&mut self) -> &mut [u32] {
176        &mut self.words
177    }
178
179    /// Record damage from an external write.
180    #[inline]
181    pub fn mark_dirty(&mut self, rect: Rect) {
182        if self.track_dirty {
183            self.dirty.include(rect);
184        }
185    }
186
187    #[inline]
188    pub fn dirty(&self) -> &RectSet<DEFAULT_SET_CAPACITY> {
189        &self.dirty
190    }
191
192    #[inline]
193    pub fn take_dirty(&mut self) -> RectSet<DEFAULT_SET_CAPACITY> {
194        core::mem::take(&mut self.dirty)
195    }
196
197    #[inline]
198    pub fn clear_dirty(&mut self) {
199        self.dirty.clear();
200    }
201
202    #[inline]
203    pub fn set_tracking(&mut self, on: bool) {
204        self.track_dirty = on;
205        if !on {
206            self.dirty.clear();
207        }
208    }
209
210    /// Build a canvas over the pixels.
211    ///
212    /// Private on purpose: a caller that drops the canvas loses its damage.
213    /// [`Self::draw`] is the safe way to run a multi-operation frame.
214    fn canvas(&mut self) -> Canvas<'_, O> {
215        let len = self.words.len() * 4;
216        // SAFETY: `Vec<u32>` guarantees a 4-byte aligned base, the length is
217        // exact, and the canvas borrows the words for `'_`.
218        let bytes =
219            unsafe { core::slice::from_raw_parts_mut(self.words.as_mut_ptr() as *mut u8, len) };
220        Canvas::with_ops(bytes, self.dims, self.pitch(), self.format, self.ops)
221            .expect("an owned surface is always a valid canvas")
222    }
223
224    /// Immutable view over the pixels.
225    pub fn view(&self) -> View<'_> {
226        let len = self.words.len() * 4;
227        // SAFETY: same reasoning as `canvas`, with a shared slice.
228        let bytes = unsafe { core::slice::from_raw_parts(self.words.as_ptr() as *const u8, len) };
229        View::new(bytes, self.dims, self.pitch(), self.format)
230            .expect("an owned surface is always a valid view")
231    }
232
233    /// Run a drawing closure and merge its damage into this surface.
234    ///
235    /// Use this to draw a whole frame through one canvas without losing
236    /// damage tracking. The per-operation helpers call it internally.
237    pub fn draw<T>(&mut self, f: impl FnOnce(&mut Canvas<'_, O>) -> T) -> T {
238        let tracking = self.track_dirty;
239        // The temporary canvas borrows `self.words`; end that borrow before
240        // merging its damage into `self.dirty`.
241        let (out, damage) = {
242            let mut canvas = self.canvas();
243            canvas.set_tracking(tracking);
244            let out = f(&mut canvas);
245            (out, canvas.take_dirty())
246        };
247        if tracking {
248            self.dirty.include_set(&damage);
249        }
250        out
251    }
252
253    pub fn fill_rect(&mut self, rect: Rect, color: Packed) -> Option<Rect> {
254        self.draw(|canvas| canvas.fill_rect(rect, color))
255    }
256
257    pub fn fill(&mut self, color: Packed) -> Rect {
258        let bounds = self.bounds();
259        self.fill_rect(bounds, color).unwrap_or(Rect::EMPTY)
260    }
261
262    pub fn blit<S: Source + ?Sized>(
263        &mut self,
264        dst: Rect,
265        src: &S,
266        src_rect: Rect,
267    ) -> Result<Option<Rect>, Error> {
268        self.draw(|canvas| canvas.blit(dst, src, src_rect))
269    }
270
271    pub fn blend_rect<S: Source + ?Sized>(
272        &mut self,
273        dst: Rect,
274        src: &S,
275        src_rect: Rect,
276        alpha: u8,
277    ) -> Result<Option<Rect>, Error> {
278        self.draw(|canvas| canvas.blend_rect(dst, src, src_rect, alpha))
279    }
280
281    pub fn convert_from<S: Source + ?Sized>(
282        &mut self,
283        dst: Rect,
284        src: &S,
285        src_rect: Rect,
286    ) -> Result<Option<Rect>, Error> {
287        self.draw(|canvas| canvas.convert_from(dst, src, src_rect))
288    }
289
290    pub fn read_pixel(&self, x: u32, y: u32) -> Option<Packed> {
291        self.view().read_pixel(x, y)
292    }
293
294    pub fn write_pixel(&mut self, x: u32, y: u32, pixel: Packed) -> bool {
295        self.draw(|canvas| canvas.write_pixel(x, y, pixel))
296    }
297}
298
299impl OwnedSurface<ScalarOps> {
300    /// Allocate a zeroed XRGB8888 surface with the scalar backend.
301    pub fn new(dims: Dims, format: Format) -> Result<Self, Error> {
302        Self::with_ops(dims, format, ScalarOps)
303    }
304}
305
306// SAFETY: the `Vec` heap allocation is stable while the surface is alive,
307// the pitch is `width * 4`, and the bytes were validated at construction.
308unsafe impl<O: PixelOps> Source for OwnedSurface<O> {
309    #[inline]
310    fn dims(&self) -> Dims {
311        self.dims
312    }
313
314    #[inline]
315    fn format(&self) -> Format {
316        self.format
317    }
318
319    #[inline]
320    fn pitch(&self) -> usize {
321        self.dims.w as usize * 4
322    }
323
324    #[inline]
325    unsafe fn row_ptr(&self, y: u32) -> *const u8 {
326        // SAFETY: `y < height` by the trait contract, and the buffer holds
327        // `pitch * height` bytes.
328        unsafe {
329            self.words
330                .as_ptr()
331                .cast::<u8>()
332                .add(y as usize * (self.dims.w as usize * 4))
333        }
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340    use crate::format::Rgb;
341
342    #[test]
343    fn damage_survives_across_drawing_calls() {
344        let mut back = OwnedSurface::new(Dims::new(8, 8), Format::XRGB8888).unwrap();
345        back.fill_rect(Rect::new(0, 0, 2, 2), Format::XRGB8888.white());
346        back.fill_rect(Rect::new(4, 4, 2, 2), Format::XRGB8888.white());
347        assert_eq!(back.dirty().len(), 2);
348        assert_eq!(back.dirty().total_area(), 8);
349    }
350
351    #[test]
352    fn drawing_goes_through_the_canvas() {
353        let mut back = OwnedSurface::new(Dims::new(4, 4), Format::XRGB8888).unwrap();
354        back.fill_rect(Rect::new(1, 1, 2, 2), Format::XRGB8888.rgb(1, 2, 3));
355        assert_eq!(
356            Format::XRGB8888.unpack(Packed::raw(back.words()[4 + 1])),
357            Rgb::new(1, 2, 3)
358        );
359        assert_eq!(back.words()[0], 0);
360    }
361
362    #[test]
363    fn two_owned_surfaces_copy_between_each_other() {
364        let mut src = OwnedSurface::new(Dims::new(4, 4), Format::XRGB8888).unwrap();
365        let mut dst = OwnedSurface::new(Dims::new(8, 8), Format::XRGB8888).unwrap();
366        src.fill(Format::XRGB8888.white());
367        let written = dst
368            .blit(Rect::new(2, 2, 4, 4), &src, Rect::new(0, 0, 4, 4))
369            .unwrap();
370        assert_eq!(written, Some(Rect::new(2, 2, 4, 4)));
371        assert_eq!(dst.words()[2 * 8 + 2], 0xFFFF_FFFF);
372        assert_eq!(dst.words()[8 + 1], 0);
373        assert_eq!(dst.dirty().bounds(), Rect::new(2, 2, 4, 4));
374    }
375
376    #[test]
377    fn full_frame_blit_uses_the_contiguous_path() {
378        let mut src = OwnedSurface::new(Dims::new(8, 8), Format::XRGB8888).unwrap();
379        let mut dst = OwnedSurface::new(Dims::new(8, 8), Format::XRGB8888).unwrap();
380        for y in 0..8 {
381            for x in 0..8 {
382                src.write_pixel(x, y, Format::XRGB8888.rgb(x as u8, y as u8, 0x5A));
383            }
384        }
385        let written = dst
386            .blit(Rect::new(0, 0, 8, 8), &src, Rect::new(0, 0, 8, 8))
387            .unwrap();
388        assert_eq!(written, Some(Rect::new(0, 0, 8, 8)));
389        assert_eq!(dst.words(), src.words());
390    }
391
392    #[test]
393    fn owned_surface_converts_to_24bpp_view() {
394        // A 24 bpp sibling is only representable as a borrowed View; the
395        // conversion path is still the same `Format::convert`.
396        let mut src = [0u8; 8 * 8 * 3];
397        src[0..3].copy_from_slice(&[0x30, 0x20, 0x10]);
398        let view = View::new(&src, Dims::new(8, 8), 8 * 3, Format::RGB888).unwrap();
399        let mut dst = OwnedSurface::new(Dims::new(8, 8), Format::XRGB8888).unwrap();
400        dst.convert_from(Rect::new(0, 0, 1, 1), &view, Rect::new(0, 0, 1, 1))
401            .unwrap();
402        assert_eq!(
403            Format::XRGB8888.unpack(Packed::raw(dst.words()[0])),
404            Rgb::new(0x10, 0x20, 0x30)
405        );
406    }
407
408    #[test]
409    fn raw_words_must_be_marked_manually() {
410        let mut back = OwnedSurface::new(Dims::new(2, 2), Format::XRGB8888).unwrap();
411        back.words_mut()[0] = 0xFFFF_FFFF;
412        assert!(back.dirty().is_empty());
413        back.mark_dirty(Rect::new(0, 0, 1, 1));
414        assert_eq!(back.dirty().len(), 1);
415    }
416
417    #[test]
418    fn constructor_rejects_bad_input() {
419        assert!(OwnedSurface::new(Dims::ZERO, Format::XRGB8888).is_err());
420        assert!(OwnedSurface::new(Dims::new(2, 2), Format::RGB888).is_err());
421        assert!(OwnedSurface::from_words(
422            alloc::vec![0u32; 2],
423            Dims::new(2, 2),
424            Format::XRGB8888,
425            ScalarOps
426        )
427        .is_err());
428    }
429}