Skip to content

Commit 2d3ec58

Browse files
committed
Cache fonts for lower memory usage
1 parent 31c664c commit 2d3ec58

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

adafruit_magtag/magtag.py

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,9 @@ def __init__(
9292
self._json_path = None
9393
self.json_path = json_path
9494

95+
# Font Cache
96+
self._fonts = {}
97+
9598
self._regexp_path = regexp_path
9699

97100
self.splash = self.graphics.splash
@@ -150,10 +153,7 @@ def add_text(
150153
position is relative to the label
151154
:param bool is_data: If True, fetch will attempt to update the label
152155
"""
153-
if text_font is terminalio.FONT:
154-
self._text_font.append(text_font)
155-
else:
156-
self._text_font.append(bitmap_font.load_font(text_font))
156+
157157
if not text_wrap:
158158
text_wrap = 0
159159
if not text_maxlen:
@@ -172,6 +172,7 @@ def add_text(
172172
if self._debug:
173173
print("Init text area")
174174
self._text.append(None)
175+
self._text_font.append(self._load_font(text_font))
175176
self._text_color.append(self.html_color_convert(text_color))
176177
self._text_position.append(text_position)
177178
self._text_wrap.append(text_wrap)
@@ -186,6 +187,19 @@ def add_text(
186187

187188
# pylint: enable=too-many-arguments
188189

190+
def _load_font(self, font):
191+
"""
192+
Load and cache a font if not previously loaded
193+
Return the key of the cached font
194+
"""
195+
if font is terminalio.FONT:
196+
if "terminal" not in self._fonts:
197+
self._fonts["terminal"] = terminalio.FONT
198+
return "terminal"
199+
if font not in self._fonts:
200+
self._fonts[font] = bitmap_font.load_font(font)
201+
return font
202+
189203
@staticmethod
190204
def html_color_convert(color):
191205
"""Convert an HTML color code to an integer
@@ -226,8 +240,8 @@ def preload_font(self, glyphs=None, index=0):
226240
if not glyphs:
227241
glyphs = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-!,. \"'?!"
228242
print("Preloading font glyphs:", glyphs)
229-
if self._text_font[index] is not terminalio.FONT:
230-
self._text_font[index].load_glyphs(glyphs)
243+
if self._fonts[self._text_font[index]] is not terminalio.FONT:
244+
self._fonts[self._text_font[index]].load_glyphs(glyphs)
231245

232246
def set_text_color(self, color, index=0):
233247
"""Update the text color, with indexing into our list of text boxes.
@@ -274,7 +288,9 @@ def set_text(self, val, index=0, auto_refresh=True):
274288

275289
if len(string) > 0:
276290
self._text[index] = Label(
277-
self._text_font[index], text=string, scale=self._text_scale[index]
291+
self._fonts[self._text_font[index]],
292+
text=string,
293+
scale=self._text_scale[index],
278294
)
279295
self._text[index].color = self._text_color[index]
280296
self._text[index].anchor_point = self._text_anchor_point[index]

0 commit comments

Comments
 (0)