1use std::{
4 any::Any,
5 borrow::Cow,
6 cell::RefCell,
7 collections::HashMap,
8 rc::Rc,
9};
10
11use bytes::Bytes;
12use freya_engine::prelude::{
13 ClipOp,
14 LocalResourceProvider,
15 Paint,
16 SkRect,
17 svg,
18};
19use rustc_hash::FxHashMap;
20use torin::{
21 prelude::Size2D,
22 size::Size,
23};
24
25use crate::{
26 data::{
27 AccessibilityData,
28 EffectData,
29 LayoutData,
30 StyleState,
31 TextStyleData,
32 },
33 diff_key::DiffKey,
34 element::{
35 ClipContext,
36 Element,
37 ElementExt,
38 EventHandlerType,
39 LayoutContext,
40 RenderContext,
41 },
42 events::name::EventName,
43 layers::Layer,
44 prelude::{
45 AccessibilityExt,
46 Color,
47 ContainerExt,
48 EventHandlersExt,
49 KeyExt,
50 LayerExt,
51 LayoutExt,
52 MaybeExt,
53 },
54 tree::DiffModifies,
55};
56
57#[derive(Clone, PartialEq)]
60pub struct SvgBytes(Bytes);
61
62impl From<Bytes> for SvgBytes {
63 fn from(bytes: Bytes) -> Self {
64 Self(bytes)
65 }
66}
67
68impl From<Vec<u8>> for SvgBytes {
69 fn from(bytes: Vec<u8>) -> Self {
70 Self(Bytes::from(bytes))
71 }
72}
73
74impl From<&'static [u8]> for SvgBytes {
75 fn from(bytes: &'static [u8]) -> Self {
76 Self(Bytes::from_static(bytes))
77 }
78}
79
80impl<const N: usize> From<&'static [u8; N]> for SvgBytes {
81 fn from(bytes: &'static [u8; N]) -> Self {
82 Self(Bytes::from_static(bytes))
83 }
84}
85
86pub fn svg(bytes: impl Into<SvgBytes>) -> Svg {
97 let mut accessibility = AccessibilityData::default();
98 accessibility.builder.set_role(accesskit::Role::SvgRoot);
99
100 Svg {
101 key: DiffKey::None,
102 element: SvgElement {
103 accessibility,
104 layout: LayoutData::default(),
105 event_handlers: HashMap::default(),
106 bytes: bytes.into(),
107 effect: None,
108 color: Color::BLACK,
109 stroke: None,
110 stroke_width: None,
111 fill: None,
112 relative_layer: Layer::default(),
113 },
114 }
115}
116
117#[derive(PartialEq, Clone)]
118pub struct SvgElement {
119 pub accessibility: AccessibilityData,
120 pub layout: LayoutData,
121 pub event_handlers: FxHashMap<EventName, EventHandlerType>,
122 pub bytes: SvgBytes,
123 pub color: Color,
124 pub stroke: Option<Color>,
125 pub stroke_width: Option<f32>,
126 pub fill: Option<Color>,
127 pub effect: Option<EffectData>,
128 pub relative_layer: Layer,
129}
130
131impl ElementExt for SvgElement {
132 fn changed(&self, other: &Rc<dyn ElementExt>) -> bool {
133 let Some(image) = (other.as_ref() as &dyn Any).downcast_ref::<SvgElement>() else {
134 return false;
135 };
136 self != image
137 }
138
139 fn diff(&self, other: &Rc<dyn ElementExt>) -> DiffModifies {
140 let Some(svg) = (other.as_ref() as &dyn Any).downcast_ref::<SvgElement>() else {
141 return DiffModifies::all();
142 };
143
144 let mut diff = DiffModifies::empty();
145
146 if self.accessibility != svg.accessibility {
147 diff.insert(DiffModifies::ACCESSIBILITY);
148 }
149
150 if self.relative_layer != svg.relative_layer {
151 diff.insert(DiffModifies::LAYER);
152 }
153
154 if self.layout != svg.layout || self.bytes != svg.bytes {
155 diff.insert(DiffModifies::LAYOUT);
156 diff.insert(DiffModifies::STYLE);
157 }
158
159 if self.color != svg.color
160 || self.stroke != svg.stroke
161 || self.stroke_width != svg.stroke_width
162 {
163 diff.insert(DiffModifies::STYLE);
164 }
165
166 if self.effect != svg.effect {
167 diff.insert(DiffModifies::EFFECT);
168 }
169
170 diff
171 }
172
173 fn layout(&'_ self) -> Cow<'_, LayoutData> {
174 Cow::Borrowed(&self.layout)
175 }
176
177 fn effect(&'_ self) -> Option<Cow<'_, EffectData>> {
178 self.effect.as_ref().map(Cow::Borrowed)
179 }
180
181 fn style(&'_ self) -> Cow<'_, StyleState> {
182 Cow::Owned(StyleState::default())
183 }
184
185 fn text_style(&'_ self) -> Cow<'_, TextStyleData> {
186 Cow::Owned(TextStyleData::default())
187 }
188
189 fn accessibility(&'_ self) -> Cow<'_, AccessibilityData> {
190 Cow::Borrowed(&self.accessibility)
191 }
192
193 fn events_handlers(&'_ self) -> Option<Cow<'_, FxHashMap<EventName, EventHandlerType>>> {
194 Some(Cow::Borrowed(&self.event_handlers))
195 }
196
197 fn layer(&self) -> Layer {
198 self.relative_layer
199 }
200
201 fn should_measure_inner_children(&self) -> bool {
202 false
203 }
204
205 fn should_hook_measurement(&self) -> bool {
206 true
207 }
208
209 fn measure(&self, context: LayoutContext) -> Option<(Size2D, Rc<dyn Any>)> {
210 let resource_provider = LocalResourceProvider::new(context.font_manager);
211 let svg_dom = svg::Dom::from_bytes(&self.bytes.0, resource_provider);
212 if let Ok(mut svg_dom) = svg_dom {
213 svg_dom.set_container_size(context.area_size.to_i32().to_tuple());
214 let mut root = svg_dom.root();
215 match self.layout.width {
216 Size::Pixels(px) => {
217 root.set_width(svg::Length::new(px.get(), svg::LengthUnit::PX));
218 }
219 Size::Percentage(per) => {
220 root.set_width(svg::Length::new(per.get(), svg::LengthUnit::Percentage));
221 }
222 Size::Fill => {
223 root.set_width(svg::Length::new(100., svg::LengthUnit::Percentage));
224 }
225 _ => {}
226 }
227 match self.layout.height {
228 Size::Pixels(px) => {
229 root.set_height(svg::Length::new(px.get(), svg::LengthUnit::PX));
230 }
231 Size::Percentage(per) => {
232 root.set_height(svg::Length::new(per.get(), svg::LengthUnit::Percentage));
233 }
234 Size::Fill => {
235 root.set_height(svg::Length::new(100., svg::LengthUnit::Percentage));
236 }
237 _ => {}
238 }
239 if let Some(stroke_width) = self.stroke_width {
240 root.set_stroke_width(svg::Length::new(stroke_width, svg::LengthUnit::PX));
241 }
242 Some((
243 Size2D::new(root.width().value, root.height().value),
244 Rc::new(RefCell::new(svg_dom)),
245 ))
246 } else {
247 None
248 }
249 }
250
251 fn clip(&self, context: ClipContext) {
252 let area = context.visible_area;
253 context.canvas.clip_rect(
254 SkRect::new(area.min_x(), area.min_y(), area.max_x(), area.max_y()),
255 ClipOp::Intersect,
256 true,
257 );
258 }
259
260 fn render(&self, context: RenderContext) {
261 let mut paint = Paint::default();
262 paint.set_anti_alias(true);
263
264 let svg_dom = context
265 .layout_node
266 .data
267 .as_ref()
268 .unwrap()
269 .downcast_ref::<RefCell<svg::Dom>>()
270 .unwrap();
271 let svg_dom = svg_dom.borrow();
272
273 let mut root = svg_dom.root();
274 context.canvas.save();
275 context
276 .canvas
277 .translate(context.layout_node.visible_area().origin.to_tuple());
278
279 root.set_color(self.color.into());
280 if let Some(fill) = self.fill {
281 root.set_fill(svg::Paint::from_color(fill.into()));
282 }
283 if let Some(stroke) = self.stroke {
284 root.set_stroke(svg::Paint::from_color(stroke.into()));
285 }
286 if let Some(stroke_width) = self.stroke_width {
287 root.set_stroke_width(svg::Length::new(stroke_width, svg::LengthUnit::PX));
288 }
289 svg_dom.render(context.canvas);
290 context.canvas.restore();
291 }
292}
293
294impl From<Svg> for Element {
295 fn from(value: Svg) -> Self {
296 Element::Element {
297 key: value.key,
298 element: Rc::new(value.element),
299 elements: vec![],
300 }
301 }
302}
303
304impl KeyExt for Svg {
305 fn write_key(&mut self) -> &mut DiffKey {
306 &mut self.key
307 }
308}
309
310impl EventHandlersExt for Svg {
311 fn get_event_handlers(&mut self) -> &mut FxHashMap<EventName, EventHandlerType> {
312 &mut self.element.event_handlers
313 }
314}
315
316impl LayoutExt for Svg {
317 fn get_layout(&mut self) -> &mut LayoutData {
318 &mut self.element.layout
319 }
320}
321
322impl ContainerExt for Svg {}
323
324impl AccessibilityExt for Svg {
325 fn get_accessibility_data(&mut self) -> &mut AccessibilityData {
326 &mut self.element.accessibility
327 }
328}
329
330impl MaybeExt for Svg {}
331
332impl LayerExt for Svg {
333 fn get_layer(&mut self) -> &mut Layer {
334 &mut self.element.relative_layer
335 }
336}
337
338pub struct Svg {
339 key: DiffKey,
340 element: SvgElement,
341}
342
343impl Svg {
344 pub fn try_downcast(element: &dyn ElementExt) -> Option<SvgElement> {
345 (element as &dyn Any).downcast_ref::<SvgElement>().cloned()
346 }
347
348 pub fn color(mut self, color: impl Into<Color>) -> Self {
349 self.element.color = color.into();
350 self
351 }
352
353 pub fn fill(mut self, fill: impl Into<Color>) -> Self {
354 self.element.fill = Some(fill.into());
355 self
356 }
357
358 pub fn stroke(mut self, stroke: impl Into<Color>) -> Self {
359 self.element.stroke = Some(stroke.into());
360 self
361 }
362
363 pub fn stroke_width(mut self, stroke_width: impl Into<f32>) -> Self {
365 self.element.stroke_width = Some(stroke_width.into());
366 self
367 }
368
369 pub fn rotate(mut self, rotation: impl Into<f32>) -> Self {
370 self.element
371 .effect
372 .get_or_insert_with(Default::default)
373 .rotation = Some(rotation.into());
374 self
375 }
376}