Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

tools: the card scripts name a font path that is not Fredoka's variable TTF

xbshengaa2a6a1743c9
diff --git a/tests/test_card_font_argument.py b/tests/test_card_font_argument.py
index e2eabe2d6..360744d52 100644
--- a/tests/test_card_font_argument.py
+++ b/tests/test_card_font_argument.py
@@ -19,10 +19,19 @@ with no Pillow still reports the font first, which is what makes this testable i
`tools/gen_tables.py --font` hands the font to two of these scripts with `check=True`, so a wrong path there
became a `CalledProcessError` traceback around their message; it now refuses the path itself.
+A path that exists is not yet a font, and both of the shapes a reader is likely to hand over reached Pillow:
+Google Fonts serves Fredoka as a zip holding the variable `Fredoka[wdth,wght].ttf` and a folder of static
+single-weight files beside it, so the zip was `OSError: unknown file format` and a static file was
+`OSError: invalid argument` - either way a Pillow traceback in the middle of a draw, naming neither the
+argument nor what it should have been. The three scripts now open the font once, before anything is drawn,
+and answer both with the file named, the variable TTF named, and 'Nothing was written.'
+
Run from the repository root: python3 -m unittest discover -s tests -v
"""
+import importlib.util
import os
import re
+import shutil
import subprocess
import sys
import tempfile
@@ -121,6 +130,116 @@ class FontArgumentTest(unittest.TestCase):
f"{name} still reports the font it was given")
+HAVE_PIL = importlib.util.find_spec("PIL") is not None
+# The launcher's own font is the one font file this checkout carries, and it is variable: a real font the
+# scripts must go on accepting.
+LAUNCHER_FONT = ROOT / "launcher" / "app" / "src" / "main" / "res" / "font" / "outfit.ttf"
+
+
+def run_plain(argv):
+ """The same run with the real Pillow, so the font this machine has is what the script reads.
+
+ From the repository root, as the scripts are documented: the two picture scripts read `docs/press/`.
+ """
+ env = dict(os.environ)
+ env.pop("PYTHONPATH", None)
+ return subprocess.run([sys.executable, *argv], cwd=ROOT, env=env, capture_output=True, text=True)
+
+
+def fonts(kind):
+ """TTF files this machine has, wanted for what Pillow says about setting a weight on them."""
+ candidates = [LAUNCHER_FONT]
+ fc_match = shutil.which("fc-match")
+ if fc_match:
+ done = subprocess.run([fc_match, "-f", "%{file}", "sans"], capture_output=True, text=True)
+ if done.stdout.strip():
+ candidates.append(Path(done.stdout.strip()))
+ for folder in ("/usr/share/fonts", "/usr/local/share/fonts", str(Path.home() / ".fonts")):
+ if Path(folder).is_dir():
+ candidates += sorted(Path(folder).rglob("*.ttf"))[:200]
+ found = []
+ if not HAVE_PIL:
+ return found
+ from PIL import ImageFont
+ for path in candidates:
+ if not path.is_file():
+ continue
+ try:
+ font = ImageFont.truetype(str(path), 12)
+ except (OSError, ValueError):
+ continue
+ try:
+ font.set_variation_by_axes([400])
+ variable = True
+ except (OSError, ValueError):
+ variable = False
+ if variable == (kind == "variable"):
+ found.append(path)
+ return found
+
+
+class FontFileTest(unittest.TestCase):
+ """A font path that is there is not a font: the zip, and one of the static files inside it."""
+
+ def assert_refused(self, font, why):
+ with tempfile.TemporaryDirectory() as tmp:
+ for name, picture in CARD_SCRIPTS.items():
+ with self.subTest(script=name):
+ out = Path(tmp) / picture
+ done = run_plain([str(TOOLS / name), str(font), str(out)])
+ self.assertNotEqual(done.returncode, 0, f"{name} accepted {why}")
+ self.assertIn(str(font), done.stderr, f"{name} does not name the font it could not use")
+ self.assertIn("variable TTF", done.stderr,
+ f"{name} does not say which of Fredoka's files it needs")
+ self.assertIn("Nothing was written", done.stderr,
+ f"{name} does not say whether a picture was written")
+ self.assertNotIn("Traceback", done.stderr, f"{name} still dies on a Pillow traceback")
+ self.assertFalse(out.exists(), f"{name} wrote {out} with {why}")
+
+ @unittest.skipUnless(HAVE_PIL, "reading a font needs Pillow (tools/requirements-perf.txt)")
+ def test_a_file_that_is_not_a_font_is_named(self):
+ # The shared download is a zip: `truetype` answers it with `unknown file format`.
+ with tempfile.TemporaryDirectory() as tmp:
+ font = Path(tmp) / "Fredoka.zip"
+ font.write_bytes(b"PK\x03\x04 a zip holding a font, not a font")
+ self.assert_refused(font, "a zip in place of the font")
+
+ @unittest.skipUnless(HAVE_PIL, "reading a font needs Pillow (tools/requirements-perf.txt)")
+ def test_a_static_single_weight_font_is_named(self):
+ # A static Fredoka-NamedInstance.ttf from the same download has no weight to set: `invalid argument`.
+ static = fonts("static")
+ if not static:
+ self.skipTest("no non-variable TTF on this machine to hand the scripts")
+ self.assert_refused(static[0], "a single-weight font in place of the variable one")
+
+ @unittest.skipUnless(HAVE_PIL, "reading a font needs Pillow (tools/requirements-perf.txt)")
+ def test_a_variable_font_still_draws_the_picture(self):
+ # The guard must not refuse the file the page asks for: a real variable TTF still writes its picture.
+ variable = fonts("variable")
+ if not variable:
+ self.skipTest("no variable TTF on this machine to hand the scripts")
+ with tempfile.TemporaryDirectory() as tmp:
+ for name, picture in CARD_SCRIPTS.items():
+ with self.subTest(script=name):
+ out = Path(tmp) / picture
+ done = run_plain([str(TOOLS / name), str(variable[0]), str(out)])
+ self.assertEqual(0, done.returncode, f"{name} refused a variable font: {done.stderr}")
+ self.assertTrue(out.is_file() and out.stat().st_size > 0, f"{name} wrote no picture")
+
+ def test_each_script_names_the_font_it_cannot_use(self):
+ # Read apart in the source, so the message cannot quietly go back to a bare Pillow error: the two
+ # calls that raise for a file that is not a variable font sit in one try, and the run stops there.
+ for name in CARD_SCRIPTS:
+ with self.subTest(script=name):
+ text = (TOOLS / name).read_text(encoding="utf-8")
+ at = text.find("set_variation_by_axes([wt])")
+ self.assertGreater(at, 0, f"{name} no longer sets a weight, so nothing is checked")
+ after = text[at + len("set_variation_by_axes([wt])"):]
+ guarded = re.match(r"[^\n]*\n\s*except \((?:OSError|ValueError)[^)]*\)", after)
+ self.assertIsNotNone(guarded, f"{name} sets the weight outside a try for OSError/ValueError")
+ self.assertIn("cannot use the font at", text, f"{name} does not name the font it cannot use")
+
+
class GenTablesFontTest(unittest.TestCase):
"""gen_tables.py --font runs two of those scripts, so it has to refuse a wrong path itself."""
diff --git a/tools/readme_card.py b/tools/readme_card.py
index 956cd889e..e1dfb55f6 100644
--- a/tools/readme_card.py
+++ b/tools/readme_card.py
@@ -41,7 +41,20 @@ except ImportError:
BG, LINE, DIM, GREEN = "#15181e", "#2c313a", "#aab3bd", "#cfffcf"
W = 1600
def f(size, wt):
- x = ImageFont.truetype(FONT, size); x.set_variation_by_axes([wt]); return x
+ # A path that exists is not yet a font: Google Fonts serves Fredoka as a zip holding the variable
+ # `Fredoka[wdth,wght].ttf` and a folder of static single-weight files beside it. `truetype` answers a
+ # zip with `OSError: unknown file format` and `set_variation_by_axes` answers a static file with
+ # `OSError: invalid argument` - neither names the argument that was wrong, and both arrive as a
+ # Pillow traceback in the middle of a draw. Name the file and what it has to be instead.
+ try:
+ x = ImageFont.truetype(FONT, size); x.set_variation_by_axes([wt])
+ except (OSError, ValueError) as error:
+ sys.exit(f"cannot use the font at {FONT}: {error}. The card is drawn with Fredoka's variable TTF\n"
+ "(Fredoka[wdth,wght].ttf from Google Fonts), not the zip it is downloaded in and not one of\n"
+ "the static single-weight files beside it, which have no weight to set. Nothing was written.")
+ return x
+f(12, 400) # the font is the argument the reader brings, so a wrong one is named before any drawing
+
def spaced(d, cx, y, t, font, sp, fill):
w = sum(d.textlength(c, font=font) for c in t) + sp * (len(t) - 1); x = cx - w / 2
for c in t: d.text((x, y), c, font=font, fill=fill); x += d.textlength(c, font=font) + sp
diff --git a/tools/readme_featured.py b/tools/readme_featured.py
index 4a90ad05e..24635cb0a 100644
--- a/tools/readme_featured.py
+++ b/tools/readme_featured.py
@@ -41,7 +41,19 @@ LOGOS = ["techcrunch", "techradar", "tomsguide", "mashable", "androidauthority",
MORE = "+181 more · 197 articles from 32 countries"
W, LH, GAP, ROWGAP, PAD = 1600, 54, 40, 36, 80
def f(size, wt):
- x = ImageFont.truetype(FONT, size); x.set_variation_by_axes([wt]); return x
+ # A path that exists is not yet a font: Google Fonts serves Fredoka as a zip holding the variable
+ # `Fredoka[wdth,wght].ttf` and a folder of static single-weight files beside it. `truetype` answers a
+ # zip with `OSError: unknown file format` and `set_variation_by_axes` answers a static file with
+ # `OSError: invalid argument` - neither names the argument that was wrong, and both arrive as a
+ # Pillow traceback in the middle of a draw. Name the file and what it has to be instead.
+ try:
+ x = ImageFont.truetype(FONT, size); x.set_variation_by_axes([wt])
+ except (OSError, ValueError) as error:
+ sys.exit(f"cannot use the font at {FONT}: {error}. The card is drawn with Fredoka's variable TTF\n"
+ "(Fredoka[wdth,wght].ttf from Google Fonts), not the zip it is downloaded in and not one of\n"
+ "the static single-weight files beside it, which have no weight to set. Nothing was written.")
+ return x
+f(12, 400) # the font is the argument the reader brings, so a wrong one is named before any drawing
logos = []
for n in LOGOS:
im = Image.open(f"docs/press/{n}.png").convert("RGBA")
diff --git a/tools/readme_stats.py b/tools/readme_stats.py
index 348677680..6173656f7 100644
--- a/tools/readme_stats.py
+++ b/tools/readme_stats.py
@@ -41,7 +41,19 @@ STATS = [("316", "TV MODELS"), ("89", "BRANDS"), ("28", "LANGUAGES"), ("523 KB",
W, H = 1600, 240
img = Image.new("RGB", (W, H), "#15181e"); d = ImageDraw.Draw(img)
def f(size, wt):
- x = ImageFont.truetype(FONT, size); x.set_variation_by_axes([wt]); return x
+ # A path that exists is not yet a font: Google Fonts serves Fredoka as a zip holding the variable
+ # `Fredoka[wdth,wght].ttf` and a folder of static single-weight files beside it. `truetype` answers a
+ # zip with `OSError: unknown file format` and `set_variation_by_axes` answers a static file with
+ # `OSError: invalid argument` - neither names the argument that was wrong, and both arrive as a
+ # Pillow traceback in the middle of a draw. Name the file and what it has to be instead.
+ try:
+ x = ImageFont.truetype(FONT, size); x.set_variation_by_axes([wt])
+ except (OSError, ValueError) as error:
+ sys.exit(f"cannot use the font at {FONT}: {error}. The card is drawn with Fredoka's variable TTF\n"
+ "(Fredoka[wdth,wght].ttf from Google Fonts), not the zip it is downloaded in and not one of\n"
+ "the static single-weight files beside it, which have no weight to set. Nothing was written.")
+ return x
+f(12, 400) # the font is the argument the reader brings, so a wrong one is named before any drawing
num, lab = f(92, 600), f(30, 500)
PAD = 70
col = (W - 2 * PAD) / len(STATS)