# -*- coding: utf-8 -*- # view/goth_text_renderer.py from __future__ import annotations import re from pathlib import Path import tkinter as tk from PIL import Image, ImageDraw, ImageFont, ImageTk from resources.code_res.game_constants import ( FONTS_REL_DIR, FONT_COLOR_BODY_DEFAULT, FONT_FILE_ALTERNATE, 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, ) _ALL_CAPS_WORD_RE = re.compile(r"\b[A-ZÄÖÜ]{4,}\b") class GothTextRenderer: """Rendert mehrzeilige Old-London-Texte mit Tracking, Kontur und Schlagschatten als PIL/Tk-Grafik.""" def __init__(self, root_dir: Path, pil_cache: dict, tk_cache: dict): self.root_dir = root_dir self._pil_cache = pil_cache self._tk_cache = tk_cache self._font_cache: dict[tuple[bool, int], ImageFont.FreeTypeFont | ImageFont.ImageFont] = {} def get_pil_font(self, size_px: int, alternate: bool = False) -> ImageFont.FreeTypeFont | ImageFont.ImageFont: size_px = max(12, int(size_px)) key = (alternate, size_px) if key not in self._font_cache: fname = FONT_FILE_ALTERNATE if alternate else FONT_FILE_PRIMARY fpath = self.root_dir / FONTS_REL_DIR / fname if not fpath.is_file(): fpath = self.root_dir / FONTS_REL_DIR / FONT_FILE_PRIMARY try: self._font_cache[key] = ImageFont.truetype(str(fpath), size_px) except Exception: self._font_cache[key] = ImageFont.load_default() return self._font_cache[key] @staticmethod def sanitize_goth_case(text: str) -> str: if not text or not FONT_FORCE_MIXED_CASE: return text return _ALL_CAPS_WORD_RE.sub(lambda m: m.group(0).capitalize(), text) @staticmethod def measure_tracked_line( draw: ImageDraw.ImageDraw, line: str, font: ImageFont.FreeTypeFont | ImageFont.ImageFont, letter_spacing: int, ) -> float: if not line: return 0.0 if letter_spacing == 0: return float(draw.textlength(line, font=font)) adv_fn = draw.textlength total = 0.0 for ch in line: total += adv_fn(ch, font=font) return total + letter_spacing * (len(line) - 1) @staticmethod def draw_tracked_line( draw: ImageDraw.ImageDraw, x: float, y: float, line: str, font: ImageFont.FreeTypeFont | ImageFont.ImageFont, 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 if letter_spacing == 0: if has_shadow: draw.text((x + sx, y + sy), line, font=font, fill=FONT_SHADOW_COLOR) if outline_px > 0: draw.text((x, y), line, font=font, fill=fill, stroke_width=outline_px, stroke_fill=FONT_OUTLINE_COLOR) else: draw.text((x, y), line, font=font, fill=fill) return adv_fn = draw.textlength cur_x = x for ch in line: if has_shadow: draw.text((cur_x + sx, y + sy), ch, font=font, fill=FONT_SHADOW_COLOR) if outline_px > 0: draw.text( (cur_x, y), ch, font=font, fill=fill, stroke_width=outline_px, stroke_fill=FONT_OUTLINE_COLOR, ) else: draw.text((cur_x, y), ch, font=font, fill=fill) cur_x += adv_fn(ch, font=font) + 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 = FONT_LETTER_SPACING_PX, alternate: bool = False, uncached: bool = False, ) -> Image.Image: clean_text = self.sanitize_goth_case(str(text or "")) cache_key = ( "goth_txt_pil", clean_text, size_px, color, max_width, align, shadow_offset, outline_px, letter_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) 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_tracked_line(d_draw, cand, font, letter_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_tracked_line(d_draw, ln, font, letter_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 + FONT_VERTICAL_OFFSET_PX) self.draw_tracked_line( draw, lx, ly, ln, font, color, letter_spacing, shadow_offset, outline_px ) if not uncached: if len(self._pil_cache) > 500: 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[:150]: 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 = FONT_LETTER_SPACING_PX, alternate: bool = False, ) -> ImageTk.PhotoImage: tk_key = ( "goth_txt_tk", 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) > 500: 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[:150]: self._tk_cache.pop(k, None) self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_img) return self._tk_cache[tk_key]