use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::ops::Range;
use std::path::{Path, PathBuf};
use roxmltree::{Document, Node};
use url::Url;
use super::{data_uri, read_data_uri};
use crate::{Error, Result};
const SVG_NS: &str = "http://www.w3.org/2000/svg";
const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
fn invalid(message: impl Into<String>) -> Error {
Error::Data(message.into().into())
}
pub(crate) fn parse(source: &str) -> Result<Document<'_>> {
let doc = Document::parse(source)
.map_err(|error| invalid(format!("invalid static SVG XML: {error}")))?;
if !doc.root_element().has_tag_name((SVG_NS, "svg")) {
return Err(invalid("asset requires an SVG document root"));
}
Ok(doc)
}
pub(super) fn utf8(bytes: &[u8]) -> Result<&str> {
std::str::from_utf8(bytes).map_err(|error| invalid(format!("SVG/CSS requires UTF-8: {error}")))
}
pub(super) fn escape(value: &str) -> String {
value
.replace('&', "&")
.replace('<', "<")
.replace('"', """)
.replace('\'', "'")
}
pub(super) fn apply_edits(source: &str, mut edits: Vec<(Range<usize>, String)>) -> Result<String> {
edits.sort_by_key(|(range, _)| (range.start, range.end));
let mut result = String::new();
let mut cursor = 0;
for (range, replacement) in edits {
if range.start < cursor || range.end > source.len() {
return Err(invalid("overlapping SVG resource edits"));
}
crate::data::source::reserve_source_string(
&mut result,
range.start - cursor + replacement.len(),
)?;
result.push_str(&source[cursor..range.start]);
result.push_str(&replacement);
cursor = range.end;
}
crate::data::source::reserve_source_string(&mut result, source.len() - cursor)?;
result.push_str(&source[cursor..]);
Ok(result)
}
pub(super) fn opening_end(source: &str, node: Node<'_, '_>) -> usize {
let mut quote = None;
for (index, ch) in source[node.range().start..].char_indices() {
match (quote, ch) {
(Some(q), ch) if q == ch => quote = None,
(None, '\'' | '"') => quote = Some(ch),
(None, '>') => return node.range().start + index,
_ => {}
}
}
unreachable!("validated XML start tag")
}
struct Resource {
mime: String,
bytes: Vec<u8>,
base: Option<Url>,
path: Option<PathBuf>,
fragment: Option<String>,
}
#[derive(Default)]
struct Closure {
files: HashMap<PathBuf, Vec<u8>>,
active: HashSet<PathBuf>,
}
pub(super) fn close(bytes: &[u8], path: Option<&Path>) -> Result<String> {
let mut closure = Closure::default();
let base = path.map(file_url).transpose()?;
if let Some(path) = path {
closure.active.insert(std::fs::canonicalize(path)?);
}
closure.svg(utf8(bytes)?, base.as_ref())
}
fn file_url(path: &Path) -> Result<Url> {
let absolute = std::path::absolute(path)?;
Url::from_file_path(&absolute).map_err(|()| {
invalid(format!(
"cannot resolve local SVG resource {}",
path.display()
))
})
}
fn resolve_url(reference: &str, base: Option<&Url>) -> Result<Url> {
let base = base.ok_or_else(|| {
invalid(format!(
"SVG byte input must be self-contained: {reference}"
))
})?;
#[cfg(windows)]
let absolute_reference = if Path::new(reference).is_absolute() {
format!("file:///{}", reference.replace('\\', "/"))
} else {
reference.to_owned()
};
#[cfg(windows)]
let reference = absolute_reference.as_str();
let url = base
.join(reference)
.map_err(|error| invalid(format!("invalid SVG resource {reference:?}: {error}")))?;
if url.scheme() != "file" || url.host_str().is_some_and(|host| host != "localhost") {
return Err(invalid(format!("SVG resource must be local: {reference}")));
}
Ok(url)
}
fn mime_type(path: &Path) -> Result<&'static str> {
match path
.extension()
.and_then(|value| value.to_str())
.map(str::to_ascii_lowercase)
.as_deref()
{
Some("svg") => Ok("image/svg+xml"),
Some("png") => Ok("image/png"),
Some("jpg" | "jpeg") => Ok("image/jpeg"),
Some("gif") => Ok("image/gif"),
Some("webp") => Ok("image/webp"),
Some("css") => Ok("text/css"),
Some("ttf") => Ok("font/ttf"),
Some("otf") => Ok("font/otf"),
Some("ttc") => Ok("font/collection"),
Some("woff") => Ok("font/woff"),
Some("woff2") => Ok("font/woff2"),
_ => Err(invalid(format!(
"unrecognized local SVG resource type: {}",
path.display()
))),
}
}
impl Closure {
fn load(&mut self, reference: &str, base: Option<&Url>) -> Result<Resource> {
crate::operation::checkpoint()?;
if reference
.get(..5)
.is_some_and(|s| s.eq_ignore_ascii_case("data:"))
{
let (mime, bytes) = read_data_uri(reference)?;
return Ok(Resource {
mime,
bytes,
base: None,
path: None,
fragment: reference
.split_once('#')
.map(|(_, fragment)| fragment.to_owned()),
});
}
let url = resolve_url(reference, base)?;
let path = url
.to_file_path()
.map_err(|()| invalid(format!("invalid local resource path: {reference}")))?;
let path_key = crate::operation::external(|| std::fs::canonicalize(&path))?;
if self.active.contains(&path_key) {
return Err(invalid(format!(
"cyclic SVG/CSS resource reference: {}",
path.display()
)));
}
let mime = mime_type(&path)?.to_owned();
if !self.files.contains_key(&path_key) {
let bytes = crate::operation::external(|| std::fs::read(&path))?;
self.files.insert(path_key.clone(), bytes);
}
let fragment = url.fragment().map(str::to_owned);
Ok(Resource {
mime,
bytes: self.files[&path_key].clone(),
base: Some(url),
path: Some(path_key),
fragment,
})
}
fn with_document<T>(
&mut self,
resource: &Resource,
f: impl FnOnce(&mut Self, &str, Option<&Url>) -> Result<T>,
) -> Result<T> {
if let Some(path) = &resource.path {
self.active.insert(path.clone());
}
let result = utf8(&resource.bytes)
.and_then(|source| f(self, source, resource.base.as_ref()))
.map_err(|error| {
error.with_prefix(
&resource
.base
.as_ref()
.map_or_else(|| "embedded SVG resource".to_owned(), Url::to_string),
)
});
if let Some(path) = &resource.path {
self.active.remove(path);
}
result
}
fn resource_uri(&mut self, reference: &str, base: Option<&Url>) -> Result<String> {
if reference.starts_with('#') || reference.is_empty() {
return Ok(reference.to_owned());
}
let resource = self.load(reference, base)?;
let fragment = resource
.fragment
.as_ref()
.map_or_else(String::new, |id| format!("#{id}"));
if resource.mime == "image/svg+xml" {
let svg = self.with_document(&resource, Self::svg)?;
return Ok(data_uri("image/svg+xml", svg.as_bytes()) + &fragment);
}
if resource.mime == "text/css" {
let css = self.with_document(&resource, Self::css)?;
return Ok(data_uri("text/css", css.as_bytes()));
}
if resource.mime == "image/png" {
super::png::metadata(&resource.bytes)?;
}
if !resource.mime.starts_with("image/")
&& !resource.mime.starts_with("font/")
&& !matches!(
resource.mime.as_str(),
"application/font-woff"
| "application/font-sfnt"
| "application/octet-stream"
| "application/x-font-ttf"
| "application/x-font-opentype"
)
{
return Err(invalid(format!(
"unsupported SVG drawing resource MIME type {}",
resource.mime
)));
}
Ok(data_uri(&resource.mime, &resource.bytes) + &fragment)
}
fn stylesheet(&mut self, reference: &str, base: Option<&Url>) -> Result<String> {
let resource = self.load(reference, base)?;
if resource.mime != "text/css" {
return Err(invalid(format!("SVG stylesheet {reference:?} is not CSS")));
}
self.with_document(&resource, Self::css)
}
fn fragment(
&mut self,
reference: &str,
base: Option<&Url>,
namespace: &str,
) -> Result<(String, String)> {
let resource = self.load(reference, base)?;
let id = resource
.fragment
.as_deref()
.filter(|id| !id.is_empty())
.ok_or_else(|| {
invalid(format!(
"external SVG use requires a fragment ID: {reference}"
))
})?;
if resource.mime != "image/svg+xml" {
return Err(invalid(format!(
"external use source is not SVG: {reference}"
)));
}
let id = percent_encoding::percent_decode_str(id)
.decode_utf8()
.map_err(|_| invalid("external SVG fragment ID is not UTF-8"))?;
let source = super::css::inline_static_styles(&self.with_document(&resource, Self::svg)?)?;
let document = parse(&source)?;
if document
.descendants()
.filter(|node| node.attribute("id") == Some(id.as_ref()))
.count()
!= 1
{
return Err(invalid(format!(
"external SVG fragment {reference:?} is missing or ambiguous"
)));
}
let root = document.root_element();
let mut edits = Vec::new();
for node in root.descendants().filter(Node::is_element) {
for attr in node.attributes() {
let value = attr.value();
let replacement = if attr.name() == "id" {
Some(format!("{namespace}{value}"))
} else if attr.name() == "href" && value.starts_with('#') {
Some(format!("#{namespace}{}", &value[1..]))
} else if contains_url(value) {
Some(namespace_urls(value, namespace)?)
} else {
None
};
if let Some(replacement) = replacement {
edits.push((attr.range_value(), escape(&replacement)));
}
}
}
let source = apply_edits(&source, edits)?;
let document = parse(&source)?;
Ok((
source[document.root_element().range()].to_owned(),
format!("#{namespace}{id}"),
))
}
#[expect(
clippy::too_many_lines,
reason = "one pass seals XML resources and records disjoint source edits"
)]
fn svg(&mut self, source: &str, base: Option<&Url>) -> Result<String> {
let doc = parse(source)?;
let mut edits = Vec::new();
let mut definitions = String::new();
let mut fragments = String::new();
for (index, node) in doc.descendants().enumerate() {
if index.is_multiple_of(64) {
crate::operation::checkpoint()?;
}
if let Some(pi) = node.pi().filter(|pi| pi.target == "xml-stylesheet") {
let attributes = format!("<stylesheet {}/>", pi.value.unwrap_or(""));
let pi_doc = Document::parse(&attributes)
.map_err(|error| invalid(format!("invalid xml-stylesheet: {error}")))?;
let stylesheet = pi_doc.root_element();
let href = stylesheet
.attribute("href")
.ok_or_else(|| invalid("xml-stylesheet lacks href"))?;
let css = self.stylesheet(href, base)?;
definitions.push_str(&style_element(&css, stylesheet.attribute("media")));
edits.push((node.range(), String::new()));
continue;
}
if !node.is_element() || node.tag_name().namespace() != Some(SVG_NS) {
continue;
}
let tag = node.tag_name().name();
if tag == "script"
|| tag.starts_with("animate")
|| matches!(tag, "set" | "discard" | "foreignObject")
{
return Err(invalid(format!(
"SVG asset is static; unsupported element {tag}"
)));
}
let effective = node_base(node, base)?;
if tag == "style" {
let css: String = node.children().filter_map(|child| child.text()).collect();
let css = self.css(&css, effective.as_ref())?;
edits.push((node.range(), style_element(&css, node.attribute("media"))));
continue;
}
if tag == "link" && node.attribute("rel") == Some("stylesheet") {
let href = node
.attribute("href")
.ok_or_else(|| invalid("SVG stylesheet link lacks href"))?;
let css = self.stylesheet(href, effective.as_ref())?;
edits.push((node.range(), style_element(&css, node.attribute("media"))));
continue;
}
for attribute in node.attributes() {
let name = attribute.name();
let value = attribute.value();
if name.starts_with("on") && attribute.namespace().is_none() {
return Err(invalid(format!(
"SVG asset contains an event handler {name}"
)));
}
if name == "base" && attribute.namespace() == Some(XML_NS) {
edits.push((attribute.range(), String::new()));
continue;
}
if name == "href" && tag != "a" {
if value.starts_with('#') || value.is_empty() {
continue;
}
if matches!(
tag,
"use"
| "linearGradient"
| "radialGradient"
| "pattern"
| "textPath"
| "mpath"
) {
let mut namespace = format!("__lichtung_resource_{index}_");
while doc.descendants().any(|node| {
node.attribute("id")
.is_some_and(|id| id.starts_with(&namespace))
}) {
namespace.push('_');
}
let (fragment, href) =
self.fragment(value, effective.as_ref(), &namespace)?;
let _ = write!(fragments, "<defs xmlns=\"{SVG_NS}\">{fragment}</defs>");
edits.push((attribute.range_value(), escape(&href)));
continue;
}
if !matches!(tag, "image" | "feImage") {
return Err(invalid(format!("external SVG fragment reference {value:?} on {tag} cannot yet be sealed")));
}
let uri = self.resource_uri(value, effective.as_ref())?;
edits.push((attribute.range_value(), escape(&uri)));
} else if name == "style" || contains_url(value) {
let css = self.css(value, effective.as_ref())?;
if css != value {
edits.push((attribute.range_value(), escape(&css)));
}
}
}
}
insert_definitions(source, doc.root_element(), definitions, &mut edits);
let source = apply_edits(source, edits)?;
if fragments.is_empty() {
return Ok(source);
}
let source = super::css::inline_static_styles(&source)?;
let doc = parse(&source)?;
let mut edits = Vec::new();
insert_definitions(&source, doc.root_element(), fragments, &mut edits);
apply_edits(&source, edits)
}
fn css(&mut self, source: &str, base: Option<&Url>) -> Result<String> {
let mut output = String::new();
let mut rest = source;
while !rest.is_empty() {
crate::operation::check()?;
if rest.starts_with("/*") {
let end = rest
.find("*/")
.ok_or_else(|| invalid("unterminated CSS comment"))?
+ 2;
output.push_str(&rest[..end]);
rest = &rest[end..];
} else if rest.starts_with(['"', '\'']) {
let (_, tail) = quoted(rest)?;
output.push_str(&rest[..rest.len() - tail.len()]);
rest = tail;
} else if let Some(tail) = keyword(rest, "@import") {
let tail = tail.trim_start();
let (reference, tail) = if let Some(url) = url_function(tail) {
url_value(url)?
} else {
quoted(tail)?
};
let end = tail
.find(';')
.ok_or_else(|| invalid("CSS @import requires a terminating semicolon"))?;
let qualifier = tail[..end].trim();
let css = self.stylesheet(&reference, base)?;
if qualifier.is_empty() || qualifier.eq_ignore_ascii_case("all") {
output.push_str(&css);
} else {
let _ = write!(output, "@media {qualifier} {{ {css} }}");
}
rest = &tail[end + 1..];
} else if let Some(tail) = url_function(rest) {
let (reference, tail) = url_value(tail)?;
let uri = self.resource_uri(&reference, base)?;
write_css_url(&mut output, &uri);
rest = tail;
} else {
let ch = rest.chars().next().expect("nonempty CSS remainder");
if ch == '\\' {
return Err(invalid(
"escaped CSS identifiers are not supported in static SVG resources",
));
}
let len = if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '-' && c != '_')
.unwrap_or(rest.len())
} else {
ch.len_utf8()
};
output.push_str(&rest[..len]);
rest = &rest[len..];
}
}
Ok(output)
}
}
fn insert_definitions(
source: &str,
root: Node<'_, '_>,
definitions: String,
edits: &mut Vec<(Range<usize>, String)>,
) {
if definitions.is_empty() {
return;
}
let end = opening_end(source, root);
if source.as_bytes()[end - 1] == b'/' {
let tag = &source[root.range().start + 1..end - 1];
let name = tag.split_whitespace().next().unwrap_or(tag);
edits.push((end - 1..end + 1, format!(">{definitions}</{name}>")));
} else {
edits.push((end + 1..end + 1, definitions));
}
}
fn namespace_urls(value: &str, namespace: &str) -> Result<String> {
let mut output = String::new();
let mut rest = value;
while let Some(start) = rest.find("url(") {
output.push_str(&rest[..start]);
let (reference, tail) = url_value(&rest[start + 4..])?;
let uri = if let Some(id) = reference.strip_prefix('#') {
format!("#{namespace}{id}")
} else {
reference
};
write_css_url(&mut output, &uri);
rest = tail;
}
output.push_str(rest);
Ok(output)
}
fn write_css_url(output: &mut String, uri: &str) {
if uri.starts_with('#')
&& !uri.chars().any(|ch| {
ch.is_whitespace() || ch.is_control() || matches!(ch, '"' | '\'' | '(' | ')' | '\\')
})
{
let _ = write!(output, "url({uri})");
} else {
let _ = write!(
output,
r#"url("{}")"#,
uri.replace('\\', "\\\\").replace('"', "\\\"")
);
}
}
fn node_base(node: Node<'_, '_>, base: Option<&Url>) -> Result<Option<Url>> {
let mut bases: Vec<&str> = node
.ancestors()
.filter_map(|node| node.attribute((XML_NS, "base")))
.collect();
let mut base = base.cloned();
while let Some(relative) = bases.pop() {
base = Some(resolve_url(relative, base.as_ref())?);
}
Ok(base)
}
pub(super) fn style_element(css: &str, media: Option<&str>) -> String {
let media = media.map_or_else(String::new, |media| format!(" media=\"{}\"", escape(media)));
format!("<style xmlns=\"{SVG_NS}\"{media}>{}</style>", escape(css))
}
fn contains_url(value: &str) -> bool {
value
.as_bytes()
.windows(3)
.any(|part| part.eq_ignore_ascii_case(b"url"))
}
fn keyword<'a>(text: &'a str, name: &str) -> Option<&'a str> {
let start = text.get(..name.len())?;
if !start.eq_ignore_ascii_case(name) {
return None;
}
let tail = &text[name.len()..];
if tail.starts_with(|ch: char| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_') {
return None;
}
Some(tail)
}
fn url_function(text: &str) -> Option<&str> {
keyword(text, "url")?.trim_start().strip_prefix('(')
}
fn url_value(text: &str) -> Result<(String, &str)> {
let text = text.trim_start();
if text.starts_with(['"', '\'']) {
let (value, tail) = quoted(text)?;
let tail = tail
.trim_start()
.strip_prefix(')')
.ok_or_else(|| invalid("invalid CSS url()"))?;
return Ok((value, tail));
}
let mut rest = text;
let mut value = String::new();
while let Some(ch) = rest.chars().next() {
rest = &rest[ch.len_utf8()..];
match ch {
')' => return Ok((value, rest)),
'\\' => {
let (decoded, tail) = css_escape(rest)?;
value.extend(decoded);
rest = tail;
}
'\'' | '"' | '(' => return Err(invalid("invalid unquoted CSS url()")),
ch if ch.is_ascii_whitespace() => {
let tail = rest
.trim_start()
.strip_prefix(')')
.ok_or_else(|| invalid("whitespace inside unquoted CSS url()"))?;
return Ok((value, tail));
}
_ => value.push(ch),
}
}
Err(invalid("unterminated CSS url()"))
}
fn quoted(text: &str) -> Result<(String, &str)> {
let quote = text
.chars()
.next()
.filter(|ch| matches!(ch, '"' | '\''))
.ok_or_else(|| invalid("CSS resource URL must be quoted or use url()"))?;
let mut value = String::new();
let mut rest = &text[1..];
while let Some(ch) = rest.chars().next() {
rest = &rest[ch.len_utf8()..];
if ch == quote {
return Ok((value, rest));
}
if ch == '\\' {
let (decoded, tail) = css_escape(rest)?;
value.extend(decoded);
rest = tail;
} else {
value.push(ch);
}
}
Err(invalid("unterminated CSS string"))
}
fn css_escape(text: &str) -> Result<(Option<char>, &str)> {
let ch = text
.chars()
.next()
.ok_or_else(|| invalid("unterminated CSS escape"))?;
let digits = text
.bytes()
.take(6)
.take_while(u8::is_ascii_hexdigit)
.count();
if digits > 0 {
let scalar = u32::from_str_radix(&text[..digits], 16)
.map_err(|_| invalid("invalid CSS hexadecimal escape"))?;
let mut tail = &text[digits..];
if let Some(ch) = tail.chars().next().filter(char::is_ascii_whitespace) {
tail = &tail[ch.len_utf8()..];
}
return Ok((
Some(
char::from_u32(scalar)
.filter(|ch| *ch != '\0')
.unwrap_or('\u{fffd}'),
),
tail,
));
}
let tail = &text[ch.len_utf8()..];
Ok(((!matches!(ch, '\n' | '\r' | '\u{c}')).then_some(ch), tail))
}