the_goth_cardgame_collection/games/solitaire/base/solitaire_theme.py

181 lines
6.7 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# games/solitaire/base/solitaire_theme.py
from __future__ import annotations
import warnings
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw, ImageTk
_ICON_PIL_CACHE: dict[Path, Image.Image] = {}
_ICON_TK_CACHE: dict[tuple[Path, int], ImageTk.PhotoImage] = {}
def _extract_best_ico_pil(icon_path: Path) -> Image.Image | None:
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
with Image.open(icon_path) as ico:
best_img = None
best_area = -1
ico_helper = getattr(ico, "ico", None)
if ico_helper is not None and hasattr(ico_helper, "sizes"):
for sz in ico_helper.sizes():
try:
frame = ico_helper.getimage(sz).convert("RGBA")
area = frame.width * frame.height
if area > best_area:
best_area = area
best_img = frame
except Exception:
continue
if best_img is None:
for idx in range(getattr(ico, "n_frames", 1)):
try:
ico.seek(idx)
frame = ico.copy().convert("RGBA")
area = frame.width * frame.height
if area > best_area:
best_area = area
best_img = frame
except Exception:
continue
return best_img if best_img is not None else ico.convert("RGBA")
except Exception:
return None
def _auto_crop_and_round_badge(img: Image.Image) -> Image.Image:
"""
Schneidet weiße/transparente Außenränder (und eventuelle Text-Artefakte ganz oben)
ab und stanzt das quadratische App-Badge sauber mit abgerundeten Ecken aus.
"""
w, h = img.size
px = img.load()
def is_badge_pixel(r: int, g: int, b: int, a: int) -> bool:
if a < 40:
return False
# Helle/weiße Schachbrett- oder Hintergrundpixel ignorieren
if r > 228 and g > 228 and b > 228:
return False
return True
# Suche horizontale & vertikale Ausdehnung des eigentlichen breiten Icon-Blocks
# (Zeilen mit nur wenigen schmalen Buchstaben-Pixeln < 35% Breite werden oben übersprungen!)
min_row_span = int(w * 0.38)
valid_rows: list[int] = []
for y in range(h):
cnt = 0
for x in range(0, w, 2):
if is_badge_pixel(*px[x, y]):
cnt += 2
if cnt >= min_row_span:
valid_rows.append(y)
min_col_span = int(h * 0.38)
valid_cols: list[int] = []
for x in range(w):
cnt = 0
for y in range(0, h, 2):
if is_badge_pixel(*px[x, y]):
cnt += 2
if cnt >= min_col_span:
valid_cols.append(x)
if valid_rows and valid_cols:
top, bottom = valid_rows[0], valid_rows[-1] + 1
left, right = valid_cols[0], valid_cols[-1] + 1
cropped = img.crop((left, top, right, bottom))
else:
cropped = img
# Auf sauberes Quadrat bringen & mit 2x Supersampling rund maskieren
side = max(cropped.width, cropped.height)
square = cropped.resize((side, side), Image.Resampling.LANCZOS)
mask_big = Image.new("L", (side * 2, side * 2), 0)
draw = ImageDraw.Draw(mask_big)
radius = int(side * 2 * 0.195)
pad = int(side * 2 * 0.008)
draw.rounded_rectangle(
(pad, pad, side * 2 - 1 - pad, side * 2 - 1 - pad),
radius=radius,
fill=255,
)
mask = mask_big.resize((side, side), Image.Resampling.LANCZOS)
r_ch, g_ch, b_ch, a_ch = square.split()
square.putalpha(ImageChops.multiply(a_ch, mask))
return square
def get_game_icon_photo(res_mgr, game_folder: str, size_px: int = 92) -> ImageTk.PhotoImage | None:
icon_path = res_mgr.get_game_icon_path(game_folder)
if icon_path is None:
return None
cache_key = (icon_path, size_px)
if cache_key in _ICON_TK_CACHE:
return _ICON_TK_CACHE[cache_key]
if icon_path not in _ICON_PIL_CACHE:
raw = _extract_best_ico_pil(icon_path)
if raw is None:
return None
_ICON_PIL_CACHE[icon_path] = _auto_crop_and_round_badge(raw)
resized = _ICON_PIL_CACHE[icon_path].resize((size_px, size_px), Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(resized)
_ICON_TK_CACHE[cache_key] = photo
return photo
class SolitaireTableBgRenderer:
"""
Zeichnet und cached resources/images/general_table.jpg passgenau auf das Solitaire-Canvas
und liefert die Rahmen-Abstände, damit alle Stapel sauber innerhalb des Holzrahmens sitzen.
"""
# Prozentuale Rahmenstärke von general_table.jpg (Steinmauer + Kerzen + Holzrahmen)
FRAME_X_RATIO = 0.075
FRAME_TOP_RATIO = 0.095
FRAME_BOT_RATIO = 0.090
def __init__(self, res_mgr):
self.res_mgr = res_mgr
self._raw_pil: Image.Image | None = None
self._loaded = False
self._cached_size: tuple[int, int] = (0, 0)
self._cached_photo: ImageTk.PhotoImage | None = None
def _ensure_pil(self) -> Image.Image | None:
if not self._loaded:
self._loaded = True
bg_path = self.res_mgr.get_ui_image_path("general_table")
if bg_path.is_file():
try:
with Image.open(bg_path) as im:
self._raw_pil = im.convert("RGB")
except Exception:
self._raw_pil = None
return self._raw_pil
def get_frame_insets(self, canvas_w: int, canvas_h: int) -> tuple[int, int, int]:
"""Gibt (inset_x, inset_top, inset_bottom) passend zum Zierrahmen zurück."""
if self._ensure_pil() is None:
return max(20, int(canvas_w * 0.04)), max(14, int(canvas_h * 0.022)), 16
ix = max(36, int(canvas_w * self.FRAME_X_RATIO))
itop = max(28, int(canvas_h * self.FRAME_TOP_RATIO))
ibot = max(26, int(canvas_h * self.FRAME_BOT_RATIO))
return ix, itop, ibot
def draw_on_canvas(self, canvas, canvas_w: int, canvas_h: int):
pil_img = self._ensure_pil()
if pil_img is None or canvas_w < 50 or canvas_h < 50:
return
target_sz = (canvas_w, canvas_h)
if self._cached_photo is None or self._cached_size != target_sz:
scaled = pil_img.resize(target_sz, Image.Resampling.BILINEAR)
self._cached_photo = ImageTk.PhotoImage(scaled)
self._cached_size = target_sz
canvas.create_image(0, 0, image=self._cached_photo, anchor="nw", tags=("table_bg",))