Skip to content

Commit 0175079

Browse files
pvcravenPaul V Cravenclaude
authored
Load font files passed as font_name, and accept lists of names (#2922)
- A path or resource handle passed as font_name was turned into the file name (e.g. "Kenney_Future.ttf") and never loaded, so pyglet drew the default font. The file is now loaded the first time it's used, and its family name is used. Each file is loaded once. - The family name comes from pyglet's on_font_loaded event, which uses the platform's name for the font. If the file was already added to pyglet some other way, it's read from the file instead. - Lists of font names raised TypeError, although the docs allow them. - A path no longer takes priority over names listed before it. - The Text.font_name setter now resolves paths too. - load_font() records the family name, so a later path is cheap. Co-authored-by: Paul V Craven <paul.craven@optimizley.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a4daef5 commit 0175079

3 files changed

Lines changed: 211 additions & 40 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Arcade [PyPi Release History](https://pypi.org/project/arcade/#history) page.
1919
- `bold` strings such as `"light"` or `"semibold"` were all treated as bold, including `"normal"`. They now set that font weight, and the `bold` property returns the weight name for weights other than bold and normal.
2020
- A `pyglet.text.LinearGradient` color raised `TypeError` in `Text`, `draw_text()`, `create_text_sprite()`, and `UILabel.update_font()`. Gradients now work, and the `color` property returns the gradient.
2121
- The `Text` constructor ignored every error while creating the label, so bad arguments such as an unknown keyword or an invalid `font_name` only raised later, the first time the text was used. Only the "no window yet" case is deferred now.
22+
- Fixed `font_name` paths to font files in `arcade.Text`, `draw_text()`, `create_text_sprite()`, and the `Text.font_name` setter. A path or resource handle such as `":resources:fonts/ttf/Custom.ttf"` used the file name as the font name, so the text was drawn in the default font. The file is now loaded the first time it's used, and its family name is used. Lists of font names, which the docs allow, raised `TypeError` and now work, and a path no longer takes priority over names listed before it.
2223

2324
### New Features
2425
- Added `arcade.sweep_sprite(sprite, dx, dy, sprite_list)`, which checks the whole path of a moving sprite and returns a `SweepInfo` for the first sprite it would hit (the `sprite`, how far along the move as a `fraction` and `distance`, and the surface `normal`), or `None`. Fast sprites can't pass through thin walls this way. A sprite that already overlaps one is an immediate hit. Added the `sprite_bullets_sweep` example comparing it with a plain collision check.

‎arcade/text.py‎

Lines changed: 87 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -42,61 +42,111 @@ def load_font(path: str | Path) -> None:
4242
# Load a font using a custom resource handle
4343
arcade.load_font(":font:Custom.ttf")
4444
45+
You can also pass the path to a font file as ``font_name``,
46+
which loads the file the first time it's used.
47+
4548
Args:
4649
path: Path to the font file
4750
Raises:
4851
FileNotFoundError: if the font specified wasn't found
4952
"""
50-
file_path = resolve(path)
51-
pyglet.font.add_file(str(file_path))
53+
_load_font_file(resolve(path))
5254

5355

5456
FontNameOrNames = str | tuple[str, ...]
5557

58+
# Family names of the font files loaded so far, so each file is only
59+
# loaded once, and a path can be used as a font name
60+
_font_file_families: dict[Path, str | None] = {}
5661

57-
def _attempt_font_name_resolution(font_name: FontNameOrNames) -> str:
58-
"""Attempt to resolve a font name.
59-
60-
Preserves the original logic of this section, even though it
61-
doesn't seem to make sense entirely. Comments are an attempt
62-
to make sense of the original code.
6362

64-
If it can't resolve a definite path, it will return the original
65-
argument for pyglet to attempt to resolve. This is consistent with
66-
the original behavior of this code before it was encapsulated.
63+
def _load_font_file(path: Path) -> str | None:
64+
"""
65+
Load a font file, if it isn't loaded yet, and return its family name.
6766
68-
Args:
69-
font_name: A font name, path to a font file, or list of names
67+
Returns ``None`` if the family name couldn't be found.
7068
"""
71-
if font_name:
72-
# ensure
73-
if isinstance(font_name, str):
74-
font_list: tuple[str, ...] = (font_name,)
75-
elif isinstance(font_name, tuple):
76-
font_list = font_name
77-
else:
78-
raise TypeError(
79-
"font_name parameter must be a string, "
80-
"or a tuple of strings that specify a font name."
81-
)
69+
if path in _font_file_families:
70+
return _font_file_families[path]
8271

83-
for font in font_list:
72+
# pyglet reports the families it added with the name the platform
73+
# uses for them, which is the name to load the font with
74+
families: list[str] = []
75+
76+
def on_font_loaded(family_name, weight, style, stretch):
77+
families.append(family_name)
78+
79+
pyglet.font.manager.push_handlers(on_font_loaded=on_font_loaded)
80+
try:
81+
pyglet.font.add_file(str(path))
82+
finally:
83+
pyglet.font.manager.remove_handlers(on_font_loaded=on_font_loaded)
84+
85+
family: str | None = families[0] if families else None
86+
if family is None:
87+
# The file was already loaded some other way, for example with
88+
# pyglet.font.add_file(), so read the name from the file itself
89+
from pyglet.font.ttf import TruetypeInfo
90+
91+
try:
92+
info = TruetypeInfo(str(path))
93+
except Exception:
94+
pass
95+
else:
8496
try:
85-
path = resolve(font)
86-
# print(f"Font path: {path=}")
97+
family = info.get_name("family")
98+
finally:
99+
info.close()
87100

88-
# found a font successfully!
89-
return path.name
101+
_font_file_families[path] = family
102+
return family
90103

91-
except FileNotFoundError:
92-
pass
93104

94-
# failed to find it ourselves, hope pyglet can make sense of it
95-
# Note this is the best approximation of what I understand the old
96-
# behavior to have been.
97-
return pyglet.font.load(font_list).name
105+
def _font_file_family(font_name: str) -> str | None:
106+
"""
107+
If a font name is the path to a font file, load it and return its
108+
family name. Otherwise, return ``None``.
109+
"""
110+
try:
111+
path = resolve(font_name)
112+
except FileNotFoundError:
113+
# Not a file, or a resource that doesn't exist
114+
return None
115+
except OSError:
116+
# Some font names aren't valid paths at all, but a resource
117+
# handle should still report what's wrong with it
118+
if font_name.strip().startswith(":"):
119+
raise
120+
return None
121+
if not path.is_file():
122+
return None
123+
return _load_font_file(path)
124+
98125

99-
raise ValueError(f"Couldn't find a font for {font_name!r}")
126+
def _attempt_font_name_resolution(font_name: FontNameOrNames) -> str:
127+
"""Resolve a font name, path, or list of them to the name of one font.
128+
129+
Paths to font files are loaded and replaced by the font's family
130+
name. The first name pyglet finds is returned, or pyglet's default
131+
font if it finds none.
132+
133+
Args:
134+
font_name: A font name, path to a font file, or a tuple or list
135+
of them.
136+
"""
137+
if isinstance(font_name, str):
138+
font_list: tuple[str, ...] = (font_name,)
139+
elif isinstance(font_name, (tuple, list)):
140+
font_list = tuple(font_name)
141+
else:
142+
raise TypeError(
143+
"font_name parameter must be a string, or a tuple of strings that specify a font name."
144+
)
145+
if not font_list or not all(font_list):
146+
raise ValueError(f"Couldn't find a font for {font_name!r}")
147+
148+
names = [_font_file_family(font) or font for font in font_list]
149+
return pyglet.font.load(names).name
100150

101151

102152
def _draw_pyglet_label(label: pyglet.text.Label) -> None:
@@ -502,10 +552,7 @@ def font_name(self, font_name: FontNameOrNames) -> None:
502552
if font_name == self._requested_font_name and label.font_name == self._resolved_font_name:
503553
return
504554
label = self._layout_label()
505-
if isinstance(font_name, str):
506-
label.font_name = font_name
507-
else:
508-
label.font_name = list(font_name)
555+
label.font_name = _attempt_font_name_resolution(font_name)
509556
self._requested_font_name = font_name
510557
self._resolved_font_name = label.font_name
511558

‎tests/unit/text/test_text_fonts.py‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
"""Tests for font names, paths to font files, and lists of them"""
2+
3+
import pyglet
4+
import pytest
5+
6+
import arcade
7+
import arcade.text
8+
9+
KENNEY = "Kenney Future"
10+
KENNEY_HANDLE = ":system:fonts/ttf/Kenney/Kenney_Future.ttf"
11+
12+
13+
@pytest.fixture
14+
def font_families(monkeypatch) -> dict:
15+
"""Forget which font files were loaded, so each test starts fresh"""
16+
families: dict = {}
17+
monkeypatch.setattr(arcade.text, "_font_file_families", families, raising=False)
18+
return families
19+
20+
21+
def _render(window, text: arcade.Text):
22+
"""Draw a Text into an offscreen framebuffer and return its pixels"""
23+
ctx = window.ctx
24+
fbo = ctx.framebuffer(color_attachments=[ctx.texture((400, 100), components=4)])
25+
with fbo.activate():
26+
fbo.clear(color=(0, 0, 0, 0))
27+
text.draw()
28+
return fbo.read(components=4)
29+
30+
31+
def _make(font_name) -> arcade.Text:
32+
return arcade.Text("Hello World", 10, 30, font_name=font_name, font_size=30)
33+
34+
35+
def _paths() -> list:
36+
path = arcade.resources.resolve(KENNEY_HANDLE)
37+
return [KENNEY_HANDLE, str(path)]
38+
39+
40+
@pytest.mark.parametrize("font_name", _paths())
41+
def test_path_uses_the_font_in_the_file(window, font_families, font_name):
42+
text = _make(font_name)
43+
assert text.label.font_name == KENNEY
44+
assert _render(window, text) == _render(window, _make(KENNEY))
45+
46+
47+
@pytest.mark.parametrize("font_name", _paths())
48+
def test_font_name_setter_accepts_path(window, font_families, font_name):
49+
text = _make("Liberation Sans")
50+
text.font_name = font_name
51+
assert text.label.font_name == KENNEY
52+
assert _render(window, text) == _render(window, _make(KENNEY))
53+
54+
55+
def test_path_in_list(window, font_families):
56+
text = _make(("NoSuchFontXYZ", KENNEY_HANDLE, "Liberation Sans"))
57+
assert text.label.font_name == KENNEY
58+
59+
60+
def test_first_available_font_is_used(window, font_families):
61+
assert _make(("NoSuchFontXYZ", "Liberation Sans", KENNEY)).label.font_name == "Liberation Sans"
62+
assert _make(("Liberation Sans", KENNEY_HANDLE)).label.font_name == "Liberation Sans"
63+
64+
65+
def test_missing_resource_falls_back_to_next_name(window, font_families):
66+
text = _make((":resources:fonts/ttf/NoSuchFont.ttf", "Liberation Sans"))
67+
assert text.label.font_name == "Liberation Sans"
68+
69+
70+
def test_unknown_resource_handle_raises(window, font_families):
71+
with pytest.raises(KeyError):
72+
_make(":nosuchhandle:fonts/NoSuchFont.ttf")
73+
74+
75+
def test_list_of_names(window, font_families):
76+
text = _make(["NoSuchFontXYZ", "Liberation Sans"]) # type: ignore
77+
assert text.label.font_name == "Liberation Sans"
78+
79+
80+
# Tests draw_text, which warns that it's slow
81+
@pytest.mark.filterwarnings("ignore::arcade.exceptions.PerformanceWarning")
82+
def test_draw_text_list_and_path(window, font_families):
83+
window.ctx.label_cache.clear()
84+
arcade.draw_text("Hello", 10, 10, font_name=["NoSuchFontXYZ", "Liberation Sans"]) # type: ignore
85+
arcade.draw_text("Hello", 10, 10, font_name=KENNEY_HANDLE)
86+
fonts = sorted(text.label.font_name for text in window.ctx.label_cache.values())
87+
assert fonts == [KENNEY, "Liberation Sans"]
88+
89+
90+
def test_each_file_is_loaded_once(window, font_families, monkeypatch):
91+
added = []
92+
add_file = pyglet.font.add_file
93+
94+
def counting_add_file(path):
95+
added.append(path)
96+
add_file(path)
97+
98+
monkeypatch.setattr(pyglet.font, "add_file", counting_add_file)
99+
for _ in range(3):
100+
_make(KENNEY_HANDLE)
101+
arcade.load_font(KENNEY_HANDLE)
102+
assert len(added) == 1
103+
104+
105+
def test_file_loaded_elsewhere(window, font_families):
106+
"""A file already added to pyglet directly reports no new fonts, so the
107+
family name is read from the file"""
108+
path = arcade.resources.resolve(KENNEY_HANDLE)
109+
pyglet.font.add_file(str(path))
110+
assert _make(str(path)).label.font_name == KENNEY
111+
assert font_families[path] == KENNEY
112+
113+
114+
def test_load_font_then_name(window, font_families):
115+
arcade.load_font(KENNEY_HANDLE)
116+
assert _make(KENNEY).label.font_name == KENNEY
117+
118+
119+
def test_empty_name_raises(window, font_families):
120+
with pytest.raises(ValueError):
121+
_make("")
122+
with pytest.raises(ValueError):
123+
_make(())

0 commit comments

Comments
 (0)