use bevy::asset::{AssetServer, Assets, Handle};
use bevy::ecs::world::EntityWorldMut;
use bevy::image::Image;
use bevy::ui::widget::ImageNode;
use super::{SvgDocument, SvgSurface};
pub(crate) fn is_svg_src(src: &str) -> bool {
src.get(src.len().wrapping_sub(4)..)
.is_some_and(|ext| ext.eq_ignore_ascii_case(".svg"))
}
pub(crate) fn warn_ignored_attrs(atlas: bool, source_rect: bool) {
for (present, name) in [(atlas, "atlas"), (source_rect, "sourceRect")] {
if present {
crate::diag::report(
"svgImageAttrs",
name,
&format!(
"`{name}` is ignored on an svg-mode <image> \
(the document rasters whole at laid-out size)"
),
);
}
}
}
pub(crate) fn ensure_svg_image(mut entity: EntityWorldMut, path: String, mut img: ImageNode) {
let doc: Handle<SvgDocument> =
entity.world_scope(|world| world.resource::<AssetServer>().load(path));
let texture = match (entity.get::<SvgSurface>(), entity.get::<ImageNode>()) {
(Some(_), Some(node)) => node.image.clone(),
_ => entity.world_scope(|world| {
world
.resource_mut::<Assets<Image>>()
.add(crate::canvas::blank_canvas_image())
}),
};
img.image = texture;
let same_doc = entity
.get::<SvgSurface>()
.map(|surface| surface.doc.as_ref().map(Handle::id) == Some(doc.id()));
match same_doc {
Some(true) => {}
Some(false) => {
if let Some(mut surface) = entity.get_mut::<SvgSurface>() {
surface.doc = Some(doc.clone());
surface.dirty = true;
}
}
None => {
entity.insert(SvgSurface::new(doc.clone()));
}
}
entity.insert(img);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn svg_extension_detection() {
assert!(is_svg_src("icons/a.svg"));
assert!(is_svg_src("ICONS/A.SVG"));
assert!(is_svg_src("a.SvG"));
assert!(!is_svg_src("a.png"));
assert!(!is_svg_src("svg"));
assert!(!is_svg_src(".sv"));
assert!(!is_svg_src("a.svg.png"));
assert!(!is_svg_src("naïve.png")); assert!(is_svg_src("naïve.svg"));
}
}