the_goth_cardgame_collection/view/widgets/button_art_compositor.py

307 lines
12 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# view/widgets/button_art_compositor.py
from __future__ import annotations
from pathlib import Path
import re
from PIL import Image, ImageChops, ImageDraw, ImageEnhance, ImageFont, ImageTk
from resources.code_res.game_constants import (
DEFAULT_UI_FONT_KEY,
FONTS_REL_DIR,
FONT_FILE_PRIMARY,
FONT_FORCE_MIXED_CASE,
FONT_LETTER_SPACING_PX,
FONT_OUTLINE_COLOR,
FONT_OUTLINE_THICKNESS_PX,
FONT_SHADOW_COLOR,
FONT_SHADOW_ENABLED,
FONT_SHADOW_OFFSET_DEFAULT,
FONT_SIZE_BUTTON,
FONT_SIZE_SMALL_MIN,
FONT_VERTICAL_OFFSET_PX,
UI_FONT_PRESETS,
)
from view.font_loader import FontLoader, resolve_font_file_case_insensitive
from view.goth_text_renderer import (
_extract_ttf_cmap_codepoints,
get_system_default_pil_font,
)
SIDE_CAP_ASPECT = 0.46
VERTICAL_FRAME_RATIO = 0.36
_ROOT_DIR = Path(__file__).resolve().parents[2]
_FONTS_DIR = _ROOT_DIR / FONTS_REL_DIR
_FONT_CACHE: dict[tuple[str, int], ImageFont.FreeTypeFont | ImageFont.ImageFont] = {}
_CMAP_CACHE: dict[str, frozenset[int]] = {}
_ALPHA_CORNER_CACHE: dict[tuple[int, int, int], Image.Image] = {}
_TRIM_BTN_CACHE: dict[tuple[int, int, int], Image.Image] = {}
_BTN_PHOTO_CACHE: dict[tuple, ImageTk.PhotoImage] = {}
_LEADING_ICON_RE = re.compile(r"^(?:[^\w\s\+\(\[\"'ÄÖÜäöüß]+|\+(?=\s))\s*", re.UNICODE)
_TRAILING_ICON_RE = re.compile(r"\s*[^\w\s\)\]\.\!\%\"'ÄÖÜäöüß]+$", re.UNICODE)
class ButtonArtCompositor:
"""Skaliert Gothic-Button-Texturen im 3-Slice-Verfahren und brennt Beschriftungen in der aktiven UI-Schrift ein."""
@staticmethod
def _get_cmap(fname: str) -> frozenset[int]:
if fname not in _CMAP_CACHE:
fpath = resolve_font_file_case_insensitive(_FONTS_DIR, fname)
_CMAP_CACHE[fname] = _extract_ttf_cmap_codepoints(fpath)
return _CMAP_CACHE[fname]
@classmethod
def get_ui_pil_font(
cls, size_px: int, 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(12, int(round(int(size_px) * float(preset.get("size_scale", 1.0)))))
cache_k = (f_key, eff_px)
if cache_k not in _FONT_CACHE:
fpath = resolve_font_file_case_insensitive(_FONTS_DIR, preset["file"])
if fpath is None:
fpath = resolve_font_file_case_insensitive(_FONTS_DIR, FONT_FILE_PRIMARY)
try:
_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:
_FONT_CACHE[cache_k] = get_system_default_pil_font(eff_px)
return _FONT_CACHE[cache_k]
@classmethod
def get_old_london(cls, size_px: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
"""Abwärtskompatibler Alias -> liefert immer die aktuell gewählte UI-Schrift."""
return cls.get_ui_pil_font(size_px)
@classmethod
def font_for_char(
cls, ch: str, size_px: int, active_key: str | None = None
) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
f_key = active_key or FontLoader.get_active_font_key()
if ch.isspace():
return cls.get_ui_pil_font(size_px, f_key)
preset = UI_FONT_PRESETS.get(f_key, UI_FONT_PRESETS[DEFAULT_UI_FONT_KEY])
cps = cls._get_cmap(preset["file"])
if not cps or ord(ch) in cps:
return cls.get_ui_pil_font(size_px, f_key)
return get_system_default_pil_font(size_px)
@staticmethod
def clean_outer_black_matte(pil_img: Image.Image) -> Image.Image:
key = (id(pil_img), pil_img.width, pil_img.height)
if key in _ALPHA_CORNER_CACHE:
return _ALPHA_CORNER_CACHE[key]
rgba = pil_img.convert("RGBA")
w, h = rgba.size
tl = rgba.getpixel((0, 0))
if tl[3] > 240 and max(tl[:3]) < 16:
r, g, b, a = rgba.split()
luma = ImageChops.lighter(ImageChops.lighter(r, g), b)
seed_img = luma.point(lambda p: 0 if p < 18 else 255)
for seed in ((0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)):
if seed_img.getpixel(seed) == 0:
ImageDraw.floodfill(seed_img, seed, 128)
ext_alpha = seed_img.point(lambda p: 0 if p == 128 else 255)
rgba.putalpha(ImageChops.darker(a, ext_alpha))
_ALPHA_CORNER_CACHE[key] = rgba
return rgba
@classmethod
def trim_button_art(cls, pil_img: Image.Image) -> Image.Image:
key = (id(pil_img), pil_img.width, pil_img.height)
if key in _TRIM_BTN_CACHE:
return _TRIM_BTN_CACHE[key]
clean = cls.clean_outer_black_matte(pil_img)
bbox = clean.getbbox()
cropped = clean.crop(bbox) if bbox else clean
_TRIM_BTN_CACHE[key] = cropped
return cropped
@classmethod
def scale_button_3slice(
cls, src_pil: Image.Image, target_w: int, target_h: int
) -> tuple[Image.Image, int]:
trimmed = cls.trim_button_art(src_pil)
sw, sh = trimmed.size
src_cap_w = max(16, int(round(sh * SIDE_CAP_ASPECT)))
dst_cap_w = max(12, min(target_w // 3, int(round(target_h * SIDE_CAP_ASPECT))))
mid_dst_w = max(4, target_w - 2 * dst_cap_w)
if sw <= 2 * src_cap_w + 8:
return trimmed.resize((target_w, target_h), Image.Resampling.LANCZOS), dst_cap_w
left_cap = trimmed.crop((0, 0, src_cap_w, sh)).resize((dst_cap_w, target_h), Image.Resampling.LANCZOS)
right_cap = trimmed.crop((sw - src_cap_w, 0, sw, sh)).resize((dst_cap_w, target_h), Image.Resampling.LANCZOS)
mid_piece = trimmed.crop((src_cap_w, 0, sw - src_cap_w, sh)).resize((mid_dst_w, target_h), Image.Resampling.LANCZOS)
out = Image.new("RGBA", (target_w, target_h), (0, 0, 0, 0))
out.paste(left_cap, (0, 0))
out.paste(mid_piece, (dst_cap_w, 0))
out.paste(right_cap, (dst_cap_w + mid_dst_w, 0))
return out, dst_cap_w
@staticmethod
def prepare_label_text(txt: str) -> str:
cleaned = _LEADING_ICON_RE.sub("", txt.strip())
cleaned = _TRAILING_ICON_RE.sub("", cleaned).strip()
cleaned = cleaned.replace("→", "-").replace("←", "-")
preset = FontLoader.get_active_preset()
if not cleaned or not preset.get("force_mixed_case", FONT_FORCE_MIXED_CASE):
return cleaned
fixed = []
for p in cleaned.split(" "):
letters = [c for c in p if c.isalpha()]
if len(letters) >= 4 and all(c.isupper() for c in letters):
fixed.append(p.capitalize())
else:
fixed.append(p)
return " ".join(fixed)
@staticmethod
def resolve_font_px(font_arg, btn_h: int) -> int:
inner_h = max(14.0, btn_h * (1.0 - VERTICAL_FRAME_RATIO))
max_safe_px = max(14, min(FONT_SIZE_BUTTON, int(round(inner_h * 0.80))))
auto_px = max(FONT_SIZE_SMALL_MIN if btn_h >= 34 else 14, max_safe_px)
if isinstance(font_arg, (tuple, list)) and len(font_arg) >= 2:
try:
fam = str(font_arg[0]).lower()
raw_sz = int(font_arg[1])
if "london" in fam or "gothic" in fam:
return max(14, min(max_safe_px, raw_sz))
return max(14, min(max_safe_px, int(round(raw_sz * 1.85))))
except Exception:
pass
return auto_px
@classmethod
def measure_text_smart(
cls, text: str, font_px: int, active_key: str, spacing: int
) -> float:
if not text:
return 0.0
draw = ImageDraw.Draw(Image.new("RGBA", (4, 4), (0, 0, 0, 0)))
total = 0.0
for i, ch in enumerate(text):
fnt = cls.font_for_char(ch, font_px, active_key)
total += draw.textlength(ch, font=fnt)
if i < len(text) - 1:
total += spacing
return total
@classmethod
def compute_framed_width(
cls, text: str, requested_w: int, btn_h: int, font_px: int, auto_expand: bool
) -> int:
if not text or not auto_expand:
return requested_w
active_key = FontLoader.get_active_font_key()
preset = FontLoader.get_active_preset()
spacing = int(preset.get("letter_spacing", FONT_LETTER_SPACING_PX))
txt_w = cls.measure_text_smart(text, font_px, active_key, spacing)
inset = max(13, int(round(btn_h * SIDE_CAP_ASPECT))) + 6
return max(requested_w, int(round(txt_w + 2 * inset)))
@classmethod
def compose_photo(
cls,
base_pil: Image.Image | None,
width: int,
height: int,
text: str,
font_px: int,
text_color: str,
dim_disabled: bool = False,
brighten_active: bool = False,
) -> ImageTk.PhotoImage | None:
if base_pil is None:
return None
active_key = FontLoader.get_active_font_key()
preset = UI_FONT_PRESETS.get(active_key, UI_FONT_PRESETS[DEFAULT_UI_FONT_KEY])
spacing = int(preset.get("letter_spacing", FONT_LETTER_SPACING_PX))
v_off = int(preset.get("v_offset", FONT_VERTICAL_OFFSET_PX))
cache_key = (
active_key, id(base_pil), width, height, text,
font_px, text_color, dim_disabled, brighten_active,
)
cached = _BTN_PHOTO_CACHE.get(cache_key)
if cached is not None:
return cached
bg, cap_w = cls.scale_button_3slice(base_pil, width, height)
if dim_disabled:
alpha = bg.getchannel("A")
rgb = ImageEnhance.Color(bg.convert("RGB")).enhance(0.10)
rgb = ImageEnhance.Brightness(rgb).enhance(0.55)
bg = rgb.convert("RGBA")
bg.putalpha(alpha)
elif brighten_active:
alpha = bg.getchannel("A")
rgb = ImageEnhance.Brightness(bg.convert("RGB")).enhance(1.12)
bg = rgb.convert("RGBA")
bg.putalpha(alpha)
if text:
draw = ImageDraw.Draw(bg)
max_txt_w = max(20, width - 2 * (cap_w + 5))
f_px = font_px
while cls.measure_text_smart(text, f_px, active_key, spacing) > max_txt_w and f_px > 12:
f_px -= 1
tw = cls.measure_text_smart(text, f_px, active_key, spacing)
main_fnt = cls.get_ui_pil_font(f_px, active_key)
try:
main_asc, descent = main_fnt.getmetrics() # type: ignore[attr-defined]
th = main_asc + descent
except Exception:
main_asc, th = f_px, f_px
cur_x = (width - tw) / 2.0
cur_y = (height - th) / 2.0 + v_off
sx, sy = FONT_SHADOW_OFFSET_DEFAULT
for ch in text:
ch_fnt = cls.font_for_char(ch, f_px, active_key)
if ch_fnt is not main_fnt:
try:
ch_asc, _ = ch_fnt.getmetrics() # type: ignore[attr-defined]
except Exception:
ch_asc = f_px
ch_y = cur_y + (main_asc - ch_asc)
else:
ch_y = cur_y
if FONT_SHADOW_ENABLED and not dim_disabled:
draw.text((cur_x + sx, ch_y + sy), ch, font=ch_fnt, fill=FONT_SHADOW_COLOR)
if FONT_OUTLINE_THICKNESS_PX > 0 and not dim_disabled:
draw.text(
(cur_x, ch_y), ch, font=ch_fnt, fill=text_color,
stroke_width=FONT_OUTLINE_THICKNESS_PX, stroke_fill=FONT_OUTLINE_COLOR,
)
else:
draw.text((cur_x, ch_y), ch, font=ch_fnt, fill=text_color)
cur_x += draw.textlength(ch, font=ch_fnt) + spacing
photo = ImageTk.PhotoImage(bg)
if len(_BTN_PHOTO_CACHE) > 450:
_BTN_PHOTO_CACHE.clear()
_BTN_PHOTO_CACHE[cache_key] = photo
return photo