the_goth_cardgame_collection/view/widgets/image_button.py

601 lines
21 KiB
Python

# -*- coding: utf-8 -*-
# view/widgets/image_button.py
from __future__ import annotations
import re
from pathlib import Path
import tkinter as tk
from typing import Callable
from PIL import Image, ImageChops, ImageDraw, ImageEnhance, ImageFont, ImageTk
from models.database import Database
from resources.code_res.game_constants import (
ACCENT_GOTH,
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,
FG_COLOR,
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,
MODAL_BG,
)
SETTING_BUTTON_HOVER_HELP = "show_button_hover_help"
_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] = {}
_HOVER_HELP_ENABLED_CACHE: bool | None = None
# Entfernt vorangestellte/nachgestellte 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
_VERTICAL_FRAME_RATIO = 0.36
def is_button_hover_help_enabled() -> bool:
"""Liest den globalen Einstellungs-Schalter für Button-Hover-Hilfetexte (gecached)."""
global _HOVER_HELP_ENABLED_CACHE
if _HOVER_HELP_ENABLED_CACHE is None:
try:
raw = Database.load_setting(SETTING_BUTTON_HOVER_HELP, default="1")
_HOVER_HELP_ENABLED_CACHE = str(raw).strip() not in ("0", "false", "False", "off")
except Exception:
_HOVER_HELP_ENABLED_CACHE = True
return _HOVER_HELP_ENABLED_CACHE
def set_button_hover_help_enabled(enabled: bool, persist: bool = True):
"""Aktualisiert den Einstellungsschalter zur Laufzeit und schließt ggf. offene Popups."""
global _HOVER_HELP_ENABLED_CACHE
_HOVER_HELP_ENABLED_CACHE = bool(enabled)
if not _HOVER_HELP_ENABLED_CACHE:
ImageButton.close_active_hover_tip()
if persist:
try:
Database.save_setting(SETTING_BUTTON_HOVER_HELP, "1" if _HOVER_HELP_ENABLED_CACHE else "0")
except Exception:
pass
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:
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
def _trim_button_art(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 = _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]:
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 automatischer Rahmen-Einberechnung
und optionalem Hover-Hilfetext (`hover_text`) in klar lesbarer Standard-Schrift,
steuerbar über die Einstellungen ('Hilfe Texte bei Buttons Anzeigen').
"""
_active_tip: tk.Toplevel | None = None
_active_tip_owner: "ImageButton | None" = None
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,
hover_text: str | Callable[[], str] | None = None,
):
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
self._hover_text = hover_text
self._hover_after_id: str | None = None
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._ensure_normal() if self._enabled else self._ensure_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("<Enter>", self._on_enter)
self.bind("<Leave>", self._on_leave)
self.bind("<ButtonPress-1>", self._on_press)
self.bind("<ButtonRelease-1>", self._on_release)
self.bind("<Destroy>", self._on_destroy)
@property
def pixel_width(self) -> int:
return self._width
@property
def pixel_height(self) -> int:
return self._height
def set_hover_text(self, hover_text: str | Callable[[], str] | None):
self._hover_text = hover_text
if not hover_text and ImageButton._active_tip_owner is self:
ImageButton.close_active_hover_tip()
@classmethod
def close_active_hover_tip(cls):
if cls._active_tip is not None:
try:
if cls._active_tip.winfo_exists():
cls._active_tip.destroy()
except Exception:
pass
cls._active_tip = None
cls._active_tip_owner = None
def _cancel_hover_timer(self):
if self._hover_after_id is not None:
try:
self.after_cancel(self._hover_after_id)
except Exception:
pass
self._hover_after_id = None
def _resolve_hover_string(self) -> str:
if self._hover_text is None:
return ""
try:
raw = self._hover_text() if callable(self._hover_text) else str(self._hover_text)
return (raw or "").strip()
except Exception:
return ""
def _show_hover_tooltip(self):
self._hover_after_id = None
if not self._hovered or not self.winfo_exists():
return
if not is_button_hover_help_enabled():
return
msg = self._resolve_hover_string()
if not msg:
return
ImageButton.close_active_hover_tip()
tip = tk.Toplevel(self)
tip.wm_overrideredirect(True)
try:
tip.wm_attributes("-topmost", True)
except Exception:
pass
border_frame = tk.Frame(tip, bg=ACCENT_GOTH, padx=1, pady=1)
border_frame.pack(fill="both", expand=True)
inner_frame = tk.Frame(border_frame, bg=MODAL_BG, padx=12, pady=8)
inner_frame.pack(fill="both", expand=True)
# Gut lesbare Standard-Schrift (wie in InfoBadge) statt Gothic/Serifenschrift
lbl = tk.Label(
inner_frame,
text=msg,
font=("Helvetica", 9),
fg=FG_COLOR,
bg=MODAL_BG,
justify="left",
wraplength=340,
)
lbl.pack()
tip.update_idletasks()
tw = tip.winfo_reqwidth()
th = tip.winfo_reqheight()
sw = self.winfo_screenwidth()
sh = self.winfo_screenheight()
bx = self.winfo_rootx()
by = self.winfo_rooty()
rx = bx + (self._width - tw) // 2
ry = by - th - 10
if ry < 14:
ry = by + self._height + 10
rx = max(12, min(sw - tw - 12, rx))
ry = max(12, min(sh - th - 16, ry))
tip.wm_geometry(f"+{rx}+{ry}")
ImageButton._active_tip = tip
ImageButton._active_tip_owner = self
@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:
cap_px = max(13, int(round(self._height * _SIDE_CAP_ASPECT)))
return cap_px + 6
def _compute_framed_width(self) -> int:
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:
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()
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_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._cancel_hover_timer()
if ImageButton._active_tip_owner is self:
ImageButton.close_active_hover_tip()
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):
self._hovered = True
if self._enabled:
ph = self._ensure_hover()
if ph:
self.configure(image=ph)
if self._hover_text is not None and is_button_hover_help_enabled():
self._cancel_hover_timer()
self._hover_after_id = self.after(220, self._show_hover_tooltip)
def _on_leave(self, _event):
self._hovered = False
self._cancel_hover_timer()
if ImageButton._active_tip_owner is self:
ImageButton.close_active_hover_tip()
if not self._enabled:
return
ph = self._ensure_normal()
if ph:
self.configure(image=ph)
def _on_press(self, _event):
self._cancel_hover_timer()
if ImageButton._active_tip_owner is self:
ImageButton.close_active_hover_tip()
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 _on_destroy(self, event=None):
if event is not None and event.widget is not self:
return
self._cancel_hover_timer()
if ImageButton._active_tip_owner is self:
ImageButton.close_active_hover_tip()