mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-05 14:55:08 +00:00
fix(display): pin one text layout engine, and give the 5x7 BDF face a size (#539)
* fix(display): pin one text layout engine, and give the 5x7 face a size Two ways a font could render differently on two machines running the same code, both found while diagnosing four plugins whose golden images passed on the machine that generated them and failed everywhere else. **Layout engine.** `ImageFont.truetype` picks its engine at load time: Raqm where the host Pillow was built with libraqm, Basic otherwise. The two round fractional glyph advances differently. `PressStart2P-Regular.ttf` at 8px has whole-pixel advances, so they agree — which is why most of the fleet matched everywhere and hid this. `4x6-font.ttf` at 6px does not: glyph positions drift cumulatively along a run, and the four plugins that draw body text in it (geochron, of-the-day, christmas-countdown, ledmatrix-weather's almanac) are exactly the four whose goldens travelled badly. Every core font load now goes through `src/common/font_layout.load_truetype`, which pins the Basic engine, so a render depends on the font file and the size and nothing else. Basic gives up complex-script shaping and kerning pairs; neither applies to bitmap-grid faces on an LED panel. Output is unchanged on a host without libraqm. **Zero font height.** `DisplayManager` built the 5x7 BDF face with `freetype.Face(path)` and never called `set_char_size`, so `face.size.height` stayed 0 and `get_font_height()` returned 0 for it — callers stacking rows by `prev_y + prev_height + gap` drew two lines on top of each other. The start-up line `Calendar font size: 0 pixels` has been printing the symptom all along. `font_manager._load_bdf_font` already called `set_char_size`, so whether measurement worked depended on which path loaded the face. `DisplayManager` now sets it too, and `get_font_height()` falls back to the strike the file declares rather than returning a zero line height. Fixes ChuckBuilds/ledmatrix-plugins#397 Refs ChuckBuilds/ledmatrix-plugins#371, #375, #378, #391 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(display): give the startup banner a rung that fits a full address at 64px CI caught what pinning the layout engine exposed rather than caused. `_fitting_font` walks PressStart2P then 4x6 at 6px, and "255.255.255.255" -- the widest thing the startup banner ever shows -- measures 66px at 4x6/6px against the 62 a 64x32 panel has to give. It used to squeak in only because the measurement depended on which layout engine the host Pillow happened to have; with the engine pinned it does not, so the rung the worst case actually needs is now in the ladder instead of implied: 4x6 at 5px, which measures 51. The fallback was wrong in the same place. When nothing in the ladder fit, it returned `self.font` -- the *widest* option, and precisely how "Initializing" came to run off the side of a 64px panel to begin with. It returns the narrowest face that loaded now. test/test_initializing_screen.py: 34 passed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(display): name the exceptions the BDF strike read can raise Codacy flagged the try/except/pass. It was already narrow in intent -- a malformed strike table on the measurement path must degrade to "size unknown" rather than take the display down -- but a bare `except Exception: pass` says neither of those things and hides a genuinely broken font behind a silent 8px fallback. It now catches what reading `available_sizes` can actually raise and logs which face failed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore: drop logo PNGs the render harness downloaded into the worktree These are fetched at runtime by the logo cache; they are not source, and they rode in on a `git add -A` while I was running check_plugin.py against this branch. Nothing in the change needs them. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
+66
-9
@@ -34,6 +34,7 @@ else:
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from src.common.font_layout import load_truetype
|
||||
import threading
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
@@ -55,6 +56,31 @@ from src.common.permission_utils import (
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.INFO) # Set to INFO level
|
||||
|
||||
#: The strike 5x7.bdf is drawn at. FreeType renders a BDF at its own fixed
|
||||
#: size regardless, but a Face needs an active size before its metrics --
|
||||
#: and therefore get_font_height() -- report anything but 0.
|
||||
_CALENDAR_FONT_PX = 7
|
||||
|
||||
|
||||
def _bdf_native_size(face) -> int:
|
||||
"""The pixel height a BDF Face declares, or 0 if it does not say.
|
||||
|
||||
Used only to rescue a Face that was built without ``set_char_size``, so a
|
||||
zero line height never reaches layout code.
|
||||
"""
|
||||
try:
|
||||
sizes = getattr(face, "available_sizes", None) or []
|
||||
if sizes:
|
||||
return int(getattr(sizes[0], "height", 0) or 0)
|
||||
except (AttributeError, IndexError, TypeError, ValueError) as exc:
|
||||
# This runs on the measurement path for a face the caller already
|
||||
# holds, so a malformed strike table must degrade to "unknown" rather
|
||||
# than take the display down. Say which face, so a font that is
|
||||
# actually broken is diagnosable rather than silently 8px.
|
||||
logger.debug("Could not read BDF strike size from %r: %s", face, exc)
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
class _LogicalMatrix:
|
||||
"""Proxy that reports a logical (per-screen) size for a physical matrix.
|
||||
@@ -377,7 +403,7 @@ class DisplayManager:
|
||||
|
||||
# Initialize font with Press Start 2P
|
||||
try:
|
||||
self.font = ImageFont.truetype("assets/fonts/PressStart2P-Regular.ttf", 8)
|
||||
self.font = load_truetype("assets/fonts/PressStart2P-Regular.ttf", 8)
|
||||
logger.info("Initial Press Start 2P font loaded successfully")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load initial font: {e}")
|
||||
@@ -557,19 +583,33 @@ class DisplayManager:
|
||||
pass
|
||||
|
||||
def _fitting_font(self, lines, width):
|
||||
"""The largest font from the usual ladder that fits every line."""
|
||||
"""The largest font from the usual ladder that fits every line.
|
||||
|
||||
The ladder ends at 4x6 at 5px because a full dotted-quad address --
|
||||
"255.255.255.255", the widest this screen ever shows -- is 66px at
|
||||
6px and a 64px panel has 62 to give it. That used to squeak in only
|
||||
because the measurement depended on which text layout engine the host
|
||||
Pillow had; with the engine pinned it does not, so the rung the
|
||||
worst case actually needs is here rather than implied.
|
||||
"""
|
||||
candidates = [self.font,
|
||||
("assets/fonts/4x6-font.ttf", 6)]
|
||||
("assets/fonts/4x6-font.ttf", 6),
|
||||
("assets/fonts/4x6-font.ttf", 5)]
|
||||
narrowest = None
|
||||
for candidate in candidates:
|
||||
try:
|
||||
font = candidate
|
||||
if isinstance(candidate, tuple):
|
||||
font = ImageFont.truetype(candidate[0], candidate[1])
|
||||
font = load_truetype(candidate[0], candidate[1])
|
||||
narrowest = font
|
||||
if all(self.draw.textlength(t, font=font) <= width for t in lines):
|
||||
return font
|
||||
except (OSError, ValueError, AttributeError):
|
||||
continue
|
||||
return self.font
|
||||
# Nothing fit. Return the smallest face that loaded, not self.font --
|
||||
# falling back to the widest option is how "Initializing" ran off the
|
||||
# side of a 64px panel in the first place.
|
||||
return narrowest or self.font
|
||||
|
||||
def _draw_startup_banner(self, lines, width: int, height: int) -> None:
|
||||
"""Centre `lines` over whatever the test pattern already drew.
|
||||
@@ -933,11 +973,11 @@ class DisplayManager:
|
||||
self._text_width_cache.clear()
|
||||
try:
|
||||
# Load Press Start 2P font
|
||||
self.regular_font = ImageFont.truetype("assets/fonts/PressStart2P-Regular.ttf", 8)
|
||||
self.regular_font = load_truetype("assets/fonts/PressStart2P-Regular.ttf", 8)
|
||||
logger.info("Press Start 2P font loaded successfully")
|
||||
|
||||
# Use the same font for small text (currently same size; adjust size here if needed)
|
||||
self.small_font = ImageFont.truetype("assets/fonts/PressStart2P-Regular.ttf", 8)
|
||||
self.small_font = load_truetype("assets/fonts/PressStart2P-Regular.ttf", 8)
|
||||
logger.info("Press Start 2P small font loaded successfully")
|
||||
|
||||
# Load 5x7 BDF font for calendar events
|
||||
@@ -950,6 +990,17 @@ class DisplayManager:
|
||||
|
||||
# Load with freetype for proper BDF handling
|
||||
face = freetype.Face(self.calendar_font_path)
|
||||
# A freshly constructed Face has no active size, so
|
||||
# face.size.height is 0 until set_char_size is called -- and
|
||||
# get_font_height() reads exactly that. Without this, every
|
||||
# caller measuring the 5x7 face got 0 and stacked rows on top
|
||||
# of one another; the "Calendar font size: 0 pixels" line
|
||||
# below has been printing the symptom on every start-up.
|
||||
# font_manager._load_bdf_font already does this; the two paths
|
||||
# disagreed about whether a Face was usable for measurement.
|
||||
# 5x7.bdf is a fixed strike, so FreeType renders 7px whatever
|
||||
# is asked for -- this sets the metrics, not the raster.
|
||||
face.set_char_size(_CALENDAR_FONT_PX * 64, _CALENDAR_FONT_PX * 64, 72, 72)
|
||||
logger.info(f"5x7 calendar font loaded successfully from {self.calendar_font_path}")
|
||||
logger.info(f"Calendar font size: {face.size.height >> 6} pixels")
|
||||
|
||||
@@ -970,7 +1021,7 @@ class DisplayManager:
|
||||
try:
|
||||
font_path = "assets/fonts/4x6-font.ttf"
|
||||
logger.info(f"Attempting to load 4x6 TTF font from: {font_path} at size 6")
|
||||
self.extra_small_font = ImageFont.truetype(font_path, 6)
|
||||
self.extra_small_font = load_truetype(font_path, 6)
|
||||
logger.info(f"4x6 TTF extra small font loaded successfully from {font_path}")
|
||||
except Exception as font_err:
|
||||
logger.error(f"Failed to load 4x6 TTF font: {font_err}. Falling back.")
|
||||
@@ -1028,7 +1079,13 @@ class DisplayManager:
|
||||
try:
|
||||
if isinstance(font, freetype.Face):
|
||||
# For FreeType faces (BDF), the 'height' metric gives the recommended line spacing.
|
||||
return font.size.height >> 6
|
||||
height = font.size.height >> 6
|
||||
if height:
|
||||
return height
|
||||
# A Face constructed without set_char_size reports 0, and a
|
||||
# zero line height collapses every stacked row onto one line.
|
||||
# Fall back to the strike the file declares.
|
||||
return _bdf_native_size(font) or 8
|
||||
else:
|
||||
# For PIL TTF fonts, getmetrics() provides ascent and descent.
|
||||
# The line height is the sum of ascent and descent.
|
||||
|
||||
Reference in New Issue
Block a user