use crate::prelude::*;
impl Render for Svg {
#[inline]
fn perform_layout(&self, clamp: BoxClamp, _: &mut LayoutCtx) -> Size { clamp.clamp(self.size()) }
fn visual_box(&self, ctx: &mut VisualCtx) -> Option<Rect> {
Some(Rect::from_size(ctx.box_size()?))
}
fn paint(&self, ctx: &mut PaintingCtx) {
let size = ctx.box_size().unwrap();
let painter = ctx.painter();
if self.size().greater_than(size).any() {
painter.clip(Path::rect(&Rect::from_size(size)).into());
}
painter.draw_svg(self);
}
}
pub mod svg_registry {
use std::sync::{LazyLock, Mutex};
pub use super::*;
static SVG_REGISTRY: LazyLock<Mutex<ahash::AHashMap<&'static str, Svg>>> =
LazyLock::new(|| Mutex::new(ahash::AHashMap::new()));
pub fn register(name: &'static str, svg: Svg) { SVG_REGISTRY.lock().unwrap().insert(name, svg); }
pub fn get(name: &str) -> Option<Svg> { SVG_REGISTRY.lock().unwrap().get(name).cloned() }
pub fn get_or_default(name: &str) -> Svg { get(name).unwrap_or_else(default_svg) }
pub fn default_svg() -> Svg {
static DEFAULT_SVG: LazyLock<Mutex<Svg>> =
LazyLock::new(|| Mutex::new(include_asset!("./icon_miss.svg", "svg", inherit_stroke = true)));
DEFAULT_SVG.lock().unwrap().clone()
}
pub fn set_default_svg(svg: Svg) {
static DEFAULT_SVG: LazyLock<Mutex<Svg>> =
LazyLock::new(|| Mutex::new(include_asset!("./icon_miss.svg", "svg", inherit_fill = true)));
let mut default_svg = DEFAULT_SVG.lock().unwrap();
*default_svg = svg;
}
pub fn clear() { SVG_REGISTRY.lock().unwrap().clear(); }
pub fn contains(name: &str) -> bool { SVG_REGISTRY.lock().unwrap().contains_key(name) }
pub fn len() -> usize { SVG_REGISTRY.lock().unwrap().len() }
pub fn is_empty() -> bool { SVG_REGISTRY.lock().unwrap().is_empty() }
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(test)]
mod tests {
use ribir_dev_helper::*;
use super::*;
fn svgs_smoke() -> Painter {
svg_registry::register(
"test::add",
Svg::parse_from_bytes(r#"<svg xmlns="http://www.w3.org/2000/svg" height="48" width="48"><path d="M22.5 38V25.5H10v-3h12.5V10h3v12.5H38v3H25.5V38Z"/></svg>"#.as_bytes(),
true, false
).unwrap(),
);
let mut painter = Painter::new(Rect::from_size(Size::new(128., 64.)));
let add = svg_registry::get("test::add").unwrap();
let x = svg_registry::get_or_default("x");
painter
.draw_svg(&add)
.translate(64., 0.)
.draw_svg(&x);
painter
}
painter_backend_eq_image_test!(svgs_smoke, comparison = 0.001);
}