Files
hyperstitionstudio-core/src/hyperstitionstud_io/publishing/fonts.py
T

48 lines
1.4 KiB
Python

"""
hyperstitionstud_io.publishing.fonts — Cross-OS TrueType Font Resolver with Built-In Fallbacks.
Searches Debian/Ubuntu, Fedora/RHEL, Arch, Alpine, macOS, and user font directories so PDF and
PNG rendering never crashes on OS-specific font paths.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
FONT_SEARCH_DIRS = [
Path("/usr/share/fonts/truetype/dejavu"),
Path("/usr/share/fonts/dejavu-sans-fonts"),
Path("/usr/share/fonts/dejavu-sans-mono-fonts"),
Path("/usr/share/fonts/TTF"),
Path("/usr/share/fonts/dejavu"),
Path.home() / ".local" / "share" / "fonts",
Path.home() / "Library" / "Fonts",
Path("/Library/Fonts"),
Path("/System/Library/Fonts"),
]
def resolve_font_path(filename: str, fallback_filename: str | None = None) -> Path | None:
for d in FONT_SEARCH_DIRS:
cand = d / filename
if cand.is_file():
return cand
if fallback_filename:
for d in FONT_SEARCH_DIRS:
cand = d / fallback_filename
if cand.is_file():
return cand
return None
def load_pillow_font(filename: str, size: int) -> Any:
from PIL import ImageFont
p = resolve_font_path(filename, fallback_filename="DejaVuSans.ttf")
if p is not None:
return ImageFont.truetype(str(p), size)
try:
return ImageFont.load_default(size=size)
except TypeError:
return ImageFont.load_default()