the_goth_cardgame_collection/view/font_loader.py

186 lines
7.6 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# view/font_loader.py
import ctypes
import shutil
import sys
import tkinter as tk
import tkinter.font as tkfont
from pathlib import Path
from resources.code_res.game_constants import (
CUSTOM_FONT_FILES, FONT_GOTH_ALT, FONT_GOTH_TITLE, FONTS_REL_DIR
)
class FontLoader:
"""
Lädt resources/fonts/OldLondon.ttf & OldLondonAlternate.ttf zur Laufzeit auf
Windows, Linux, ChromeOS (Crostini) und macOS ohne System-Installation.
"""
_active_title_family: str = "Georgia"
_active_alt_family: str = "Georgia"
_hook_installed: bool = False
@classmethod
def register_fonts(cls, root_dir: Path) -> None:
fonts_dir = root_dir / FONTS_REL_DIR
if not fonts_dir.is_dir():
return
ttf_paths = [fonts_dir / fname for fname in CUSTOM_FONT_FILES if (fonts_dir / fname).is_file()]
if not ttf_paths:
return
if sys.platform.startswith("win"):
cls._register_windows(ttf_paths)
elif sys.platform == "darwin":
cls._register_macos(ttf_paths)
elif sys.platform.startswith("linux"):
cls._register_linux_and_chromeos(ttf_paths)
@staticmethod
def _register_windows(ttf_paths: list[Path]) -> None:
"""Win32 AddFontResourceExW mit FR_PRIVATE (0x10): nur für diesen Prozess sichtbar."""
FR_PRIVATE = 0x10
try:
gdi32 = ctypes.windll.gdi32
for p in ttf_paths:
gdi32.AddFontResourceExW(ctypes.c_wchar_p(str(p)), FR_PRIVATE, 0)
except Exception:
pass
@staticmethod
def _register_linux_and_chromeos(ttf_paths: list[Path]) -> None:
"""
1. Sofortige Prozess-Registrierung über libfontconfig (FcConfigAppFontAddFile).
2. Sicherheits-Kopie nach ~/.local/share/fonts/goth_cardgames für X11/Crostini-Builds.
"""
try:
fc = ctypes.CDLL("libfontconfig.so.1")
fc.FcConfigGetCurrent.restype = ctypes.c_void_p
fc.FcConfigAppFontAddFile.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
fc.FcConfigAppFontAddFile.restype = ctypes.c_int
cfg = fc.FcConfigGetCurrent()
if cfg:
for p in ttf_paths:
fc.FcConfigAppFontAddFile(cfg, str(p).encode("utf-8"))
except Exception:
pass
try:
user_font_dir = Path.home() / ".local" / "share" / "fonts" / "goth_cardgames"
user_font_dir.mkdir(parents=True, exist_ok=True)
for p in ttf_paths:
dst = user_font_dir / p.name
if not dst.is_file():
shutil.copy2(p, dst)
except Exception:
pass
@staticmethod
def _register_macos(ttf_paths: list[Path]) -> None:
"""macOS CoreText CTFontManagerRegisterFontsForURL (kCTFontManagerScopeProcess = 1)."""
try:
ct = ctypes.CDLL("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices")
cf = ctypes.CDLL("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
cf.CFURLCreateFromFileSystemRepresentation.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.c_long, ctypes.c_bool
]
cf.CFURLCreateFromFileSystemRepresentation.restype = ctypes.c_void_p
cf.CFRelease.argtypes = [ctypes.c_void_p]
ct.CTFontManagerRegisterFontsForURL.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_void_p]
ct.CTFontManagerRegisterFontsForURL.restype = ctypes.c_bool
kCTFontManagerScopeProcess = 1
for p in ttf_paths:
raw = str(p).encode("utf-8")
url = cf.CFURLCreateFromFileSystemRepresentation(None, raw, len(raw), False)
if url:
ct.CTFontManagerRegisterFontsForURL(url, kCTFontManagerScopeProcess, None)
cf.CFRelease(url)
except Exception:
pass
@classmethod
def bind_to_tk_root(cls, root: tk.Tk) -> None:
"""
Prüft nach Erstellung des Tk-Fensters, ob 'Old London' erkannt wurde,
setzt Standard-Schriften und aktiviert das automatische Titel-Font-Mapping.
"""
available = {f.lower(): f for f in tkfont.families(root)}
if FONT_GOTH_TITLE.lower() in available:
cls._active_title_family = available[FONT_GOTH_TITLE.lower()]
elif "oldlondon" in available:
cls._active_title_family = available["oldlondon"]
if FONT_GOTH_ALT.lower() in available:
cls._active_alt_family = available[FONT_GOTH_ALT.lower()]
else:
cls._active_alt_family = cls._active_title_family
# Falls Old London erfolgreich geladen wurde, alle ("Georgia", ...) Überschriften
# im gesamten Spiel automatisch und gut lesbar (+3pt) auf Old London heben!
if cls._active_title_family != "Georgia" and not cls._hook_installed:
cls._install_georgia_to_old_london_bridge()
cls._hook_installed = True
@classmethod
def title_font(cls, size: int = 16, weight: str = "normal") -> tuple:
boost = 3 if cls._active_title_family != "Georgia" else 0
return (cls._active_title_family, size + boost, weight)
@classmethod
def alt_font(cls, size: int = 16, weight: str = "normal") -> tuple:
boost = 3 if cls._active_alt_family != "Georgia" else 0
return (cls._active_alt_family, size + boost, weight)
@classmethod
def _remap_font_arg(cls, font_val):
if isinstance(font_val, tuple) and len(font_val) >= 2:
fam = str(font_val[0])
if fam.lower() == "georgia":
base_sz = int(font_val[1])
# Frakturschrift braucht ~2-3pt mehr Höhe für dieselbe optische Größe wie Georgia;
# "normal" statt "bold" verhindert bei Old London das Zulaufen feiner Linien!
new_sz = base_sz + (3 if base_sz >= 12 else 2)
return (cls._active_title_family, new_sz)
return font_val
@classmethod
def _install_georgia_to_old_london_bridge(cls) -> None:
"""
Transparentes Upgrade für bestehende Tk-Widgets (Label, Canvas.create_text, Button):
Wandelt ("Georgia", X, "bold") automatisch in scharfes ("Old London", X+3) um.
"""
orig_widget_init = tk.Widget.__init__
orig_configure = tk.Misc._configure
orig_canvas_text = tk.Canvas.create_text
def _patched_init(self, master, widgetName, cnf={}, kw={}, extra=()):
if "font" in kw:
kw = dict(kw)
kw["font"] = cls._remap_font_arg(kw["font"])
elif isinstance(cnf, dict) and "font" in cnf:
cnf = dict(cnf)
cnf["font"] = cls._remap_font_arg(cnf["font"])
return orig_widget_init(self, master, widgetName, cnf, kw, extra)
def _patched_configure(self, cmd, cnf, kw):
if isinstance(kw, dict) and "font" in kw:
kw = dict(kw)
kw["font"] = cls._remap_font_arg(kw["font"])
if isinstance(cnf, dict) and "font" in cnf:
cnf = dict(cnf)
cnf["font"] = cls._remap_font_arg(cnf["font"])
return orig_configure(self, cmd, cnf, kw)
def _patched_canvas_text(self, *args, **kw):
if "font" in kw:
kw["font"] = cls._remap_font_arg(kw["font"])
return orig_canvas_text(self, *args, **kw)
tk.Widget.__init__ = _patched_init
tk.Misc._configure = _patched_configure
tk.Canvas.create_text = _patched_canvas_text