# -*- coding: utf-8 -*- # view/widgets/button_art_compositor.py from __future__ import annotations import re from pathlib import Path from PIL import Image, ImageChops, ImageDraw, ImageEnhance, ImageFont, ImageTk from resources.code_res.game_constants import ( 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, ) SIDE_CAP_ASPECT = 0.46 VERTICAL_FRAME_RATIO = 0.36 _ROOT_DIR = Path(__file__).resolve().parents[2] _FONT_CACHE: dict[int, ImageFont.FreeTypeFont | ImageFont.ImageFont] = {} _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 OldLondon-Beschriftungen ein.""" @staticmethod def get_old_london(size_px: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont: size_px = max(13, int(size_px)) if size_px not in _FONT_CACHE: fpath = _ROOT_DIR / FONTS_REL_DIR / FONT_FILE_PRIMARY try: _FONT_CACHE[size_px] = ImageFont.truetype(str(fpath), size_px) except Exception: _FONT_CACHE[size_px] = ImageFont.load_default() return _FONT_CACHE[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("←", "-") if not cleaned or not 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: 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 @staticmethod def measure_text_px(text: str, pil_font) -> 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): total += draw.textlength(ch, font=pil_font) if i < len(text) - 1: total += FONT_LETTER_SPACING_PX 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 pil_font = cls.get_old_london(font_px) txt_w = cls.measure_text_px(text, pil_font) 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 cache_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 pil_font = cls.get_old_london(f_px) while cls.measure_text_px(text, pil_font) > max_txt_w and f_px > 13: f_px -= 1 pil_font = cls.get_old_london(f_px) tw = cls.measure_text_px(text, pil_font) try: ascent, descent = pil_font.getmetrics() # type: ignore[attr-defined] th = ascent + descent except Exception: th = f_px cur_x = (width - tw) / 2.0 cur_y = (height - th) / 2.0 + FONT_VERTICAL_OFFSET_PX sx, sy = FONT_SHADOW_OFFSET_DEFAULT for ch in text: if FONT_SHADOW_ENABLED and not dim_disabled: draw.text((cur_x + sx, cur_y + sy), ch, font=pil_font, fill=FONT_SHADOW_COLOR) if FONT_OUTLINE_THICKNESS_PX > 0 and not dim_disabled: draw.text( (cur_x, cur_y), ch, font=pil_font, fill=text_color, stroke_width=FONT_OUTLINE_THICKNESS_PX, stroke_fill=FONT_OUTLINE_COLOR, ) else: draw.text((cur_x, cur_y), ch, font=pil_font, fill=text_color) cur_x += draw.textlength(ch, font=pil_font) + FONT_LETTER_SPACING_PX photo = ImageTk.PhotoImage(bg) if len(_BTN_PHOTO_CACHE) > 400: _BTN_PHOTO_CACHE.clear() _BTN_PHOTO_CACHE[cache_key] = photo return photo