# -*- coding: utf-8 -*- import os import signal import subprocess import sys import tempfile import tkinter as tk 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") if sys.platform.startswith("linux"): # Entspannt PulseAudio/CRAS-Pufferung unter Linux & ChromeOS (Crostini) gegen krakeligen Ton os.environ.setdefault("PULSE_LATENCY_MSEC", "80") 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.widgets.error_report_overlay import ErrorReportOverlay # Oben in view/main_window.py: APP_WM_CLASS = "TheGothCardgameCollection" def _install_linux_label_descent_fix(): """ Xft/FreeType unter Linux & Crostini meldet für Zierschriften (wie OldLondon) zu knappe Unterlängen (descent), wodurch Buchstaben wie g, j, p, y unten abgeschnitten werden. Sorgt bei reinen Text-Labels auf Linux automatisch für minimalen vertikalen Innenabstand. """ if not sys.platform.startswith("linux") or getattr(tk.Label, "_goth_descent_patched", False): return orig_init = tk.Label.__init__ def _patched_label_init(self, master=None, cnf={}, **kw): has_image = ("image" in kw and kw["image"] is not None) or (isinstance(cnf, dict) and cnf.get("image")) if not has_image: cur_pady = kw.get("pady", cnf.get("pady") if isinstance(cnf, dict) else None) if cur_pady is None: kw["pady"] = 3 elif isinstance(cur_pady, int) and cur_pady < 3: kw["pady"] = 3 orig_init(self, master, cnf, **kw) tk.Label.__init__ = _patched_label_init tk.Label._goth_descent_patched = True 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"): 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 # Audio-Pre-Init vor jeglicher Pygame-Initialisierung setzen try: is_linux = sys.platform.startswith("linux") is_cros = is_linux and ( Path("/dev/.cros_milestone").exists() or "sommelier" in os.environ.get("XDG_RUNTIME_DIR", "").lower() or Path("/opt/google/cros-containers").exists() ) freq = 48000 if is_linux else 44100 buf_size = 8192 if is_cros else (4096 if is_linux else 1024) pygame.mixer.pre_init(frequency=freq, size=-16, channels=2, buffer=buf_size) 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: """ Registriert unter ChromeOS (Crostini) Icon & .desktop mit absolutem PNG-Pfad und exakter Groß-/Kleinschreibung passend zu Tkinters X11 WM_CLASS. """ 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" pixmaps_dir = data_home / "pixmaps" desktop_id = wm_class.lower() # Alte Fehlversuchs-Dateien aufräumen, damit garcon nicht verwirrt wird for stale in ("goth-cardgame-collection.desktop", "thegothcardgamecollection.desktop"): stale_p = apps_dir / stale if stale != f"{desktop_id}.desktop" and stale_p.is_file(): stale_p.unlink(missing_ok=True) best_pil, _ = _extract_ico_frames(icon_ico_path) if best_pil is None: return # 1. Direkt in pixmaps + hicolor speichern & absoluten Pfad nutzen (umgeht fehlenden Icon-Cache!) pixmaps_dir.mkdir(parents=True, exist_ok=True) abs_icon_png = pixmaps_dir / f"{desktop_id}.png" best_pil.resize((128, 128), Image.Resampling.LANCZOS).save(abs_icon_png, format="PNG") for px in (128, 64, 48): icon_dir = data_home / "icons" / "hicolor" / f"{px}x{px}" / "apps" icon_dir.mkdir(parents=True, exist_ok=True) best_pil.resize((px, px), Image.Resampling.LANCZOS).save( icon_dir / f"{desktop_id}.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()}"' # StartupWMClass MUSS exakt "TheGothCardgameCollection" sein (Tkinter großgeschrieben!) 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={abs_icon_png}\n" f"StartupWMClass={wm_class}\n" "Categories=Game;CardGame;\n" "Terminal=false\n" ) apps_dir.mkdir(parents=True, exist_ok=True) desktop_file = apps_dir / f"{desktop_id}.desktop" if not desktop_file.is_file() or desktop_file.read_text(encoding="utf-8") != desktop_content: desktop_file.write_text(desktop_content, encoding="utf-8") subprocess.run( ["update-desktop-database", str(apps_dir)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, ) 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 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: 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 ErrorReportOverlay.install_global_hooks( app, is_shutting_down_cb=lambda: shutting_down, ) 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() _install_linux_label_descent_fix() root_path = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent)) 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) 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()