Skip to main content

cranpose_ui/
background_draw.rs

1//! What a background modifier draws, kept as plain data.
2
3use cranpose_ui_graphics::{
4    BlendMode, CornerRadii, DrawScope, Rect, RoundedCornerShape, ShapeRecorder, Size,
5};
6
7use crate::modifier::{Brush, Color, CoordinatorRect};
8
9/// What a background modifier draws: its color over the rect of its
10/// coordinator, rounded when a corner shape of the chain shapes it. It is
11/// plain data, so a renderer can keep it as one shape.
12#[derive(Clone)]
13pub struct BackgroundDraw {
14    color: Color,
15    shape: Option<RoundedCornerShape>,
16    coordinator: CoordinatorRect,
17}
18
19impl BackgroundDraw {
20    pub(crate) fn new(
21        color: Color,
22        shape: Option<RoundedCornerShape>,
23        coordinator: CoordinatorRect,
24    ) -> Self {
25        Self {
26            color,
27            shape,
28            coordinator,
29        }
30    }
31
32    /// The color the background fills with.
33    pub fn color(&self) -> Color {
34        self.color
35    }
36
37    /// The rect the background fills in a node of `size`, with the radii of
38    /// its corners when a corner shape rounds it.
39    pub fn shape_in(&self, size: Size) -> (Rect, Option<CornerRadii>) {
40        let rect = self.coordinator.rect(size);
41        let radii = self
42            .shape
43            .map(|shape| shape.resolve(rect.width, rect.height));
44        (rect, radii)
45    }
46
47    /// Records the background into `scope`, whose size is the node's.
48    pub fn draw(&self, scope: &mut dyn DrawScope) {
49        let brush = Brush::solid(self.color);
50        match self.shape_in(scope.size()) {
51            (rect, Some(radii)) => scope.draw_round_rect_at(rect, brush, radii),
52            (rect, None) => scope.draw_rect_at(rect, brush),
53        }
54    }
55
56    /// Records the background into `recorder` as `shape`, which
57    /// [`Self::shape_in`] gives for the node's size: the shape [`Self::draw`]
58    /// records into a draw scope.
59    pub fn record(&self, shape: (Rect, Option<CornerRadii>), recorder: &mut ShapeRecorder) {
60        let brush = Brush::solid(self.color);
61        match shape {
62            (rect, Some(radii)) => {
63                recorder.push_round_rect(rect, &brush, radii, None, BlendMode::SrcOver);
64            }
65            (rect, None) => {
66                recorder.push_rect(rect, &brush, None, BlendMode::SrcOver);
67            }
68        }
69    }
70
71    // Whether `other` draws the same in every node.
72    pub(crate) fn same_as(&self, other: &Self) -> bool {
73        self.color == other.color
74            && self.shape == other.shape
75            && self.coordinator.same_as(&other.coordinator)
76    }
77}