Skip to content

Commit 18cd638

Browse files
authored
1 parent ff8cccf commit 18cd638

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

matplotlib_pyodide/html5_canvas_backend.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import base64
22
import io
33
import math
4+
from functools import lru_cache
45

56
import numpy as np
67
from matplotlib import __version__, interactive
@@ -10,7 +11,6 @@
1011
RendererBase,
1112
_Backend,
1213
)
13-
from matplotlib.cbook import maxdict
1414
from matplotlib.colors import colorConverter, rgb2hex
1515
from matplotlib.font_manager import findfont
1616
from matplotlib.ft2font import LOAD_NO_HINTING, FT2Font
@@ -204,8 +204,8 @@ def __init__(self, ctx, width, height, dpi, fig):
204204
self.ctx.width = self.width
205205
self.ctx.height = self.height
206206
self.dpi = dpi
207-
self.fontd = maxdict(50)
208207
self.mathtext_parser = MathTextParser("bitmap")
208+
self._get_font_helper = lru_cache(maxsize=50)(self._get_font_helper)
209209

210210
# Keep the state of fontfaces that are loading
211211
self.fonts_loading = {}
@@ -309,22 +309,22 @@ def draw_image(self, gc, x, y, im, transform=None):
309309
pixels_proxy.destroy()
310310
pixels_buf.release()
311311

312+
def _get_font_helper(self, prop):
313+
"""Cached font lookup
314+
315+
We wrap this in an lru-cache in the constructor.
316+
"""
317+
fname = findfont(prop)
318+
font = FT2Font(str(fname))
319+
font_file_name = fname.rpartition("/")[-1]
320+
return (font, font_file_name)
321+
312322
def _get_font(self, prop):
313-
key = hash(prop)
314-
font_value = self.fontd.get(key)
315-
if font_value is None:
316-
fname = findfont(prop)
317-
font_value = self.fontd.get(fname)
318-
if font_value is None:
319-
font = FT2Font(str(fname))
320-
font_file_name = fname[fname.rfind("/") + 1 :]
321-
font_value = font, font_file_name
322-
self.fontd[fname] = font_value
323-
self.fontd[key] = font_value
324-
font, font_file_name = font_value
323+
result = self._get_font_helper(prop)
324+
font = result[0]
325325
font.clear()
326326
font.set_size(prop.get_size_in_points(), self.dpi)
327-
return font, font_file_name
327+
return result
328328

329329
def get_text_width_height_descent(self, s, prop, ismath):
330330
w: float

0 commit comments

Comments
 (0)