use super::{svg_geometry::trim_space, svg_length};
use std::collections::{BTreeMap, HashSet};
pub(crate) const PROPERTIES: &[&str] = &[
"fill",
"stroke",
"opacity",
"fill-opacity",
"stroke-opacity",
"stroke-width",
"stroke-linecap",
"stroke-linejoin",
"stroke-miterlimit",
"stroke-dasharray",
"stroke-dashoffset",
"fill-rule",
"clip-rule",
"clip-path",
"mask",
"filter",
"color",
"display",
"visibility",
"transform",
"stop-color",
"stop-opacity",
"overflow",
"vector-effect",
"enable-background",
"font-size",
"font-family",
"isolation",
"mix-blend-mode",
];
#[derive(Debug, PartialEq)]
pub struct Rule {
pub classes: Vec<String>,
pub declarations: BTreeMap<String, String>,
}
impl Rule {
pub fn matches(&self, classes: &HashSet<String>) -> bool {
self.classes.iter().any(|class| classes.contains(class))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TransformOriginRule {
pub classes: Vec<String>,
pub ids: Vec<String>,
pub tags: Vec<String>,
pub match_all: bool,
pub property: String,
}
impl TransformOriginRule {
pub fn matches(&self, name: &str, id: &str, classes: &HashSet<String>) -> bool {
if self.match_all {
return true;
}
if self.classes.iter().any(|class| classes.contains(class)) {
return true;
}
if !id.is_empty() && self.ids.iter().any(|candidate| candidate == id) {
return true;
}
self.tags.iter().any(|tag| name.eq_ignore_ascii_case(tag))
}
}
fn trim_animation_vendor_prefix(name: &str) -> &str {
for prefix in ["-webkit-", "-moz-", "-o-", "-ms-"] {
if let Some(trimmed) = name.strip_prefix(prefix) {
return trimmed;
}
}
name
}
pub(crate) fn is_animation_property(name: &str) -> bool {
if name == "will-change" {
return true;
}
matches!(
trim_animation_vendor_prefix(name),
"animation"
| "animation-name"
| "animation-duration"
| "animation-timing-function"
| "animation-delay"
| "animation-iteration-count"
| "animation-direction"
| "animation-fill-mode"
| "animation-play-state"
| "animation-composition"
| "animation-timeline"
| "animation-range"
| "animation-range-start"
| "animation-range-end"
| "transition"
| "transition-property"
| "transition-duration"
| "transition-timing-function"
| "transition-delay"
| "transition-behavior"
)
}
pub(crate) fn is_transform_origin_property(name: &str) -> bool {
name == "transform-box" || trim_animation_vendor_prefix(name) == "transform-origin"
}
pub(crate) fn strip_css_comments(
source: &str,
input: &str,
cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<String, String> {
let error = |reason: &str| format!("d2svgimport: {source}: {reason}");
let bytes = input.as_bytes();
let mut out = String::new();
let mut last = 0;
let mut quote = 0u8;
let mut index = 0;
while index < bytes.len() {
if index & 4095 == 0 {
context(cancel)?;
}
let c = bytes[index];
if quote != 0 {
if c == b'\\' {
if index + 1 < bytes.len() {
index += 1;
}
} else if c == quote || c == b'\n' || c == b'\r' || c == b'\x0c' {
quote = 0;
}
index += 1;
continue;
}
match c {
b'\\' => {
if index + 1 < bytes.len() {
index += 1;
}
}
b'\'' | b'"' => quote = c,
b'/' if index + 1 < bytes.len() && bytes[index + 1] == b'*' => {
out.push_str(&input[last..index]);
out.push(' ');
index += 2;
let mut closed = false;
while index + 1 < bytes.len() {
if index & 4095 == 0 {
context(cancel)?;
}
if bytes[index] == b'*' && bytes[index + 1] == b'/' {
index += 1;
last = index + 1;
closed = true;
break;
}
index += 1;
}
if !closed {
return Err(error("unterminated CSS comment"));
}
}
b'*' if index + 1 < bytes.len() && bytes[index + 1] == b'/' => {
return Err(error("malformed CSS comment"));
}
_ => {}
}
index += 1;
}
context(cancel)?;
if last == 0 && out.is_empty() {
return Ok(input.to_owned());
}
out.push_str(&input[last..]);
Ok(out)
}
#[derive(serde::Serialize, serde::Deserialize)]
struct RuleRecord {
class: String,
declarations: BTreeMap<String, String>,
}
impl serde::Serialize for Rule {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
RuleRecord {
class: self.classes.join(","),
declarations: self.declarations.clone(),
}
.serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for Rule {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let record = RuleRecord::deserialize(deserializer)?;
Ok(Rule {
classes: record.class.split(',').map(str::to_owned).collect(),
declarations: record.declarations,
})
}
}
fn context(cancel: Option<&d2_rs_core::CancellationToken>) -> Result<(), String> {
match cancel.and_then(d2_rs_core::CancellationToken::error) {
Some(d2_rs_core::LayoutError::DeadlineExceeded) => Err("context deadline exceeded".into()),
Some(_) => Err("context canceled".into()),
None => Ok(()),
}
}
pub(crate) fn background(
raw: &str,
cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<(), String> {
let raw = trim_space(raw, cancel)?;
if ["new", "accumulate", "inherit"]
.iter()
.any(|v| raw.eq_ignore_ascii_case(v))
{
return Ok(());
}
let data = raw.as_bytes();
let space = |b: u8| b" \t\n\r\x0c".contains(&b);
let mut end = 0;
while end < data.len() && !space(data[end]) {
end += 1;
if end & 4095 == 0 {
context(cancel)?;
}
}
let invalid = || "only a finite new x y width height region is supported".to_owned();
if !raw[..end].eq_ignore_ascii_case("new") || end == data.len() {
return Err(invalid());
}
let tail = &raw[end..];
let bytes = tail.as_bytes();
let mut start = None;
let mut fields = Vec::with_capacity(4);
for offset in 0..=bytes.len() {
if offset & 4095 == 0 {
context(cancel)?;
}
if offset < bytes.len() && !space(bytes[offset]) {
if bytes[offset] == b',' {
return Err(
"only whitespace-separated enable-background coordinates are supported".into(),
);
}
if start.is_none() {
start = Some(offset);
}
continue;
}
if let Some(from) = start.take() {
if fields.len() == 4 {
return Err(invalid());
}
fields.push(&tail[from..offset]);
}
}
context(cancel)?;
if fields.len() != 4 {
return Err(invalid());
}
let mut numbers = [0.; 4];
for (index, field) in fields.iter().enumerate() {
context(cancel)?;
numbers[index] = svg_length::number(field).map_err(|_| invalid())?;
}
if numbers[2] <= 0. || numbers[3] <= 0. {
return Err("enable-background width and height must be positive".into());
}
context(cancel)
}
pub fn collect(
source: &str,
name: &str,
root: bool,
attrs: &BTreeMap<String, String>,
classes: &HashSet<String>,
rules: &[Rule],
origins: &[TransformOriginRule],
mathjax: &mut bool,
cancel: Option<&d2_rs_core::CancellationToken>,
) -> Result<BTreeMap<String, String>, String> {
let error = |reason: String| format!("d2svgimport: {source}: {reason}");
let mut declarations = BTreeMap::new();
for &property in PROPERTIES {
if let Some(raw) = attrs.get(property) {
declarations.insert(property.into(), trim_space(raw, cancel)?.into());
}
}
for (index, rule) in rules.iter().enumerate() {
if index & 255 == 0 {
context(cancel)?;
}
if rule.matches(classes) {
declarations.extend(rule.declarations.clone());
}
}
let mut transform_origin = String::new();
let id = attrs.get("id").map(String::as_str).unwrap_or("");
for (index, rule) in origins.iter().enumerate() {
if index & 255 == 0 {
context(cancel)?;
}
if rule.matches(name, id, classes) {
transform_origin = rule.property.clone();
break;
}
}
if let Some(raw_inline) = attrs.get("style") {
let inline = strip_css_comments(source, raw_inline, cancel)?;
let data = inline.as_bytes();
for index in 0..data.len() {
if index & 4095 == 0 {
context(cancel)?;
}
if matches!(data[index], b'{' | b'}') {
return Err(error(format!(
"element <{name}> has unsupported inline CSS syntax"
)));
}
}
let malformed = || error(format!("element <{name}> has malformed inline style"));
let mut start = 0;
while start <= data.len() {
context(cancel)?;
let mut end = start;
while end < data.len() && data[end] != b';' {
end += 1;
if end & 4095 == 0 {
context(cancel)?;
}
}
let raw = trim_space(&inline[start..end], cancel)?;
start = if end == data.len() {
data.len() + 1
} else {
end + 1
};
if raw.is_empty() {
continue;
}
let mut colon = None;
for (index, byte) in raw.as_bytes().iter().enumerate() {
if index & 4095 == 0 {
context(cancel)?;
}
if *byte == b':' {
colon = Some(index);
break;
}
}
let colon = colon.filter(|&n| n > 0).ok_or_else(malformed)?;
let property = trim_space(&raw[..colon], cancel)?;
let value = trim_space(&raw[colon + 1..], cancel)?;
if property.len() > 64 {
return Err(malformed());
}
let property =
String::from_utf8(d2_rs_core::ir::go_lowercase(property.as_bytes())).unwrap();
if property.is_empty()
|| !property
.bytes()
.all(|b| b.is_ascii_lowercase() || b == b'-')
|| value.is_empty()
{
return Err(malformed());
}
if property == "vertical-align" {
if !root {
return Err(error(format!(
"element <{name}> has unsupported vertical-align outside the root <svg>"
)));
}
svg_length::mathjax_ex(value).map_err(|e| {
error(format!(
"root <svg> has invalid MathJax vertical-align: {e}"
))
})?;
*mathjax = true;
continue;
}
if is_animation_property(&property) {
continue;
}
if is_transform_origin_property(&property) {
if transform_origin.is_empty() {
transform_origin = property;
}
continue;
}
if !PROPERTIES.contains(&property.as_str()) {
return Err(error(format!(
"element <{name}> has unsupported style property {property:?}"
)));
}
if property == "transform" {
return Err(error(format!(
"element <{name}> has unsupported CSS transform; use the transform presentation attribute"
)));
}
let pattern = b"!important";
if let Some(maximum) = value.len().checked_sub(pattern.len()) {
for offset in 0..=maximum {
if offset & 4095 == 0 {
context(cancel)?;
}
if value
.as_bytes()
.get(offset..offset + pattern.len())
.is_some_and(|p| p.eq_ignore_ascii_case(pattern))
{
return Err(error(format!(
"element <{name}> uses unsupported !important"
)));
}
}
}
context(cancel)?;
declarations.insert(property, value.to_string());
}
}
if !transform_origin.is_empty() {
if let Some(raw) = declarations.get("transform") {
if !raw.is_empty() && !raw.eq_ignore_ascii_case("none") {
return Err(error(format!(
"element <{name}> combines transform with unsupported {transform_origin}"
)));
}
}
}
Ok(declarations)
}
#[cfg(all(test, feature = "oracle-fixtures"))]
mod tests {
use super::*;
#[test]
fn original_cascade_inline_errors_and_root_metadata() {
let rows: serde_json::Value = serde_json::from_str(d2_rs_testdata::oracle_fixture!(
"tests/fixtures/svg-declarations-v090.json"
))
.unwrap();
for row in rows.as_array().unwrap() {
let attrs = serde_json::from_value(row["attrs"].clone()).unwrap();
let classes: HashSet<String> = serde_json::from_value(row["classes"].clone()).unwrap();
let rules: Vec<_> = row["rules"]
.as_array()
.unwrap()
.iter()
.map(|r| Rule {
classes: r["class"]
.as_str()
.unwrap()
.split(',')
.map(str::to_owned)
.collect(),
declarations: serde_json::from_value(r["declarations"].clone()).unwrap(),
})
.collect();
let mut mathjax = false;
let result = collect(
"math",
row["name"].as_str().unwrap(),
row["root"].as_bool().unwrap(),
&attrs,
&classes,
&rules,
&[],
&mut mathjax,
None,
);
assert_eq!(
result.as_ref().err().map(String::as_str).unwrap_or(""),
row["error"].as_str().unwrap(),
"{row}"
);
assert_eq!(mathjax, row["mathjax"].as_bool().unwrap(), "{row}");
assert_eq!(
serde_json::to_value(result.ok()).unwrap(),
row["declarations"],
"{row}"
);
}
}
}