# -*- coding: utf-8 -*- # view/widgets/image_button.py from __future__ import annotations import re from pathlib import Path import tkinter as tk from PIL import Image, ImageDraw, ImageEnhance, ImageFont, ImageTk, ImageChops from resources.code_res.game_constants import ( BG_COLOR, BTN_AMETHYST_TEXT_ACTIVE, BTN_AMETHYST_TEXT_DISABLED, BTN_AMETHYST_TEXT_HOVER, BTN_AMETHYST_TEXT_NORMAL, BTN_FIRE_TEXT_ACTIVE, BTN_FIRE_TEXT_DISABLED, BTN_FIRE_TEXT_HOVER, BTN_FIRE_TEXT_NORMAL, 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, ) _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] = {} # Entfernt alle vorangestellten/nachgestellten Sonder-Icons & Emojis (behält Buchstaben, Ziffern, '+' vor Zahl & Klammern) _LEADING_ICON_RE = re.compile(r"^(?:[^\w\s\+\(\[\"'ÄÖÜäöüß]+|\+(?=\s))\s*", re.UNICODE) _TRAILING_ICON_RE = re.compile(r"\s*[^\w\s\)\]\.\!\%\"'ÄÖÜäöüß]+$", re.UNICODE) # Geometrie-Anteil der seitlichen Zierkappen & oberen/unteren Rahmenleisten in button*.png _SIDE_CAP_ASPECT = 0.46 # Breite einer Seitenkappe relativ zur Button-Höhe (inkl. Innenspitze) _VERTICAL_FRAME_RATIO = 0.36 # Anteil oben + unten für Metallrahmen & Mittel-Ornament 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] def _clean_outer_black_matte(pil_img: Image.Image) -> Image.Image: """ Entfernt schwarze JPEG-Außenränder in C-Geschwindigkeit über ImageDraw.floodfill statt langsamer Python-Pixel-Stacks. """ 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)) # Nur ausführen, wenn das Bild überhaupt einen opaken schwarzen Rand hat (z. B. .jpg) if tl[3] > 240 and max(tl[:3]) < 16: # Helligkeitsmaske in C berechnen: alles < 18 wird 0, Rest 255 r, g, b, a = rgba.split() luma = ImageChops.lighter(ImageChops.lighter(r, g), b) # Floodfill vom Rand auf Kopie markiert zusammenhängendes Außenschwarz mit Wert 128 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) # Überall wo 128 steht -> Alpha = 0, sonst Original-Alpha behalten 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 def _trim_button_art(pil_img: Image.Image) -> Image.Image: """Entfernt leere transparente/schwarze Außenränder um die eigentliche Button-Grafik.""" key = (id(pil_img), pil_img.width, pil_img.height) if key in _TRIM_BTN_CACHE: return _TRIM_BTN_CACHE[key] clean = _clean_outer_black_matte(pil_img) bbox = clean.getbbox() cropped = clean.crop(bbox) if bbox else clean _TRIM_BTN_CACHE[key] = cropped return cropped def _scale_button_3slice(src_pil: Image.Image, target_w: int, target_h: int) -> tuple[Image.Image, int]: """ Skaliert die Button-Grafik verzerrungsfrei per 3-Slice: - Linke & rechte Zierkappe skalieren proportional zur Zielhöhe (keine plattgezogenen Spitzen!). - Das Mittelstück (Damast + Mittel-Ornament) übernimmt die restliche Breite. Gibt (fertiges RGBA-Bild, effektive Seitenkappen-Breite in px) zurück. """ trimmed = _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 class ImageButton(tk.Label): """ Gothic UI Button (Amethyst & Fire) mit echter Rahmen-Einberechnung: Berechnet Seitenkappen + oberen/unteren Zierrahmen automatisch in die Button-Größe ein, sodass Text niemals in die Eck-Spitzen oder Rahmenlinien ragt. """ def __init__( self, parent, text: str, pil_normal, pil_hover, command, sound_mgr=None, width: int = 150, height: int = 36, font=None, enabled: bool = True, style: str | None = None, auto_expand: bool = True, ): try: parent_bg = parent.cget("bg") except Exception: parent_bg = BG_COLOR self._requested_width = max(56, int(width)) self._height = max(28, int(height)) self._auto_expand = bool(auto_expand) self._text = self._prepare_label_text(str(text or "")) self._pil_normal = pil_normal self._pil_hover = pil_hover or pil_normal self._sound_mgr = sound_mgr self._user_cmd = command self._enabled = bool(enabled) self._hovered = False if style in ("fire", "amethyst"): self._style = style else: self._style = self._detect_style(parent, pil_normal, pil_hover) self._font_px = self._resolve_font_px(font, self._height) self._width = self._compute_framed_width() self._rebuild_state_photos() init_photo = self._photo_normal if self._enabled else self._photo_disabled super().__init__( parent, text="" if init_photo is not None else self._text, image=init_photo if init_photo is not None else "", bg=parent_bg, bd=0, padx=0, pady=0, highlightthickness=0, cursor="hand2" if self._enabled else "arrow", ) self.bind("", self._on_enter) self.bind("", self._on_leave) self.bind("", self._on_press) self.bind("", self._on_release) @property def pixel_width(self) -> int: """Tatsächliche Gesamtbreite des Buttons inklusive Rahmen-Aufschlag.""" return self._width @property def pixel_height(self) -> int: return self._height @staticmethod def _measure_text_px(text: str, pil_font) -> float: if not text: return 0.0 dummy = Image.new("RGBA", (4, 4), (0, 0, 0, 0)) draw = ImageDraw.Draw(dummy) 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 def _horizontal_frame_inset(self) -> int: """Breite EINER seitlichen Rahmenkappe + Sicherheitsabstand vor der Innenspitze.""" cap_px = max(13, int(round(self._height * _SIDE_CAP_ASPECT))) return cap_px + 6 def _compute_framed_width(self) -> int: """Stellt sicher, dass width immer groß genug für Text + beide Seitenrahmen ist.""" if not self._text or not self._auto_expand: return self._requested_width pil_font = _get_old_london(self._font_px) txt_w = self._measure_text_px(self._text, pil_font) needed_w = int(round(txt_w + 2 * self._horizontal_frame_inset())) return max(self._requested_width, needed_w) @classmethod def _prepare_label_text(cls, 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 parts = cleaned.split(" ") fixed = [] for p in parts: 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 _detect_style(parent, pil_normal, pil_hover) -> str: try: top = parent.winfo_toplevel() assets = getattr(top, "assets", None) if assets is not None and getattr(assets, "raw_btn_fire", None) is not None: if pil_normal is assets.raw_btn_fire or pil_hover is assets.raw_btn_fire: return "fire" except Exception: pass return "amethyst" @staticmethod def _resolve_font_px(font_arg, btn_h: int) -> int: # Nur das innere Feld abzüglich oberem/unterem Zierrahmen (_VERTICAL_FRAME_RATIO) für die Schrift nutzen! 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)) scaled = int(round(raw_sz * 1.85)) return max(14, min(max_safe_px, scaled)) except Exception: pass return auto_px def _palette(self) -> tuple[str, str, str, str]: if self._style == "fire": return ( BTN_FIRE_TEXT_NORMAL, BTN_FIRE_TEXT_HOVER, BTN_FIRE_TEXT_ACTIVE, BTN_FIRE_TEXT_DISABLED, ) return ( BTN_AMETHYST_TEXT_NORMAL, BTN_AMETHYST_TEXT_HOVER, BTN_AMETHYST_TEXT_ACTIVE, BTN_AMETHYST_TEXT_DISABLED, ) def _compose_button_photo( self, base_pil: Image.Image | None, 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), self._width, self._height, self._text, self._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 = _scale_button_3slice(base_pil, self._width, self._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 self._text: draw = ImageDraw.Draw(bg) side_inset = cap_w + 5 max_txt_w = max(20, self._width - 2 * side_inset) f_px = self._font_px pil_font = _get_old_london(f_px) def _line_w(fnt) -> float: total = 0.0 for i, ch in enumerate(self._text): total += draw.textlength(ch, font=fnt) if i < len(self._text) - 1: total += FONT_LETTER_SPACING_PX return total while _line_w(pil_font) > max_txt_w and f_px > 13: f_px -= 1 pil_font = _get_old_london(f_px) tw = _line_w(pil_font) try: ascent, descent = pil_font.getmetrics() # type: ignore[attr-defined] th = ascent + descent except Exception: th = f_px cur_x = (self._width - tw) / 2.0 cur_y = (self._height - th) / 2.0 + FONT_VERTICAL_OFFSET_PX sx, sy = FONT_SHADOW_OFFSET_DEFAULT for ch in self._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 def _rebuild_state_photos(self): c_norm, _c_hov, _c_act, c_dis = self._palette() # Lazy Rendering: Nur den initial sichtbaren Zustand sofort berechnen! self._photo_normal = self._compose_button_photo(self._pil_normal, c_norm) if self._enabled else None self._photo_disabled = None if self._enabled else self._compose_button_photo(self._pil_normal, c_dis, dim_disabled=True) self._photo_hover = None self._photo_active = None def _ensure_normal(self) -> ImageTk.PhotoImage | None: if self._photo_normal is None: c_norm, _, _, _ = self._palette() self._photo_normal = self._compose_button_photo(self._pil_normal, c_norm) return self._photo_normal def _ensure_hover(self) -> ImageTk.PhotoImage | None: if self._photo_hover is None: _, c_hov, _, _ = self._palette() self._photo_hover = self._compose_button_photo(self._pil_hover, c_hov) return self._photo_hover def _ensure_active(self) -> ImageTk.PhotoImage | None: if self._photo_active is None: _, _, c_act, _ = self._palette() self._photo_active = self._compose_button_photo(self._pil_hover, c_act, brighten_active=True) return self._photo_active def _ensure_disabled(self) -> ImageTk.PhotoImage | None: if self._photo_disabled is None: _, _, _, c_dis = self._palette() self._photo_disabled = self._compose_button_photo(self._pil_normal, c_dis, dim_disabled=True) return self._photo_disabled def set_enabled(self, enabled: bool): self._enabled = bool(enabled) if not self._enabled: self._hovered = False ph = self._ensure_disabled() self.configure(image=ph if ph else "", cursor="arrow") else: ph = self._ensure_hover() if self._hovered else self._ensure_normal() self.configure(image=ph if ph else "", cursor="hand2") def _on_enter(self, _event): if not self._enabled: return self._hovered = True ph = self._ensure_hover() if ph: self.configure(image=ph) def _on_leave(self, _event): self._hovered = False if not self._enabled: return ph = self._ensure_normal() if ph: self.configure(image=ph) def _on_press(self, _event): if not self._enabled: return ph = self._ensure_active() if ph: self.configure(image=ph) def _on_release(self, event): if not self._enabled: return inside = (0 <= event.x < self._width) and (0 <= event.y < self._height) self._hovered = inside ph = self._ensure_hover() if inside else self._ensure_normal() if ph: self.configure(image=ph) if inside: if self._sound_mgr: self._sound_mgr.play("click") if self._user_cmd: self._user_cmd() def _rebuild_state_photos(self): c_norm, c_hov, c_act, c_dis = self._palette() self._photo_normal = self._compose_button_photo(self._pil_normal, c_norm) self._photo_hover = self._compose_button_photo(self._pil_hover, c_hov) self._photo_active = self._compose_button_photo(self._pil_hover, c_act, brighten_active=True) self._photo_disabled = self._compose_button_photo(self._pil_normal, c_dis, dim_disabled=True) def set_text(self, new_text: str): self._text = self._prepare_label_text(str(new_text or "")) self._width = self._compute_framed_width() self._rebuild_state_photos() self.set_enabled(self._enabled) def set_enabled(self, enabled: bool): self._enabled = bool(enabled) if not self._enabled: self._hovered = False self.configure( image=self._photo_disabled if self._photo_disabled else "", cursor="arrow", ) else: target = self._photo_hover if self._hovered else self._photo_normal self.configure( image=target if target else "", cursor="hand2", ) def _on_enter(self, _event): if not self._enabled: return self._hovered = True if self._photo_hover: self.configure(image=self._photo_hover) def _on_leave(self, _event): self._hovered = False if not self._enabled: return if self._photo_normal: self.configure(image=self._photo_normal) def _on_press(self, _event): if not self._enabled: return if self._photo_active: self.configure(image=self._photo_active) def _on_release(self, event): if not self._enabled: return inside = (0 <= event.x < self._width) and (0 <= event.y < self._height) self._hovered = inside target = self._photo_hover if inside else self._photo_normal if target: self.configure(image=target) if inside: if self._sound_mgr: self._sound_mgr.play("click") if self._user_cmd: self._user_cmd()