# -*- coding: utf-8 -*- # view/font_loader.py from __future__ import annotations import ctypes import shutil import sys import tkinter as tk import tkinter.font as tkfont from pathlib import Path from models.db_locator import DbLocator from resources.code_res.game_constants import ( CUSTOM_FONT_FILES, DEFAULT_UI_FONT_KEY, FONT_GOTH_ALT, FONT_GOTH_TITLE, FONTS_REL_DIR, UI_FONT_PRESETS, UI_FONT_SETTING_KEY, ) def resolve_font_file_case_insensitive(fonts_dir: Path, filename: str) -> Path | None: """Findet Font-Dateien auch unter Linux/macOS unabhängig von Groß-/Kleinschreibung (.TTF vs .ttf).""" direct = fonts_dir / filename if direct.is_file(): return direct if not fonts_dir.is_dir(): return None target_low = filename.lower() for p in fonts_dir.iterdir(): if p.is_file() and p.name.lower() == target_low: return p return None class FontLoader: """ Registriert alle gebündelten TTF-Schriften zur Laufzeit (Windows, Linux/Crostini, macOS) und verwaltet die aktuell gewählte UI-Schriftart inklusive Persistenz. """ _active_font_key: str = DEFAULT_UI_FONT_KEY _prefs_loaded: bool = False _active_title_family: str = "Georgia" _active_alt_family: str = "Georgia" _tk_available_map: dict[str, str] = {} _hook_installed: bool = False @classmethod def ensure_loaded_from_storage(cls) -> str: if not cls._prefs_loaded: saved = "" try: from models.database import Database if Database._connection is not None: saved = str(Database.load_setting(UI_FONT_SETTING_KEY, "")).strip() except Exception: saved = "" if not saved: saved = str(DbLocator.load_config().get(UI_FONT_SETTING_KEY, "")).strip() if saved in UI_FONT_PRESETS: cls._active_font_key = saved cls._prefs_loaded = True return cls._active_font_key @classmethod def get_active_font_key(cls) -> str: return cls.ensure_loaded_from_storage() @classmethod def get_active_preset(cls) -> dict: key = cls.get_active_font_key() return UI_FONT_PRESETS.get(key, UI_FONT_PRESETS[DEFAULT_UI_FONT_KEY]) @classmethod def set_active_font_key( cls, font_key: str, root: tk.Misc | None = None, persist: bool = True ) -> None: clean_key = font_key if font_key in UI_FONT_PRESETS else DEFAULT_UI_FONT_KEY cls._active_font_key = clean_key cls._prefs_loaded = True if persist: DbLocator.save_config({UI_FONT_SETTING_KEY: clean_key}) try: from models.database import Database Database.save_setting(UI_FONT_SETTING_KEY, clean_key) except Exception: pass if root is not None: try: cls._sync_tk_families(root) except Exception: pass @classmethod def sync_from_database(cls, root: tk.Misc | None = None) -> bool: """Synchronisiert die Schriftart nach dem Laden einer anderen user_data.db.""" prev = cls._active_font_key try: from models.database import Database db_val = str(Database.load_setting(UI_FONT_SETTING_KEY, "")).strip() if db_val in UI_FONT_PRESETS: cls._active_font_key = db_val DbLocator.save_config({UI_FONT_SETTING_KEY: db_val}) except Exception: pass if root is not None: cls._sync_tk_families(root) return cls._active_font_key != prev @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: list[Path] = [] for fname in CUSTOM_FONT_FILES: resolved = resolve_font_file_case_insensitive(fonts_dir, fname) if resolved is not None and resolved not in ttf_paths: ttf_paths.append(resolved) 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: 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: 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: 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 _sync_tk_families(cls, root: tk.Misc) -> None: cls._tk_available_map = {f.lower(): f for f in tkfont.families(root)} preset = cls.get_active_preset() target_fam = str(preset.get("family", FONT_GOTH_TITLE)).lower() target_compact = target_fam.replace(" ", "") matched = cls._tk_available_map.get(target_fam) if matched is None: for k_low, real_name in cls._tk_available_map.items(): if k_low.replace(" ", "") == target_compact or target_fam in k_low: matched = real_name break if matched is None: matched = ( cls._tk_available_map.get(FONT_GOTH_TITLE.lower()) or cls._tk_available_map.get("oldlondon") or "Georgia" ) cls._active_title_family = matched if cls.get_active_font_key() == DEFAULT_UI_FONT_KEY and FONT_GOTH_ALT.lower() in cls._tk_available_map: cls._active_alt_family = cls._tk_available_map[FONT_GOTH_ALT.lower()] else: cls._active_alt_family = matched @classmethod def bind_to_tk_root(cls, root: tk.Tk) -> None: cls.ensure_loaded_from_storage() cls._sync_tk_families(root) 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: scale = float(cls.get_active_preset().get("size_scale", 1.0)) boost = 3 if cls._active_title_family != "Georgia" else 0 eff_sz = max(10, int(round((size + boost) * scale))) return (cls._active_title_family, eff_sz, weight) @classmethod def alt_font(cls, size: int = 16, weight: str = "normal") -> tuple: scale = float(cls.get_active_preset().get("size_scale", 1.0)) boost = 3 if cls._active_alt_family != "Georgia" else 0 eff_sz = max(10, int(round((size + boost) * scale))) return (cls._active_alt_family, eff_sz, 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]) scale = float(cls.get_active_preset().get("size_scale", 1.0)) new_sz = max( 9, int(round((base_sz + (3 if base_sz >= 12 else 2)) * scale)) ) return (cls._active_title_family, new_sz) return font_val @classmethod def _install_georgia_to_old_london_bridge(cls) -> None: 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