the_goth_cardgame_collection/view/widgets/image_button.py

437 lines
16 KiB
Python
Raw Normal View History

2026-11-14 04:25:51 +00:00
# -*- coding: utf-8 -*-
# view/widgets/image_button.py
from __future__ import annotations
import re
from pathlib import Path
2026-11-14 04:25:51 +00:00
import tkinter as tk
from PIL import Image, ImageDraw, ImageEnhance, ImageFont, ImageTk
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] = {}
_LEADING_ICON_RE = re.compile(r"^(?:[←→↑↓↔❖†•✦★☆▶◀«»]+|\+(?=\s))\s*")
_TRAILING_ICON_RE = re.compile(r"\s*[←→↑↓↔❖†•✦★☆▶◀«»]+$")
# 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:
"""Macht rein schwarze Außenpixel außerhalb der Button-Zierspitzen transparent."""
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")
px = rgba.load()
w, h = rgba.size
if px[0, 0][3] > 240 and max(px[0, 0][:3]) < 14:
visited = bytearray(w * h)
stack = [
(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1),
(w // 2, 0), (w // 2, h - 1), (0, h // 2), (w - 1, h // 2),
]
while stack:
x, y = stack.pop()
idx = y * w + x
if visited[idx]:
continue
visited[idx] = 1
r, g, b, a = px[x, y]
mx = max(r, g, b)
if mx < 18:
new_a = 0 if mx < 8 else int((mx - 8) * 25.5)
px[x, y] = (r, g, b, min(a, new_a))
if x > 0:
stack.append((x - 1, y))
if x + 1 < w:
stack.append((x + 1, y))
if y > 0:
stack.append((x, y - 1))
if y + 1 < h:
stack.append((x, y + 1))
_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
2026-11-14 04:25:51 +00:00
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.
"""
2026-11-14 04:25:51 +00:00
def __init__(
self,
parent,
text: str,
pil_normal,
pil_hover,
command,
sound_mgr=None,
width: int = 150,
height: int = 36,
font=None,
2026-11-14 04:25:51 +00:00
enabled: bool = True,
style: str | None = None,
auto_expand: bool = True,
2026-11-14 04:25:51 +00:00
):
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
2026-11-14 04:25:51 +00:00
self._sound_mgr = sound_mgr
self._user_cmd = command
self._enabled = bool(enabled)
self._hovered = False
2026-11-14 04:25:51 +00:00
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
2026-11-14 04:25:51 +00:00
super().__init__(
parent,
text="" if init_photo is not None else self._text,
image=init_photo if init_photo is not None else "",
2026-11-14 04:25:51 +00:00
bg=parent_bg,
bd=0,
padx=0,
pady=0,
highlightthickness=0,
cursor="hand2" if self._enabled else "arrow",
)
self.bind("<Enter>", self._on_enter)
self.bind("<Leave>", self._on_leave)
self.bind("<ButtonPress-1>", self._on_press)
self.bind("<ButtonRelease-1>", 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
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)
# Verfügbare Innenbreite strikt zwischen linker und rechter Zierkappe!
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
return ImageTk.PhotoImage(bg)
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)
2026-11-14 04:25:51 +00:00
def set_enabled(self, enabled: bool):
self._enabled = bool(enabled)
if not self._enabled:
self._hovered = False
2026-11-14 04:25:51 +00:00
self.configure(
image=self._photo_disabled if self._photo_disabled else "",
cursor="arrow",
2026-11-14 04:25:51 +00:00
)
else:
target = self._photo_hover if self._hovered else self._photo_normal
2026-11-14 04:25:51 +00:00
self.configure(
image=target if target else "",
cursor="hand2",
2026-11-14 04:25:51 +00:00
)
def _on_enter(self, _event):
if not self._enabled:
return
self._hovered = True
if self._photo_hover:
self.configure(image=self._photo_hover)
2026-11-14 04:25:51 +00:00
def _on_leave(self, _event):
self._hovered = False
2026-11-14 04:25:51 +00:00
if not self._enabled:
return
if self._photo_normal:
self.configure(image=self._photo_normal)
2026-11-14 04:25:51 +00:00
def _on_press(self, _event):
2026-11-14 04:25:51 +00:00
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()