413 lines
13 KiB
Python
413 lines
13 KiB
Python
# -*- coding: utf-8 -*-
|
|
import os
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import warnings
|
|
from pathlib import Path
|
|
from PIL import Image, ImageTk
|
|
|
|
# Unterdrückt die "Hello from the pygame community"-Konsole beim Start
|
|
os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1")
|
|
|
|
import pygame
|
|
|
|
from controller.app_controller import AppController
|
|
from models.database import Database
|
|
from resources.code_res.game_constants import APP_ICON_REL_PATH
|
|
from view.font_loader import FontLoader
|
|
from view.main_window import GothCardCollectionView
|
|
from view.window_state import WindowStatePersistence
|
|
|
|
APP_WM_CLASS = "goth-cardgame-collection"
|
|
|
|
|
|
def _prepare_os_app_identity():
|
|
if sys.platform.startswith("win"):
|
|
try:
|
|
import ctypes
|
|
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
|
|
"kuro.goth_cardgame_collection.app.1"
|
|
)
|
|
except Exception:
|
|
pass
|
|
elif sys.platform.startswith("linux"):
|
|
# Hilft X11/Tkinter bereits vor Fenstererstellung bei der Ressourcen-Zuordnung
|
|
os.environ.setdefault("RESOURCE_NAME", APP_WM_CLASS)
|
|
try:
|
|
import ctypes
|
|
libc = ctypes.CDLL("libc.so.6")
|
|
libc.prctl(15, APP_WM_CLASS.encode("utf-8")[:15], 0, 0, 0)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _extract_ico_frames(icon_path: Path) -> tuple[Image.Image | None, list[Image.Image]]:
|
|
"""Liest das größte Bild aus game_icon.ico (auch wenn es intern PNG/JPEG/BMP-codiert ist)."""
|
|
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:
|
|
n_frames = getattr(ico, "n_frames", 1)
|
|
for idx in range(n_frames):
|
|
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
|
|
|
|
if best_img is None:
|
|
best_img = ico.convert("RGBA")
|
|
|
|
cascade = [
|
|
best_img.resize((px, px), Image.Resampling.LANCZOS)
|
|
for px in (256, 128, 64, 48, 32, 16)
|
|
]
|
|
return best_img, cascade
|
|
except Exception:
|
|
return None, []
|
|
|
|
|
|
def ensure_crostini_shelf_icon(icon_ico_path: Path, wm_class: str = APP_WM_CLASS) -> None:
|
|
"""
|
|
Erzeugt unter ChromeOS (Crostini) vollautomatisch im User-Verzeichnis (~/.local)
|
|
ein PNG-Icon + .desktop-Zuordnung für den garcon-Daemon, damit das Shelf-Icon
|
|
ohne manuelle System-Installation statt eines grauen Kastens erscheint.
|
|
"""
|
|
if not sys.platform.startswith("linux"):
|
|
return
|
|
|
|
is_crostini = (
|
|
Path("/dev/.cros_milestone").exists()
|
|
or "sommelier" in os.environ.get("XDG_RUNTIME_DIR", "").lower()
|
|
or Path("/opt/google/cros-containers").exists()
|
|
)
|
|
if not is_crostini or not icon_ico_path.is_file():
|
|
return
|
|
|
|
try:
|
|
data_home = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
|
|
apps_dir = data_home / "applications"
|
|
desktop_file = apps_dir / f"{wm_class}.desktop"
|
|
|
|
best_pil, _ = _extract_ico_frames(icon_ico_path)
|
|
if best_pil is not None:
|
|
for px in (128, 64, 48):
|
|
icon_dir = data_home / "icons" / "hicolor" / f"{px}x{px}" / "apps"
|
|
icon_png = icon_dir / f"{wm_class}.png"
|
|
if not icon_png.is_file():
|
|
icon_dir.mkdir(parents=True, exist_ok=True)
|
|
best_pil.resize((px, px), Image.Resampling.LANCZOS).save(icon_png, format="PNG")
|
|
|
|
if getattr(sys, "frozen", False):
|
|
exec_cmd = f'"{Path(sys.executable).resolve()}"'
|
|
else:
|
|
exec_cmd = f'"{sys.executable}" "{Path(sys.argv[0]).resolve()}"'
|
|
|
|
desktop_content = (
|
|
"[Desktop Entry]\n"
|
|
"Version=1.0\n"
|
|
"Type=Application\n"
|
|
"Name=The Goth Cardgame Collection\n"
|
|
f"Exec={exec_cmd}\n"
|
|
f"Icon={wm_class}\n"
|
|
f"StartupWMClass={wm_class}\n"
|
|
"Categories=Game;CardGame;\n"
|
|
"Terminal=false\n"
|
|
)
|
|
|
|
if not desktop_file.is_file() or desktop_file.read_text(encoding="utf-8") != desktop_content:
|
|
apps_dir.mkdir(parents=True, exist_ok=True)
|
|
desktop_file.write_text(desktop_content, encoding="utf-8")
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _apply_windows_icon(app, icon_path: Path, best_pil: Image.Image | None):
|
|
"""
|
|
Setzt das Icon unter Windows nativ via Tk iconbitmap + Win32 WM_SETICON,
|
|
ohne dass iconphoto() es wieder mit der Standard-Feder überschreibt.
|
|
"""
|
|
import ctypes
|
|
|
|
target_ico = icon_path
|
|
|
|
if best_pil is not None:
|
|
try:
|
|
with open(icon_path, "rb") as f:
|
|
magic = f.read(4)
|
|
is_real_ico = (magic == b"\x00\x00\x01\x00")
|
|
except Exception:
|
|
is_real_ico = False
|
|
|
|
try:
|
|
if not is_real_ico:
|
|
raise ValueError("Kein nativer ICO-Header")
|
|
app.wm_iconbitmap(default=str(target_ico))
|
|
app.wm_iconbitmap(str(target_ico))
|
|
except Exception:
|
|
tmp_ico = Path(tempfile.gettempdir()) / "goth_cardgame_collection_win.ico"
|
|
best_pil.save(
|
|
tmp_ico,
|
|
format="ICO",
|
|
sizes=[(16, 16), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
|
|
)
|
|
target_ico = tmp_ico
|
|
try:
|
|
app.wm_iconbitmap(default=str(target_ico))
|
|
app.wm_iconbitmap(str(target_ico))
|
|
except Exception:
|
|
pass
|
|
else:
|
|
try:
|
|
app.wm_iconbitmap(default=str(target_ico))
|
|
app.wm_iconbitmap(str(target_ico))
|
|
except Exception:
|
|
pass
|
|
|
|
try:
|
|
app.update_idletasks()
|
|
hwnd = ctypes.windll.user32.GetParent(app.winfo_id()) or app.winfo_id()
|
|
IMAGE_ICON = 1
|
|
LR_LOADFROMFILE = 0x0010
|
|
LR_DEFAULTSIZE = 0x0040
|
|
WM_SETICON = 0x0080
|
|
ICON_SMALL = 0
|
|
ICON_BIG = 1
|
|
|
|
hicon_big = ctypes.windll.user32.LoadImageW(
|
|
None, str(target_ico), IMAGE_ICON, 48, 48, LR_LOADFROMFILE
|
|
) or ctypes.windll.user32.LoadImageW(
|
|
None, str(target_ico), IMAGE_ICON, 0, 0, LR_LOADFROMFILE | LR_DEFAULTSIZE
|
|
)
|
|
hicon_small = ctypes.windll.user32.LoadImageW(
|
|
None, str(target_ico), IMAGE_ICON, 16, 16, LR_LOADFROMFILE
|
|
) or hicon_big
|
|
|
|
if hicon_big:
|
|
ctypes.windll.user32.SendMessageW(hwnd, WM_SETICON, ICON_BIG, hicon_big)
|
|
if hicon_small:
|
|
ctypes.windll.user32.SendMessageW(hwnd, WM_SETICON, ICON_SMALL, hicon_small)
|
|
app._win_hicons = (hicon_big, hicon_small)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _apply_cross_platform_icon(app, root_path: Path):
|
|
"""Setzt game_icon.ico zuverlässig auf Windows, Linux, ChromeOS (Crostini) und macOS."""
|
|
if sys.platform.startswith("linux"):
|
|
try:
|
|
app.tk.call("tk", "appname", APP_WM_CLASS)
|
|
except Exception:
|
|
pass
|
|
# Erzwingt die exakte X11 WM_CLASS am Top-Level-Fenster für Sommelier/Wayland
|
|
try:
|
|
app.update_idletasks()
|
|
subprocess.run(
|
|
[
|
|
"xprop",
|
|
"-id",
|
|
hex(app.winfo_id()),
|
|
"-f",
|
|
"WM_CLASS",
|
|
"8s",
|
|
"-set",
|
|
"WM_CLASS",
|
|
APP_WM_CLASS,
|
|
],
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
timeout=1.5,
|
|
check=False,
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
icon_path = (root_path / APP_ICON_REL_PATH).resolve()
|
|
if not icon_path.is_file():
|
|
return
|
|
|
|
best_pil, cascade_pils = _extract_ico_frames(icon_path)
|
|
|
|
if sys.platform.startswith("win"):
|
|
_apply_windows_icon(app, icon_path, best_pil)
|
|
return
|
|
|
|
if cascade_pils:
|
|
try:
|
|
# Unter Linux/XWayland max. 128x128 übergeben, da 256x256 in _NET_WM_ICON oft grau wird
|
|
usable_pils = (
|
|
[im for im in cascade_pils if im.width <= 128]
|
|
if sys.platform.startswith("linux")
|
|
else cascade_pils
|
|
)
|
|
tk_photos = [ImageTk.PhotoImage(im) for im in usable_pils]
|
|
app._app_icon_refs = tk_photos
|
|
app.iconphoto(True, *tk_photos)
|
|
except Exception:
|
|
pass
|
|
|
|
if sys.platform == "darwin" and best_pil is not None:
|
|
try:
|
|
import io
|
|
from AppKit import NSApplication, NSImage, NSData # type: ignore
|
|
buf = io.BytesIO()
|
|
best_pil.save(buf, format="PNG")
|
|
raw = buf.getvalue()
|
|
ns_data = NSData.dataWithBytes_length_(raw, len(raw))
|
|
ns_img = NSImage.alloc().initWithData_(ns_data)
|
|
if ns_img is not None:
|
|
NSApplication.sharedApplication().setApplicationIconImage_(ns_img)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _install_clean_shutdown(app: GothCardCollectionView):
|
|
shutting_down = False
|
|
prev_wm_delete_cmd = None
|
|
try:
|
|
prev_wm_delete_cmd = app.protocol("WM_DELETE_WINDOW")
|
|
except Exception:
|
|
prev_wm_delete_cmd = None
|
|
|
|
orig_report = getattr(app, "report_callback_exception", None)
|
|
|
|
def _filtered_callback_exc(exc, val, tb):
|
|
if shutting_down or exc is KeyboardInterrupt:
|
|
return
|
|
if callable(orig_report):
|
|
orig_report(exc, val, tb)
|
|
|
|
app.report_callback_exception = _filtered_callback_exc
|
|
|
|
def graceful_exit(*_args):
|
|
nonlocal shutting_down
|
|
if shutting_down:
|
|
return
|
|
shutting_down = True
|
|
|
|
try:
|
|
for child in list(app.winfo_children()):
|
|
try:
|
|
child.destroy()
|
|
except Exception:
|
|
pass
|
|
except Exception:
|
|
pass
|
|
|
|
if prev_wm_delete_cmd:
|
|
try:
|
|
app.tk.call(prev_wm_delete_cmd)
|
|
except Exception:
|
|
pass
|
|
|
|
try:
|
|
for after_id in app.tk.call("after", "info"):
|
|
try:
|
|
app.after_cancel(after_id)
|
|
except Exception:
|
|
pass
|
|
except Exception:
|
|
pass
|
|
|
|
try:
|
|
if pygame.mixer.get_init():
|
|
pygame.mixer.music.stop()
|
|
pygame.quit()
|
|
except Exception:
|
|
pass
|
|
|
|
try:
|
|
Database.close()
|
|
except Exception:
|
|
pass
|
|
|
|
try:
|
|
app.quit()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
if app.winfo_exists():
|
|
app.destroy()
|
|
except Exception:
|
|
pass
|
|
|
|
app.protocol("WM_DELETE_WINDOW", graceful_exit)
|
|
|
|
try:
|
|
signal.signal(signal.SIGINT, lambda _sig, _frm: graceful_exit())
|
|
except Exception:
|
|
pass
|
|
|
|
def _sigint_heartbeat():
|
|
if not shutting_down:
|
|
try:
|
|
if app.winfo_exists():
|
|
app.after(200, _sigint_heartbeat)
|
|
except Exception:
|
|
pass
|
|
|
|
app.after(200, _sigint_heartbeat)
|
|
return graceful_exit
|
|
|
|
|
|
def main():
|
|
_prepare_os_app_identity()
|
|
root_path = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))
|
|
|
|
# Vor dem Erstellen des Tk-Fensters aufrufen, damit garcon das Icon bereits kennt!
|
|
ensure_crostini_shelf_icon((root_path / APP_ICON_REL_PATH).resolve(), APP_WM_CLASS)
|
|
|
|
FontLoader.register_fonts(root_path)
|
|
|
|
controller = AppController(root_path)
|
|
app = GothCardCollectionView(controller, root_path)
|
|
|
|
FontLoader.bind_to_tk_root(app)
|
|
_apply_cross_platform_icon(app, root_path)
|
|
WindowStatePersistence(app)
|
|
|
|
graceful_exit = _install_clean_shutdown(app)
|
|
|
|
controller.bind_view(app)
|
|
controller.start()
|
|
|
|
if sys.platform.startswith("win"):
|
|
def _delayed_icon():
|
|
try:
|
|
if app.winfo_exists():
|
|
_apply_cross_platform_icon(app, root_path)
|
|
except Exception:
|
|
pass
|
|
|
|
app.after(60, _delayed_icon)
|
|
|
|
try:
|
|
app.mainloop()
|
|
except KeyboardInterrupt:
|
|
graceful_exit()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |