Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,13 @@ This can also be enabled programmatically with `warnings.simplefilter('default',
* SVG: a `<line>` in a `<clipPath>` no longer fails with `TypeError: ShapeBuilder.line() takes 2 positional arguments but 3 were given`; it has no area, so it clips everything away, as in browsers - thanks to @RavSinghChandan
* `FPDF.image()` and `write_html()` now read a `data:` URI that holds an SVG, such as `data:image/svg+xml;base64,...`, as an SVG instead of failing with `UnidentifiedImageError`, and a `data:` URI without `;base64`, which is percent-encoded, instead of failing with `NotImplementedError: Unsupported non-base64 image data`, so the placeholder `data:image/svg+xml,%3Csvg...` that WordPress puts in the `src` of lazy-loaded images no longer stops `write_html()` - thanks to @RavSinghChandan
* SVG: a `fill` or `stroke` of `currentColor` now takes the `color` property when the SVG sets one, on the element or an ancestor, as an attribute or in CSS, as icon sets are written; without a `color` property it still takes the color set on the `FPDF` - thanks to @RavSinghChandan
<<<<<<< HEAD
* SVG: the CSS rules of a `<style>` with an id selector, a compound selector or a descendant or child combinator, such as the `#mermaid-svg .node rect { fill: #ECECFF }` of Mermaid flowcharts, now apply, by specificity and then in order, instead of being ignored, also in the contents of a `<pattern>`: the nodes of Mermaid flowcharts were drawn black - thanks to @RavSinghChandan
=======
* SVG: a `<linearGradient>` or `<radialGradient>` that is not a child of a `<defs>`, such as the one Mermaid writes in the group of each link of a Sankey diagram, is now applied to the shapes that reference it, as in browsers: those shapes were drawn without any fill or stroke, so the links of Sankey diagrams were missing - thanks to @RavSinghChandan
* SVG: an `rgb()` or `rgba()` color with commas whose red, green or blue is a number that is not an integer, such as the `rgb(45,179.9999999999,184.5)` of the stylesheets of Mermaid diagrams, is now read as in CSS Color 4, instead of failing with `ValueError: invalid literal for int() with base 10`; an integer alpha is still read from 0 to 255 - thanks to @RavSinghChandan
* SVG: the `letter-spacing` of a `<text>` or `<tspan>`, such as the `letter-spacing: 2px` of the labels of spaCy's dependency diagrams, is now applied, with the PDF character spacing, also to the width used by `text-anchor`, instead of being ignored - thanks to @RavSinghChandan
>>>>>>> origin/master
* SVG: an `@import`, `@charset` or other at-rule without a block at the start of a `<style>`, such as the `@import` of a Google Font, no longer hides the CSS rule that follows it; a `;` inside its URL, as in `wght@600;700`, is part of the URL - thanks to @RavSinghChandan
* `FPDF.write_html()`: a link with `href="#"`, as in the "Back to top" links of many web pages, now goes to the top of the document, like in browsers, instead of making `output()` fail with `FPDFException: Named destination '' was referenced but never set` - thanks to @RavSinghChandan
* SVG: a gradient in `userSpaceOnUse` units on a shape inside nested transformed groups, such as `<g transform="scale(2)"><g transform="translate(10 0)">`, now gets the transforms of the groups from the innermost to the outermost, as a shape does: it got them the other way round, so the gradient was misplaced and, for example, the translation was 10 instead of 20 - thanks to @RavSinghChandan
Expand Down
227 changes: 193 additions & 34 deletions fpdf/svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -1490,20 +1490,73 @@ def _extract_css_rules(css_text: str) -> list[tuple[str, dict[str, Any]]]:
return rules


def _extract_css_class_styles(css_text: str) -> list[tuple[str, dict[str, Any]]]:
styles: list[tuple[str, dict[str, Any]]] = []
for selector, declarations in _extract_css_rules(css_text):
if not selector.startswith("."):
continue
class_name = selector[1:].split(":", 1)[0].strip()
if not class_name:
continue
styles.append((class_name, declarations))
return styles


# A universal selector or an element name, such as "*" or "rect"
CSS_TYPE_SELECTOR_RE = re.compile(r"\*|[A-Za-z][\w-]*")
# A class selector, with or without a pseudo-class, such as .a or .a:hover
CSS_CLASS_SELECTOR_RE = re.compile(r"\.[\w-]+(?::.*)?", re.DOTALL)
# A compound selector: an element name or "*", then ids and classes, as in rect#a.b
CSS_COMPOUND_SELECTOR_RE = re.compile(r"(\*|[A-Za-z][\w-]*)?((?:[#.][\w-]+)*)")
CSS_SELECTOR_TOKEN_RE = re.compile(r"\s*>\s*|\s+|[^\s>]+")
# longer selectors are ignored, so that matching them stays fast
_MAX_CSS_COMPOUND_SELECTORS = 32


class CSSCompoundSelector(NamedTuple):
combinator: str # " " for a descendant, ">" for a child, "" for the first one
element_name: Optional[str]
ids: tuple[str, ...]
classes: frozenset[str]

def matches(self, element: "Element") -> bool:
if self.element_name not in (None, "*") and (
without_ns(element.tag) != self.element_name
):
return False
if any(element.attrib.get("id") != element_id for element_id in self.ids):
return False
return self.classes <= set(element.attrib.get("class", "").split())


def _parse_css_selector(
selector: str,
) -> Optional[tuple[tuple[CSSCompoundSelector, ...], tuple[int, int, int]]]:
"""
The compound selectors of a selector made of element names, ids and classes,
joined by descendant or child combinators, as in "#mermaid-svg .node rect", from
the outermost, and its specificity; None for other selectors.
"""
compounds: list[CSSCompoundSelector] = []
combinator = ""
for token in CSS_SELECTOR_TOKEN_RE.findall(selector.strip()):
if not token.strip():
combinator = combinator or " "
continue
if token.strip() == ">":
combinator = ">"
continue
match = CSS_COMPOUND_SELECTOR_RE.fullmatch(token)
if match is None or (combinator == "") != (not compounds):
return None
element_name, rest = match.groups()
parts = re.findall(r"[#.][\w-]+", rest)
compounds.append(
CSSCompoundSelector(
combinator,
element_name,
tuple(part[1:] for part in parts if part[0] == "#"),
frozenset(part[1:] for part in parts if part[0] == "."),
)
)
combinator = ""
if not compounds or combinator or len(compounds) > _MAX_CSS_COMPOUND_SELECTORS:
return None
specificity = (
sum(len(compound.ids) for compound in compounds),
# a repeated class counts each time, as in .a.a
sum(token.count(".") for token in CSS_SELECTOR_TOKEN_RE.findall(selector)),
sum(compound.element_name not in (None, "*") for compound in compounds),
)
return tuple(compounds), specificity


@force_nodocument
Expand Down Expand Up @@ -1934,9 +1987,27 @@ def __init__(
self.cross_references: dict[str, Any] = {}
self._cross_reference_costs: dict[str, int] = {}
self.symbol_info: dict[str, SymbolInfo] = {}
self.css_class_styles: dict[str, dict[str, Any]] = {}
# the (order in the stylesheets, declarations) of each rule
self.css_class_styles: dict[str, list[tuple[int, dict[str, Any]]]] = {}
# rules of "*" and element names, such as matplotlib's * { stroke-linejoin: round }
self.css_type_styles: dict[str, dict[str, Any]] = {}
self.css_type_styles: dict[str, list[tuple[int, dict[str, Any]]]] = {}
# rules of the other selectors with ids, classes and combinators, such as
# Mermaid's #mermaid-svg .node rect, with their specificity and order
self.css_selector_rules: list[
tuple[
tuple[CSSCompoundSelector, ...],
tuple[int, int, int],
dict[str, Any],
int,
]
] = []
self._selector_rules_cache: dict[
"Element", list[tuple[tuple[int, int, int], int, dict[str, Any]]]
] = {}
self._selector_memos: dict[
int,
tuple[dict[tuple[int, "Element"], bool], dict[tuple[int, "Element"], bool]],
] = {}
self.gradient_definitions: dict[str, GradientPaint] = (
{}
) # Store parsed gradients by ID
Expand Down Expand Up @@ -1973,7 +2044,7 @@ def __init__(
for element in svg_tree.iter()
if element.attrib.get("id")
}
self._pattern_parents = {
self._pattern_parents: dict[Element, Optional[Element]] = {
child: parent for parent in svg_tree.iter() for child in parent
}
self._collect_css_styles(svg_tree)
Expand Down Expand Up @@ -2147,21 +2218,92 @@ def projected_cost(element: "Element") -> int:
projected_cost(root_tag)

def _collect_css_styles(self, root_tag: "Element") -> None:
order = 0
for node in root_tag.iter():
if node.tag in xmlns_lookup("svg", "style"):
css_text = "".join(node.itertext() or [])
for class_name, declarations in _extract_css_class_styles(css_text):
existing = self.css_class_styles.setdefault(class_name, {})
for key, value in declarations.items():
# a later rule does not override an !important declaration
if key not in existing or _overrides(existing[key], value):
existing[key] = value
for selector, declarations in _extract_css_rules(css_text):
if CSS_TYPE_SELECTOR_RE.fullmatch(selector):
existing = self.css_type_styles.setdefault(selector, {})
for key, value in declarations.items():
if key not in existing or _overrides(existing[key], value):
existing[key] = value
self.css_type_styles.setdefault(selector, []).append(
(order, declarations)
)
elif CSS_CLASS_SELECTOR_RE.fullmatch(selector):
class_name = selector[1:].split(":", 1)[0].strip()
self.css_class_styles.setdefault(class_name, []).append(
(order, declarations)
)
else:
parsed = _parse_css_selector(selector)
if parsed is not None:
self.css_selector_rules.append(
(*parsed, declarations, order)
)
order += 1

def _selector_matches(self, rule_index: int, tag: "Element") -> bool:
"""
Whether a selector rule matches an element, through its ancestors. What is known
of each element is kept, so that matching takes linear time in their number.
"""
compounds = self.css_selector_rules[rule_index][0]
# whether compounds[:index + 1] match, with the last one on an element, and
# whether they match on an ancestor of it
matched, ancestor_matched = self._selector_memos.setdefault(
rule_index, ({}, {})
)

def matches(index: int, element: "Element") -> bool:
key = (index, element)
if key not in matched:
compound = compounds[index]
result = compound.matches(element)
if result and index > 0:
parent = self._pattern_parents.get(element)
if parent is None:
result = False
elif compound.combinator == ">":
result = matches(index - 1, parent)
else:
result = matches(index - 1, parent) or ancestor_matches(
index - 1, parent
)
matched[key] = result
return matched[key]

def ancestor_matches(index: int, element: "Element") -> bool:
chain: list["Element"] = []
node = element
while (index, node) not in ancestor_matched:
parent = self._pattern_parents.get(node)
chain.append(node)
if parent is None:
result = False
break
if matches(index, parent):
result = True
break
node = parent
else:
result = ancestor_matched[(index, node)]
for node in chain:
ancestor_matched[(index, node)] = result
return result

return matches(len(compounds) - 1, tag)

def _selector_rules_for(
self, tag: "Element"
) -> list[tuple[tuple[int, int, int], int, dict[str, Any]]]:
"""The (specificity, order, declarations) of the selector rules of an element."""
if tag not in self._selector_rules_cache:
self._selector_rules_cache[tag] = [
(specificity, order, declarations)
for index, (_, specificity, declarations, order) in enumerate(
self.css_selector_rules
)
if self._selector_matches(index, tag)
]
return self._selector_rules_cache[tag]

def _is_display_none(self, tag: "Element") -> bool:
display = _get_attr_or_style(tag, "display", self._style_map_for(tag))
Expand All @@ -2181,18 +2323,28 @@ def apply_rules(rules: dict[str, Any]) -> None:
if is_important:
important.add(key)

# as in CSS, a class rule wins over an element rule, which wins over "*"
for selector in ("*", without_ns(tag.tag)):
type_styles = self.css_type_styles.get(selector)
if type_styles:
apply_rules(type_styles)
# as in CSS, the rules apply by specificity, then in order: a class rule wins
# over an element rule, which wins over "*"
rules: list[tuple[tuple[int, int, int], int, dict[str, Any]]] = []
for selector, specificity in (
("*", (0, 0, 0)),
(without_ns(tag.tag), (0, 0, 1)),
):
for order, declarations in self.css_type_styles.get(selector, ()):
rules.append((specificity, order, declarations))
if self.css_class_styles:
class_attr = tag.attrib.get("class")
if class_attr:
for class_name in class_attr.split():
class_styles = self.css_class_styles.get(class_name)
if class_styles:
apply_rules(class_styles)
for class_name in dict.fromkeys(class_attr.split()):
for order, declarations in self.css_class_styles.get(
class_name, ()
):
rules.append(((0, 1, 0), order, declarations))
if self.css_selector_rules:
rules.extend(self._selector_rules_for(tag))
rules.sort(key=lambda rule: rule[:2])
for _, _, declarations in rules:
apply_rules(declarations)
inline = _parse_css_declarations(tag.attrib.get("style", ""))
for key, declared in inline.items():
value, is_important = _split_important(declared)
Expand Down Expand Up @@ -2584,6 +2736,13 @@ def _resolve_pattern_element(
for child in list(resolved):
resolved.remove(child)
resolved.extend(deepcopy(list(template)))
# The copy has the ancestors of the pattern, and its own children have it as
# their parent, so that selectors such as "pattern rect" or "g > rect" match
# inside a tile
self._pattern_parents[resolved] = self._pattern_parents.get(element)
self._pattern_parents.update(
{child: parent for parent in resolved.iter() for child in parent}
)
return resolved

def _get_pattern_paint(self, pattern_id: str) -> Optional[SVGPatternPaint]:
Expand Down
Loading
Loading