1use crate::{Color, Radians, Rectangle, Size};
3
4use rustc_hash::FxHasher;
5use std::borrow::Cow;
6use std::hash::{Hash, Hasher as _};
7use std::path::PathBuf;
8use std::sync::Arc;
9
10#[derive(Debug, Clone, PartialEq)]
12pub struct Svg<H = Handle> {
13 pub handle: H,
15
16 pub color: Option<Color>,
24
25 pub rotation: Radians,
27
28 pub opacity: f32,
32
33 pub border_radius: [f32; 4],
35}
36
37impl Svg<Handle> {
38 pub fn new(handle: impl Into<Handle>) -> Self {
40 Self {
41 handle: handle.into(),
42 color: None,
43 rotation: Radians(0.0),
44 opacity: 1.0,
45 border_radius: [0.0; 4],
46 }
47 }
48
49 pub fn color(mut self, color: impl Into<Color>) -> Self {
51 self.color = Some(color.into());
52 self
53 }
54
55 pub fn rotation(mut self, rotation: impl Into<Radians>) -> Self {
57 self.rotation = rotation.into();
58 self
59 }
60
61 pub fn opacity(mut self, opacity: impl Into<f32>) -> Self {
63 self.opacity = opacity.into();
64 self
65 }
66
67 pub fn border_radius(mut self, border_radius: impl Into<[f32; 4]>) -> Self {
69 self.border_radius = border_radius.into();
70 self
71 }
72}
73
74impl From<&Handle> for Svg {
75 fn from(handle: &Handle) -> Self {
76 Svg::new(handle.clone())
77 }
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Handle {
83 id: u64,
84 data: Arc<Data>,
85}
86
87impl Handle {
88 pub fn from_path(path: impl Into<PathBuf>) -> Handle {
91 Self::from_data(Data::Path(path.into()))
92 }
93
94 pub fn from_memory(bytes: impl Into<Cow<'static, [u8]>>) -> Handle {
100 Self::from_data(Data::Bytes(bytes.into()))
101 }
102
103 fn from_data(data: Data) -> Handle {
104 let mut hasher = FxHasher::default();
105 data.hash(&mut hasher);
106
107 Handle {
108 id: hasher.finish(),
109 data: Arc::new(data),
110 }
111 }
112
113 pub fn id(&self) -> u64 {
115 self.id
116 }
117
118 pub fn data(&self) -> &Data {
120 &self.data
121 }
122}
123
124impl<T> From<T> for Handle
125where
126 T: Into<PathBuf>,
127{
128 fn from(path: T) -> Handle {
129 Handle::from_path(path.into())
130 }
131}
132
133impl Hash for Handle {
134 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
135 self.id.hash(state);
136 }
137}
138
139#[derive(Clone, Hash, PartialEq, Eq)]
141pub enum Data {
142 Path(PathBuf),
144
145 Bytes(Cow<'static, [u8]>),
149}
150
151impl std::fmt::Debug for Data {
152 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153 match self {
154 Data::Path(path) => write!(f, "Path({path:?})"),
155 Data::Bytes(_) => write!(f, "Bytes(...)"),
156 }
157 }
158}
159
160pub trait Renderer: crate::Renderer {
164 fn measure_svg(&self, handle: &Handle) -> Size<u32>;
166
167 fn draw_svg(&mut self, svg: Svg, bounds: Rectangle);
169}