Skip to main content

cranpose_ui/modifier_nodes/
background.rs

1// The background modifier and the corner shape it draws in: plain elements,
2// which a chain keeps as words.
3
4use cranpose_foundation::{NodeCapabilities, PlainElement};
5
6use crate::modifier::{Color, RoundedCornerShape};
7
8/// Element of a background: a fill behind the node's content.
9#[derive(Debug, Clone, PartialEq)]
10pub struct BackgroundElement {
11    color: Color,
12}
13
14impl BackgroundElement {
15    /// Creates an element that fills its node's bounds with `color`.
16    pub fn new(color: Color) -> Self {
17        Self { color }
18    }
19
20    /// Returns the fill color.
21    pub fn color(&self) -> Color {
22        self.color
23    }
24}
25
26impl PlainElement for BackgroundElement {
27    const WORDS: usize = 4;
28    const CAPABILITIES: NodeCapabilities = NodeCapabilities::DRAW;
29
30    fn to_words(&self, words: &mut [u32]) {
31        let Color(red, green, blue, alpha) = self.color;
32        words.copy_from_slice(&[red, green, blue, alpha].map(f32::to_bits));
33    }
34
35    #[inline]
36    fn from_words(words: &[u32]) -> Self {
37        let channels = match *words {
38            [red, green, blue, alpha, ..] => [red, green, blue, alpha],
39            _ => [0; 4],
40        };
41        let [red, green, blue, alpha] = channels.map(f32::from_bits);
42        Self {
43            color: Color(red, green, blue, alpha),
44        }
45    }
46}
47
48/// Element of the rounded corner shape a node's backgrounds draw in.
49#[derive(Debug, Clone, PartialEq)]
50pub struct CornerShapeElement {
51    shape: RoundedCornerShape,
52}
53
54impl CornerShapeElement {
55    /// Creates an element that holds `shape` as the current rounded corner shape.
56    pub fn new(shape: RoundedCornerShape) -> Self {
57        Self { shape }
58    }
59
60    /// Returns the corner shape.
61    pub fn shape(&self) -> RoundedCornerShape {
62        self.shape
63    }
64}
65
66impl PlainElement for CornerShapeElement {
67    const WORDS: usize = 4;
68    const CAPABILITIES: NodeCapabilities = NodeCapabilities::DRAW;
69
70    fn to_words(&self, words: &mut [u32]) {
71        let radii = self.shape.radii();
72        words.copy_from_slice(
73            &[
74                radii.top_left,
75                radii.top_right,
76                radii.bottom_right,
77                radii.bottom_left,
78            ]
79            .map(f32::to_bits),
80        );
81    }
82
83    #[inline]
84    fn from_words(words: &[u32]) -> Self {
85        let radii = match *words {
86            [top_left, top_right, bottom_right, bottom_left, ..] => {
87                [top_left, top_right, bottom_right, bottom_left]
88            }
89            _ => [0; 4],
90        };
91        let [top_left, top_right, bottom_right, bottom_left] = radii.map(f32::from_bits);
92        Self {
93            shape: RoundedCornerShape::new(top_left, top_right, bottom_right, bottom_left),
94        }
95    }
96}