use std::any::TypeId;
use std::sync::Arc;
use accesskit::{Node, Role};
use resvg::tiny_skia;
use resvg::usvg::Tree;
use tracing::{Span, trace_span};
use crate::core::{
AccessCtx, ArcStr, ChildrenIds, LayoutCtx, MeasureCtx, NoAction, PaintCtx, PropertiesMut,
PropertiesRef, Property, RegisterCtx, Update, UpdateCtx, UsesProperty, Widget, WidgetId,
WidgetMut,
};
use crate::imaging::Painter;
use crate::kurbo::{Affine, Axis, Size};
use crate::layout::{LenReq, Length};
use crate::peniko::{ImageAlphaType, ImageBrush, ImageData, ImageFormat};
use crate::properties::ObjectFit;
const SVG_SCALE: f64 = 1.0;
pub struct Svg {
tree: Arc<Tree>,
rasterized: Option<ImageBrush>,
decorative: bool,
alt_text: Option<ArcStr>,
}
impl Svg {
pub fn new(tree: Arc<Tree>) -> Self {
Self {
tree,
rasterized: None,
decorative: false,
alt_text: None,
}
}
pub fn decorative(mut self, is_decorative: bool) -> Self {
self.decorative = is_decorative;
self
}
pub fn with_alt_text(mut self, alt_text: impl Into<ArcStr>) -> Self {
self.alt_text = Some(alt_text.into());
self
}
}
impl Svg {
pub fn set_tree(this: &mut WidgetMut<'_, Self>, tree: Arc<Tree>) {
this.widget.tree = tree;
this.ctx.request_layout();
}
pub fn set_decorative(this: &mut WidgetMut<'_, Self>, is_decorative: bool) {
this.widget.decorative = is_decorative;
this.ctx.request_accessibility_update();
}
pub fn set_alt_text(this: &mut WidgetMut<'_, Self>, alt_text: Option<impl Into<ArcStr>>) {
this.widget.alt_text = alt_text.map(Into::into);
this.ctx.request_accessibility_update();
}
}
impl Svg {
fn preferred_size(&self) -> Size {
let size = self.tree.size();
Size::new(
size.width() as f64 / SVG_SCALE,
size.height() as f64 / SVG_SCALE,
)
}
}
impl UsesProperty<ObjectFit> for Svg {}
impl Widget for Svg {
type Action = NoAction;
fn register_children(&mut self, _ctx: &mut RegisterCtx<'_>) {}
fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
if ObjectFit::matches(property_type) {
ctx.request_layout();
}
}
fn update(
&mut self,
_ctx: &mut UpdateCtx<'_>,
_props: &mut PropertiesMut<'_>,
_event: &Update,
) {
}
fn measure(
&mut self,
ctx: &mut MeasureCtx<'_>,
props: &PropertiesRef<'_>,
axis: Axis,
len_req: LenReq,
cross_length: Option<Length>,
) -> Length {
let cache = ctx.property_cache();
let object_fit = props.get::<ObjectFit>(cache);
let preferred_size = self.preferred_size();
object_fit.measure(axis, len_req, cross_length, preferred_size)
}
fn layout(&mut self, _ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, _size: Size) {
self.rasterized = None;
}
fn paint(
&mut self,
ctx: &mut PaintCtx<'_>,
props: &PropertiesRef<'_>,
painter: &mut Painter<'_>,
) {
let content_box = ctx.content_box();
if self.rasterized.is_none() {
let pixmap_width = content_box.width().ceil() as u32;
let pixmap_height = content_box.height().ceil() as u32;
if pixmap_width == 0 || pixmap_height == 0 {
return;
}
let mut pixmap = tiny_skia::Pixmap::new(pixmap_width, pixmap_height).unwrap();
let cache = ctx.property_cache();
let object_fit = props.get::<ObjectFit>(cache);
let svg_size = self.tree.size();
let svg_size = Size::new(svg_size.width() as f64, svg_size.height() as f64);
let coeffs = object_fit
.affine(content_box.size().to_rect(), svg_size.to_rect())
.as_coeffs();
let transform = tiny_skia::Transform::from_row(
coeffs[0] as f32,
coeffs[1] as f32,
coeffs[2] as f32,
coeffs[3] as f32,
coeffs[4] as f32,
coeffs[5] as f32,
);
resvg::render(&self.tree, transform, &mut pixmap.as_mut());
let image = ImageBrush::new(ImageData {
data: pixmap.data().to_vec().into(),
format: ImageFormat::Rgba8,
alpha_type: ImageAlphaType::AlphaPremultiplied,
width: pixmap_width,
height: pixmap_height,
});
self.rasterized = Some(image);
}
let image = self.rasterized.as_ref().unwrap();
painter.with_fill_clip(content_box, |painter| {
painter.draw_image(image, Affine::IDENTITY);
});
}
fn accessibility_role(&self) -> Role {
Role::Image
}
fn accessibility(
&mut self,
_ctx: &mut AccessCtx<'_>,
_props: &PropertiesRef<'_>,
node: &mut Node,
) {
if let Some(alt_text) = &self.alt_text {
node.set_description(&**alt_text);
}
if self.decorative {
node.set_hidden();
}
}
fn children_ids(&self) -> ChildrenIds {
ChildrenIds::new()
}
fn make_trace_span(&self, id: WidgetId) -> Span {
trace_span!("Svg", id = id.trace())
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use resvg::usvg;
use resvg::usvg::fontdb::Database;
use super::*;
use crate::testing::{ROBOTO, TestHarness, assert_render_snapshot};
use crate::theme::test_property_set;
#[test]
fn empty_tree() {
let xml = r#"<svg xmlns="http://www.w3.org/2000/svg"/>"#;
let tree = Tree::from_str(xml, &usvg::Options::default()).unwrap();
let svg = Svg::new(Arc::new(tree)).prepare();
let mut harness = TestHarness::create(test_property_set(), svg);
let _ = harness.render();
}
#[test]
fn brick_wall() {
let xml = r###"
<svg xmlns="http://www.w3.org/2000/svg" width="852" height="320" viewBox="0 0 852 320">
<defs>
<!-- Clip the wall so we can reuse full bricks as edge half-bricks -->
<clipPath id="wall-clip">
<rect x="10" y="10" width="833" height="310" />
</clipPath>
<!-- One reusable brick -->
<g id="brick">
<rect x="0" y="0" width="160" height="70" rx="4" ry="4"
fill="#b24a3a" stroke="#8b3429" stroke-width="2" />
<text x="80" y="42"
text-anchor="middle"
font-family="Roboto"
font-size="24"
fill="#f7e7cf">Masonry</text>
</g>
</defs>
<!-- Mortar background -->
<rect x="0" y="0" width="852" height="320" fill="#d8d3cd" />
<!-- All bricks are clipped to the wall area -->
<g clip-path="url(#wall-clip)">
<!-- Row 1 -->
<use href="#brick" x="10" y="10" />
<use href="#brick" x="178" y="10" />
<use href="#brick" x="346" y="10" />
<use href="#brick" x="514" y="10" />
<use href="#brick" x="682" y="10" />
<!-- Row 2 (staggered + clipped) -->
<use href="#brick" x="-70" y="88" />
<use href="#brick" x="98" y="88" />
<use href="#brick" x="266" y="88" />
<use href="#brick" x="434" y="88" />
<use href="#brick" x="602" y="88" />
<use href="#brick" x="770" y="88" />
<!-- Row 3 -->
<use href="#brick" x="10" y="166" />
<use href="#brick" x="178" y="166" />
<use href="#brick" x="346" y="166" />
<use href="#brick" x="514" y="166" />
<use href="#brick" x="682" y="166" />
<!-- Row 4 (staggered + clipped) -->
<use href="#brick" x="-70" y="244" />
<use href="#brick" x="98" y="244" />
<use href="#brick" x="266" y="244" />
<use href="#brick" x="434" y="244" />
<use href="#brick" x="602" y="244" />
<use href="#brick" x="770" y="244" />
</g>
</svg>
"###;
let mut fontdb = Database::new();
fontdb.load_font_data(ROBOTO.into());
let opts = usvg::Options {
fontdb: Arc::new(fontdb),
..usvg::Options::default()
};
let tree = Tree::from_str(xml, &opts).unwrap();
let svg = Svg::new(Arc::new(tree)).prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), svg, (852, 320));
assert_render_snapshot!(harness, "svg_brick_wall");
}
}