Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for the !important attribute #843

Merged
merged 4 commits into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified crates/resvg/tests/tests/structure/style/important.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 4 additions & 2 deletions crates/usvg/src/parser/svgtree/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,14 +205,16 @@ pub struct Attribute<'input> {
pub name: AId,
/// Attribute's value.
pub value: roxmltree::StringStorage<'input>,
/// Attribute's importance
pub important: bool
}

impl std::fmt::Debug for Attribute<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(
f,
"Attribute {{ name: {:?}, value: {} }}",
self.name, self.value
"Attribute {{ name: {:?}, value: {}, important: {} }}",
self.name, self.value, self.important
)
}
}
Expand Down
71 changes: 41 additions & 30 deletions crates/usvg/src/parser/svgtree/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ impl<'input> Document<'input> {
new_child_id
}

fn append_attribute(&mut self, name: AId, value: roxmltree::StringStorage<'input>) {
self.attrs.push(Attribute { name, value });
fn append_attribute(&mut self, name: AId, value: roxmltree::StringStorage<'input>, important: bool) {
self.attrs.push(Attribute { name, value, important });
}
}

Expand Down Expand Up @@ -251,10 +251,10 @@ pub(crate) fn parse_svg_element<'input>(
continue;
}

append_attribute(parent_id, tag_name, aid, attr.value_storage().clone(), doc);
append_attribute(parent_id, tag_name, aid, attr.value_storage().clone(), false, doc);
}

let mut insert_attribute = |aid, value: &str| {
let mut insert_attribute = |aid, value: &str, important: bool| {
// Check that attribute already exists.
let idx = doc.attrs[attrs_start_idx..]
.iter_mut()
Expand All @@ -266,15 +266,23 @@ pub(crate) fn parse_svg_element<'input>(
tag_name,
aid,
roxmltree::StringStorage::new_owned(value),
important,
doc,
);

// Check that attribute was actually added, because it could be skipped.
if added {
if let Some(idx) = idx {
// Swap the last attribute with an existing one.
let last_idx = doc.attrs.len() - 1;
doc.attrs.swap(attrs_start_idx + idx, last_idx);
let existing_idx = attrs_start_idx + idx;

// Swap the last attribute with an existing one. However, if the currently existing
// attribute is important and the new one not, we don't want to overwrite it, since
// the important one takes precedence.
if !(doc.attrs[existing_idx].important && !doc.attrs[last_idx].important) {
doc.attrs.swap(existing_idx, last_idx);
}

// Remove last.
doc.attrs.pop();
}
Expand All @@ -284,40 +292,40 @@ pub(crate) fn parse_svg_element<'input>(
let mut write_declaration = |declaration: &Declaration| {
// TODO: perform XML attribute normalization
if declaration.name == "marker" {
insert_attribute(AId::MarkerStart, declaration.value);
insert_attribute(AId::MarkerMid, declaration.value);
insert_attribute(AId::MarkerEnd, declaration.value);
insert_attribute(AId::MarkerStart, declaration.value, declaration.important);
RazrFalcon marked this conversation as resolved.
Show resolved Hide resolved
insert_attribute(AId::MarkerMid, declaration.value, declaration.important);
insert_attribute(AId::MarkerEnd, declaration.value, declaration.important);
} else if declaration.name == "font" {
if let Ok(shorthand) = FontShorthand::from_str(declaration.value) {
// First we need to reset all values to their default.
insert_attribute(AId::FontStyle, "normal");
insert_attribute(AId::FontVariant, "normal");
insert_attribute(AId::FontWeight, "normal");
insert_attribute(AId::FontStretch, "normal");
insert_attribute(AId::LineHeight, "normal");
insert_attribute(AId::FontSizeAdjust, "none");
insert_attribute(AId::FontKerning, "auto");
insert_attribute(AId::FontVariantCaps, "normal");
insert_attribute(AId::FontVariantLigatures, "normal");
insert_attribute(AId::FontVariantNumeric, "normal");
insert_attribute(AId::FontVariantEastAsian, "normal");
insert_attribute(AId::FontVariantPosition, "normal");
insert_attribute(AId::FontStyle, "normal", declaration.important);
insert_attribute(AId::FontVariant, "normal", declaration.important);
insert_attribute(AId::FontWeight, "normal", declaration.important);
insert_attribute(AId::FontStretch, "normal", declaration.important);
insert_attribute(AId::LineHeight, "normal", declaration.important);
insert_attribute(AId::FontSizeAdjust, "none", declaration.important);
insert_attribute(AId::FontKerning, "auto", declaration.important);
insert_attribute(AId::FontVariantCaps, "normal", declaration.important);
insert_attribute(AId::FontVariantLigatures, "normal", declaration.important);
insert_attribute(AId::FontVariantNumeric, "normal", declaration.important);
insert_attribute(AId::FontVariantEastAsian, "normal", declaration.important);
insert_attribute(AId::FontVariantPosition, "normal", declaration.important);

// Then, we set the properties that have been declared.
shorthand
.font_stretch
.map(|s| insert_attribute(AId::FontStretch, s));
.map(|s| insert_attribute(AId::FontStretch, s, declaration.important));
shorthand
.font_weight
.map(|s| insert_attribute(AId::FontWeight, s));
.map(|s| insert_attribute(AId::FontWeight, s, declaration.important));
shorthand
.font_variant
.map(|s| insert_attribute(AId::FontVariant, s));
.map(|s| insert_attribute(AId::FontVariant, s, declaration.important));
shorthand
.font_style
.map(|s| insert_attribute(AId::FontStyle, s));
insert_attribute(AId::FontSize, shorthand.font_size);
insert_attribute(AId::FontFamily, shorthand.font_family);
.map(|s| insert_attribute(AId::FontStyle, s, declaration.important));
insert_attribute(AId::FontSize, shorthand.font_size, declaration.important);
insert_attribute(AId::FontFamily, shorthand.font_family, declaration.important);
} else {
log::warn!(
"Failed to parse {} value: '{}'",
Expand All @@ -328,7 +336,7 @@ pub(crate) fn parse_svg_element<'input>(
} else if let Some(aid) = AId::from_str(declaration.name) {
// Parse only the presentation attributes.
if aid.is_presentation() {
insert_attribute(aid, declaration.value);
insert_attribute(aid, declaration.value, declaration.important);
}
}
};
Expand Down Expand Up @@ -369,6 +377,7 @@ fn append_attribute<'input>(
tag_name: EId,
aid: AId,
value: roxmltree::StringStorage<'input>,
important: bool,
doc: &mut Document<'input>,
) -> bool {
match aid {
Expand All @@ -389,7 +398,7 @@ fn append_attribute<'input>(
return resolve_inherit(parent_id, aid, doc);
}

doc.append_attribute(aid, value);
doc.append_attribute(aid, value, important);
true
}

Expand All @@ -412,6 +421,7 @@ fn resolve_inherit(parent_id: NodeId, aid: AId, doc: &mut Document) -> bool {
doc.attrs.push(Attribute {
name: aid,
value: attr.value,
important: attr.important
});

return true;
Expand All @@ -429,6 +439,7 @@ fn resolve_inherit(parent_id: NodeId, aid: AId, doc: &mut Document) -> bool {
doc.attrs.push(Attribute {
name: aid,
value: attr.value,
important: attr.important
});

return true;
Expand Down Expand Up @@ -483,7 +494,7 @@ fn resolve_inherit(parent_id: NodeId, aid: AId, doc: &mut Document) -> bool {
_ => return false,
};

doc.append_attribute(aid, roxmltree::StringStorage::Borrowed(value));
doc.append_attribute(aid, roxmltree::StringStorage::Borrowed(value), false);
true
}

Expand Down
59 changes: 59 additions & 0 deletions crates/usvg/tests/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,65 @@ fn stylesheet_injection() {
);
}

#[test]
fn stylesheet_injection_with_important() {
let svg = "<svg id='svg1' viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'>
<style>
#rect4 {
fill: green
}
</style>
<rect id='rect1' x='20' y='20' width='60' height='60'/>
<rect id='rect2' x='120' y='20' width='60' height='60' fill='green'/>
<rect id='rect3' x='20' y='120' width='60' height='60' style='fill: green'/>
<rect id='rect4' x='120' y='120' width='60' height='60'/>
</svg>
";

let stylesheet = "rect { fill: red !important }".to_string();

let options = usvg::Options {
style_sheet: Some(stylesheet),
..usvg::Options::default()
};

let tree = usvg::Tree::from_str(&svg, &options).unwrap();

let usvg::Node::Path(ref first) = &tree.root().children()[0] else {
unreachable!()
};

// All rects should be overriden, since we use `important`.
assert_eq!(
first.fill().unwrap().paint(),
&usvg::Paint::Color(Color::new_rgb(255, 0, 0))
);

let usvg::Node::Path(ref second) = &tree.root().children()[1] else {
unreachable!()
};
assert_eq!(
second.fill().unwrap().paint(),
&usvg::Paint::Color(Color::new_rgb(255, 0, 0))
);

let usvg::Node::Path(ref third) = &tree.root().children()[2] else {
unreachable!()
};
assert_eq!(
third.fill().unwrap().paint(),
&usvg::Paint::Color(Color::new_rgb(255, 0, 0))
);

let usvg::Node::Path(ref third) = &tree.root().children()[3] else {
unreachable!()
};
assert_eq!(
third.fill().unwrap().paint(),
&usvg::Paint::Color(Color::new_rgb(255, 0, 0))
);
}

#[test]
fn simplify_paths() {
let svg = "
Expand Down
Loading