Skip to main content

slint_sc/
lib.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Software-3.0
3
4#![doc = include_str!("README.md")]
5#![no_std]
6#![forbid(unsafe_code)]
7#![forbid(missing_docs)]
8#![forbid(clippy::shadow_same, clippy::shadow_reuse, clippy::shadow_unrelated)]
9// The unit tests report a failure by panicking
10#![cfg_attr(
11    not(test),
12    forbid(
13        clippy::unwrap_used,
14        clippy::expect_used,
15        clippy::panic,
16        clippy::unreachable,
17        clippy::todo,
18        clippy::unimplemented,
19        clippy::question_mark_used
20    )
21)]
22
23/// The size of a window, in pixels.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub struct Size {
26    /// The width in pixels.
27    pub width: u32,
28    /// The height in pixels.
29    pub height: u32,
30}
31
32impl Size {
33    /// Construct a size from a width and a height.
34    pub const fn new(width: u32, height: u32) -> Self {
35        Self { width, height }
36    }
37}
38
39#[test]
40fn test_size() {
41    let size = Size::new(320, 240);
42    assert_eq!((size.width, size.height), (320, 240));
43    assert_eq!(size, Size { width: 320, height: 240 });
44    assert_ne!(size, Size::new(240, 320));
45    // The default size is empty
46    assert_eq!(Size::default(), Size::new(0, 0));
47    assert_eq!(Sink::format(format_args!("{size:?}")).as_str(), "Size { width: 320, height: 240 }");
48}
49
50/// An RGBA color, as held by properties of the `color` type.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
52pub struct Color {
53    red: u8,
54    green: u8,
55    blue: u8,
56    alpha: u8,
57}
58
59impl Color {
60    /// Construct a color from its ARGB value, e.g. `0xff123456`.
61    pub const fn from_argb_encoded(argb: u32) -> Self {
62        let [alpha, red, green, blue] = argb.to_be_bytes();
63        Self { red, green, blue, alpha }
64    }
65
66    /// Construct a fully opaque color from its red, green, and blue channels.
67    pub const fn from_rgb_u8(red: u8, green: u8, blue: u8) -> Self {
68        Self { red, green, blue, alpha: 0xff }
69    }
70
71    /// The red channel, from 0 to 255.
72    pub const fn red(self) -> u8 {
73        self.red
74    }
75
76    /// The green channel, from 0 to 255.
77    pub const fn green(self) -> u8 {
78        self.green
79    }
80
81    /// The blue channel, from 0 to 255.
82    pub const fn blue(self) -> u8 {
83        self.blue
84    }
85
86    /// The alpha channel: the color's opacity, from 0 for a fully transparent
87    /// color to 255 for a fully opaque one.
88    pub const fn alpha(self) -> u8 {
89        self.alpha
90    }
91
92    /// Returns this color composited over `destination`, the Porter-Duff *over*
93    /// operation.
94    ///
95    /// ```
96    /// use slint_sc::Color;
97    ///
98    /// let red = Color::from_rgb_u8(0xff, 0, 0);
99    ///
100    /// // A fully transparent color leaves the destination as it was
101    /// assert_eq!(Color::default().composite_over(red), red);
102    ///
103    /// // A fully opaque one replaces it
104    /// let green = Color::from_rgb_u8(0, 0xff, 0);
105    /// assert_eq!(green.composite_over(red), green);
106    ///
107    /// // Half-transparent blue over opaque red keeps half of each, and the
108    /// // two halves round apart
109    /// let half_blue = Color::from_argb_encoded(0x800000ff);
110    /// assert_eq!(half_blue.composite_over(red), Color::from_rgb_u8(127, 0, 128));
111    ///
112    /// // Compositing two transparent colors has nothing to show
113    /// assert_eq!(Color::default().composite_over(Color::default()), Color::default());
114    /// ```
115    pub fn composite_over(self, destination: Self) -> Self {
116        let alpha = self.alpha as u32;
117        // How much each color contributes, both over a denominator of
118        // 255 * 255, which keeps the channels and the alpha exact over one
119        // common divisor instead of rounding the weights separately
120        let src_weight: u32 = alpha * 255;
121        let dst_weight: u32 = destination.alpha as u32 * (255 - alpha);
122        let total: u32 = src_weight + dst_weight;
123        // Neither color contributes anything, so there's nothing to weigh the
124        // channels by and the result is transparent
125        if total == 0 {
126            return Self::default();
127        }
128        // Both weights are at most 255 * 255 and so is their total, which
129        // bounds a channel's numerator by 255 * 255 * 255: well within a u32,
130        // and the quotient within a u8. Adding half the divisor first rounds
131        // to the nearest integer.
132        let channel = |src: u8, dst: u8| {
133            ((src as u32 * src_weight + dst as u32 * dst_weight + total / 2) / total) as u8
134        };
135        Self {
136            red: channel(self.red, destination.red),
137            green: channel(self.green, destination.green),
138            blue: channel(self.blue, destination.blue),
139            alpha: ((total + 127) / 255) as u8,
140        }
141    }
142}
143
144#[test]
145fn test_color() {
146    let c = Color::from_argb_encoded(0x87123456);
147    assert_eq!((c.red(), c.green(), c.blue(), c.alpha()), (0x12, 0x34, 0x56, 0x87));
148    assert_eq!(Color::from_rgb_u8(0x12, 0x34, 0x56).alpha(), 0xff);
149    // The default color is transparent
150    assert_eq!(Color::default().alpha(), 0);
151}
152
153#[test]
154fn test_composite_over() {
155    let destination = Color::from_rgb_u8(0, 255, 200);
156    // A fully opaque color is the result itself, a fully transparent one
157    // leaves the destination as it was: the rounding never drifts at either end
158    assert_eq!(
159        Color::from_argb_encoded(0xffff000a).composite_over(destination),
160        Color::from_rgb_u8(255, 0, 10)
161    );
162    assert_eq!(Color::from_argb_encoded(0x00ff000a).composite_over(destination), destination);
163    // Halfway between, each channel rounds to the nearest whole number, and
164    // the channels don't mix into one another
165    assert_eq!(
166        Color::from_argb_encoded(0x80ff000a).composite_over(destination),
167        Color::from_rgb_u8(128, 127, 105)
168    );
169    // The brightest possible result still fits in a u8
170    assert_eq!(
171        Color::from_argb_encoded(0x80ffffff).composite_over(Color::from_rgb_u8(255, 255, 255)),
172        Color::from_rgb_u8(255, 255, 255)
173    );
174    // Over a translucent destination the result keeps an alpha of its own: half
175    // over half leaves three quarters covered
176    assert_eq!(
177        Color::from_argb_encoded(0x80ff0000).composite_over(Color::from_argb_encoded(0x800000ff)),
178        Color::from_argb_encoded(0xc0aa0055)
179    );
180    // With nothing to composite, the result is transparent
181    assert_eq!(Color::default().composite_over(Color::default()), Color::default());
182}
183
184#[test]
185fn test_composite_over_matches_the_specified_formula() {
186    // Over an opaque destination, the case rendering is specified for, every
187    // channel comes out as the specified `(src * alpha + dst * (255 - alpha) +
188    // 127) / 255`, for every channel value and every alpha rather than only
189    // the ones the test cases happen to paint.
190    //#sls.paint.blend.formula
191    for alpha in 0..=255u32 {
192        for src in 0..=255u32 {
193            for dst in 0..=255u32 {
194                let color = Color::from_argb_encoded((alpha << 24) | (src << 16));
195                let got = color.composite_over(Color::from_rgb_u8(dst as u8, 0, 0)).red();
196                let weighted = src * alpha + dst * (255 - alpha);
197                let expected = ((weighted + 127) / 255) as u8;
198                assert_eq!(got, expected, "alpha {alpha}, src {src}, dst {dst}");
199                // And that is the nearest whole number, as specified: the
200                // remainder is itself a whole number, so it never lands on an
201                // exact half that could round either way
202                let nearest = (weighted / 255 + u32::from(weighted % 255 >= 128)) as u8;
203                assert_eq!(expected, nearest, "alpha {alpha}, src {src}, dst {dst}");
204            }
205        }
206    }
207}
208
209/// A position in the window, in pixels: the origin is the top-left corner of
210/// the window, x grows to the right, and y grows downwards.
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
212pub struct Point {
213    /// The distance from the left edge of the window.
214    pub x: i32,
215    /// The distance from the top edge of the window.
216    pub y: i32,
217}
218
219impl Point {
220    /// Construct a position from its distance to the left and top edges.
221    pub const fn new(x: i32, y: i32) -> Self {
222        Self { x, y }
223    }
224}
225
226/// A touch of the display, delivered to the generated `dispatch_touch_event`.
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228#[non_exhaustive]
229pub enum TouchEvent {
230    /// A finger touched the display.
231    #[non_exhaustive]
232    Pressed {
233        /// Where the finger touched.
234        position: Point,
235    },
236    /// The finger lifted off the display.
237    #[non_exhaustive]
238    Released {
239        /// Where the finger lifted off.
240        position: Point,
241    },
242}
243
244impl TouchEvent {
245    /// A finger touching the display at `position`.
246    pub const fn pressed(position: Point) -> Self {
247        Self::Pressed { position }
248    }
249
250    /// A finger lifting off the display at `position`.
251    pub const fn released(position: Point) -> Self {
252        Self::Released { position }
253    }
254}
255
256/// An image, as held by properties of the `image` type.
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
258#[non_exhaustive]
259pub enum Image {
260    /// No image, the value of an `image` property without one.
261    #[default]
262    None,
263    /// An image decoded at compile time into a static array of packed bytes.
264    /// Bytes rather than [`Color`] values so that the generated code can
265    /// carry the image in a byte-string literal, which parses much faster
266    /// than an array of per-pixel constructor calls.
267    StaticArgb {
268        /// Four bytes per pixel, alpha, red, green, and blue, the pixels row
269        /// by row from the top-left corner.
270        argb: &'static [u8],
271        /// The number of pixels in each row.
272        width: usize,
273    },
274}
275
276impl Image {
277    /// The width in pixels. An [`Image::None`] has a width of 0.
278    ///
279    /// ```
280    /// use slint_sc::Image;
281    ///
282    /// assert_eq!(Image::None.width(), 0);
283    ///
284    /// let image = Image::StaticArgb { argb: &[0x80; 24], width: 3 };
285    /// assert_eq!(image.width(), 3);
286    /// ```
287    pub const fn width(self) -> usize {
288        match self {
289            Self::None => 0,
290            Self::StaticArgb { width, .. } => width,
291        }
292    }
293
294    /// The height in pixels, derived from the pixel count and the width: an
295    /// incomplete last pixel or row is not counted. An [`Image::None`], and
296    /// an [`Image::StaticArgb`] with a width of 0, have a height of 0.
297    ///
298    /// ```
299    /// use slint_sc::Image;
300    ///
301    /// assert_eq!(Image::None.height(), 0);
302    ///
303    /// let image = Image::StaticArgb { argb: &[0x80; 24], width: 3 };
304    /// assert_eq!(image.height(), 2);
305    /// ```
306    pub const fn height(self) -> usize {
307        match self {
308            Self::None => 0,
309            Self::StaticArgb { width: 0, .. } => 0,
310            Self::StaticArgb { argb, width } => argb.len() / 4 / width,
311        }
312    }
313}
314
315#[test]
316fn test_touch_event() {
317    let pressed = TouchEvent::pressed(Point::new(3, -4));
318    assert_eq!(pressed, TouchEvent::Pressed { position: Point { x: 3, y: -4 } });
319    // A press and a release of the same position are different events
320    assert_ne!(pressed, TouchEvent::released(Point::new(3, -4)));
321    // The default position is the origin
322    assert_eq!(Point::default(), Point::new(0, 0));
323    assert_eq!(
324        Sink::format(format_args!("{pressed:?}")).as_str(),
325        "Pressed { position: Point { x: 3, y: -4 } }"
326    );
327}
328
329#[test]
330fn test_image() {
331    // The default image is no image
332    //#sls.gen.prop.types.image
333    assert_eq!(Image::default(), Image::None);
334    assert_eq!((Image::None.width(), Image::None.height()), (0, 0));
335
336    // Four bytes per pixel, so six pixels of bytes make a 2x3 image
337    let image = Image::StaticArgb { argb: &[0x80; 24], width: 2 };
338    assert_eq!((image.width(), image.height()), (2, 3));
339
340    // Incomplete trailing pixels and rows don't count towards the height,
341    // and a width of 0 derives a height of 0 rather than dividing by it
342    assert_eq!(Image::StaticArgb { argb: &[0x80; 23], width: 2 }.height(), 2);
343    assert_eq!(Image::StaticArgb { argb: &[0x80; 24], width: 4 }.height(), 1);
344    assert_eq!(Image::StaticArgb { argb: &[0x80; 24], width: 0 }.height(), 0);
345
346    // The image is Copy and compares by its parts
347    let copy = image;
348    assert_eq!(copy, image);
349    assert_ne!(copy, Image::None);
350}
351
352/// Error returned by the generated render functions.
353#[derive(Debug, Clone, PartialEq, Eq)]
354#[non_exhaustive]
355pub enum RenderError {
356    /// The frame buffer size doesn't match the size of the window.
357    InvalidFrameBufferSize,
358}
359
360impl core::fmt::Display for RenderError {
361    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
362        match self {
363            Self::InvalidFrameBufferSize => {
364                f.write_str("the frame buffer size doesn't match the size of the window")
365            }
366        }
367    }
368}
369
370impl core::error::Error for RenderError {}
371
372#[test]
373fn test_render_error_display() {
374    assert_eq!(
375        Sink::format(format_args!("{}", RenderError::InvalidFrameBufferSize)).as_str(),
376        "the frame buffer size doesn't match the size of the window"
377    );
378}
379
380/// Names this crate's version so that generated code built for another version
381/// fails to compile against it.
382#[doc(hidden)]
383#[allow(non_camel_case_types)]
384pub struct VersionCheck_1_19_0;
385
386/// Module only meant to be used by the code generated by the Slint SC compiler.
387#[doc(hidden)]
388pub mod private_unstable_api {
389    /// Painting into a frame buffer.
390    pub mod renderer;
391}
392
393/// A sink that captures formatted output in a fixed buffer, so that a test can
394/// assert on a `Debug` or `Display` implementation without an allocator.
395#[cfg(test)]
396struct Sink {
397    buf: [u8; 128],
398    len: usize,
399}
400
401#[cfg(test)]
402impl core::fmt::Write for Sink {
403    fn write_str(&mut self, s: &str) -> core::fmt::Result {
404        let end = self.len + s.len();
405        self.buf[self.len..end].copy_from_slice(s.as_bytes());
406        self.len = end;
407        Ok(())
408    }
409}
410
411#[cfg(test)]
412impl Sink {
413    /// The formatted arguments, held by the returned sink.
414    fn format(args: core::fmt::Arguments<'_>) -> Self {
415        use core::fmt::Write;
416        let mut sink = Self { buf: [0; 128], len: 0 };
417        sink.write_fmt(args).unwrap();
418        sink
419    }
420
421    fn as_str(&self) -> &str {
422        core::str::from_utf8(&self.buf[..self.len]).unwrap()
423    }
424}