1use std::{
2 rc::Rc,
3 sync::LazyLock,
4};
5
6use anyhow::Context;
7use async_lock::Semaphore;
8use bytes::Bytes;
9use freya_core::{
10 element::EventHandlers,
11 elements::image::*,
12 prelude::*,
13};
14use freya_engine::prelude::{
15 FontMgr,
16 SkImage,
17 raster_n32_premul,
18 svg,
19};
20use torin::prelude::{
21 Size,
22 Size2D,
23};
24
25use crate::{
26 cache::*,
27 image_viewer::{
28 DecodeSize,
29 ImageSource,
30 },
31 loader::CircularLoader,
32 theming::hooks::get_theme_or_default,
33};
34
35static RASTER_LIMIT: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(4));
37
38#[derive(Default, Clone, Copy, PartialEq)]
40struct SvgStyle {
41 color: Option<Color>,
42 fill: Option<Color>,
43 stroke: Option<Color>,
44 stroke_width: Option<f32>,
45}
46
47impl SvgStyle {
48 fn as_key(&self) -> (Option<Color>, Option<Color>, Option<Color>, Option<u32>) {
50 (
51 self.color,
52 self.fill,
53 self.stroke,
54 self.stroke_width.map(f32::to_bits),
55 )
56 }
57}
58
59fn rasterize_bytes(bytes: &[u8], size: DecodeSize, style: SvgStyle) -> anyhow::Result<SkImage> {
61 let width = size.width.max(1) as i32;
62 let height = size.height.max(1) as i32;
63
64 let mut dom = svg::Dom::from_bytes(bytes, FontMgr::empty())
65 .map_err(|err| anyhow::anyhow!("Failed to parse SVG: {err:?}"))?;
66 dom.set_container_size((width, height));
67
68 let mut root = dom.root();
69 root.set_width(svg::Length::new(width as f32, svg::LengthUnit::PX));
70 root.set_height(svg::Length::new(height as f32, svg::LengthUnit::PX));
71 root.set_color(style.color.unwrap_or(Color::BLACK).into());
72 if let Some(fill) = style.fill {
73 root.set_fill(svg::Paint::from_color(fill.into()));
74 }
75 if let Some(stroke) = style.stroke {
76 root.set_stroke(svg::Paint::from_color(stroke.into()));
77 }
78 if let Some(stroke_width) = style.stroke_width {
79 root.set_stroke_width(svg::Length::new(stroke_width, svg::LengthUnit::PX));
80 }
81
82 let mut surface =
83 raster_n32_premul((width, height)).context("Failed to create the SVG surface.")?;
84 dom.render(surface.canvas());
85 Ok(surface.image_snapshot())
86}
87
88fn store_raster(
90 mut asset_cacher: AssetCacher,
91 asset_config: AssetConfiguration,
92 result: anyhow::Result<SkImage>,
93) {
94 match result {
95 Ok(image) => {
96 asset_cacher.update_asset(
97 asset_config,
98 Asset::Cached(Rc::new(ImageHandle::new(image, Bytes::new()))),
99 );
100 }
101 Err(err) => {
102 asset_cacher.update_asset(asset_config, Asset::Error(err.to_string()));
103 }
104 }
105}
106
107#[derive(PartialEq)]
128pub struct SvgViewer {
129 source: ImageSource,
130 asset_age: AssetAge,
131
132 layout: LayoutData,
133 image_data: ImageData,
134 accessibility: AccessibilityData,
135 effect: EffectData,
136 event_handlers: EventHandlers,
137 style: SvgStyle,
138 show_loader: bool,
139 async_rasterization: bool,
140
141 children: Vec<Element>,
142 error_renderer: Option<Callback<String, Element>>,
143
144 key: DiffKey,
145}
146
147impl SvgViewer {
148 pub fn new(source: impl Into<ImageSource>) -> Self {
149 let mut accessibility = AccessibilityData::default();
150 accessibility.builder.set_role(AccessibilityRole::SvgRoot);
151
152 SvgViewer {
153 source: source.into(),
154 asset_age: AssetAge::default(),
155 layout: LayoutData::default(),
156 image_data: ImageData {
157 snap_to_grid: true,
158 ..ImageData::default()
159 },
160 accessibility,
161 effect: EffectData::default(),
162 event_handlers: EventHandlers::default(),
163 style: SvgStyle::default(),
164 show_loader: true,
165 async_rasterization: false,
166 children: Vec::new(),
167 error_renderer: None,
168 key: DiffKey::None,
169 }
170 }
171
172 pub fn show_loader(mut self, show_loader: bool) -> Self {
174 self.show_loader = show_loader;
175 self
176 }
177
178 pub fn async_rasterization(mut self, async_rasterization: bool) -> Self {
181 self.async_rasterization = async_rasterization;
182 self
183 }
184
185 pub fn color(mut self, color: impl Into<Color>) -> Self {
188 self.style.color = Some(color.into());
189 self
190 }
191
192 pub fn fill(mut self, fill: impl Into<Color>) -> Self {
194 self.style.fill = Some(fill.into());
195 self
196 }
197
198 pub fn stroke(mut self, stroke: impl Into<Color>) -> Self {
200 self.style.stroke = Some(stroke.into());
201 self
202 }
203
204 pub fn stroke_width(mut self, stroke_width: f32) -> Self {
206 self.style.stroke_width = Some(stroke_width);
207 self
208 }
209
210 pub fn asset_age(mut self, asset_age: impl Into<AssetAge>) -> Self {
212 self.asset_age = asset_age.into();
213 self
214 }
215
216 pub fn error_renderer(mut self, renderer: impl Into<Callback<String, Element>>) -> Self {
218 self.error_renderer = Some(renderer.into());
219 self
220 }
221}
222
223impl KeyExt for SvgViewer {
224 fn key_mut(&mut self) -> &mut DiffKey {
225 &mut self.key
226 }
227}
228
229impl LayoutExt for SvgViewer {
230 fn layout_mut(&mut self) -> &mut LayoutData {
231 &mut self.layout
232 }
233}
234
235impl ContainerSizeExt for SvgViewer {}
236impl ContainerWithContentExt for SvgViewer {}
237impl ContainerPositionExt for SvgViewer {}
238
239impl ChildrenExt for SvgViewer {
240 fn children_mut(&mut self) -> &mut Vec<Element> {
241 &mut self.children
242 }
243}
244
245impl ImageExt for SvgViewer {
246 fn image_data_mut(&mut self) -> &mut ImageData {
247 &mut self.image_data
248 }
249}
250
251impl AccessibilityExt for SvgViewer {
252 fn accessibility_data_mut(&mut self) -> &mut AccessibilityData {
253 &mut self.accessibility
254 }
255}
256
257impl EffectExt for SvgViewer {
258 fn effect_mut(&mut self) -> &mut EffectData {
259 &mut self.effect
260 }
261}
262
263impl EventHandlersExt for SvgViewer {
264 fn event_handlers_mut(&mut self) -> &mut EventHandlers {
265 &mut self.event_handlers
266 }
267}
268
269impl Component for SvgViewer {
270 fn render(&self) -> impl IntoElement {
271 let scale_factor = *Platform::get().current_window().scale_factor.read();
272 let layout = self.layout.clone();
273 let mut measured = use_state(|| match (&layout.width, &layout.height) {
274 (Size::Pixels(width), Size::Pixels(height)) => {
275 Some(Size2D::new(width.get(), height.get()))
276 }
277 _ => None,
278 });
279 let mut asset_cacher = use_hook(AssetCacher::get);
280 let mut inherited_color = use_state::<Option<Color>>(|| None);
281
282 let target = measured().map(|logical| {
283 DecodeSize::new(
284 (logical.width * scale_factor as f32).round().max(1.) as u32,
285 (logical.height * scale_factor as f32).round().max(1.) as u32,
286 )
287 });
288
289 let mut style = self.style;
290 if style.color.is_none() {
291 style.color = inherited_color();
292 }
293
294 let asset_config =
295 AssetConfiguration::new((&self.source, target, style.as_key()), self.asset_age);
296 use_asset(&asset_config);
297
298 let mut previous_configuration = use_state(|| None);
300 if *previous_configuration.peek() != Some((asset_config.clone(), self.async_rasterization))
301 {
302 previous_configuration.set(Some((asset_config.clone(), self.async_rasterization)));
303
304 if let Some(target) = target
305 && matches!(
306 asset_cacher.read_asset(&asset_config),
307 Some(Asset::Pending) | Some(Asset::Error(_))
308 )
309 {
310 asset_cacher.update_asset(asset_config.clone(), Asset::Loading);
311
312 if self.async_rasterization || self.source.is_remote() {
313 let source = self.source.clone();
314 let asset_config = asset_config.clone();
315 spawn_in_window(async move {
316 let result = match source.bytes().await {
317 Ok(bytes) => {
318 let _permit = RASTER_LIMIT.acquire().await;
319 thread(move || rasterize_bytes(&bytes, target, style)).await
320 }
321 Err(err) => Err(err),
322 };
323 store_raster(asset_cacher, asset_config.clone(), result);
324 });
325 } else {
326 let result = self
327 .source
328 .clone()
329 .fetch()
330 .and_then(|bytes| rasterize_bytes(&bytes, target, style));
331 store_raster(asset_cacher, asset_config.clone(), result);
332 }
333 }
334 }
335
336 let asset = asset_cacher
337 .read_asset(&asset_config)
338 .expect("Asset should exist by now");
339
340 match asset {
341 Asset::Cached(asset) => {
342 let handle = asset.downcast_ref::<ImageHandle>().unwrap().clone();
343 image(handle)
344 .accessibility(self.accessibility.clone())
345 .layout(layout)
346 .image_data(self.image_data.clone())
347 .effect(self.effect.clone())
348 .children(self.children.clone())
349 .event_handlers(self.event_handlers.clone())
350 .on_sized(move |event: Event<SizedEventData>| {
351 measured.set_if_modified(Some(event.visible_area.size));
352 })
353 .on_styled(move |event: Event<StyledEventData>| {
354 let color = event.text_style.color.as_color().unwrap_or(Color::BLACK);
355 inherited_color.set_if_modified(Some(color));
356 })
357 .into_element()
358 }
359 Asset::Error(err) => match &self.error_renderer {
360 Some(renderer) => renderer.call(err),
361 None => err.into(),
362 },
363 Asset::Pending | Asset::Loading => rect()
364 .layout(layout)
365 .event_handlers(self.event_handlers.clone())
366 .on_sized(move |event: Event<SizedEventData>| {
367 measured.set_if_modified(Some(event.visible_area.size));
368 })
369 .on_styled(move |event: Event<StyledEventData>| {
370 let color = event.text_style.color.as_color().unwrap_or(Color::BLACK);
371 inherited_color.set_if_modified(Some(color));
372 })
373 .center()
374 .maybe(self.show_loader, |loading| {
375 loading.child(CircularLoader::new())
376 })
377 .into_element(),
378 }
379 }
380
381 fn render_key(&self) -> DiffKey {
382 self.key.clone().or(self.default_key())
383 }
384}
385
386pub trait SvgThemeExt {
388 fn theme_color(self) -> Self;
389 fn theme_accent_color(self) -> Self;
390 fn theme_fill(self) -> Self;
391 fn theme_stroke(self) -> Self;
392 fn theme_accent_fill(self) -> Self;
393 fn theme_accent_stroke(self) -> Self;
394}
395
396impl SvgThemeExt for SvgViewer {
397 fn theme_color(self) -> Self {
398 let theme = get_theme_or_default();
399 self.color(theme.read().colors.text_primary)
400 }
401
402 fn theme_accent_color(self) -> Self {
403 let theme = get_theme_or_default();
404 self.color(theme.read().colors.primary)
405 }
406
407 fn theme_fill(self) -> Self {
408 let theme = get_theme_or_default();
409 self.fill(theme.read().colors.text_primary)
410 }
411
412 fn theme_stroke(self) -> Self {
413 let theme = get_theme_or_default();
414 self.stroke(theme.read().colors.text_primary)
415 }
416
417 fn theme_accent_fill(self) -> Self {
418 let theme = get_theme_or_default();
419 self.fill(theme.read().colors.primary)
420 }
421
422 fn theme_accent_stroke(self) -> Self {
423 let theme = get_theme_or_default();
424 self.stroke(theme.read().colors.primary)
425 }
426}