Skip to content

Commit

Permalink
Cache SVG use tags
Browse files Browse the repository at this point in the history
Fix #1439.
  • Loading branch information
liZe committed Sep 11, 2021
1 parent 223e97d commit 37af386
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 4 deletions.
40 changes: 40 additions & 0 deletions tests/draw/svg/test_defs.py
@@ -0,0 +1,40 @@
"""
weasyprint.tests.test_draw.svg.test_defs
----------------------------------------
Test how SVG definitions are drawn.
"""

from ...testing_utils import assert_no_logs
from .. import assert_pixels


@assert_no_logs
def test_use():
assert_pixels('use', 10, 10, '''
RRRRR_____
RRRRR_____
__________
___RRRRR__
___RRRRR__
__________
_____RRRRR
_____RRRRR
__________
__________
''', '''
<style>
@page { size: 10px }
svg { display: block }
</style>
<svg width="10px" height="10px" xmlns="http://www.w3.org/2000/svg"
xlink="http://www.w3.org/1999/xlink">
<defs>
<rect id="rectangle" width="5" height="2" fill="red" />
</defs>
<use xlink:href="#rectangle" />
<use xlink:href="#rectangle" x="3" y="3" />
<use xlink:href="#rectangle" x="5" y="6" />
</svg>
''')
2 changes: 2 additions & 0 deletions weasyprint/svg/__init__.py
Expand Up @@ -294,6 +294,8 @@ def __init__(self, bytestring_svg, url):
self.patterns = {}
self.paths = {}

self.use_cache = {}

self.cursor_position = [0, 0]
self.cursor_d_position = [0, 0]
self.text_path_width = 0
Expand Down
13 changes: 9 additions & 4 deletions weasyprint/svg/defs.py
Expand Up @@ -27,10 +27,15 @@ def use(svg, node, font_size):

parsed_url = parse_url(node.get_href())
if parsed_url.fragment and not parsed_url.path:
try:
tree = svg.tree.get_child(parsed_url.fragment).copy()
except AttributeError:
return
if parsed_url.fragment in svg.use_cache:
tree = svg.use_cache[parsed_url.fragment].copy()
else:
try:
tree = svg.tree.get_child(parsed_url.fragment).copy()
except AttributeError:
return
else:
svg.use_cache[parsed_url.fragment] = tree
else:
url = parsed_url.geturl()
try:
Expand Down

0 comments on commit 37af386

Please sign in to comment.