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        self.fill(scope, self.color);
50    }
51
52    // Fills the background's shape with `color` in place of its own.
53    pub(crate) fn fill(&self, scope: &mut dyn DrawScope, color: Color) {
54        let brush = Brush::solid(color);
55        match self.shape_in(scope.size()) {
56            (rect, Some(radii)) => scope.draw_round_rect_at(rect, brush, radii),
57            (rect, None) => scope.draw_rect_at(rect, brush),
58        }
59    }
60
61    /// Records the background into `recorder` as `shape`, which
62    /// [`Self::shape_in`] gives for the node's size: the shape [`Self::draw`]
63    /// records into a draw scope.
64    pub fn record(&self, shape: (Rect, Option<CornerRadii>), recorder: &mut ShapeRecorder) {
65        let brush = Brush::solid(self.color);
66        match shape {
67            (rect, Some(radii)) => {
68                recorder.push_round_rect(rect, &brush, radii, None, BlendMode::SrcOver);
69            }
70            (rect, None) => {
71                recorder.push_rect(rect, &brush, None, BlendMode::SrcOver);
72            }
73        }
74    }
75
76    // Whether `other` draws the same in every node.
77    pub(crate) fn same_as(&self, other: &Self) -> bool {
78        self.color == other.color
79            && self.shape == other.shape
80            && self.coordinator.same_as(&other.coordinator)
81    }
82}