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
34impl Svg<Handle> {
35 pub fn new(handle: impl Into<Handle>) -> Self {
37 Self {
38 handle: handle.into(),
39 color: None,
40 rotation: Radians(0.0),
41 opacity: 1.0,
42 }
43 }
44
45 pub fn color(mut self, color: impl Into<Color>) -> Self {
47 self.color = Some(color.into());
48 self
49 }
50
51 pub fn rotation(mut self, rotation: impl Into<Radians>) -> Self {
53 self.rotation = rotation.into();
54 self
55 }
56
57 pub fn opacity(mut self, opacity: impl Into<f32>) -> Self {
59 self.opacity = opacity.into();
60 self
61 }
62}
63
64impl From<&Handle> for Svg {
65 fn from(handle: &Handle) -> Self {
66 Svg::new(handle.clone())
67 }
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct Handle {
73 id: u64,
74 data: Arc<Data>,
75}
76
77impl Handle {
78 pub fn from_path(path: impl Into<PathBuf>) -> Handle {
81 Self::from_data(Data::Path(path.into()))
82 }
83
84 pub fn from_memory(bytes: impl Into<Cow<'static, [u8]>>) -> Handle {
90 Self::from_data(Data::Bytes(bytes.into()))
91 }
92
93 fn from_data(data: Data) -> Handle {
94 let mut hasher = FxHasher::default();
95 data.hash(&mut hasher);
96
97 Handle {
98 id: hasher.finish(),
99 data: Arc::new(data),
100 }
101 }
102
103 pub fn id(&self) -> u64 {
105 self.id
106 }
107
108 pub fn data(&self) -> &Data {
110 &self.data
111 }
112}
113
114impl<T> From<T> for Handle
115where
116 T: Into<PathBuf>,
117{
118 fn from(path: T) -> Handle {
119 Handle::from_path(path.into())
120 }
121}
122
123impl Hash for Handle {
124 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
125 self.id.hash(state);
126 }
127}
128
129#[derive(Clone, Hash, PartialEq, Eq)]
131pub enum Data {
132 Path(PathBuf),
134
135 Bytes(Cow<'static, [u8]>),
139}
140
141impl std::fmt::Debug for Data {
142 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143 match self {
144 Data::Path(path) => write!(f, "Path({path:?})"),
145 Data::Bytes(_) => write!(f, "Bytes(...)"),
146 }
147 }
148}
149
150pub trait Renderer: crate::Renderer {
154 fn measure_svg(&self, handle: &Handle) -> Size<u32>;
156
157 fn draw_svg(&mut self, svg: Svg, bounds: Rectangle);
159}