the_goth_cardgame_collection/view/goth_text_renderer.py

451 lines
17 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# view/goth_text_renderer.py
from __future__ import annotations
from pathlib import Path
import re
import struct
import subprocess
import sys
from PIL import Image, ImageDraw, ImageFont, ImageTk
from resources.code_res.game_constants import (
DEFAULT_UI_FONT_KEY,
FONTS_REL_DIR,
FONT_COLOR_BODY_DEFAULT,
FONT_FILE_PRIMARY,
FONT_FORCE_MIXED_CASE,
FONT_LETTER_SPACING_PX,
FONT_LINE_HEIGHT_FACTOR,
FONT_OUTLINE_COLOR,
FONT_OUTLINE_THICKNESS_PX,
FONT_SHADOW_COLOR,
FONT_SHADOW_ENABLED,
FONT_SHADOW_OFFSET_DEFAULT,
FONT_VERTICAL_OFFSET_PX,
UI_FONT_PRESETS,
)
from view.font_loader import FontLoader, resolve_font_file_case_insensitive
_ALL_CAPS_WORD_RE = re.compile(r"\b[A-ZÄÖÜ]{4,}\b")
_SYS_FONT_PATH_RESOLVED: bool = False
_SYS_FONT_PATH: str | None = None
_SYS_PIL_FONT_CACHE: dict[int, ImageFont.FreeTypeFont | ImageFont.ImageFont] = {}
def _extract_ttf_cmap_codepoints(ttf_path: Path | None) -> frozenset[int]:
"""Liest einmalig alle unterstützen Unicode-Codepoints (Format 4 & 12) aus der TTF-Datei."""
if ttf_path is None or not ttf_path.is_file():
return frozenset()
try:
data = ttf_path.read_bytes()
if len(data) < 12:
return frozenset()
num_tables = struct.unpack_from(">H", data, 4)[0]
cmap_off = 0
for i in range(num_tables):
tag, _csum, off, _ln = struct.unpack_from(">4sIII", data, 12 + i * 16)
if tag == b"cmap":
cmap_off = off
break
if not cmap_off:
return frozenset()
_ver, num_sub = struct.unpack_from(">HH", data, cmap_off)
cps: set[int] = set()
for i in range(num_sub):
pid, eid, rel_off = struct.unpack_from(">HHI", data, cmap_off + 4 + i * 8)
if not (pid == 0 or (pid == 3 and eid in (1, 10))):
continue
sub = cmap_off + rel_off
fmt = struct.unpack_from(">H", data, sub)[0]
if fmt == 4:
seg_x2 = struct.unpack_from(">H", data, sub + 6)[0]
seg_cnt = seg_x2 // 2
end_pos = sub + 14
start_pos = end_pos + seg_x2 + 2
delta_pos = start_pos + seg_x2
ro_pos = delta_pos + seg_x2
for s_i in range(seg_cnt):
end_c = struct.unpack_from(">H", data, end_pos + 2 * s_i)[0]
start_c = struct.unpack_from(">H", data, start_pos + 2 * s_i)[0]
if start_c == 0xFFFF:
break
delta = struct.unpack_from(">h", data, delta_pos + 2 * s_i)[0]
ro = struct.unpack_from(">H", data, ro_pos + 2 * s_i)[0]
for cp in range(start_c, end_c + 1):
if ro == 0:
gid = (cp + delta) & 0xFFFF
else:
g_addr = ro_pos + 2 * s_i + ro + 2 * (cp - start_c)
if g_addr + 2 > len(data):
continue
gid = struct.unpack_from(">H", data, g_addr)[0]
if gid != 0:
gid = (gid + delta) & 0xFFFF
if gid != 0:
cps.add(cp)
elif fmt == 12:
n_grp = struct.unpack_from(">I", data, sub + 12)[0]
for g_i in range(n_grp):
s_c, e_c, s_gid = struct.unpack_from(">III", data, sub + 16 + g_i * 12)
if s_gid != 0 and e_c - s_c < 0x10000:
cps.update(range(s_c, e_c + 1))
return frozenset(cps)
except Exception:
return frozenset()
def _find_system_default_font_path() -> str | None:
"""Ermittelt einmalig die Standard-Systemschrift des Betriebssystems."""
global _SYS_FONT_PATH_RESOLVED, _SYS_FONT_PATH
if _SYS_FONT_PATH_RESOLVED:
return _SYS_FONT_PATH
_SYS_FONT_PATH_RESOLVED = True
if sys.platform.startswith("win"):
candidates = (
"C:/Windows/Fonts/segoeui.ttf",
"C:/Windows/Fonts/arial.ttf",
"C:/Windows/Fonts/tahoma.ttf",
)
elif sys.platform == "darwin":
candidates = (
"/System/Library/Fonts/SFNS.ttf",
"/System/Library/Fonts/Helvetica.ttc",
"/System/Library/Fonts/Supplemental/Arial.ttf",
)
else:
try:
res = subprocess.run(
["fc-match", "-f", "%{file}", "sans-serif"],
capture_output=True,
text=True,
timeout=1.5,
)
fc_path = (res.stdout or "").strip()
if fc_path and Path(fc_path).is_file():
_SYS_FONT_PATH = fc_path
return _SYS_FONT_PATH
except Exception:
pass
candidates = (
"/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/TTF/DejaVuSans.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
)
for c in candidates:
if Path(c).is_file():
_SYS_FONT_PATH = c
return _SYS_FONT_PATH
return None
def get_system_default_pil_font(size_px: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
"""Liefert die skalierte Standard-Systemschrift als direkten Fallback für fehlende Zeichen."""
eff_px = max(11, int(round(int(size_px) * 0.86)))
if eff_px not in _SYS_PIL_FONT_CACHE:
spath = _find_system_default_font_path()
if spath is not None:
try:
_SYS_PIL_FONT_CACHE[eff_px] = ImageFont.truetype(spath, eff_px)
return _SYS_PIL_FONT_CACHE[eff_px]
except Exception:
pass
try:
_SYS_PIL_FONT_CACHE[eff_px] = ImageFont.load_default(size=eff_px)
except TypeError:
_SYS_PIL_FONT_CACHE[eff_px] = ImageFont.load_default()
return _SYS_PIL_FONT_CACHE[eff_px]
class GothTextRenderer:
"""Rendert mehrzeilige UI-Texte in der gewählten Schriftart inkl. Systemschrift-Fallback."""
def __init__(self, root_dir: Path, pil_cache: dict, tk_cache: dict):
self.root_dir = root_dir
self.fonts_dir = root_dir / FONTS_REL_DIR
self._pil_cache = pil_cache
self._tk_cache = tk_cache
self._font_cache: dict[tuple[str, bool, int], ImageFont.FreeTypeFont | ImageFont.ImageFont] = {}
self._cmap_cache: dict[str, frozenset[int]] = {}
def _get_cmap_for_file(self, fname: str) -> frozenset[int]:
if fname not in self._cmap_cache:
fpath = resolve_font_file_case_insensitive(self.fonts_dir, fname)
self._cmap_cache[fname] = _extract_ttf_cmap_codepoints(fpath)
return self._cmap_cache[fname]
def get_pil_font(
self, size_px: int, alternate: bool = False, font_key: str | None = None
) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
f_key = font_key or FontLoader.get_active_font_key()
preset = UI_FONT_PRESETS.get(f_key, UI_FONT_PRESETS[DEFAULT_UI_FONT_KEY])
eff_px = max(11, int(round(int(size_px) * float(preset.get("size_scale", 1.0)))))
cache_k = (f_key, alternate, eff_px)
if cache_k not in self._font_cache:
fname = preset["alt_file"] if alternate else preset["file"]
fpath = resolve_font_file_case_insensitive(self.fonts_dir, fname)
if fpath is None:
fpath = resolve_font_file_case_insensitive(self.fonts_dir, FONT_FILE_PRIMARY)
try:
self._font_cache[cache_k] = (
ImageFont.truetype(str(fpath), eff_px)
if fpath is not None
else get_system_default_pil_font(eff_px)
)
except Exception:
self._font_cache[cache_k] = get_system_default_pil_font(eff_px)
return self._font_cache[cache_k]
def _get_fallback_font_for_char(
self, ch: str, size_px: int, active_key: str, active_fname: str
) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
if ch.isspace():
return self.get_pil_font(size_px, alternate=False, font_key=active_key)
active_cps = self._get_cmap_for_file(active_fname)
if not active_cps or ord(ch) in active_cps:
return self.get_pil_font(size_px, alternate=False, font_key=active_key)
return get_system_default_pil_font(size_px)
@staticmethod
def sanitize_goth_case(text: str) -> str:
if not text:
return text
preset = FontLoader.get_active_preset()
if not preset.get("force_mixed_case", FONT_FORCE_MIXED_CASE):
return text
return _ALL_CAPS_WORD_RE.sub(lambda m: m.group(0).capitalize(), text)
def _measure_line_smart(
self,
draw: ImageDraw.ImageDraw,
line: str,
size_px: int,
active_key: str,
active_fname: str,
letter_spacing: int,
) -> float:
if not line:
return 0.0
adv_fn = draw.textlength
total = 0.0
for ch in line:
fnt = self._get_fallback_font_for_char(ch, size_px, active_key, active_fname)
total += adv_fn(ch, font=fnt)
return total + letter_spacing * (len(line) - 1)
@staticmethod
def _font_ascent(fnt: ImageFont.FreeTypeFont | ImageFont.ImageFont, fallback_px: int) -> int:
try:
asc, _desc = fnt.getmetrics() # type: ignore[attr-defined]
return int(asc)
except Exception:
return int(fallback_px)
def _draw_line_smart(
self,
draw: ImageDraw.ImageDraw,
x: float,
y: float,
line: str,
size_px: int,
active_key: str,
active_fname: str,
fill: str,
letter_spacing: int,
shadow_offset: tuple[int, int] | None,
outline_px: int,
) -> None:
if not line:
return
has_shadow = bool(
FONT_SHADOW_ENABLED and shadow_offset and (shadow_offset[0] or shadow_offset[1])
)
sx = shadow_offset[0] if (has_shadow and shadow_offset) else 0
sy = shadow_offset[1] if (has_shadow and shadow_offset) else 0
main_fnt = self.get_pil_font(size_px, alternate=False, font_key=active_key)
active_cps = self._get_cmap_for_file(active_fname)
all_supported = (not active_cps) or all(
ch.isspace() or (ord(ch) in active_cps) for ch in line
)
if letter_spacing == 0 and all_supported:
if has_shadow:
draw.text((x + sx, y + sy), line, font=main_fnt, fill=FONT_SHADOW_COLOR)
if outline_px > 0:
draw.text(
(x, y), line, font=main_fnt, fill=fill,
stroke_width=outline_px, stroke_fill=FONT_OUTLINE_COLOR,
)
else:
draw.text((x, y), line, font=main_fnt, fill=fill)
return
main_asc = self._font_ascent(main_fnt, size_px)
adv_fn = draw.textlength
cur_x = x
for ch in line:
fnt = self._get_fallback_font_for_char(ch, size_px, active_key, active_fname)
# Exakt auf dieselbe Grundlinie (Baseline) setzen!
ch_y = y + (main_asc - self._font_ascent(fnt, size_px)) if fnt is not main_fnt else y
if has_shadow:
draw.text((cur_x + sx, ch_y + sy), ch, font=fnt, fill=FONT_SHADOW_COLOR)
if outline_px > 0:
draw.text(
(cur_x, ch_y), ch, font=fnt, fill=fill,
stroke_width=outline_px, stroke_fill=FONT_OUTLINE_COLOR,
)
else:
draw.text((cur_x, ch_y), ch, font=fnt, fill=fill)
cur_x += adv_fn(ch, font=fnt) + letter_spacing
def render_pil(
self,
text: str,
size_px: int,
color: str = FONT_COLOR_BODY_DEFAULT,
max_width: int | None = None,
align: str = "center",
shadow_offset: tuple[int, int] | None = FONT_SHADOW_OFFSET_DEFAULT,
outline_px: int = FONT_OUTLINE_THICKNESS_PX,
letter_spacing: int | None = None,
alternate: bool = False,
uncached: bool = False,
) -> Image.Image:
active_key = FontLoader.get_active_font_key()
preset = UI_FONT_PRESETS.get(active_key, UI_FONT_PRESETS[DEFAULT_UI_FONT_KEY])
active_fname = preset["alt_file"] if alternate else preset["file"]
eff_spacing = (
int(preset.get("letter_spacing", FONT_LETTER_SPACING_PX))
if (letter_spacing is None or letter_spacing == FONT_LETTER_SPACING_PX)
else int(letter_spacing)
)
v_offset = int(preset.get("v_offset", FONT_VERTICAL_OFFSET_PX))
clean_text = self.sanitize_goth_case(str(text or ""))
cache_key = (
"goth_txt_pil", active_key, clean_text, size_px, color,
max_width, align, shadow_offset, outline_px, eff_spacing, alternate,
)
if not uncached and cache_key in self._pil_cache:
return self._pil_cache[cache_key]
font = self.get_pil_font(size_px, alternate=alternate, font_key=active_key)
dummy = Image.new("RGBA", (8, 8), (0, 0, 0, 0))
d_draw = ImageDraw.Draw(dummy)
lines: list[str] = []
for para in clean_text.split("\n"):
if not max_width or max_width <= 20 or not para.strip():
lines.append(para)
continue
cur = ""
for w in para.split(" "):
cand = f"{cur} {w}".strip() if cur else w
if (
self._measure_line_smart(d_draw, cand, size_px, active_key, active_fname, eff_spacing)
<= max_width
or not cur
):
cur = cand
else:
lines.append(cur)
cur = w
lines.append(cur)
if not lines:
lines = [""]
try:
ascent, descent = font.getmetrics() # type: ignore[attr-defined]
except Exception:
ascent, descent = size_px, max(6, size_px // 3)
base_line_h = max(size_px + 4, ascent + descent)
step_y = int(round(base_line_h * FONT_LINE_HEIGHT_FACTOR))
pad_x = max(6, outline_px * 2 + (abs(shadow_offset[0]) if shadow_offset else 0) + 4)
pad_top = max(6, outline_px * 2 + 4)
pad_bot = max(
8, descent // 2 + outline_px * 2 + (abs(shadow_offset[1]) if shadow_offset else 0) + 6
)
line_widths = [
self._measure_line_smart(d_draw, ln, size_px, active_key, active_fname, eff_spacing)
for ln in lines
]
content_w = int(round(max(line_widths, default=1.0)))
img_w = max(4, content_w + pad_x * 2)
img_h = max(4, pad_top + base_line_h + max(0, len(lines) - 1) * step_y + pad_bot)
canvas_img = Image.new("RGBA", (img_w, img_h), (0, 0, 0, 0))
draw = ImageDraw.Draw(canvas_img)
for idx, (ln, lw) in enumerate(zip(lines, line_widths)):
if align == "left":
lx = float(pad_x)
elif align == "right":
lx = float(img_w - pad_x) - lw
else:
lx = (img_w - lw) / 2.0
ly = float(pad_top + idx * step_y + v_offset)
self._draw_line_smart(
draw, lx, ly, ln, size_px, active_key, active_fname,
color, eff_spacing, shadow_offset, outline_px,
)
if not uncached:
if len(self._pil_cache) > 550:
txt_keys = [
k for k in self._pil_cache
if isinstance(k, tuple) and k and k[0] == "goth_txt_pil"
]
for k in txt_keys[:180]:
self._pil_cache.pop(k, None)
self._pil_cache[cache_key] = canvas_img
return canvas_img
def get_photo(
self,
text: str,
size_px: int,
color: str = FONT_COLOR_BODY_DEFAULT,
max_width: int | None = None,
align: str = "center",
shadow_offset: tuple[int, int] | None = FONT_SHADOW_OFFSET_DEFAULT,
outline_px: int = FONT_OUTLINE_THICKNESS_PX,
letter_spacing: int | None = None,
alternate: bool = False,
) -> ImageTk.PhotoImage:
active_key = FontLoader.get_active_font_key()
tk_key = (
"goth_txt_tk", active_key, text, size_px, color,
max_width, align, shadow_offset, outline_px, letter_spacing, alternate,
)
if tk_key not in self._tk_cache:
pil_img = self.render_pil(
text=text,
size_px=size_px,
color=color,
max_width=max_width,
align=align,
shadow_offset=shadow_offset,
outline_px=outline_px,
letter_spacing=letter_spacing,
alternate=alternate,
)
if len(self._tk_cache) > 550:
txt_keys = [
k for k in self._tk_cache
if isinstance(k, tuple) and k and k[0] == "goth_txt_tk"
]
for k in txt_keys[:180]:
self._tk_cache.pop(k, None)
self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_img)
return self._tk_cache[tk_key]