Skip to main content

mitsuami_core/
draw.rs

1//! The drawn tier of custom widgets: a small, platform-neutral 2D API.
2//!
3//! Drawing records a [`DisplayList`]: plain data the core sends to the
4//! backend as a prop. Backends rasterize it with the platform's own 2D
5//! library (CoreGraphics, Direct2D, Cairo/GSK) and resolve semantic colors
6//! against the current appearance, so drawn widgets follow dark mode and
7//! the accent color without redrawing in app code.
8
9use crate::backend::PlatformMetrics;
10use crate::geometry::{Point, Rect, Size};
11
12/// Semantic colors follow the platform's appearance; `Rgba` is fixed.
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
14pub enum Color {
15    Label,
16    SecondaryLabel,
17    Accent,
18    Separator,
19    ControlBackground,
20    WindowBackground,
21    /// Something went wrong, or is destructive: the platform's red.
22    Error,
23    /// Something needs attention: the platform's orange or yellow.
24    Warning,
25    /// Something went well: the platform's green.
26    Success,
27    /// A field's placeholder: the faint text it shows while it's empty.
28    Placeholder,
29    /// Text and icons on an `Accent` fill (a badge, a selected row): the
30    /// platform's pairing, dark on a light accent where it makes one.
31    OnAccent,
32    Rgba(u8, u8, u8, u8),
33}
34
35impl Color {
36    pub const fn rgb(r: u8, g: u8, b: u8) -> Color {
37        Color::Rgba(r, g, b, 255)
38    }
39
40    /// A fixed colour as `#rrggbb`, as a colour well's value reads; `None`
41    /// for a semantic one.
42    pub fn hex(self) -> Option<String> {
43        match self {
44            Color::Rgba(r, g, b, _) => Some(format!("#{r:02x}{g:02x}{b:02x}")),
45            _ => None,
46        }
47    }
48
49    /// `#rrggbb` (or `rrggbb`) as an opaque colour.
50    pub fn from_hex(hex: &str) -> Option<Color> {
51        let hex = hex.trim().trim_start_matches('#');
52        if hex.len() != 6 || !hex.is_ascii() {
53            return None;
54        }
55        let byte = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok();
56        Some(Color::rgb(byte(0)?, byte(2)?, byte(4)?))
57    }
58}
59
60#[derive(Clone, Copy, Debug, PartialEq)]
61pub enum PathElement {
62    MoveTo(Point),
63    LineTo(Point),
64    /// A cubic Bézier curve to `to`.
65    CurveTo {
66        c1: Point,
67        c2: Point,
68        to: Point,
69    },
70    Close,
71}
72
73/// A vector path, built by chaining: `Path::new().move_to(0.0, 0.0).line_to(10.0, 0.0).close()`.
74#[derive(Clone, Debug, Default, PartialEq)]
75pub struct Path {
76    elements: Vec<PathElement>,
77}
78
79impl Path {
80    pub fn new() -> Path {
81        Path::default()
82    }
83
84    pub fn move_to(mut self, x: f32, y: f32) -> Path {
85        self.elements.push(PathElement::MoveTo(Point::new(x, y)));
86        self
87    }
88
89    pub fn line_to(mut self, x: f32, y: f32) -> Path {
90        self.elements.push(PathElement::LineTo(Point::new(x, y)));
91        self
92    }
93
94    pub fn curve_to(mut self, c1: Point, c2: Point, to: Point) -> Path {
95        self.elements.push(PathElement::CurveTo { c1, c2, to });
96        self
97    }
98
99    pub fn close(mut self) -> Path {
100        self.elements.push(PathElement::Close);
101        self
102    }
103
104    /// A closed polygon through `points`.
105    pub fn polygon(points: impl IntoIterator<Item = Point>) -> Path {
106        let mut path = Path::new();
107        for (i, p) in points.into_iter().enumerate() {
108            path = if i == 0 { path.move_to(p.x, p.y) } else { path.line_to(p.x, p.y) };
109        }
110        path.close()
111    }
112
113    pub fn elements(&self) -> &[PathElement] {
114        &self.elements
115    }
116}
117
118#[derive(Clone, Debug, PartialEq)]
119pub enum Shape {
120    Rect(Rect),
121    RoundedRect(Rect, f32),
122    Ellipse(Rect),
123    Path(Path),
124}
125
126impl From<Rect> for Shape {
127    fn from(rect: Rect) -> Shape {
128        Shape::Rect(rect)
129    }
130}
131
132impl From<Path> for Shape {
133    fn from(path: Path) -> Shape {
134        Shape::Path(path)
135    }
136}
137
138#[derive(Clone, Debug, PartialEq)]
139pub enum DrawOp {
140    Fill { shape: Shape, color: Color },
141    Stroke { shape: Shape, color: Color, width: f32 },
142}
143
144/// What a drawn widget looks like, in its own coordinates (logical units,
145/// origin at the top-left).
146#[derive(Clone, Debug, Default, PartialEq)]
147pub struct DisplayList(pub Vec<DrawOp>);
148
149impl DisplayList {
150    pub fn ops(&self) -> &[DrawOp] {
151        &self.0
152    }
153}
154
155/// Where a drawn widget draws. Records operations; draws nothing itself.
156pub struct Canvas<'a> {
157    size: Size,
158    metrics: &'a PlatformMetrics,
159    ops: Vec<DrawOp>,
160}
161
162impl<'a> Canvas<'a> {
163    pub fn new(size: Size, metrics: &'a PlatformMetrics) -> Canvas<'a> {
164        Canvas { size, metrics, ops: Vec::new() }
165    }
166
167    /// The widget's laid-out size.
168    pub fn size(&self) -> Size {
169        self.size
170    }
171
172    /// Font sizes and spacing tokens, for sizing things like the platform does.
173    pub fn metrics(&self) -> &PlatformMetrics {
174        self.metrics
175    }
176
177    pub fn fill(&mut self, shape: impl Into<Shape>, color: Color) {
178        self.ops.push(DrawOp::Fill { shape: shape.into(), color });
179    }
180
181    pub fn stroke(&mut self, shape: impl Into<Shape>, color: Color, width: f32) {
182        self.ops.push(DrawOp::Stroke { shape: shape.into(), color, width });
183    }
184
185    pub fn finish(self) -> DisplayList {
186        DisplayList(self.ops)
187    }
188}