svg.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. from __future__ import annotations
  2. import re
  3. from functools import cache
  4. from itertools import chain, count
  5. from typing import Dict, Iterable, Iterator, List, Optional, Set, Tuple
  6. try:
  7. from lxml import etree
  8. except ImportError:
  9. # lxml is required for subsetting SVG, but we prefer to delay the import error
  10. # until subset_glyphs() is called (i.e. if font to subset has an 'SVG ' table)
  11. etree = None
  12. from fontTools import ttLib
  13. from fontTools.subset.util import _add_method
  14. from fontTools.ttLib.tables.S_V_G_ import SVGDocument
  15. __all__ = ["subset_glyphs"]
  16. GID_RE = re.compile(r"^glyph(\d+)$")
  17. NAMESPACES = {
  18. "svg": "http://www.w3.org/2000/svg",
  19. "xlink": "http://www.w3.org/1999/xlink",
  20. }
  21. XLINK_HREF = f'{{{NAMESPACES["xlink"]}}}href'
  22. @cache
  23. def xpath(path):
  24. # compile XPath upfront, caching result to reuse on multiple elements
  25. return etree.XPath(path, namespaces=NAMESPACES)
  26. def group_elements_by_id(tree: etree.Element) -> Dict[str, etree.Element]:
  27. # select all svg elements with 'id' attribute no matter where they are
  28. # including the root element itself:
  29. # https://github.com/fonttools/fonttools/issues/2548
  30. return {el.attrib["id"]: el for el in xpath("//svg:*[@id]")(tree)}
  31. def parse_css_declarations(style_attr: str) -> Dict[str, str]:
  32. # https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/style
  33. # https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations
  34. result = {}
  35. for declaration in style_attr.split(";"):
  36. if declaration.count(":") == 1:
  37. property_name, value = declaration.split(":")
  38. property_name = property_name.strip()
  39. result[property_name] = value.strip()
  40. elif declaration.strip():
  41. raise ValueError(f"Invalid CSS declaration syntax: {declaration}")
  42. return result
  43. def iter_referenced_ids(tree: etree.Element) -> Iterator[str]:
  44. # Yield all the ids that can be reached via references from this element tree.
  45. # We currently support xlink:href (as used by <use> and gradient templates),
  46. # and local url(#...) links found in fill or clip-path attributes
  47. # TODO(anthrotype): Check we aren't missing other supported kinds of reference
  48. find_svg_elements_with_references = xpath(
  49. ".//svg:*[ "
  50. "starts-with(@xlink:href, '#') "
  51. "or starts-with(@fill, 'url(#') "
  52. "or starts-with(@clip-path, 'url(#') "
  53. "or contains(@style, ':url(#') "
  54. "]",
  55. )
  56. for el in chain([tree], find_svg_elements_with_references(tree)):
  57. ref_id = href_local_target(el)
  58. if ref_id is not None:
  59. yield ref_id
  60. attrs = el.attrib
  61. if "style" in attrs:
  62. attrs = {**dict(attrs), **parse_css_declarations(el.attrib["style"])}
  63. for attr in ("fill", "clip-path"):
  64. if attr in attrs:
  65. value = attrs[attr]
  66. if value.startswith("url(#") and value.endswith(")"):
  67. ref_id = value[5:-1]
  68. assert ref_id
  69. yield ref_id
  70. def closure_element_ids(
  71. elements: Dict[str, etree.Element], element_ids: Set[str]
  72. ) -> None:
  73. # Expand the initial subset of element ids to include ids that can be reached
  74. # via references from the initial set.
  75. unvisited = element_ids
  76. while unvisited:
  77. referenced: Set[str] = set()
  78. for el_id in unvisited:
  79. if el_id not in elements:
  80. # ignore dangling reference; not our job to validate svg
  81. continue
  82. referenced.update(iter_referenced_ids(elements[el_id]))
  83. referenced -= element_ids
  84. element_ids.update(referenced)
  85. unvisited = referenced
  86. def subset_elements(el: etree.Element, retained_ids: Set[str]) -> bool:
  87. # Keep elements if their id is in the subset, or any of their children's id is.
  88. # Drop elements whose id is not in the subset, and either have no children,
  89. # or all their children are being dropped.
  90. if el.attrib.get("id") in retained_ids:
  91. # if id is in the set, don't recurse; keep whole subtree
  92. return True
  93. # recursively subset all the children; we use a list comprehension instead
  94. # of a parentheses-less generator expression because we don't want any() to
  95. # short-circuit, as our function has a side effect of dropping empty elements.
  96. if any([subset_elements(e, retained_ids) for e in el]):
  97. return True
  98. assert len(el) == 0
  99. parent = el.getparent()
  100. if parent is not None:
  101. parent.remove(el)
  102. return False
  103. def remap_glyph_ids(
  104. svg: etree.Element, glyph_index_map: Dict[int, int]
  105. ) -> Dict[str, str]:
  106. # Given {old_gid: new_gid} map, rename all elements containing id="glyph{gid}"
  107. # special attributes
  108. elements = group_elements_by_id(svg)
  109. id_map = {}
  110. for el_id, el in elements.items():
  111. m = GID_RE.match(el_id)
  112. if not m:
  113. continue
  114. old_index = int(m.group(1))
  115. new_index = glyph_index_map.get(old_index)
  116. if new_index is not None:
  117. if old_index == new_index:
  118. continue
  119. new_id = f"glyph{new_index}"
  120. else:
  121. # If the old index is missing, the element correspond to a glyph that was
  122. # excluded from the font's subset.
  123. # We rename it to avoid clashes with the new GIDs or other element ids.
  124. new_id = f".{el_id}"
  125. n = count(1)
  126. while new_id in elements:
  127. new_id = f"{new_id}.{next(n)}"
  128. id_map[el_id] = new_id
  129. el.attrib["id"] = new_id
  130. return id_map
  131. def href_local_target(el: etree.Element) -> Optional[str]:
  132. if XLINK_HREF in el.attrib:
  133. href = el.attrib[XLINK_HREF]
  134. if href.startswith("#") and len(href) > 1:
  135. return href[1:] # drop the leading #
  136. return None
  137. def update_glyph_href_links(svg: etree.Element, id_map: Dict[str, str]) -> None:
  138. # update all xlink:href="#glyph..." attributes to point to the new glyph ids
  139. for el in xpath(".//svg:*[starts-with(@xlink:href, '#glyph')]")(svg):
  140. old_id = href_local_target(el)
  141. assert old_id is not None
  142. if old_id in id_map:
  143. new_id = id_map[old_id]
  144. el.attrib[XLINK_HREF] = f"#{new_id}"
  145. def ranges(ints: Iterable[int]) -> Iterator[Tuple[int, int]]:
  146. # Yield sorted, non-overlapping (min, max) ranges of consecutive integers
  147. sorted_ints = iter(sorted(set(ints)))
  148. try:
  149. start = end = next(sorted_ints)
  150. except StopIteration:
  151. return
  152. for v in sorted_ints:
  153. if v - 1 == end:
  154. end = v
  155. else:
  156. yield (start, end)
  157. start = end = v
  158. yield (start, end)
  159. @_add_method(ttLib.getTableClass("SVG "))
  160. def subset_glyphs(self, s) -> bool:
  161. if etree is None:
  162. raise ImportError("No module named 'lxml', required to subset SVG")
  163. # glyph names (before subsetting)
  164. glyph_order: List[str] = s.orig_glyph_order
  165. # map from glyph names to original glyph indices
  166. rev_orig_glyph_map: Dict[str, int] = s.reverseOrigGlyphMap
  167. # map from original to new glyph indices (after subsetting)
  168. glyph_index_map: Dict[int, int] = s.glyph_index_map
  169. new_docs: List[SVGDocument] = []
  170. for doc in self.docList:
  171. glyphs = {
  172. glyph_order[i] for i in range(doc.startGlyphID, doc.endGlyphID + 1)
  173. }.intersection(s.glyphs)
  174. if not glyphs:
  175. # no intersection: we can drop the whole record
  176. continue
  177. svg = etree.fromstring(
  178. # encode because fromstring dislikes xml encoding decl if input is str.
  179. # SVG xml encoding must be utf-8 as per OT spec.
  180. doc.data.encode("utf-8"),
  181. parser=etree.XMLParser(
  182. # Disable libxml2 security restrictions to support very deep trees.
  183. # Without this we would get an error like this:
  184. # `lxml.etree.XMLSyntaxError: internal error: Huge input lookup`
  185. # when parsing big fonts e.g. noto-emoji-picosvg.ttf.
  186. huge_tree=True,
  187. # ignore blank text as it's not meaningful in OT-SVG; it also prevents
  188. # dangling tail text after removing an element when pretty_print=True
  189. remove_blank_text=True,
  190. # don't replace entities; we don't expect any in OT-SVG and they may
  191. # be abused for XXE attacks
  192. resolve_entities=False,
  193. ),
  194. )
  195. elements = group_elements_by_id(svg)
  196. gids = {rev_orig_glyph_map[g] for g in glyphs}
  197. element_ids = {f"glyph{i}" for i in gids}
  198. closure_element_ids(elements, element_ids)
  199. if not subset_elements(svg, element_ids):
  200. continue
  201. if not s.options.retain_gids:
  202. id_map = remap_glyph_ids(svg, glyph_index_map)
  203. update_glyph_href_links(svg, id_map)
  204. new_doc = etree.tostring(svg, pretty_print=s.options.pretty_svg).decode("utf-8")
  205. new_gids = (glyph_index_map[i] for i in gids)
  206. for start, end in ranges(new_gids):
  207. new_docs.append(SVGDocument(new_doc, start, end, doc.compressed))
  208. self.docList = new_docs
  209. return bool(self.docList)