336 lines
10 KiB
Python
336 lines
10 KiB
Python
# -*- coding: utf-8 -*-
|
|
import os
|
|
import signal
|
|
import sys
|
|
import tempfile
|
|
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"):
|
|
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 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 _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
|
|
|
|
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:
|
|
tk_photos = [ImageTk.PhotoImage(im) for im in cascade_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):
|
|
"""
|
|
Sorgt für komplett lautloses Beenden beim Klick auf X und bei Strg+C:
|
|
1. Führt evtl. bestehenden WindowStatePersistence-Close-Hook aus (solange DB offen ist)
|
|
2. Zerstört Kind-Widgets kontrolliert (feuert <Destroy>-Save-Hooks aktiver Spieltische)
|
|
3. Bricht restlos alle noch geplanten Tcl-after()-Timer ab
|
|
4. Beendet pygame und schließt SQLite sauber ohne Traceback
|
|
"""
|
|
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
|
|
|
|
# Unterdrückt verwaiste Tcl-Callback-Fehlermeldungen während des Shutdowns
|
|
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
|
|
|
|
# 1. Kind-Widgets zuerst abräumen, damit aktive Spieltische ihren Stand noch speichern können
|
|
try:
|
|
for child in list(app.winfo_children()):
|
|
try:
|
|
child.destroy()
|
|
except Exception:
|
|
pass
|
|
except Exception:
|
|
pass
|
|
|
|
# 2. Falls WindowStatePersistence vorher einen WM_DELETE_WINDOW-Tcl-Befehl gesetzt hat,
|
|
# Geometrie noch sichern, bevor wir Timer & DB schließen
|
|
if prev_wm_delete_cmd:
|
|
try:
|
|
app.tk.call(prev_wm_delete_cmd)
|
|
except Exception:
|
|
pass
|
|
|
|
# 3. Alle noch ausstehenden Tcl-after()-Jobs abbrechen
|
|
try:
|
|
for after_id in app.tk.call("after", "info"):
|
|
try:
|
|
app.after_cancel(after_id)
|
|
except Exception:
|
|
pass
|
|
except Exception:
|
|
pass
|
|
|
|
# 4. Audio & SQLite kontrolliert herunterfahren
|
|
try:
|
|
if pygame.mixer.get_init():
|
|
pygame.mixer.music.stop()
|
|
pygame.quit()
|
|
except Exception:
|
|
pass
|
|
|
|
try:
|
|
Database.close()
|
|
except Exception:
|
|
pass
|
|
|
|
# 5. Tk-Hauptschleife und Fenster sauber schließen
|
|
try:
|
|
app.quit()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
if app.winfo_exists():
|
|
app.destroy()
|
|
except Exception:
|
|
pass
|
|
|
|
app.protocol("WM_DELETE_WINDOW", graceful_exit)
|
|
|
|
# Strg+C (SIGINT) abfangen + kurzer Python-Heartbeat, damit Windows SIGINT sofort zustellt
|
|
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(__file__).resolve().parent
|
|
|
|
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() |