Skip to main content

mitsuami_core/
vector_icon.rs

1//! An app's own icon, from vector path data, shown the way each platform
2//! shows its symbolic icons: in the colour it gives icons, which follows
3//! dark mode, and in an icon's size.
4
5use std::fmt;
6use std::sync::Arc;
7
8use kurbo::{Affine, BezPath, PathEl, Shape};
9
10use crate::geometry::{Point, Rect, Size};
11
12/// An icon the app draws, as path data in the SVG path syntax (`M0 0L10
13/// 10Z`, arcs too), which SVG files, XAML's and Avalonia's geometries and
14/// most icon sets use. A leading `F0` (even-odd) or `F1` (non-zero), as
15/// XAML's path data has, sets the fill rule; non-zero by default.
16///
17/// It's filled in the colour the platform gives symbolic icons: AppKit
18/// draws it as a template image, GTK as a symbolic SVG, Kirigami as a mask,
19/// WinUI as a `PathIcon`.
20#[derive(Clone)]
21pub struct VectorIcon(Arc<Inner>);
22
23struct Inner {
24    path: BezPath,
25    view_box: Rect,
26    even_odd: bool,
27}
28
29/// A step of an icon's path, in points from the icon's top left corner.
30#[derive(Clone, Copy, Debug, PartialEq)]
31pub enum PathStep {
32    Move(Point),
33    Line(Point),
34    Quad(Point, Point),
35    Cubic(Point, Point, Point),
36    Close,
37}
38
39impl VectorIcon {
40    /// The path fitted to its own bounds, as XAML's `Path` with uniform
41    /// stretch shows it.
42    pub fn new(data: &str) -> Result<VectorIcon, String> {
43        let (path, even_odd) = parse(data)?;
44        let b = path.bounding_box();
45        let view_box = Rect::new(b.x0 as f32, b.y0 as f32, b.width() as f32, b.height() as f32);
46        Ok(VectorIcon(Arc::new(Inner { path, view_box, even_odd })))
47    }
48
49    /// The path in a view box, as an SVG file's `viewBox`: icon sets draw
50    /// on a grid (24 by 24, say), with room around each shape.
51    pub fn with_view_box(data: &str, view_box: Rect) -> Result<VectorIcon, String> {
52        let (path, even_odd) = parse(data)?;
53        Ok(VectorIcon(Arc::new(Inner { path, view_box, even_odd })))
54    }
55
56    pub fn view_box(&self) -> Rect {
57        self.0.view_box
58    }
59
60    /// Whether it fills by the even-odd rule, not the non-zero one.
61    pub fn even_odd(&self) -> bool {
62        self.0.even_odd
63    }
64
65    /// The path in a square of `side` points, its view box fitted inside,
66    /// keeping its proportions, and centred; y goes down.
67    pub fn steps(&self, side: f32) -> Vec<PathStep> {
68        let p = |p: kurbo::Point| Point::new(p.x as f32, p.y as f32);
69        self.fitted(side)
70            .elements()
71            .iter()
72            .map(|el| match *el {
73                PathEl::MoveTo(a) => PathStep::Move(p(a)),
74                PathEl::LineTo(a) => PathStep::Line(p(a)),
75                PathEl::QuadTo(a, b) => PathStep::Quad(p(a), p(b)),
76                PathEl::CurveTo(a, b, c) => PathStep::Cubic(p(a), p(b), p(c)),
77                PathEl::ClosePath => PathStep::Close,
78            })
79            .collect()
80    }
81
82    /// The path data fitted in a square of `side` points, as for
83    /// [`steps`](Self::steps): for platforms that take path data (XAML).
84    pub fn path_data(&self, side: f32) -> String {
85        self.fitted(side).to_svg()
86    }
87
88    /// An SVG file of it, `side` points square, filled black: for
89    /// platforms that recolour symbolic SVGs (GTK, Kirigami).
90    pub fn svg(&self, side: f32) -> String {
91        let rule = if self.0.even_odd { "evenodd" } else { "nonzero" };
92        format!(
93            "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{side}\" height=\"{side}\" viewBox=\"0 0 {side} {side}\">\
94             <path fill=\"#000\" fill-rule=\"{rule}\" d=\"{}\"/></svg>",
95            self.path_data(side)
96        )
97    }
98
99    fn fitted(&self, side: f32) -> BezPath {
100        let Rect { origin, size: Size { width, height } } = self.0.view_box;
101        let longest = width.max(height);
102        if longest <= 0.0 {
103            return BezPath::new();
104        }
105        let scale = f64::from(side / longest);
106        let dx = f64::from(side - width * side / longest) / 2.0 - f64::from(origin.x) * scale;
107        let dy = f64::from(side - height * side / longest) / 2.0 - f64::from(origin.y) * scale;
108        Affine::new([scale, 0.0, 0.0, scale, dx, dy]) * &self.0.path
109    }
110}
111
112fn parse(data: &str) -> Result<(BezPath, bool), String> {
113    let data = data.trim();
114    let (data, even_odd) = match data.get(..2) {
115        Some("F0") => (&data[2..], true),
116        Some("F1") => (&data[2..], false),
117        _ => (data, false),
118    };
119    let path = BezPath::from_svg(data).map_err(|e| format!("bad path data: {e}"))?;
120    Ok((path, even_odd))
121}
122
123impl PartialEq for VectorIcon {
124    fn eq(&self, other: &VectorIcon) -> bool {
125        Arc::ptr_eq(&self.0, &other.0)
126            || (self.0.view_box == other.0.view_box
127                && self.0.even_odd == other.0.even_odd
128                && self.0.path == other.0.path)
129    }
130}
131
132/// Its size, not its path: props print in snapshots.
133impl fmt::Debug for VectorIcon {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        let Size { width, height } = self.0.view_box.size;
136        write!(f, "VectorIcon({} steps in {width}×{height})", self.0.path.elements().len())
137    }
138}