the_goth_cardgame_collection/view/widgets/info_badge.py

129 lines
3.8 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# view/widgets/info_badge.py
import tkinter as tk
from resources.code_res.game_constants import (
ACCENT_GOLD, ACCENT_GOTH, FG_COLOR, MODAL_BG, MUTED_FG
)
class InfoBadge(tk.Label):
"""Kompaktes ⓘ (U+24D8) Info-Icon mit Hover- & Klick-Hilfepopup."""
_active_tip: tk.Toplevel | None = None
_active_owner = None
def __init__(self, parent, text_provider, bg: str, font_size: int = 10):
super().__init__(
parent,
text="\u24d8",
font=("Helvetica", font_size, "bold"),
fg=MUTED_FG,
bg=bg,
cursor="hand2",
padx=2,
pady=0,
)
self._text_provider = text_provider
self._pinned = False
self.bind("<Enter>", self._on_enter)
self.bind("<Leave>", self._on_leave)
self.bind("<Button-1>", self._on_click)
self.bind("<Destroy>", self._on_destroy)
@classmethod
def close_global_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
if cls._active_owner is not None:
cls._active_owner._pinned = False
try:
if cls._active_owner.winfo_exists():
cls._active_owner.configure(fg=MUTED_FG)
except Exception:
pass
cls._active_owner = None
def _get_text(self) -> str:
return self._text_provider() if callable(self._text_provider) else str(self._text_provider)
def _show_popup(self):
msg = self._get_text().strip()
if not msg:
return
if InfoBadge._active_owner is not self:
InfoBadge.close_global_tip()
elif InfoBadge._active_tip is not None and InfoBadge._active_tip.winfo_exists():
return
tip = tk.Toplevel(self)
tip.wm_overrideredirect(True)
try:
tip.wm_attributes("-topmost", True)
except Exception:
pass
outer = tk.Frame(tip, bg=ACCENT_GOTH, padx=1, pady=1)
outer.pack(fill="both", expand=True)
lbl = tk.Label(
outer,
text=msg,
font=("Helvetica", 9),
fg=FG_COLOR,
bg=MODAL_BG,
justify="left",
wraplength=290,
padx=12,
pady=8,
)
lbl.pack()
tip.update_idletasks()
tw = tip.winfo_reqwidth()
th = tip.winfo_reqheight()
sw = self.winfo_screenwidth()
sh = self.winfo_screenheight()
rx = self.winfo_rootx() + self.winfo_width() + 8
ry = self.winfo_rooty() - th // 2 + 8
if rx + tw > sw - 16:
rx = max(12, self.winfo_rootx() - tw - 8)
if ry + th > sh - 24:
ry = sh - th - 24
if ry < 12:
ry = 12
tip.wm_geometry(f"+{rx}+{ry}")
tip.bind("<Button-1>", lambda _e: InfoBadge.close_global_tip())
InfoBadge._active_tip = tip
InfoBadge._active_owner = self
def _on_enter(self, _event):
self.configure(fg=ACCENT_GOLD)
self._show_popup()
def _on_leave(self, _event):
if not self._pinned:
self.configure(fg=MUTED_FG)
if InfoBadge._active_owner is self:
InfoBadge.close_global_tip()
def _on_click(self, _event):
if self._pinned and InfoBadge._active_owner is self:
InfoBadge.close_global_tip()
else:
self._pinned = True
self.configure(fg=ACCENT_GOLD)
self._show_popup()
def _on_destroy(self, _event):
if InfoBadge._active_owner is self:
InfoBadge.close_global_tip()