Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
frontend-qt: mirror Mac SwiftUI 3-page UI, game library, KeyCheck, cheats, and space sheets
LNPANDY7e601cb37de4
diff --git a/frontend-qt/nspb_qt/features.py b/frontend-qt/nspb_qt/features.pynew file mode 100644index 00000000..a3652f3d--- /dev/null+++ b/frontend-qt/nspb_qt/features.py@@ -0,0 +1,637 @@+"""KeyCheck (pure-Python AES-128-XTS NCA header verifier), CheatFiles, and Diagnostics.++Mirrors KeyCheck.swift, CheatFiles.swift, and Diagnostics.swift from the Mac Swift launcher.+"""+from __future__ import annotations++import os+import platform+import re+import shutil+import struct+import zipfile+from dataclasses import dataclass, field+from pathlib import Path++# ---------------------------------------------------------------------------+# Pure-Python AES-128-ECB & Nintendo Switch AES-128-XTS (for 1 KB NCA header)+# ---------------------------------------------------------------------------++_SBOX = (+ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,+ 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,+ 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,+ 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,+ 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,+ 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,+ 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,+ 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,+ 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,+ 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,+ 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,+ 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,+ 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,+ 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,+ 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,+ 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,+)++_INV_SBOX = [0] * 256+for _i, _v in enumerate(_SBOX):+ _INV_SBOX[_v] = _i++_RCON = (0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36)+++def _xtime(a: int) -> int:+ return ((a << 1) ^ 0x1B) & 0xFF if (a & 0x80) else (a << 1)+++def _gmul(a: int, b: int) -> int:+ p = 0+ for _ in range(8):+ if b & 1:+ p ^= a+ hi = a & 0x80+ a = (a << 1) & 0xFF+ if hi:+ a ^= 0x1B+ b >>= 1+ return p+++def _expand_key_128(key: bytes) -> list[list[int]]:+ w = [list(key[i:i + 4]) for i in range(0, 16, 4)]+ for i in range(4, 44):+ temp = list(w[i - 1])+ if i % 4 == 0:+ temp = [_SBOX[temp[1]] ^ _RCON[i // 4], _SBOX[temp[2]], _SBOX[temp[3]], _SBOX[temp[0]]]+ w.append([w[i - 4][j] ^ temp[j] for j in range(4)])+ return [[w[r * 4 + c][row] for c in range(4) for row in range(4)] for r in range(11)]+++def _aes128_encrypt_block(block: bytes, rkeys: list[list[int]]) -> bytes:+ s = [block[i] ^ rkeys[0][i] for i in range(16)]+ for r in range(1, 10):+ # SubBytes + ShiftRows+ s = [+ _SBOX[s[0]], _SBOX[s[5]], _SBOX[s[10]], _SBOX[s[15]],+ _SBOX[s[4]], _SBOX[s[9]], _SBOX[s[14]], _SBOX[s[3]],+ _SBOX[s[8]], _SBOX[s[13]], _SBOX[s[2]], _SBOX[s[7]],+ _SBOX[s[12]], _SBOX[s[1]], _SBOX[s[6]], _SBOX[s[11]],+ ]+ # MixColumns + AddRoundKey+ rk = rkeys[r]+ ns = [0] * 16+ for c in range(4):+ i = c * 4+ a0, a1, a2, a3 = s[i], s[i + 1], s[i + 2], s[i + 3]+ t = a0 ^ a1 ^ a2 ^ a3+ ns[i] = a0 ^ t ^ _xtime(a0 ^ a1) ^ rk[i]+ ns[i + 1] = a1 ^ t ^ _xtime(a1 ^ a2) ^ rk[i + 1]+ ns[i + 2] = a2 ^ t ^ _xtime(a2 ^ a3) ^ rk[i + 2]+ ns[i + 3] = a3 ^ t ^ _xtime(a3 ^ a0) ^ rk[i + 3]+ s = ns+ s = [+ _SBOX[s[0]], _SBOX[s[5]], _SBOX[s[10]], _SBOX[s[15]],+ _SBOX[s[4]], _SBOX[s[9]], _SBOX[s[14]], _SBOX[s[3]],+ _SBOX[s[8]], _SBOX[s[13]], _SBOX[s[2]], _SBOX[s[7]],+ _SBOX[s[12]], _SBOX[s[1]], _SBOX[s[6]], _SBOX[s[11]],+ ]+ rk = rkeys[10]+ return bytes(s[i] ^ rk[i] for i in range(16))+++def _aes128_decrypt_block(block: bytes, rkeys: list[list[int]]) -> bytes:+ s = [block[i] ^ rkeys[10][i] for i in range(16)]+ for r in range(9, 0, -1):+ # InvShiftRows + InvSubBytes+ s = [+ _INV_SBOX[s[0]], _INV_SBOX[s[13]], _INV_SBOX[s[10]], _INV_SBOX[s[7]],+ _INV_SBOX[s[4]], _INV_SBOX[s[1]], _INV_SBOX[s[14]], _INV_SBOX[s[11]],+ _INV_SBOX[s[8]], _INV_SBOX[s[5]], _INV_SBOX[s[2]], _INV_SBOX[s[15]],+ _INV_SBOX[s[12]], _INV_SBOX[s[9]], _INV_SBOX[s[6]], _INV_SBOX[s[3]],+ ]+ rk = rkeys[r]+ s = [s[i] ^ rk[i] for i in range(16)]+ # InvMixColumns+ ns = [0] * 16+ for c in range(4):+ i = c * 4+ a0, a1, a2, a3 = s[i], s[i + 1], s[i + 2], s[i + 3]+ ns[i] = _gmul(a0, 0x0e) ^ _gmul(a1, 0x0b) ^ _gmul(a2, 0x0d) ^ _gmul(a3, 0x09)+ ns[i + 1] = _gmul(a0, 0x09) ^ _gmul(a1, 0x0e) ^ _gmul(a2, 0x0b) ^ _gmul(a3, 0x0d)+ ns[i + 2] = _gmul(a0, 0x0d) ^ _gmul(a1, 0x09) ^ _gmul(a2, 0x0e) ^ _gmul(a3, 0x0b)+ ns[i + 3] = _gmul(a0, 0x0b) ^ _gmul(a1, 0x0d) ^ _gmul(a2, 0x09) ^ _gmul(a3, 0x0e)+ s = ns+ s = [+ _INV_SBOX[s[0]], _INV_SBOX[s[13]], _INV_SBOX[s[10]], _INV_SBOX[s[7]],+ _INV_SBOX[s[4]], _INV_SBOX[s[1]], _INV_SBOX[s[14]], _INV_SBOX[s[11]],+ _INV_SBOX[s[8]], _INV_SBOX[s[5]], _INV_SBOX[s[2]], _INV_SBOX[s[15]],+ _INV_SBOX[s[12]], _INV_SBOX[s[9]], _INV_SBOX[s[6]], _INV_SBOX[s[3]],+ ]+ rk = rkeys[0]+ return bytes(s[i] ^ rk[i] for i in range(16))+++def decrypt_nca_sector(cipher: bytes, sector: int, key1: bytes, key2: bytes) -> bytes:+ """Decrypt a 0x200-byte Nintendo Switch NCA header sector with AES-128-XTS."""+ rk1 = _expand_key_128(key1)+ rk2 = _expand_key_128(key2)+ # Nintendo Switch tweak is big-endian sector number+ tweak = list(_aes128_encrypt_block(sector.to_bytes(16, 'big'), rk2))+ out = bytearray(len(cipher))+ for off in range(0, len(cipher), 16):+ xored = bytes(cipher[off + i] ^ tweak[i] for i in range(16))+ dec = _aes128_decrypt_block(xored, rk1)+ for i in range(16):+ out[off + i] = dec[i] ^ tweak[i]+ # GF(2^128) multiply tweak by alpha (little-endian carry)+ carry = 0+ for i in range(16):+ nxt = (tweak[i] >> 7) & 1+ tweak[i] = ((tweak[i] << 1) | carry) & 0xFF+ carry = nxt+ if carry:+ tweak[0] ^= 0x87+ return bytes(out)+++# ---------------------------------------------------------------------------+# KeyCheck (mirrors KeyCheck.swift)+# ---------------------------------------------------------------------------++@dataclass+class KeyVerdict:+ kind: str # 'fits', 'unreadableKeys', 'missingHeaderKey', 'wrongHeaderKey', 'missingKey', 'cannotCheck'+ part: str = '' # 'base', 'update', 'dlc'+ key: str = ''+ firmware: str | None = None+ reason: str = ''+++class KeyCheck:+ KEY_AREA_NAMES = ['application', 'ocean', 'system']+ FIRMWARE_BY_GEN = {+ '00': '1.0.0',+ '01': '1.0.0',+ '02': '3.0.0',+ '03': '3.0.1',+ '04': '4.0.0',+ '05': '5.0.0',+ '06': '6.0.0',+ '07': '6.2.0',+ '08': '7.0.0',+ '09': '8.1.0',+ '0a': '9.0.0',+ '0b': '9.1.0',+ '0c': '12.1.0',+ '0d': '13.0.0',+ '0e': '14.0.0',+ '0f': '15.0.0',+ '10': '16.0.0',+ '11': '17.0.0',+ '12': '18.0.0',+ '13': '19.0.0',+ '14': '20.0.0',+ '15': '21.0.0',+ }++ @staticmethod+ def firmware_for_key(key_name: str) -> str | None:+ suf = key_name[-2:].lower() if len(key_name) >= 2 else ''+ return KeyCheck.FIRMWARE_BY_GEN.get(suf)++ @staticmethod+ def parse_keys(text: str) -> dict[str, str]:+ out: dict[str, str] = {}+ for line in text.splitlines():+ s = line.split('#', 1)[0].strip()+ if '=' not in s:+ continue+ k, v = s.split('=', 1)+ k = k.strip().lower()+ v = v.strip().lower()+ if k and len(v) >= 16 and len(v) % 2 == 0 and all(c in '0123456789abcdef' for c in v):+ out[k] = v+ return out++ @staticmethod+ def load_keys(path: str) -> dict[str, str] | None:+ if not path or not os.path.isfile(path):+ return None+ try:+ with open(path, encoding='utf-8', errors='replace') as f:+ return KeyCheck.parse_keys(f.read())+ except OSError:+ return None++ @staticmethod+ def check(+ keys_path: str,+ base_path: str,+ update_path: str = '',+ dlc_paths: list[str] | None = None,+ ) -> KeyVerdict:+ keys = KeyCheck.load_keys(keys_path)+ if keys is None:+ return KeyVerdict('unreadableKeys')+ hk_hex = keys.get('header_key', '')+ if len(hk_hex) != 64:+ return KeyVerdict('missingHeaderKey')+ header_key = bytes.fromhex(hk_hex)++ items: list[tuple[str, str]] = [('base', base_path)]+ if update_path:+ items.append(('update', update_path))+ for dp in (dlc_paths or []):+ if dp:+ items.append(('dlc', dp))++ cannot_check: KeyVerdict | None = None+ for part, path in items:+ if not path or not os.path.isfile(path):+ continue+ v = KeyCheck._check_package(path, part, keys, header_key)+ if v.kind in ('wrongHeaderKey', 'missingKey'):+ return v+ if v.kind == 'cannotCheck' and cannot_check is None:+ cannot_check = v++ return cannot_check or KeyVerdict('fits')++ @staticmethod+ def _check_package(+ path: str,+ part: str,+ keys: dict[str, str],+ header_key: bytes,+ ) -> KeyVerdict:+ ext = os.path.splitext(path)[1].lower()+ if ext in ('.xci', '.xcz'):+ return KeyVerdict('cannotCheck', part=part, reason=ext[1:].upper())+ try:+ with open(path, 'rb') as f:+ head = f.read(16)+ if len(head) < 16 or head[:4] != b'PFS0':+ return KeyVerdict('cannotCheck', part=part, reason=os.path.basename(path))+ count, str_size, _ = struct.unpack_from('<III', head, 4)+ if count <= 0 or count > 4096 or str_size > 1_000_000:+ return KeyVerdict('cannotCheck', part=part, reason=os.path.basename(path))+ entries_raw = f.read(count * 24)+ str_tab = f.read(str_size)+ if len(entries_raw) < count * 24 or len(str_tab) < str_size:+ return KeyVerdict('cannotCheck', part=part, reason=os.path.basename(path))+ data_base = 16 + count * 24 + str_size++ tik_entry = None+ best_nca = None+ for i in range(count):+ off, sz, soff, _ = struct.unpack_from('<QQII', entries_raw, i * 24)+ end = str_tab.find(b'\x00', soff)+ name = str_tab[soff:end if end != -1 else len(str_tab)].decode('utf-8', errors='replace')+ low = name.lower()+ if low.endswith('.tik') and sz >= 0x286:+ tik_entry = (off, sz)+ elif low.endswith('.nca') and not low.endswith('.cnmt.nca') and sz >= 0x400:+ if best_nca is None or sz > best_nca[1]:+ best_nca = (off, sz)+ elif low.endswith('.ncz') and best_nca is None:+ return KeyVerdict('cannotCheck', part=part, reason='NSZ')++ if best_nca is None:+ return KeyVerdict('cannotCheck', part=part, reason=os.path.basename(path))++ tik_gen: int | None = None+ if tik_entry is not None:+ f.seek(data_base + tik_entry[0] + 0x285)+ b = f.read(1)+ if len(b) == 1:+ tik_gen = b[0]++ f.seek(data_base + best_nca[0] + 0x200)+ sector1 = f.read(0x200)+ if len(sector1) < 0x200:+ return KeyVerdict('cannotCheck', part=part, reason=os.path.basename(path))+ except OSError:+ return KeyVerdict('cannotCheck', part=part, reason=os.path.basename(path))++ plain1 = decrypt_nca_sector(sector1, 1, header_key[:16], header_key[16:32])+ if plain1[:4] not in (b'NCA2', b'NCA3'):+ return KeyVerdict('wrongHeaderKey', part=part)++ old_gen = plain1[0x06]+ new_gen = plain1[0x20]+ raw_gen = max(old_gen, new_gen)+ gen = max(0, raw_gen - 1)+ key_idx = plain1[0x07]+ has_rights_id = any(b != 0 for b in plain1[0x30:0x40])++ if has_rights_id:+ tgen = max(0, tik_gen - 1) if tik_gen is not None else gen+ g_str = f'{tgen:02x}'+ tk = f'titlekek_{g_str}'+ mk = f'master_key_{g_str}'+ if tk not in keys and mk not in keys:+ return KeyVerdict('missingKey', part=part, key=mk, firmware=KeyCheck.firmware_for_key(mk))+ else:+ g_str = f'{gen:02x}'+ area = KeyCheck.KEY_AREA_NAMES[key_idx] if 0 <= key_idx < len(KeyCheck.KEY_AREA_NAMES) else 'application'+ ka = f'key_area_key_{area}_{g_str}'+ mk = f'master_key_{g_str}'+ if ka not in keys and mk not in keys:+ return KeyVerdict('missingKey', part=part, key=mk, firmware=KeyCheck.firmware_for_key(mk))++ return KeyVerdict('fits')+++# ---------------------------------------------------------------------------+# CheatFiles (mirrors CheatFiles.swift)+# ---------------------------------------------------------------------------++@dataclass+class CheatItem:+ name: str+ lines: list[str] = field(default_factory=list)+ is_master: bool = False++ @property+ def is_valid(self) -> bool:+ if not self.lines:+ return False+ for ln in self.lines:+ parts = ln.split()+ if not parts or any(len(p) != 8 or not all(c in '0123456789abcdefABCDEF' for c in p) for p in parts):+ return False+ return True++ @property+ def runs_once(self) -> bool:+ if not self.is_valid:+ return False+ for ln in self.lines:+ first = ln.split()[0].upper()+ if not (first.startswith('04') or first.startswith('08')):+ return False+ return True+++@dataclass+class CheatBuildFile:+ build_id: str+ path: str+ cheats: list[CheatItem]+ enabled: set[str]+++class CheatFiles:+ BUILD_ID_RE = re.compile(r'^([0-9A-Fa-f]{16})\.txt$')++ @staticmethod+ def cheats_dir(title_id: str, work_dir: str | None = None, archive_dir: str | None = None, state_dir: Path | None = None) -> str:+ tid = title_id.upper()+ if archive_dir and os.path.isdir(archive_dir):+ return os.path.join(archive_dir, 'cheats')+ if work_dir and os.path.isdir(work_dir):+ return os.path.join(work_dir, 'cheats', tid)+ from . import library as lib+ base = state_dir or lib.default_state_dir()+ return str(base / 'cheats' / tid)++ @staticmethod+ def read_build_id(work_dir: str | None = None, ipa_path: str | None = None, title_id: str = '') -> str | None:+ # 1. Check <work_dir>/main.fixups.tsv or <work_dir>/<tid>/main.fixups.tsv+ candidates: list[str] = []+ if work_dir and os.path.isdir(work_dir):+ candidates.append(os.path.join(work_dir, 'main.fixups.tsv'))+ if title_id:+ candidates.append(os.path.join(work_dir, title_id.upper(), 'main.fixups.tsv'))+ try:+ for sub in os.listdir(work_dir):+ p = os.path.join(work_dir, sub, 'main.fixups.tsv')+ if os.path.isfile(p):+ candidates.append(p)+ except OSError:+ pass++ for p in candidates:+ if os.path.isfile(p):+ bid = CheatFiles._parse_fixups_build_id_file(p)+ if bid:+ return bid++ # 2. Check inside .ipa+ if ipa_path and os.path.isfile(ipa_path):+ try:+ with zipfile.ZipFile(ipa_path, 'r') as zf:+ for name in zf.namelist():+ if name.endswith('main.fixups.tsv'):+ head = zf.read(name)[:1024].decode('utf-8', errors='replace')+ bid = CheatFiles._parse_fixups_build_id_text(head)+ if bid:+ return bid+ except Exception:+ pass+ return None++ @staticmethod+ def _parse_fixups_build_id_file(path: str) -> str | None:+ try:+ with open(path, encoding='utf-8', errors='replace') as f:+ return CheatFiles._parse_fixups_build_id_text(f.read(1024))+ except OSError:+ return None++ @staticmethod+ def _parse_fixups_build_id_text(text: str) -> str | None:+ for line in text.splitlines():+ if line.startswith('# BUILD_ID'):+ parts = line.split()+ if len(parts) >= 3 and len(parts[2]) >= 16:+ cand = parts[2][:16].upper()+ if all(c in '0123456789ABCDEF' for c in cand):+ return cand+ return None++ @staticmethod+ def parse_txt(text: str) -> list[CheatItem]:+ items: list[CheatItem] = []+ curr: CheatItem | None = None+ for raw in text.splitlines():+ line = raw.strip()+ if not line or line.startswith('#') or line.startswith('//'):+ continue+ if line.startswith('[') and line.endswith(']') and len(line) > 2:+ curr = CheatItem(name=line[1:-1].strip(), is_master=False)+ items.append(curr)+ elif line.startswith('{') and line.endswith('}') and len(line) > 2:+ curr = CheatItem(name=line[1:-1].strip(), is_master=True)+ items.append(curr)+ elif curr is not None:+ curr.lines.append(line)+ return items++ @staticmethod+ def load_folder(folder: str, title_id: str) -> tuple[bool, list[CheatBuildFile]]:+ """Return (master_enabled, build_files)."""+ tid = title_id.upper()+ off_marker = os.path.join(folder, f'.cheats-off-{tid}')+ master_on = not os.path.exists(off_marker)+ if not os.path.isdir(folder):+ return master_on, []+ files: list[CheatBuildFile] = []+ try:+ entries = sorted(os.listdir(folder))+ except OSError:+ return master_on, []+ for name in entries:+ m = CheatFiles.BUILD_ID_RE.match(name)+ if not m:+ continue+ bid = m.group(1).upper()+ txt_path = os.path.join(folder, name)+ en_path = os.path.join(folder, f'{bid}.enabled')+ try:+ text = Path(txt_path).read_text(encoding='utf-8', errors='replace')+ except OSError:+ continue+ cheats = CheatFiles.parse_txt(text)+ enabled: set[str] = set()+ if os.path.isfile(en_path):+ try:+ for ln in Path(en_path).read_text(encoding='utf-8', errors='replace').splitlines():+ s = ln.strip()+ if s:+ enabled.add(s)+ except OSError:+ pass+ files.append(CheatBuildFile(build_id=bid, path=txt_path, cheats=cheats, enabled=enabled))+ return master_on, files++ @staticmethod+ def set_master(folder: str, title_id: str, enabled: bool) -> None:+ os.makedirs(folder, exist_ok=True)+ off_marker = os.path.join(folder, f'.cheats-off-{title_id.upper()}')+ if enabled:+ if os.path.exists(off_marker):+ try:+ os.remove(off_marker)+ except OSError:+ pass+ else:+ try:+ Path(off_marker).write_text('', encoding='utf-8')+ except OSError:+ pass++ @staticmethod+ def set_cheat_enabled(folder: str, build_id: str, cheat_name: str, enabled: bool) -> None:+ os.makedirs(folder, exist_ok=True)+ bid = build_id.upper()+ en_path = Path(folder) / f'{bid}.enabled'+ current: list[str] = []+ if en_path.is_file():+ try:+ current = [ln.strip() for ln in en_path.read_text(encoding='utf-8', errors='replace').splitlines() if ln.strip()]+ except OSError:+ current = []+ if enabled and cheat_name not in current:+ current.append(cheat_name)+ elif not enabled and cheat_name in current:+ current = [x for x in current if x != cheat_name]+ try:+ en_path.write_text('\n'.join(current) + ('\n' if current else ''), encoding='utf-8')+ except OSError:+ pass++ @staticmethod+ def import_paths(paths: list[str], dest_folder: str, title_id: str = '') -> tuple[int, list[str]]:+ """Import <buildID>.txt files from given file or directory paths. Return (imported_count, rejected_names)."""+ os.makedirs(dest_folder, exist_ok=True)+ imported = 0+ rejected: list[str] = []+ for p in paths:+ if os.path.isfile(p):+ bn = os.path.basename(p)+ m = CheatFiles.BUILD_ID_RE.match(bn)+ if m:+ dst = os.path.join(dest_folder, f'{m.group(1).upper()}.txt')+ try:+ if os.path.abspath(p) != os.path.abspath(dst):+ shutil.copy2(p, dst)+ imported += 1+ except OSError:+ rejected.append(bn)+ else:+ rejected.append(bn)+ elif os.path.isdir(p):+ for root, _, files in os.walk(p):+ if title_id and len(title_id) == 16:+ # If walking an Atmosphere SD card with many title IDs, filter by title_id if present in path+ other_tids = re.findall(r'[0-9A-Fa-f]{16}', root)+ if other_tids and all(t.upper() != title_id.upper() for t in other_tids):+ continue+ for fn in files:+ m = CheatFiles.BUILD_ID_RE.match(fn)+ if m:+ src = os.path.join(root, fn)+ dst = os.path.join(dest_folder, f'{m.group(1).upper()}.txt')+ try:+ if os.path.abspath(src) != os.path.abspath(dst):+ shutil.copy2(src, dst)+ imported += 1+ except OSError:+ pass+ return imported, rejected+++# ---------------------------------------------------------------------------+# Diagnostics (mirrors Diagnostics.swift)+# ---------------------------------------------------------------------------++class Diagnostics:+ @staticmethod+ def redact(text: str) -> str:+ home = os.path.expanduser('~')+ out = text+ if home:+ out = out.replace(home, '~')+ out = out.replace(home.replace('\\', '/'), '~')+ # Redact --keys <path>+ out = re.sub(r'(--keys\s+)("[^"]+"|\'[^\']+\'|\S+)', r'\1<redacted>', out)+ return out++ @staticmethod+ def format_report(+ app_version: str,+ repo_path: str,+ deps: list,+ last_log: str,+ ) -> str:+ lines = [+ '## NX2Apple Diagnostics',+ f'- Launcher: v{app_version} (Qt / {platform.system()})',+ f'- OS: {platform.platform()} ({platform.machine()})',+ f'- Python: {platform.python_version()}',+ ]+ if repo_path:+ lines.append(f'- Engine repo: `{Diagnostics.redact(repo_path)}`')+ else:+ lines.append('- Engine repo: (not set)')++ lines.append('')+ lines.append('### Dependencies')+ for d in deps:+ state = 'OK' if getattr(d, 'ok', False) else ('Optional' if not getattr(d, 'required', True) else 'MISSING')+ detail = Diagnostics.redact(str(getattr(d, 'detail', '')))+ lines.append(f'- {getattr(d, "name", "")}: [{state}] {detail}')++ if last_log.strip():+ tail = last_log.strip().splitlines()[-50:]+ redacted_tail = Diagnostics.redact('\n'.join(tail))+ lines.append('')+ lines.append('### Last Build Log (last 50 lines)')+ lines.append('```')+ lines.append(redacted_tail)+ lines.append('```')+ return '\n'.join(lines)diff --git a/frontend-qt/nspb_qt/library.py b/frontend-qt/nspb_qt/library.pynew file mode 100644index 00000000..6ee72159--- /dev/null+++ b/frontend-qt/nspb_qt/library.py@@ -0,0 +1,1305 @@+"""Game library, Switch 2 folder/NUP scanner, artwork store, build-folder cleaner, game deletion, and drive copy.++Mirrors the Mac Swift launcher's Library.swift, GameFolder.swift, Artwork.swift,+FreeSpace.swift, GameDeletion.swift, and DriveCopy.swift for the Windows/Qt front end.+"""+from __future__ import annotations++import json+import os+import re+import shutil+import struct+import tempfile+import threading+import time+import urllib.request+from dataclasses import dataclass, field+from pathlib import Path+from typing import Callable++from . import platform_util as pu+++def default_state_dir() -> Path:+ env_dir = os.environ.get('NSPB_STATE_DIR')+ if env_dir:+ return Path(env_dir)+ if os.environ.get('QT_QPA_PLATFORM') == 'offscreen':+ return Path(tempfile.gettempdir()) / f'nspb-offscreen-{os.getpid()}'+ if pu.IS_WIN:+ root = Path(os.environ.get('LOCALAPPDATA') or (Path.home() / 'AppData' / 'Local'))+ return root / 'NS Port Builder'+ return Path.home() / 'Library' / 'Application Support' / 'NS Port Builder'++_TID_RE = re.compile(r'\[([0-9A-Fa-f]{16})\]')+_TID_ANY_RE = re.compile(r'(?<![0-9A-Fa-f])([0-9A-Fa-f]{16})(?![0-9A-Fa-f])')+_VER_TAG_RE = re.compile(r'\[v\d+\]', re.IGNORECASE)+_PAREN_TAG_RE = re.compile(r'\([^)]*\)')+_BRACKET_TAG_RE = re.compile(r'\[[^\]]*\]')+_KIND_SUFFIX_RE = re.compile(r'[-_\s]*(upd|update|base|dlc|patch)\s*$', re.IGNORECASE)++PACKAGE_EXTS = {'.nsp', '.xci', '.nsz', '.xcz'}++BUNDLED_ART: dict[str, str] = {+ '01007EF00011E000': 'docs/images/botw-2.png',+ '0100F2C0115B6000': 'docs/images/totk-2.png',+ '0100000000010000': 'docs/images/odyssey-2.png',+ '010028600EBDA000': 'docs/images/3dw-2.png',+ '0100152000022000': 'docs/images/mk8d-2.png',+ '01006A800016E000': 'docs/images/ssbu-2.png',+ '0100E95004038000': 'docs/images/xc2-1.png',+ '010074F013262000': 'docs/images/xc3-2.png',+ '0100453019AA8000': 'docs/images/xcx-1.png',+ '0100A3D008C5C000': 'docs/images/sv-1.png',+ '01001F5010DFA000': 'docs/images/pla-2.png',+ '01008F6008C5E000': 'docs/images/sword-1.png',+ '0100000011D90000': 'docs/images/bd-2.png',+ '0100F43008C44000': 'docs/images/fe-engage-1.png',+ '010055D009F78000': 'docs/images/fe3h-1.png',+ '010085000B772000': 'docs/images/feth-1.png',+ '0100D71004694000': 'docs/images/p5r-1.png',+ '0100A6301214E000': 'docs/images/smt5v-1.png',+ '010025C00D410000': 'docs/images/acnh-1.png',+ '0100626011656000': 'docs/images/dread-1.png',+ '0100C4B0034B2000': 'docs/images/mp-remastered-1.png',+ '010016501B772000': 'docs/images/mp4-1.png',+ '010049900F546000': 'docs/images/kirby-fl-2.png',+ '01004D300C5AE000': 'docs/images/krtdld-1.png',+ '01008CF01BAAC000': 'docs/images/zelda-eow-1.png',+ '01006BB00C6F0000': 'docs/images/la-1.png',+ '01002DA013484000': 'docs/images/sshd-1.png',+ '010028A017892000': 'docs/images/pikmin4-1.png',+ '0100A3900C3E2000': 'docs/images/pm-ttyd-1.png',+ '0100F8F0000A2000': 'docs/images/smbw-2.png',+ '01001B300B9BE000': 'docs/images/lm3-1.png',+ '0100C25013430000': 'docs/images/bayo3-1.png',+ '01004A400D244000': 'docs/images/astral-chain-1.png',+ '0100D870045B6000': 'docs/images/nier-1.png',+ '0100E2F017572000': 'docs/images/unicorn-1.png',+ '010057D00ECE4000': 'docs/images/octopath2-1.png',+ '0100E66010ADE000': 'docs/images/triangle-1.png',+ '0100B7D01605C000': 'docs/images/starocean2r-1.png',+ '01006C300E9F0000': 'docs/images/dq11s-1.png',+ '01006C1017892000': 'docs/images/dq3hd2d-1.png',+ '0100B04011742000': 'docs/images/mhr-2.png',+ '0100770008DD8000': 'docs/images/mhgu-1.png',+ '010010A01D54E000': 'docs/images/silksong-1.png',+ '0100633007D48000': 'docs/images/hk-1.png',+ '0100535012974000': 'docs/images/hades-1.png',+ '0100F7B00BB5C000': 'docs/images/celeste-1.png',+ '0100CD301A5C8000': 'docs/images/balatro-1.png',+ '01002E7016C46000': 'docs/images/dave-1.png',+ '010040600C5CE000': 'docs/images/cuphead-1.png',+ '0100E6500B9AC000': 'docs/images/dead-cells-1.png',+ '01006C900EC02000': 'docs/images/subnautica-1.png',+ '01000890195B8000': 'docs/images/pop-tlc-1.png',+ '0100B8E016F76000': 'docs/images/dredge-1.png',+ '0100C1F0051B6000': 'docs/images/factorio-1.png',+ '01003D20137F8000': 'docs/images/splatoon3-1.png',+ '0100B0C0115B8000': 'docs/images/sky-1.png',+ '01005CA01580E000': 'docs/images/diablo3-1.png',+ '0100C4C00A922000': 'docs/images/darksouls-1.png',+ '0100DE900C3E4000': 'docs/images/skyrim-1.png',+ '0100830004FB6000': 'docs/images/doom-1.png',+ '01003D100E9C6000': 'docs/images/witcher3-1.png',+}+++def format_bytes(size: int) -> str:+ if size <= 0:+ return '0 B'+ units = ['B', 'KB', 'MB', 'GB', 'TB']+ val = float(size)+ idx = 0+ while val >= 1024.0 and idx < len(units) - 1:+ val /= 1024.0+ idx += 1+ if idx == 0:+ return f'{int(val)} B'+ if val >= 100 or idx == 1:+ return f'{val:.0f} {units[idx]}'+ return f'{val:.1f} {units[idx]}'+++def clean_game_name(filename: str) -> str:+ stem = os.path.splitext(os.path.basename(filename))[0]+ s = _BRACKET_TAG_RE.sub('', stem)+ s = _PAREN_TAG_RE.sub('', s)+ s = _KIND_SUFFIX_RE.sub('', s)+ s = s.replace('_', ' ').strip(' -._')+ return s or stem+++def extract_title_id(path: str) -> str | None:+ name = os.path.basename(path)+ m = _TID_RE.search(name)+ if m:+ return m.group(1).upper()+ m2 = _TID_ANY_RE.search(name)+ if m2:+ return m2.group(1).upper()+ return None+++def base_family_id(tid: str) -> str:+ if len(tid) != 16:+ return tid.upper()+ try:+ val = int(tid, 16)+ return f'{val & ~0x1FFF:016X}'+ except ValueError:+ return tid.upper()+++def classify_tid(tid: str) -> str:+ """Return 'base', 'update', or 'dlc' based on low 12 bits of Title ID."""+ if len(tid) != 16:+ return 'base'+ try:+ low = int(tid, 16) & 0xFFF+ if low == 0x000:+ return 'base'+ if low == 0x800:+ return 'update'+ return 'dlc'+ except ValueError:+ return 'base'+++# ---------------------------------------------------------------------------+# Switch 2 GameFolder & NUP scanner (mirrors GameFolder.swift)+# ---------------------------------------------------------------------------++@dataclass+class GameFolderContents:+ folder: str+ title_id: int+ updates: list[tuple[int, str]] = field(default_factory=list)+ dlc: list[tuple[int, str]] = field(default_factory=list)+ nup: str | None = None++ @property+ def title_id_hex(self) -> str:+ return f'{self.title_id:016X}' if self.title_id else ''++ @property+ def base_path(self) -> str:+ return self.nup or os.path.join(self.folder, 'base')++ @property+ def script_input(self) -> str:+ return self.nup or self.folder++ @property+ def has_title_id(self) -> bool:+ return self.title_id != 0++ @property+ def newest_update(self) -> tuple[int, str] | None:+ return self.updates[-1] if self.updates else None+++@dataclass+class GameFolderProblem:+ kind: str # 'missing', 'noBaseFolder', 'unreadableNPDM', 'notBaseTitle', 'packageBeside', 'dlcName', 'notDLC', 'dlcRomFS', 'notNUP', 'nupPartial', 'severalNUPs'+ arg1: object = None+ arg2: object = None+++class GameFolder:+ @staticmethod+ def nup_files(folder: str) -> list[str]:+ try:+ entries = sorted(os.listdir(folder))+ except OSError:+ return []+ out = []+ for name in entries:+ if not name.startswith('._') and name.lower().endswith('.nup'):+ full = os.path.join(folder, name)+ if os.path.isfile(full):+ out.append(name)+ return out++ @staticmethod+ def is_candidate(path: str) -> bool:+ if not path:+ return False+ if path.lower().endswith('.nup') and os.path.isfile(path):+ return True+ if os.path.isfile(os.path.join(path, 'base', 'exefs', 'main.npdm')):+ return True+ if GameFolder.nup_files(path):+ return True+ return (+ os.path.isfile(os.path.join(path, 'exefs', 'main.npdm'))+ and not os.path.exists(os.path.join(path, 'base'))+ )++ @staticmethod+ def program_id(npdm_bytes: bytes) -> int | None:+ if len(npdm_bytes) < 0x78 or npdm_bytes[:4] != b'META':+ return None+ off, size = struct.unpack_from('<II', npdm_bytes, 0x70)+ if size < 0x18 or off + 0x18 > len(npdm_bytes):+ return None+ if npdm_bytes[off:off + 4] != b'ACI0':+ return None+ return struct.unpack_from('<Q', npdm_bytes, off + 0x10)[0]++ @staticmethod+ def read_nup(path: str) -> GameFolderContents | GameFolderProblem:+ name = os.path.basename(path)+ try:+ size = os.path.getsize(path)+ with open(path, 'rb') as f:+ head = f.read(0x80)+ if len(head) != 0x80 or head[:3] != b'NUP' or head[3] != 1:+ return GameFolderProblem('notNUP', name)+ expected_size = struct.unpack_from('<Q', head, 0x40)[0]+ if expected_size != size:+ return GameFolderProblem('nupPartial', name)+ toc = struct.unpack_from('<Q', head, 0x08)[0]+ count = struct.unpack_from('<I', head, 0x48)[0]+ if count <= 0 or count >= 100_000 or toc + 0x30 + count * 0x40 > size:+ return GameFolderProblem('notNUP', name)+ f.seek(toc)+ table = f.read(0x30 + count * 0x40)+ if len(table) != 0x30 + count * 0x40 or table[:4] != b'TOC\x01':+ return GameFolderProblem('notNUP', name)+ except OSError:+ return GameFolderProblem('notNUP', name)++ base = 0+ update_title = 0+ updates: list[tuple[int, str]] = []+ addons: list[int] = []+ for i in range(count):+ o = 0x30 + i * 0x40+ tid = struct.unpack_from('<Q', table, o)[0]+ ver = struct.unpack_from('<I', table, o + 20)[0]+ kind = table[o + 24]+ if kind == 0:+ base = tid+ elif kind == 1:+ updates.append((ver, path))+ if update_title == 0:+ update_title = tid & ~0xFFF+ elif kind == 2:+ addons.append(tid)+ app = base if (base != 0 and (base & 0xFFF) == 0) else update_title+ updates.sort(key=lambda x: x[0])+ addons.sort()+ return GameFolderContents(+ folder=os.path.dirname(path),+ title_id=app,+ updates=updates,+ dlc=[(t, path) for t in addons],+ nup=path,+ )++ @staticmethod+ def scan(folder: str) -> GameFolderContents | GameFolderProblem:+ if folder.lower().endswith('.nup') and os.path.isfile(folder):+ return GameFolder.read_nup(folder)+ try:+ top = sorted(os.listdir(folder))+ except OSError:+ return GameFolderProblem('missing', 'base/exefs/main.npdm')++ for name in top:+ if not name.startswith('._') and os.path.splitext(name)[1].lower() in PACKAGE_EXTS:+ if os.path.isfile(os.path.join(folder, name)):+ return GameFolderProblem('packageBeside', name)++ nups = GameFolder.nup_files(folder)+ if len(nups) > 1:+ return GameFolderProblem('severalNUPs', len(nups))+ if len(nups) == 1:+ return GameFolder.read_nup(os.path.join(folder, nups[0]))++ npdm_path = os.path.join(folder, 'base', 'exefs', 'main.npdm')+ if not os.path.isfile(npdm_path):+ if os.path.isfile(os.path.join(folder, 'exefs', 'main.npdm')) and not os.path.exists(os.path.join(folder, 'base')):+ return GameFolderProblem('noBaseFolder')+ return GameFolderProblem('missing', 'base/exefs/main.npdm')++ def subdirs(p: str) -> list[str]:+ if not os.path.isdir(p):+ return []+ try:+ return sorted(d for d in os.listdir(p) if not d.startswith('.') and os.path.isdir(os.path.join(p, d)))+ except OSError:+ return []++ updates_dir = os.path.join(folder, 'updates')+ versions = [v for v in subdirs(updates_dir) if v.isdigit()]+ has_romfs = os.path.isdir(os.path.join(folder, 'base', 'romfs')) or any(+ os.path.isdir(os.path.join(updates_dir, v, 'romfs')) for v in versions+ )+ if not has_romfs:+ return GameFolderProblem('missing', 'base/romfs')++ try:+ with open(npdm_path, 'rb') as f:+ data = f.read()+ except OSError:+ return GameFolderProblem('unreadableNPDM')++ app = GameFolder.program_id(data)+ if app is None:+ return GameFolderProblem('unreadableNPDM')+ if (app & 0xFFF) != 0:+ return GameFolderProblem('notBaseTitle', app)++ updates = sorted((int(v), os.path.join(updates_dir, v)) for v in versions)+ dlc: list[tuple[int, str]] = []+ dlc_dir = os.path.join(folder, 'dlc')+ for name in subdirs(dlc_dir):+ dpath = os.path.join(dlc_dir, name)+ if len(name) > 16:+ return GameFolderProblem('dlcName', name)+ try:+ tid = int(name, 16)+ except ValueError:+ return GameFolderProblem('dlcName', name)+ if not (tid > app + 0x1000 and tid - app - 0x1000 <= 2000):+ return GameFolderProblem('notDLC', name, tid)+ numbered = [sub for sub in subdirs(dpath) if os.path.isdir(os.path.join(dpath, sub, 'romfs'))]+ cnt = len(numbered) if numbered else (1 if os.path.isdir(os.path.join(dpath, 'romfs')) else 0)+ if cnt != 1:+ return GameFolderProblem('dlcRomFS', name, cnt)+ dlc.append((tid, dpath))++ dlc.sort(key=lambda x: x[0])+ return GameFolderContents(folder=folder, title_id=app, updates=updates, dlc=dlc)++ @staticmethod+ def profile_name(title_id: str | int, repo_path: str) -> str | None:+ if not repo_path:+ return None+ tid_hex = f'{title_id:016X}' if isinstance(title_id, int) else title_id.upper()+ tsv = os.path.join(repo_path, 'dm', 'games', tid_hex, 'game.tsv')+ if not os.path.isfile(tsv):+ return None+ try:+ with open(tsv, encoding='utf-8', errors='replace') as f:+ for line in f:+ if line.startswith('name\t'):+ val = line[5:].strip()+ return val if val else None+ except OSError:+ pass+ return None++ @staticmethod+ def profile_is_switch2(title_id: str, repo_path: str) -> bool:+ if not repo_path or len(title_id) != 16:+ return False+ tsv = os.path.join(repo_path, 'dm', 'games', title_id.upper(), 'game.tsv')+ if not os.path.isfile(tsv):+ return False+ try:+ with open(tsv, encoding='utf-8', errors='replace') as f:+ first = f.readline()+ return first.startswith('#') and '(Switch 2' in first+ except OSError:+ return False++ @staticmethod+ def engine_has_profile(title_id: int | str, repo_path: str) -> bool:+ if not repo_path:+ return False+ tid_hex = f'{title_id:016X}' if isinstance(title_id, int) else title_id.upper()+ return os.path.isfile(os.path.join(repo_path, 'dm', 'games', tid_hex, 'game.tsv'))++ @staticmethod+ def engine_builds_folders(repo_path: str) -> bool:+ return bool(repo_path and os.path.isfile(os.path.join(repo_path, 'scripts', 'pack_dump.py')))++ @staticmethod+ def engine_builds_nups(repo_path: str) -> bool:+ return bool(repo_path and os.path.isfile(os.path.join(repo_path, 'scripts', 'pack_nup.py')))+++# ---------------------------------------------------------------------------+# LibraryGame & GameLibrary (mirrors Library.swift)+# ---------------------------------------------------------------------------++@dataclass+class LibraryGame:+ title_id: str+ name: str+ app_path: str = ''+ ipa_path: str = ''+ archive_path: str = ''+ ios_app_path: str = ''+ output_dir: str = ''+ inputs: dict[str, list[str]] = field(default_factory=dict)+ added_at: float = field(default_factory=time.time)+ last_built_at: float | None = None+ built_chain_tag: str = ''++ @property+ def id(self) -> str:+ return self.title_id++ @property+ def has_app(self) -> bool:+ return bool(self.app_path and os.path.exists(self.app_path))++ @property+ def has_ipa(self) -> bool:+ return bool(self.ipa_path and os.path.isfile(self.ipa_path))++ @property+ def has_ios_app(self) -> bool:+ return bool(self.ios_app_path and os.path.exists(self.ios_app_path))++ @property+ def has_archive(self) -> bool:+ return bool(self.archive_path and os.path.isdir(self.archive_path))++ @property+ def has_any_build(self) -> bool:+ return self.has_app or self.has_ipa or self.has_ios_app or self.has_archive++ @property+ def has_inputs(self) -> bool:+ base = (self.inputs.get('base') or [''])[0]+ if not base or not os.path.exists(base):+ return False+ if GameFolder.is_candidate(base):+ return True+ keys = (self.inputs.get('keys') or [''])[0]+ return bool(keys and os.path.isfile(keys))++ @property+ def can_rebuild(self) -> bool:+ base = (self.inputs.get('base') or [''])[0]+ return bool(base and os.path.exists(base))++ @property+ def work_dir(self) -> str | None:+ out = self.output_dir+ if not out:+ base = (self.inputs.get('base') or [''])[0]+ if base:+ out = os.path.dirname(base)+ if not out:+ return None+ return os.path.join(out, f'{self.title_id}_build')++ def is_switch2(self, repo_path: str) -> bool:+ return GameFolder.profile_is_switch2(self.title_id, repo_path)++ def to_dict(self) -> dict:+ return {+ 'titleID': self.title_id,+ 'name': self.name,+ 'appPath': self.app_path,+ 'ipaPath': self.ipa_path,+ 'archivePath': self.archive_path,+ 'iosAppPath': self.ios_app_path,+ 'outputDir': self.output_dir,+ 'inputs': self.inputs,+ 'addedAt': self.added_at,+ 'lastBuiltAt': self.last_built_at,+ 'builtChainTag': self.built_chain_tag,+ }++ @classmethod+ def from_dict(cls, d: dict) -> LibraryGame:+ return cls(+ title_id=str(d.get('titleID') or d.get('title_id') or '').upper(),+ name=str(d.get('name') or ''),+ app_path=str(d.get('appPath') or ''),+ ipa_path=str(d.get('ipaPath') or ''),+ archive_path=str(d.get('archivePath') or ''),+ ios_app_path=str(d.get('iosAppPath') or ''),+ output_dir=str(d.get('outputDir') or ''),+ inputs=dict(d.get('inputs') or {}),+ added_at=float(d.get('addedAt') or time.time()),+ last_built_at=float(d['lastBuiltAt']) if d.get('lastBuiltAt') is not None else None,+ built_chain_tag=str(d.get('builtChainTag') or ''),+ )+++class GameLibrary:+ def __init__(self, state_dir: Path | None = None) -> None:+ self.state_dir = state_dir or default_state_dir()+ self.file_path = self.state_dir / 'library.json'+ self.games: list[LibraryGame] = []+ self.selected_id: str | None = None+ self.games_folder: str = ''+ self.load()++ @property+ def selected(self) -> LibraryGame | None:+ if self.selected_id:+ for g in self.games:+ if g.title_id == self.selected_id:+ return g+ return self.games[0] if self.games else None++ def select(self, title_id: str | None) -> None:+ self.selected_id = title_id.upper() if title_id else None++ def load(self) -> None:+ if not self.file_path.is_file():+ return+ try:+ raw = json.loads(self.file_path.read_text(encoding='utf-8'))+ if isinstance(raw, list):+ self.games = [LibraryGame.from_dict(x) for x in raw if isinstance(x, dict)]+ elif isinstance(raw, dict):+ self.games = [LibraryGame.from_dict(x) for x in raw.get('games', []) if isinstance(x, dict)]+ self.games_folder = str(raw.get('gamesFolder') or '')+ self.selected_id = raw.get('selectedID')+ if self.games and not self.selected_id:+ self.selected_id = self.games[0].title_id+ except Exception:+ pass++ def save(self) -> None:+ try:+ self.state_dir.mkdir(parents=True, exist_ok=True)+ payload = {+ 'gamesFolder': self.games_folder,+ 'selectedID': self.selected_id,+ 'games': [g.to_dict() for g in self.games],+ }+ self.file_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding='utf-8')+ except OSError:+ pass++ def set_games_folder(self, folder: str, repo_path: str = '', default_keys: str = '') -> None:+ self.games_folder = folder+ if folder and os.path.isdir(folder):+ self.rescan_games_folder(repo_path=repo_path, default_keys=default_keys)+ self.save()++ def remove(self, title_id: str) -> None:+ tid = title_id.upper()+ self.games = [g for g in self.games if g.title_id != tid]+ if self.selected_id == tid:+ self.selected_id = self.games[0].title_id if self.games else None+ self.save()++ def upsert(self, game: LibraryGame) -> LibraryGame:+ tid = game.title_id.upper()+ game.title_id = tid+ for i, existing in enumerate(self.games):+ if existing.title_id == tid:+ if not game.name or game.name == tid:+ game.name = existing.name+ if not game.ipa_path:+ game.ipa_path = existing.ipa_path+ if not game.archive_path:+ game.archive_path = existing.archive_path+ if not game.output_dir:+ game.output_dir = existing.output_dir+ if not game.inputs:+ game.inputs = existing.inputs+ if game.last_built_at is None:+ game.last_built_at = existing.last_built_at+ self.games[i] = game+ self.save()+ return game+ self.games.insert(0, game)+ if not self.selected_id:+ self.selected_id = game.title_id+ self.save()+ return game++ def remember_inputs(+ self,+ base_path: str,+ update_path: str,+ dlc_paths: list[str],+ keys_path: str,+ output_dir: str,+ repo_path: str = '',+ ) -> LibraryGame | None:+ if not base_path:+ return None+ tid = ''+ name = ''+ if GameFolder.is_candidate(base_path):+ res = GameFolder.scan(base_path if not os.path.basename(base_path) == 'base' else os.path.dirname(base_path))+ if isinstance(res, GameFolderContents) and res.has_title_id:+ tid = res.title_id_hex+ name = GameFolder.profile_name(tid, repo_path) or clean_game_name(res.folder)+ if not tid:+ tid_raw = extract_title_id(base_path)+ if tid_raw:+ tid = base_family_id(tid_raw)+ if not tid:+ return None+ if not name:+ name = GameFolder.profile_name(tid, repo_path) or clean_game_name(base_path)++ inputs: dict[str, list[str]] = {'base': [base_path]}+ if update_path:+ inputs['update'] = [update_path]+ if dlc_paths:+ inputs['dlc'] = list(dlc_paths)+ if keys_path:+ inputs['keys'] = [keys_path]++ out = output_dir or os.path.dirname(base_path)+ ipa_candidate = os.path.join(out, f'{name}.ipa')+ archive_candidate = os.path.join(out, 'games', tid)+ game = LibraryGame(+ title_id=tid,+ name=name,+ ipa_path=ipa_candidate if os.path.isfile(ipa_candidate) else '',+ archive_path=archive_candidate if os.path.isdir(archive_candidate) else '',+ output_dir=output_dir,+ inputs=inputs,+ )+ g = self.upsert(game)+ self.selected_id = g.title_id+ self.save()+ return g++ def record_completed_ios(+ self,+ ipa_path: str,+ archive_path: str,+ base_path: str,+ output_dir: str,+ inputs: dict[str, list[str]],+ repo_path: str = '',+ ) -> LibraryGame | None:+ tid = ''+ if archive_path:+ bn = os.path.basename(archive_path.rstrip('/\\'))+ if len(bn) == 16:+ tid = bn.upper()+ if not tid and base_path:+ if GameFolder.is_candidate(base_path):+ res = GameFolder.scan(base_path if os.path.basename(base_path) != 'base' else os.path.dirname(base_path))+ if isinstance(res, GameFolderContents) and res.has_title_id:+ tid = res.title_id_hex+ if not tid:+ tid_raw = extract_title_id(base_path)+ if tid_raw:+ tid = base_family_id(tid_raw)+ if not tid and ipa_path:+ tid_raw = extract_title_id(ipa_path)+ if tid_raw:+ tid = base_family_id(tid_raw)+ if not tid:+ tid = '0100000000000000'++ name = GameFolder.profile_name(tid, repo_path)+ if not name:+ if ipa_path:+ name = clean_game_name(ipa_path)+ elif base_path:+ name = clean_game_name(base_path)+ else:+ name = tid++ game = LibraryGame(+ title_id=tid,+ name=name,+ ipa_path=ipa_path if (ipa_path and os.path.isfile(ipa_path)) else '',+ archive_path=archive_path if (archive_path and os.path.isdir(archive_path)) else '',+ output_dir=output_dir,+ inputs=inputs,+ last_built_at=time.time(),+ )+ g = self.upsert(game)+ self.selected_id = g.title_id+ self.save()+ return g++ def rescan_games_folder(self, repo_path: str = '', default_keys: str = '') -> int:+ folder = self.games_folder+ if not folder or not os.path.isdir(folder):+ return 0+ discovered = self.discover_in_folder(folder, repo_path=repo_path, default_keys=default_keys)+ count = 0+ for g in discovered:+ self.upsert(g)+ count += 1+ self.save()+ return count++ @staticmethod+ def discover_in_folder(folder: str, repo_path: str = '', default_keys: str = '') -> list[LibraryGame]:+ if not folder or not os.path.isdir(folder):+ return []+ families: dict[str, dict[str, list[str]]] = {}+ names: dict[str, str] = {}+ ipas: dict[str, str] = {}+ archives: dict[str, str] = {}+ found_keys = default_keys if (default_keys and os.path.isfile(default_keys)) else ''++ def walk_dir(curr: str, depth: int) -> None:+ nonlocal found_keys+ if depth > 3:+ return+ if GameFolder.is_candidate(curr):+ res = GameFolder.scan(curr)+ if isinstance(res, GameFolderContents) and res.has_title_id:+ tid = res.title_id_hex+ families.setdefault(tid, {})['base'] = [res.script_input]+ if res.newest_update:+ families[tid]['update'] = [res.newest_update[1]]+ if res.dlc:+ families[tid]['dlc'] = [p for _, p in res.dlc]+ names[tid] = GameFolder.profile_name(tid, repo_path) or clean_game_name(curr)+ return++ try:+ entries = sorted(os.listdir(curr))+ except OSError:+ return++ for entry in entries:+ if entry.startswith('.'):+ continue+ full = os.path.join(curr, entry)+ low = entry.lower()+ if os.path.isfile(full):+ if low in ('prod.keys', 'keys.txt') or low.endswith('.keys'):+ if not found_keys:+ found_keys = full+ continue+ ext = os.path.splitext(low)[1]+ if ext == '.nup':+ res = GameFolder.read_nup(full)+ if isinstance(res, GameFolderContents) and res.has_title_id:+ tid = res.title_id_hex+ families.setdefault(tid, {})['base'] = [full]+ names[tid] = GameFolder.profile_name(tid, repo_path) or clean_game_name(full)+ elif ext in PACKAGE_EXTS:+ tid_raw = extract_title_id(entry)+ if tid_raw:+ fam = base_family_id(tid_raw)+ kind = classify_tid(tid_raw)+ slot = families.setdefault(fam, {})+ if kind == 'base':+ slot['base'] = [full]+ names[fam] = GameFolder.profile_name(fam, repo_path) or clean_game_name(entry)+ elif kind == 'update':+ slot.setdefault('update', []).append(full)+ else:+ slot.setdefault('dlc', []).append(full)+ elif ext == '.ipa':+ tid_raw = extract_title_id(entry)+ if tid_raw:+ ipas[base_family_id(tid_raw)] = full+ elif os.path.isdir(full):+ if entry.endswith('_build'):+ continue+ if entry == 'games':+ try:+ for sub in os.listdir(full):+ sub_full = os.path.join(full, sub)+ if len(sub) == 16 and os.path.isdir(sub_full):+ archives[sub.upper()] = sub_full+ except OSError:+ pass+ continue+ walk_dir(full, depth + 1)++ walk_dir(folder, 0)+ results: list[LibraryGame] = []+ for tid, slots in families.items():+ if 'base' not in slots:+ continue+ if found_keys and 'keys' not in slots:+ slots['keys'] = [found_keys]+ if 'update' in slots and len(slots['update']) > 1:+ slots['update'] = [sorted(slots['update'])[-1]]+ gname = names.get(tid) or GameFolder.profile_name(tid, repo_path) or tid+ base_dir = os.path.dirname(slots['base'][0])+ ipa = ipas.get(tid, '')+ if not ipa:+ cand = os.path.join(base_dir, f'{gname}.ipa')+ if os.path.isfile(cand):+ ipa = cand+ arch = archives.get(tid, '')+ if not arch:+ cand_arch = os.path.join(base_dir, 'games', tid)+ if os.path.isdir(cand_arch):+ arch = cand_arch+ results.append(+ LibraryGame(+ title_id=tid,+ name=gname,+ ipa_path=ipa,+ archive_path=arch,+ output_dir=base_dir,+ inputs=slots,+ )+ )+ return results+++# ---------------------------------------------------------------------------+# ArtworkStore & eShop Banner fetcher (mirrors Artwork.swift & BannerPick.swift)+# ---------------------------------------------------------------------------++class ArtworkStore:+ TITLEDB_URL = 'https://raw.githubusercontent.com/blawar/titledb/master/US.en.json'++ def __init__(self, state_dir: Path | None = None, on_updated: Callable[[str], None] | None = None) -> None:+ self.state_dir = state_dir or default_state_dir()+ self.banners_dir = self.state_dir / 'banners'+ self.custom_file = self.state_dir / 'custom_artwork.json'+ self.on_updated = on_updated+ self.custom_paths: dict[str, str] = {}+ self._fetching: set[str] = set()+ self._titledb_cache: dict[str, str] | None = None+ self._lock = threading.Lock()+ self._load_custom()++ def _load_custom(self) -> None:+ if self.custom_file.is_file():+ try:+ data = json.loads(self.custom_file.read_text(encoding='utf-8'))+ if isinstance(data, dict):+ self.custom_paths = {k.upper(): str(v) for k, v in data.items() if v}+ except Exception:+ pass++ def _save_custom(self) -> None:+ try:+ self.state_dir.mkdir(parents=True, exist_ok=True)+ self.custom_file.write_text(json.dumps(self.custom_paths, indent=2), encoding='utf-8')+ except OSError:+ pass++ def set_custom(self, title_id: str, image_path: str) -> None:+ tid = title_id.upper()+ self.custom_paths[tid] = image_path+ self._save_custom()+ if self.on_updated:+ self.on_updated(tid)++ def clear_custom(self, title_id: str) -> None:+ tid = title_id.upper()+ self.custom_paths.pop(tid, None)+ self._save_custom()+ if self.on_updated:+ self.on_updated(tid)++ def has_custom(self, title_id: str) -> bool:+ tid = title_id.upper()+ p = self.custom_paths.get(tid, '')+ return bool(p and os.path.isfile(p))++ def image_path(self, title_id: str, repo_path: str = '') -> str | None:+ tid = title_id.upper()+ custom = self.custom_paths.get(tid, '')+ if custom and os.path.isfile(custom):+ return custom+ cached = self.banners_dir / f'{tid}.jpg'+ if cached.is_file():+ return str(cached)+ cached_png = self.banners_dir / f'{tid}.png'+ if cached_png.is_file():+ return str(cached_png)+ if repo_path:+ gal = self._gallery_map(repo_path)+ if tid in gal:+ p = os.path.join(repo_path, 'docs', 'images', gal[tid])+ if os.path.isfile(p):+ return p+ if tid in BUNDLED_ART:+ bundled = os.path.join(repo_path, BUNDLED_ART[tid])+ if os.path.isfile(bundled):+ return bundled+ return None++ def _gallery_map(self, repo_path: str) -> dict[str, str]:+ cache: dict[str, dict[str, str]] = getattr(self, '_gal_cache', {})+ if repo_path in cache:+ return cache[repo_path]+ out: dict[str, str] = {}+ tsv = os.path.join(repo_path, 'docs', 'images', 'gallery.tsv')+ if os.path.isfile(tsv):+ try:+ with open(tsv, encoding='utf-8', errors='replace') as f:+ for line in f:+ if not line or line.startswith('#'):+ continue+ parts = line.rstrip('\r\n').split('\t')+ if len(parts) >= 4 and len(parts[3]) == 16:+ out[parts[3].upper()] = parts[0]+ except OSError:+ pass+ cache[repo_path] = out+ self._gal_cache = cache+ return out++ def request_banner_async(self, title_id: str) -> None:+ if os.environ.get('QT_QPA_PLATFORM') == 'offscreen':+ return+ tid = title_id.upper()+ if self.has_custom(tid) or (self.banners_dir / f'{tid}.jpg').is_file():+ return+ with self._lock:+ if tid in self._fetching:+ return+ self._fetching.add(tid)++ def worker() -> None:+ try:+ self._fetch_one(tid)+ finally:+ with self._lock:+ self._fetching.discard(tid)++ threading.Thread(target=worker, daemon=True).start()++ def _fetch_one(self, tid: str) -> None:+ index_file = self.banners_dir / 'banners_index.json'+ mapping: dict[str, str] = {}+ if index_file.is_file():+ try:+ mapping = json.loads(index_file.read_text(encoding='utf-8'))+ except Exception:+ mapping = {}++ url = mapping.get(tid)+ if not url and not mapping:+ try:+ req = urllib.request.Request(self.TITLEDB_URL, headers={'User-Agent': 'NX2Apple/1.1'})+ with urllib.request.urlopen(req, timeout=15) as resp:+ raw = json.loads(resp.read().decode('utf-8', errors='replace'))+ if isinstance(raw, dict):+ for entry in raw.values():+ if isinstance(entry, dict):+ etid = str(entry.get('id') or '').upper()+ burl = str(entry.get('bannerUrl') or '')+ if len(etid) == 16 and burl.startswith('http'):+ mapping[etid] = burl+ self.banners_dir.mkdir(parents=True, exist_ok=True)+ index_file.write_text(json.dumps(mapping), encoding='utf-8')+ url = mapping.get(tid)+ except Exception:+ return++ if not url:+ return+ try:+ req = urllib.request.Request(url, headers={'User-Agent': 'NX2Apple/1.1'})+ with urllib.request.urlopen(req, timeout=15) as resp:+ data = resp.read()+ if len(data) > 1024:+ self.banners_dir.mkdir(parents=True, exist_ok=True)+ dest = self.banners_dir / f'{tid}.jpg'+ dest.write_bytes(data)+ if self.on_updated:+ self.on_updated(tid)+ except Exception:+ pass+++# ---------------------------------------------------------------------------+# BuildFolder Space Measurement & Cleanup (mirrors FreeSpace.swift)+# ---------------------------------------------------------------------------++@dataclass+class BuildFolderItem:+ part: str # 'extracted', 'shaders', 'oldShaders', 'xcode', 'caches'+ bytes: int+ paths: list[str]+++@dataclass+class BuildFolderReport:+ folder: str+ items: list[BuildFolderItem]+ kept_bytes: int++ @property+ def total_freeable(self) -> int:+ # oldShaders is a subset of shaders+ return sum(i.bytes for i in self.items if i.part != 'oldShaders')+++class BuildFolder:+ PART_ORDER = ['extracted', 'shaders', 'oldShaders', 'xcode', 'caches']++ @staticmethod+ def size(path: str) -> int:+ if not path or not os.path.exists(path):+ return 0+ if os.path.isfile(path) or os.path.islink(path):+ try:+ return os.path.getsize(path)+ except OSError:+ return 0+ total = 0+ for root, _, files in os.walk(path):+ for f in files:+ fp = os.path.join(root, f)+ try:+ if not os.path.islink(fp):+ total += os.path.getsize(fp)+ except OSError:+ pass+ return total++ @staticmethod+ def location(game: LibraryGame) -> str | None:+ w = game.work_dir+ if w and os.path.isdir(w):+ return w+ return None++ @staticmethod+ def inspect(folder: str, title_id: str) -> BuildFolderReport:+ if not folder or not os.path.isdir(folder):+ return BuildFolderReport(folder=folder or '', items=[], kept_bytes=0)++ tid = title_id.upper()+ extracted_paths: list[str] = []+ shader_paths: list[str] = []+ old_shader_paths: list[str] = []+ xcode_paths: list[str] = []+ cache_paths: list[str] = []+ kept_paths: list[str] = []++ tid_dir = os.path.join(folder, tid)+ if os.path.isdir(tid_dir):+ extracted_paths.append(tid_dir)++ for sub in ('shaders', 'shader_cache', 'ios_shaders', 'mac_shaders'):+ p = os.path.join(folder, sub)+ if os.path.exists(p):+ shader_paths.append(p)+ # Look for older shader chain directories inside+ if os.path.isdir(p):+ try:+ chains = [+ os.path.join(p, d)+ for d in os.listdir(p)+ if d.startswith('b-') and os.path.isdir(os.path.join(p, d))+ ]+ if len(chains) > 1:+ chains.sort(key=lambda x: os.path.getmtime(x))+ old_shader_paths.extend(chains[:-1])+ except OSError:+ pass++ for sub in ('ios_xcode', 'xcode', 'app_build', 'build'):+ p = os.path.join(folder, sub)+ if os.path.exists(p):+ xcode_paths.append(p)++ known = {tid, 'shaders', 'shader_cache', 'ios_shaders', 'mac_shaders', 'ios_xcode', 'xcode', 'app_build', 'build'}+ kept_names = {'run', 'saves', 'build.log', 'game.tsv'}+ try:+ for name in os.listdir(folder):+ if name in known:+ continue+ full = os.path.join(folder, name)+ if name in kept_names or name.endswith('.log') or name.endswith('.tsv') or name.endswith('.nsp'):+ kept_paths.append(full)+ else:+ cache_paths.append(full)+ except OSError:+ pass++ items: list[BuildFolderItem] = []+ for part, plist in (+ ('extracted', extracted_paths),+ ('shaders', shader_paths),+ ('oldShaders', old_shader_paths),+ ('xcode', xcode_paths),+ ('caches', cache_paths),+ ):+ b = sum(BuildFolder.size(p) for p in plist)+ if b > 0:+ items.append(BuildFolderItem(part=part, bytes=b, paths=plist))++ kept_bytes = sum(BuildFolder.size(p) for p in kept_paths)+ return BuildFolderReport(folder=folder, items=items, kept_bytes=kept_bytes)++ @staticmethod+ def remove(report: BuildFolderReport, selected_parts: set[str]) -> tuple[int, list[str]]:+ parts = set(selected_parts)+ if 'shaders' in parts:+ parts.discard('oldShaders')+ freed = 0+ failed: list[str] = []+ for item in report.items:+ if item.part not in parts:+ continue+ for p in item.paths:+ if not os.path.exists(p):+ continue+ sz = BuildFolder.size(p)+ try:+ if os.path.isdir(p) and not os.path.islink(p):+ shutil.rmtree(p)+ else:+ os.remove(p)+ freed += sz+ except OSError:+ failed.append(p)+ return freed, failed+++# ---------------------------------------------------------------------------+# GameDeletion (mirrors GameDeletion.swift)+# ---------------------------------------------------------------------------++@dataclass+class GameDeletionItem:+ kind: str # 'macApp', 'ipa', 'iosApp', 'archive', 'shellFramework', 'buildFolder', 'log', 'saves'+ paths: list[str]+ bytes: int = 0+++@dataclass+class GameDeletionPlan:+ title_id: str+ items: list[GameDeletionItem]+ saves: GameDeletionItem | None = None++ @staticmethod+ def plan(game: LibraryGame, measure: bool = True) -> GameDeletionPlan:+ items: list[GameDeletionItem] = []+ if game.has_app:+ items.append(GameDeletionItem('macApp', [game.app_path]))+ if game.has_ipa:+ items.append(GameDeletionItem('ipa', [game.ipa_path]))+ if game.has_archive and os.path.basename(game.archive_path.rstrip('/\\')).upper() == game.title_id.upper():+ items.append(GameDeletionItem('archive', [game.archive_path]))++ bf = BuildFolder.location(game)+ if bf:+ try:+ sub_paths = [+ os.path.join(bf, name)+ for name in sorted(os.listdir(bf))+ if name != 'run'+ ]+ except OSError:+ sub_paths = []+ if sub_paths:+ items.append(GameDeletionItem('buildFolder', sub_paths))++ saves_paths: list[str] = []+ if bf and os.path.exists(os.path.join(bf, 'run')):+ saves_paths.append(os.path.join(bf, 'run'))++ saves_item = GameDeletionItem('saves', saves_paths) if saves_paths else None+ if measure:+ for it in items:+ it.bytes = sum(BuildFolder.size(p) for p in it.paths)+ if saves_item:+ saves_item.bytes = sum(BuildFolder.size(p) for p in saves_item.paths)++ return GameDeletionPlan(title_id=game.title_id, items=items, saves=saves_item)++ def run(self, delete_saves: bool = False) -> list[str]:+ failed: list[str] = []+ all_items = list(self.items)+ if delete_saves and self.saves:+ all_items.append(self.saves)+ for it in all_items:+ for p in it.paths:+ if not os.path.exists(p):+ continue+ try:+ if os.path.isdir(p) and not os.path.islink(p):+ shutil.rmtree(p)+ else:+ os.remove(p)+ except OSError:+ failed.append(p)+ return failed+++# ---------------------------------------------------------------------------+# DriveCopy (mirrors DriveCopy.swift)+# ---------------------------------------------------------------------------++class DriveCopy:+ FAT32_LIMIT = 4_294_967_295++ @staticmethod+ def collect_archive_files(archive_dir: str) -> dict[str, int]:+ out: dict[str, int] = {}+ if not archive_dir or not os.path.isdir(archive_dir):+ return out+ for root, _, files in os.walk(archive_dir):+ for f in files:+ if f.startswith('.'):+ continue+ full = os.path.join(root, f)+ rel = os.path.relpath(full, archive_dir).replace('\\', '/')+ try:+ out[rel] = os.path.getsize(full)+ except OSError:+ pass+ return out++ @staticmethod+ def free_space(folder: str) -> int:+ probe = folder+ while probe and not os.path.exists(probe):+ parent = os.path.dirname(probe)+ if parent == probe:+ break+ probe = parent+ try:+ return shutil.disk_usage(probe or '.').free+ except OSError:+ return 0++ @staticmethod+ def copy_to_folder(+ archive_dir: str,+ dest_root: str,+ title_id: str,+ progress_cb: Callable[[int, int], None] | None = None,+ ) -> tuple[bool, str]:+ files = DriveCopy.collect_archive_files(archive_dir)+ if not files:+ return False, 'No game data files found'+ dest_dir = os.path.join(dest_root, title_id.upper())+ total = sum(files.values())+ free = DriveCopy.free_space(dest_root)+ if free > 0 and total > free:+ return False, f'Not enough space ({format_bytes(total)} needed, {format_bytes(free)} free)'+ done = 0+ if progress_cb:+ progress_cb(0, total)+ try:+ for rel, sz in sorted(files.items()):+ src = os.path.join(archive_dir, rel)+ dst = os.path.join(dest_dir, rel)+ os.makedirs(os.path.dirname(dst), exist_ok=True)+ if os.path.isfile(dst) and os.path.getsize(dst) == sz:+ done += sz+ if progress_cb:+ progress_cb(done, total)+ continue+ partial = dst + '.partial'+ with open(src, 'rb') as fin, open(partial, 'wb') as fout:+ while True:+ buf = fin.read(4 * 1024 * 1024)+ if not buf:+ break+ fout.write(buf)+ done += len(buf)+ if progress_cb:+ progress_cb(done, total)+ if os.path.exists(dst):+ os.remove(dst)+ os.replace(partial, dst)+ return True, dest_dir+ except OSError as e:+ return False, str(e)diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pyindex 366c6e81..65ccfa38 100644--- a/frontend-qt/nspb_qt/model.py+++ b/frontend-qt/nspb_qt/model.py@@ -19,6 +19,7 @@ from . import build_failure as bffrom . import enginefrom . import input_stagingfrom . import inputs+from . import library as libfrom . import platform_util as pufrom .i18n import Langfrom .l10n import t@@ -79,6 +80,7 @@ class Model(QObject):runningChanged = Signal(bool)finished = Signal(bool, str) # ok, noteappUpdateFound = Signal(str, str) # tag, url+ libraryChanged = Signal()#: Set by the window: asks for a folder (QFileDialog lives in the UI layer) and returns the#: path, or '' when the user cancelled. `pick_dep_folder` calls it, so the model stays UI-free.@@ -116,6 +118,10 @@ class Model(QObject):self.archive_path = ''self.mac_app_path = ''self.target = 'ios' # 'ios' (an IPA) or 'mac-app' (a double-clickable Mac app; macOS only)+ self.bc_on_cpu = False+ self.ipa_kind = 'shared' # 'shared' (shell.ipaShared) or 'oneGame' (shell.ipaOneGame)+ self.library = lib.GameLibrary()+ self.artwork = lib.ArtworkStore(on_updated=lambda _tid: self._emit_library_changed())self.repo_busy = Falseself.repo_behind: int | None = Noneself.repo_status = ''@@ -157,6 +163,40 @@ class Model(QObject):self.repoChanged.emit()self.depsChanged.emit()+ def set_lang(self, lang: Lang) -> None:+ self.lang = lang+ self.repoChanged.emit()+ self.depsChanged.emit()++ @Slot()+ def _emit_library_changed(self) -> None:+ try:+ if QThread.currentThread() is self.thread():+ self.libraryChanged.emit()+ else:+ QMetaObject.invokeMethod(self, '_emit_library_changed', Qt.QueuedConnection)+ except RuntimeError:+ pass++ def load_game_from_library(self, game: lib.LibraryGame) -> None:+ base = (game.inputs.get('base') or [''])[0]+ if base and inputs.is_game_folder_candidate(base):+ self.take_game_folder(base)+ else:+ self.leave_game_folder()+ self.base_path = base+ self.update_path = (game.inputs.get('update') or [''])[0]+ self.dlc_paths = list(game.inputs.get('dlc') or [])+ keys = (game.inputs.get('keys') or [''])[0]+ if keys:+ self.keys_path = keys+ if game.output_dir:+ self.out_dir = game.output_dir+ self.ipa_path = game.ipa_path if game.has_ipa else ''+ self.archive_path = game.archive_path if game.has_archive else ''+ self.library.select(game.title_id)+ self.repoChanged.emit()+# ---- repository@staticmethod@@ -273,13 +313,18 @@ class Model(QObject):"""try:self._check_deps()+ except RuntimeError:+ returnexcept Exception as e: # noqa: BLE001 - a check must never be fatalimport tracebackself.log(f'dependency check failed: {type(e).__name__}: {e}\n')self.log(traceback.format_exc() + '\n')self.deps = []self.deps_checked = True- self.depsChanged.emit()+ try:+ self.depsChanged.emit()+ except RuntimeError:+ passdef _python_row(self, py: str, py_ok: bool, py_ver: str) -> Dep:"""The interpreter row: fine, missing packages, missing interpreter, or too old.@@ -387,7 +432,10 @@ class Model(QObject):self.python_path, self.python_ok, self.python_ver = py, py_ok, py_verself.dotnet_path, self.dotnet_ok = dn, dn_okself.deps_checked = True- self.depsChanged.emit()+ try:+ self.depsChanged.emit()+ except RuntimeError:+ pass@propertydef all_deps_ok(self) -> bool:@@ -1163,11 +1211,14 @@ class Model(QObject):log file received everything. QMetaObject.invokeMethod with QueuedConnection hands thecall to the main thread explicitly, which works regardless of how the slot is connected."""- if QThread.currentThread() is self.thread():- self.logAppended.emit(s)- else:- QMetaObject.invokeMethod(self, '_emit_log', Qt.QueuedConnection,- Q_ARG(str, s))+ try:+ if QThread.currentThread() is self.thread():+ self.logAppended.emit(s)+ else:+ QMetaObject.invokeMethod(self, '_emit_log', Qt.QueuedConnection,+ Q_ARG(str, s))+ except RuntimeError:+ returnif getattr(self, 'log_path', None):try:with open(self.log_path, 'a', encoding='utf-8', errors='replace') as f:@@ -1357,9 +1408,29 @@ class Model(QObject):self.ipa_path = str(Path(self.out_dir, f'{tid_hex}.ipa'))args += ['-o', self.ipa_path]self.effective_work_dir = work_dir if has_work_dir else str(Path(base_dir if folder is not None else input_dir, f'{tid_hex}_build'))+ if self.bc_on_cpu and not mac_app:+ try:+ Path(self.effective_work_dir).mkdir(parents=True, exist_ok=True)+ env_file = Path(self.effective_work_dir, '_env.txt')+ env_file.write_text('DM_TEX_BC_CPU=1\n', encoding='utf-8')+ args += ['--env-file', str(env_file)]+ self.log(self.t('msg.bcOn') + '\n')+ except OSError as e:+ self.log(self.t('msg.bcEnvFailed', str(e)) + '\n')flag = self.override.take() # for this build only: the next one asks againargs = bf.arguments(args, flag)+ if self.base_path:+ self.library.remember_inputs(+ base_path=self.base_path,+ update_path=self.update_path,+ dlc_paths=self.dlc_paths,+ keys_path=self.keys_path,+ output_dir=self.out_dir,+ repo_path=self.engine_path,+ )+ self._emit_library_changed()+self.running = Trueself.runningChanged.emit(True)self.stages = []@@ -1373,6 +1444,8 @@ class Model(QObject):self.log(self.t('msg.running', py + ' ' + ' '.join(args)) + '\n')env = pu.child_env()+ if self.ipa_kind == 'oneGame' and not mac_app:+ env['DM_FULL_ROMFS'] = '1'droot = pu.dotnet_root(self.dotnet_path) if self.dotnet_ok else Noneif droot:env['DOTNET_ROOT'] = droot@@ -1416,7 +1489,11 @@ class Model(QObject):exists = bool(self.mac_app_path) and Path(self.mac_app_path).exists()self.finished.emit(exists, self.t('target.macDone' if exists else 'target.missingApp'))elif ok:- self.pack_archive()+ if self.ipa_kind == 'oneGame':+ self._record_library_ios_completion()+ self.finished.emit(True, self.t('shell.oneGameDone', self.ipa_path))+ else:+ self.pack_archive()else:if self.stages:self.stages[-1].state = 'failed'@@ -1582,11 +1659,35 @@ class Model(QObject):if self.stages:self.stages[-1].state = 'done' if ok else 'failed'self.archive_path = dest if ok else ''+ if ok:+ self._record_library_ios_completion()self.stagesChanged.emit()self.finished.emit(ok, '' if ok else self.t('msg.archiveFailed'))threading.Thread(target=work_, daemon=True).start()+ def _record_library_ios_completion(self) -> None:+ inputs_map: dict[str, list[str]] = {}+ if self.base_path:+ inputs_map['base'] = [self.base_path]+ if self.update_path:+ inputs_map['update'] = [self.update_path]+ if self.dlc_paths:+ inputs_map['dlc'] = list(self.dlc_paths)+ if self.keys_path:+ inputs_map['keys'] = [self.keys_path]+ g = self.library.record_completed_ios(+ ipa_path=self.ipa_path,+ archive_path=self.archive_path,+ base_path=self.base_path,+ output_dir=self.out_dir,+ inputs=inputs_map,+ repo_path=self.engine_path,+ )+ if g:+ self.artwork.request_banner_async(g.title_id)+ self._emit_library_changed()+@staticmethoddef _title_id(nsp: str) -> int | None:"""The title ID from a dump's file name: bracketed [0100…] or a bare 16-digit ID."""diff --git a/frontend-qt/nspb_qt/sheets.py b/frontend-qt/nspb_qt/sheets.pynew file mode 100644index 00000000..b3fcfc02--- /dev/null+++ b/frontend-qt/nspb_qt/sheets.py@@ -0,0 +1,703 @@+"""Modal dialogs (FreeSpace, DeleteGame, Cheats, Onboarding) mirroring the Mac SwiftUI sheets."""+from __future__ import annotations++import os+import shutil+from pathlib import Path+from typing import TYPE_CHECKING++from PySide6.QtCore import Qt+from PySide6.QtWidgets import (+ QDialog,+ QFileDialog,+ QFrame,+ QHBoxLayout,+ QLabel,+ QMessageBox,+ QPushButton,+ QScrollArea,+ QVBoxLayout,+ QWidget,+)++from . import features as feat+from . import library as lib+from . import platform_util as pu+from . import style+from .widgets import CardGroup, LauncherSwitch, StatusDot++if TYPE_CHECKING:+ from .model import Model+++class FreeSpaceDialog(QDialog):+ """Build-folder cleanup dialog mirroring FreeSpaceSheet in FreeSpace.swift."""++ def __init__(self, model: 'Model', game: lib.LibraryGame, parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self.m = model+ self.game = game+ self.setWindowTitle(f"{self.m.t('free.title')} — {game.name}")+ self.setMinimumSize(580, 460)+ self.setStyleSheet(style.STYLESHEET)++ folder = lib.BuildFolder.location(game) or (game.work_dir or '')+ self.report = lib.BuildFolder.inspect(folder, game.title_id)+ self.selected_parts: set[str] = {+ it.part for it in self.report.items if it.part in ('extracted', 'oldShaders', 'xcode', 'caches')+ }+ self._switches: dict[str, LauncherSwitch] = {}++ lay = QVBoxLayout(self)+ lay.setContentsMargins(24, 22, 24, 20)+ lay.setSpacing(14)++ title = QLabel(f"{self.m.t('free.title')} · {game.name}")+ title.setStyleSheet('font-size: 20px; font-weight: 800;')+ lay.addWidget(title)++ note = QLabel(self.m.t('free.note'))+ note.setObjectName('muted')+ note.setWordWrap(True)+ lay.addWidget(note)++ if not self.report.items:+ empty_card = CardGroup()+ r = QWidget()+ rl = QHBoxLayout(r)+ rl.setContentsMargins(18, 18, 18, 18)+ lbl = QLabel(self.m.t('free.empty'))+ lbl.setObjectName('muted')+ rl.addWidget(lbl)+ empty_card.add_row(r)+ lay.addWidget(empty_card)+ else:+ group = CardGroup()+ for idx, item in enumerate(self.report.items):+ if idx > 0:+ group.add_divider()+ row = QWidget()+ rl = QHBoxLayout(row)+ rl.setContentsMargins(18, 12, 18, 12)+ rl.setSpacing(12)++ sw = LauncherSwitch(checked=(item.part in self.selected_parts))+ sw.toggled.connect(lambda checked, p=item.part: self._on_toggle(p, checked))+ self._switches[item.part] = sw+ rl.addWidget(sw)++ col = QVBoxLayout()+ col.setSpacing(2)+ p_title = QLabel(self.m.t('free.part.' + item.part))+ p_title.setObjectName('rowTitle')+ p_cost = QLabel(self.m.t('free.cost.' + item.part))+ p_cost.setObjectName('muted')+ p_cost.setWordWrap(True)+ col.addWidget(p_title)+ col.addWidget(p_cost)+ rl.addLayout(col, 1)++ sz_lbl = QLabel(lib.format_bytes(item.bytes))+ sz_lbl.setObjectName('mono')+ rl.addWidget(sz_lbl)+ group.add_row(row)++ if self.report.kept_bytes > 0:+ group.add_divider()+ krow = QWidget()+ krl = QHBoxLayout(krow)+ krl.setContentsMargins(18, 12, 18, 12)+ kcol = QVBoxLayout()+ kcol.setSpacing(2)+ kt = QLabel(self.m.t('free.kept'))+ kt.setObjectName('rowTitle')+ kn = QLabel(self.m.t('free.keptNote'))+ kn.setObjectName('muted')+ kcol.addWidget(kt)+ kcol.addWidget(kn)+ krl.addLayout(kcol, 1)+ ksz = QLabel(lib.format_bytes(self.report.kept_bytes))+ ksz.setObjectName('mono')+ krl.addWidget(ksz)+ group.add_row(krow)++ lay.addWidget(group)++ lay.addStretch(1)++ foot = QHBoxLayout()+ self.sel_label = QLabel('')+ self.sel_label.setObjectName('muted')+ foot.addWidget(self.sel_label)+ foot.addStretch(1)++ self.remove_btn = QPushButton(self.m.t('free.remove'))+ self.remove_btn.setObjectName('danger')+ self.remove_btn.clicked.connect(self._do_remove)+ if not self.report.items:+ self.remove_btn.hide()+ foot.addWidget(self.remove_btn)++ done_btn = QPushButton(self.m.t('free.done'))+ done_btn.setObjectName('creamPill')+ done_btn.clicked.connect(self.accept)+ foot.addWidget(done_btn)+ lay.addLayout(foot)++ self._update_summary()++ def _on_toggle(self, part: str, checked: bool) -> None:+ if checked:+ self.selected_parts.add(part)+ else:+ self.selected_parts.discard(part)+ self._update_summary()++ def _selected_bytes(self) -> int:+ parts = set(self.selected_parts)+ if 'shaders' in parts:+ parts.discard('oldShaders')+ return sum(it.bytes for it in self.report.items if it.part in parts)++ def _update_summary(self) -> None:+ b = self._selected_bytes()+ self.sel_label.setText(self.m.t('free.selected', lib.format_bytes(b)))+ self.remove_btn.setEnabled(b > 0 and not self.m.running)++ def _do_remove(self) -> None:+ b = self._selected_bytes()+ if b <= 0:+ return+ ans = QMessageBox.question(+ self,+ self.m.t('free.confirm', lib.format_bytes(b)),+ self.m.t('free.confirmNote'),+ QMessageBox.Yes | QMessageBox.No,+ QMessageBox.No,+ )+ if ans != QMessageBox.Yes:+ return+ freed, failed = lib.BuildFolder.remove(self.report, self.selected_parts)+ if failed:+ self.sel_label.setText(self.m.t('free.failed', ', '.join(os.path.basename(p) for p in failed)))+ else:+ self.sel_label.setText(self.m.t('free.freed', lib.format_bytes(freed)))+ self.remove_btn.setEnabled(False)+++class DeleteGameDialog(QDialog):+ """Game deletion dialog mirroring DeleteGameSheet.swift."""++ def __init__(self, model: 'Model', game: lib.LibraryGame, parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self.m = model+ self.game = game+ self.confirmed = False+ self.setWindowTitle(self.m.t('delete.question', game.name))+ self.setMinimumSize(520, 380)+ self.setStyleSheet(style.STYLESHEET)++ self.plan = lib.GameDeletionPlan.plan(game, measure=True)+ self.delete_saves = False++ lay = QVBoxLayout(self)+ lay.setContentsMargins(24, 22, 24, 20)+ lay.setSpacing(14)++ title = QLabel(self.m.t('delete.question', game.name))+ title.setStyleSheet('font-size: 20px; font-weight: 800;')+ lay.addWidget(title)++ note = QLabel(self.m.t('delete.note') + ' ' + self.m.t('delete.sources'))+ note.setObjectName('muted')+ note.setWordWrap(True)+ lay.addWidget(note)++ part_labels = {+ 'macApp': self.m.t('delete.part.macApp'),+ 'ipa': self.m.t('delete.part.ipa'),+ 'iosApp': self.m.t('delete.part.iosApp'),+ 'archive': self.m.t('delete.part.archive'),+ 'shellFramework': self.m.t('delete.part.shellFramework'),+ 'buildFolder': self.m.t('delete.part.buildFolder'),+ 'log': self.m.t('delete.part.log'),+ }++ group = CardGroup()+ if not self.plan.items:+ r = QWidget()+ rl = QHBoxLayout(r)+ rl.setContentsMargins(18, 14, 18, 14)+ lbl = QLabel(self.m.t('delete.nothing'))+ lbl.setObjectName('muted')+ lbl.setWordWrap(True)+ rl.addWidget(lbl)+ group.add_row(r)+ else:+ for idx, it in enumerate(self.plan.items):+ if idx > 0:+ group.add_divider()+ r = QWidget()+ rl = QHBoxLayout(r)+ rl.setContentsMargins(18, 12, 18, 12)+ t_lbl = QLabel(part_labels.get(it.kind, it.kind))+ t_lbl.setObjectName('rowTitle')+ rl.addWidget(t_lbl, 1)+ s_lbl = QLabel(lib.format_bytes(it.bytes))+ s_lbl.setObjectName('mono')+ rl.addWidget(s_lbl)+ group.add_row(r)+ lay.addWidget(group)++ if self.plan.saves:+ sgroup = CardGroup()+ sr = QWidget()+ srl = QHBoxLayout(sr)+ srl.setContentsMargins(18, 12, 18, 12)+ scol = QVBoxLayout()+ st = QLabel(self.m.t('delete.saves'))+ st.setObjectName('rowTitle')+ self.save_note_lbl = QLabel(self.m.t('delete.savesOff'))+ self.save_note_lbl.setObjectName('muted')+ scol.addWidget(st)+ scol.addWidget(self.save_note_lbl)+ srl.addLayout(scol, 1)+ ssz = QLabel(lib.format_bytes(self.plan.saves.bytes))+ ssz.setObjectName('mono')+ srl.addWidget(ssz)+ sw = LauncherSwitch(False)+ sw.toggled.connect(self._on_saves_toggled)+ srl.addWidget(sw)+ sgroup.add_row(sr)+ lay.addWidget(sgroup)++ lay.addStretch(1)++ foot = QHBoxLayout()+ foot.addStretch(1)+ cancel_btn = QPushButton(self.m.t('fail.confirm.cancel'))+ cancel_btn.clicked.connect(self.reject)+ foot.addWidget(cancel_btn)++ self.confirm_btn = QPushButton(self.m.t('delete.confirm'))+ self.confirm_btn.setObjectName('danger')+ self.confirm_btn.setEnabled(not self.m.running)+ self.confirm_btn.clicked.connect(self._do_delete)+ foot.addWidget(self.confirm_btn)+ lay.addLayout(foot)++ def _on_saves_toggled(self, checked: bool) -> None:+ self.delete_saves = checked+ if hasattr(self, 'save_note_lbl'):+ self.save_note_lbl.setText(self.m.t('delete.savesOn' if checked else 'delete.savesOff'))+ self.confirm_btn.setText(self.m.t('delete.confirmSaves' if checked else 'delete.confirm'))++ def _do_delete(self) -> None:+ failed = self.plan.run(delete_saves=self.delete_saves)+ if failed:+ QMessageBox.warning(self, self.m.t('library.error'), self.m.t('delete.failed', '\n'.join(failed)))+ self.m.library.remove(self.game.title_id)+ self.m._emit_library_changed()+ self.confirmed = True+ self.accept()+++class CheatsDialog(QDialog):+ """Atmosphere cheat manager dialog mirroring CheatsView.swift."""++ def __init__(self, model: 'Model', game: lib.LibraryGame, parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self.m = model+ self.game = game+ self.setWindowTitle(f"{self.m.t('cheats.title')} — {game.name}")+ self.setMinimumSize(620, 520)+ self.setStyleSheet(style.STYLESHEET)++ self.folder = feat.CheatFiles.cheats_dir(+ game.title_id,+ work_dir=game.work_dir,+ archive_dir=game.archive_path if game.has_archive else None,+ )+ self.build_id = feat.CheatFiles.read_build_id(+ work_dir=game.work_dir,+ ipa_path=game.ipa_path if game.has_ipa else None,+ title_id=game.title_id,+ )++ lay = QVBoxLayout(self)+ lay.setContentsMargins(24, 22, 24, 20)+ lay.setSpacing(14)++ head = QHBoxLayout()+ title = QLabel(f"{self.m.t('cheats.title')} · {game.name}")+ title.setStyleSheet('font-size: 20px; font-weight: 800;')+ head.addWidget(title)+ head.addStretch(1)++ import_btn = QPushButton(self.m.t('cheats.import'))+ import_btn.clicked.connect(self._import_cheats)+ head.addWidget(import_btn)++ open_btn = QPushButton(self.m.t('cheats.showFolder'))+ open_btn.clicked.connect(self._open_folder)+ head.addWidget(open_btn)+ lay.addLayout(head)++ ios_note = QLabel(self.m.t('cheats.iosNote'))+ ios_note.setObjectName('muted')+ ios_note.setWordWrap(True)+ lay.addWidget(ios_note)++ # Master switch & Build ID card+ top_group = CardGroup()+ mrow = QWidget()+ mrl = QHBoxLayout(mrow)+ mrl.setContentsMargins(18, 12, 18, 12)+ mcol = QVBoxLayout()+ mt = QLabel(self.m.t('cheats.master'))+ mt.setObjectName('rowTitle')+ mn = QLabel(self.m.t('cheats.note'))+ mn.setObjectName('muted')+ mcol.addWidget(mt)+ mcol.addWidget(mn)+ mrl.addLayout(mcol, 1)+ self.master_sw = LauncherSwitch(True)+ self.master_sw.toggled.connect(self._on_master_toggled)+ mrl.addWidget(self.master_sw)+ top_group.add_row(mrow)+ top_group.add_divider()++ brow = QWidget()+ brl = QHBoxLayout(brow)+ brl.setContentsMargins(18, 12, 18, 12)+ bt = QLabel(self.m.t('cheats.buildLabel'))+ bt.setObjectName('rowTitle')+ brl.addWidget(bt, 1)+ bval = QLabel(self.build_id or self.m.t('cheats.buildUnknown'))+ bval.setObjectName('mono')+ brl.addWidget(bval)+ top_group.add_row(brow)+ lay.addWidget(top_group)++ self.status_lbl = QLabel('')+ self.status_lbl.setObjectName('muted')+ lay.addWidget(self.status_lbl)++ self.scroll = QScrollArea()+ self.scroll.setWidgetResizable(True)+ self.list_host = QWidget()+ self.list_layout = QVBoxLayout(self.list_host)+ self.list_layout.setContentsMargins(0, 0, 0, 0)+ self.list_layout.setSpacing(12)+ self.scroll.setWidget(self.list_host)+ lay.addWidget(self.scroll, 1)++ foot = QHBoxLayout()+ foot.addStretch(1)+ done_btn = QPushButton(self.m.t('free.done'))+ done_btn.setObjectName('creamPill')+ done_btn.clicked.connect(self.accept)+ foot.addWidget(done_btn)+ lay.addLayout(foot)++ self._reload()++ def _reload(self) -> None:+ while self.list_layout.count():+ it = self.list_layout.takeAt(0)+ if it.widget():+ it.widget().deleteLater()++ master_on, files = feat.CheatFiles.load_folder(self.folder, self.game.title_id)+ self.master_sw.setChecked(master_on)++ if not files:+ empty = CardGroup()+ r = QWidget()+ rl = QHBoxLayout(r)+ rl.setContentsMargins(18, 18, 18, 18)+ lbl = QLabel(self.m.t('cheats.empty'))+ lbl.setObjectName('muted')+ lbl.setWordWrap(True)+ rl.addWidget(lbl)+ empty.add_row(r)+ self.list_layout.addWidget(empty)+ self.list_layout.addStretch(1)+ return++ for bf in files:+ is_curr = (self.build_id is None) or (bf.build_id.upper() == self.build_id.upper())+ badge = self.m.t('cheats.thisBuild') if is_curr else self.m.t('cheats.otherBuild')+ grp = CardGroup(title=f'{bf.build_id} · {badge}')+ for idx, ch in enumerate(bf.cheats):+ if idx > 0:+ grp.add_divider()+ row = QWidget()+ rl = QHBoxLayout(row)+ rl.setContentsMargins(18, 10, 18, 10)+ col = QVBoxLayout()+ t_lbl = QLabel(ch.name)+ t_lbl.setObjectName('rowTitle')+ col.addWidget(t_lbl)+ if not ch.is_valid:+ sub = QLabel(self.m.t('cheats.broken'))+ sub.setStyleSheet(f'color: {style.RED}; font-size: 11.5px;')+ col.addWidget(sub)+ elif ch.is_master:+ sub = QLabel(self.m.t('cheats.alwaysOn'))+ sub.setObjectName('muted')+ col.addWidget(sub)+ elif ch.runs_once:+ sub = QLabel(self.m.t('cheats.once'))+ sub.setObjectName('muted')+ col.addWidget(sub)+ rl.addLayout(col, 1)++ if ch.is_valid and not ch.is_master and is_curr:+ sw = LauncherSwitch(ch.name in bf.enabled)+ sw.toggled.connect(+ lambda checked, b=bf.build_id, cname=ch.name: feat.CheatFiles.set_cheat_enabled(+ self.folder, b, cname, checked+ )+ )+ rl.addWidget(sw)+ grp.add_row(row)+ self.list_layout.addWidget(grp)+ self.list_layout.addStretch(1)++ def _on_master_toggled(self, checked: bool) -> None:+ feat.CheatFiles.set_master(self.folder, self.game.title_id, checked)++ def _import_cheats(self) -> None:+ files, _ = QFileDialog.getOpenFileNames(+ self,+ self.m.t('cheats.pickMessage'),+ '',+ 'Cheat files (*.txt)',+ )+ if not files:+ return+ cnt, rejected = feat.CheatFiles.import_paths(files, self.folder, self.game.title_id)+ if cnt > 0:+ self.status_lbl.setText(self.m.t('cheats.imported', cnt))+ elif rejected:+ self.status_lbl.setText(self.m.t('cheats.notNamed', ', '.join(rejected)))+ else:+ self.status_lbl.setText(self.m.t('cheats.nothingFound'))+ self._reload()++ def _open_folder(self) -> None:+ os.makedirs(self.folder, exist_ok=True)+ pu.reveal(self.folder)+++class OnboardingDialog(QDialog):+ """First-run setup assistant mirroring OnboardingView.swift."""++ def __init__(self, model: 'Model', parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self.m = model+ self.step = 0+ self.setWindowTitle('NX2Apple Setup')+ self.setMinimumSize(640, 480)+ self.setStyleSheet(style.STYLESHEET)++ lay = QVBoxLayout(self)+ lay.setContentsMargins(32, 28, 32, 24)+ lay.setSpacing(16)++ self.step_badge = QLabel('')+ self.step_badge.setObjectName('muted')+ lay.addWidget(self.step_badge)++ self.head_title = QLabel('')+ self.head_title.setStyleSheet('font-size: 28px; font-weight: 800;')+ self.head_title.setWordWrap(True)+ lay.addWidget(self.head_title)++ self.head_note = QLabel('')+ self.head_note.setObjectName('pageNote')+ self.head_note.setWordWrap(True)+ lay.addWidget(self.head_note)++ self.body_host = QWidget()+ self.body_layout = QVBoxLayout(self.body_host)+ self.body_layout.setContentsMargins(0, 8, 0, 8)+ self.body_layout.setSpacing(12)+ lay.addWidget(self.body_host, 1)++ foot = QHBoxLayout()+ self.later_btn = QPushButton(self.m.t('onboarding.later'))+ self.later_btn.setObjectName('ghost')+ self.later_btn.clicked.connect(self.reject)+ foot.addWidget(self.later_btn)+ foot.addStretch(1)++ self.back_btn = QPushButton(self.m.t('onboarding.back'))+ self.back_btn.clicked.connect(self._prev_step)+ foot.addWidget(self.back_btn)++ self.next_btn = QPushButton(self.m.t('onboarding.continue'))+ self.next_btn.setObjectName('creamPill')+ self.next_btn.clicked.connect(self._next_step)+ foot.addWidget(self.next_btn)+ lay.addLayout(foot)++ self._render_step()++ def _clear_body(self) -> None:+ while self.body_layout.count():+ it = self.body_layout.takeAt(0)+ if it.widget():+ it.widget().deleteLater()++ def _render_step(self) -> None:+ self._clear_body()+ self.step_badge.setText(self.m.t('onboarding.stepCount', self.step + 1, 4))+ self.back_btn.setVisible(self.step > 0)++ if self.step == 0:+ self.head_title.setText(self.m.t('onboarding.welcome.title'))+ self.head_note.setText(self.m.t('onboarding.welcome.note'))+ self.next_btn.setText(self.m.t('onboarding.start'))++ grp = CardGroup()+ free_gb = int(shutil.disk_usage(Path.home()).free // (1024 ** 3))+ r1 = QWidget()+ rl1 = QHBoxLayout(r1)+ rl1.setContentsMargins(18, 14, 18, 14)+ rl1.addWidget(StatusDot(style.GREEN if free_gb >= 15 else style.AMBER))+ c1 = QVBoxLayout()+ t1 = QLabel(self.m.t('onboarding.require.disk'))+ t1.setObjectName('rowTitle')+ n1 = QLabel(self.m.t('onboarding.require.diskNote', free_gb, 15))+ n1.setObjectName('muted')+ c1.addWidget(t1)+ c1.addWidget(n1)+ rl1.addLayout(c1, 1)+ grp.add_row(r1)+ grp.add_divider()++ r2 = QWidget()+ rl2 = QHBoxLayout(r2)+ rl2.setContentsMargins(18, 14, 18, 14)+ rl2.addWidget(StatusDot(style.GREEN))+ c2 = QVBoxLayout()+ t2 = QLabel(self.m.t('onboarding.require.files'))+ t2.setObjectName('rowTitle')+ n2 = QLabel(self.m.t('onboarding.require.filesNote'))+ n2.setObjectName('muted')+ c2.addWidget(t2)+ c2.addWidget(n2)+ rl2.addLayout(c2, 1)+ grp.add_row(r2)+ self.body_layout.addWidget(grp)++ elif self.step == 1:+ self.head_title.setText(self.m.t('onboarding.background.title'))+ self.head_note.setText(self.m.t('dep.title'))+ self.next_btn.setText(self.m.t('onboarding.continue'))++ grp = CardGroup()+ for idx, d in enumerate(self.m.deps[:5]):+ if idx > 0:+ grp.add_divider()+ r = QWidget()+ rl = QHBoxLayout(r)+ rl.setContentsMargins(18, 10, 18, 10)+ rl.addWidget(StatusDot(style.GREEN if d.ok else (style.AMBER if not d.required else style.RED)))+ tl = QLabel(self.m.t(d.title_key))+ tl.setObjectName('rowTitle')+ rl.addWidget(tl, 1)+ st = QLabel(self.m.t('onboarding.ready') if d.ok else self.m.t('onboarding.failed'))+ st.setObjectName('muted')+ rl.addWidget(st)+ grp.add_row(r)+ self.body_layout.addWidget(grp)++ if any(not d.ok and d.install for d in self.m.deps):+ ibtn = QPushButton(self.m.t('dep.installAll'))+ ibtn.clicked.connect(self.m.install_all_missing)+ self.body_layout.addWidget(ibtn)++ elif self.step == 2:+ self.head_title.setText(self.m.t('onboarding.keys.title'))+ self.head_note.setText(self.m.t('onboarding.keys.note'))+ self.next_btn.setText(self.m.t('onboarding.continue'))++ grp = CardGroup(footer=self.m.t('onboarding.keys.privacy'))+ r = QWidget()+ rl = QHBoxLayout(r)+ rl.setContentsMargins(18, 14, 18, 14)+ parsed = feat.KeyCheck.load_keys(self.m.keys_path) if self.m.keys_path else None+ valid = bool(parsed and len(parsed.get('header_key', '')) == 64)+ rl.addWidget(StatusDot(style.GREEN if valid else style.NEUTRAL_DOT))+ col = QVBoxLayout()+ kt = QLabel(self.m.t('onboarding.keys.valid') if valid else (self.m.t('onboarding.keys.invalid') if self.m.keys_path else self.m.t('onboarding.keys.empty')))+ kt.setObjectName('rowTitle')+ kn = QLabel(self.m.keys_path or self.m.t('data.notSelected'))+ kn.setObjectName('mono')+ col.addWidget(kt)+ col.addWidget(kn)+ rl.addLayout(col, 1)+ pick_btn = QPushButton(self.m.t('onboarding.choose'))+ pick_btn.clicked.connect(self._pick_keys)+ rl.addWidget(pick_btn)+ grp.add_row(r)+ self.body_layout.addWidget(grp)++ elif self.step == 3:+ self.head_title.setText(self.m.t('onboarding.games.title'))+ self.head_note.setText(self.m.t('onboarding.games.note'))+ self.next_btn.setText(self.m.t('onboarding.openLibrary'))++ grp = CardGroup()+ r = QWidget()+ rl = QHBoxLayout(r)+ rl.setContentsMargins(18, 14, 18, 14)+ folder = self.m.library.games_folder+ rl.addWidget(StatusDot(style.GREEN if folder else style.NEUTRAL_DOT))+ col = QVBoxLayout()+ gt = QLabel(self.m.t('onboarding.games.count', len(self.m.library.games)) if folder else self.m.t('library.folderTitle'))+ gt.setObjectName('rowTitle')+ gn = QLabel(folder or self.m.t('library.folderUnset'))+ gn.setObjectName('mono')+ col.addWidget(gt)+ col.addWidget(gn)+ rl.addLayout(col, 1)+ pick_btn = QPushButton(self.m.t('onboarding.choose'))+ pick_btn.clicked.connect(self._pick_games_folder)+ rl.addWidget(pick_btn)+ grp.add_row(r)+ self.body_layout.addWidget(grp)++ self.body_layout.addStretch(1)++ def _pick_keys(self) -> None:+ f, _ = QFileDialog.getOpenFileName(self, self.m.t('data.keys'), '', 'Keys (prod.keys *.keys *);;All files (*)')+ if f:+ self.m.keys_path = f+ self.m.repoChanged.emit()+ self._render_step()++ def _pick_games_folder(self) -> None:+ d = QFileDialog.getExistingDirectory(self, self.m.t('library.folderTitle'), self.m.library.games_folder or str(Path.home()))+ if d:+ self.m.library.set_games_folder(d, repo_path=self.m.engine_path, default_keys=self.m.keys_path)+ for g in self.m.library.games:+ self.m.artwork.request_banner_async(g.title_id)+ self.m._emit_library_changed()+ self._render_step()++ def _prev_step(self) -> None:+ if self.step > 0:+ self.step -= 1+ self._render_step()++ def _next_step(self) -> None:+ if self.step < 3:+ self.step += 1+ self._render_step()+ else:+ self.m.settings_set('onboardingComplete', True)+ self.accept()diff --git a/frontend-qt/nspb_qt/style.py b/frontend-qt/nspb_qt/style.pyindex 5dff7e5c..53694ddb 100644--- a/frontend-qt/nspb_qt/style.py+++ b/frontend-qt/nspb_qt/style.py@@ -1,47 +1,54 @@-"""Visual language: the Mac launcher's near-black look with a cream accent, in Qt style sheets.--The palette, the Manrope typeface and the control shapes follow the SwiftUI launcher-(`frontend/Sources/NXLauncher/LauncherPalette.swift` and `frontend/Sources/NXLauncher/LauncherStyles.swift`),-so the two front ends stay recognisable as the same product. The translucent white fills of the-Mac controls are pre-mixed here into opaque colours, since a Qt style sheet has no cheap overlay.-"""+"""Palette and stylesheet mirroring the Mac SwiftUI launcher (LauncherStyles.swift & LauncherCard.swift)."""from __future__ import annotationsimport osimport sys-# The palette: LauncherPalette's values as hex.-BG = '#0e0e0f' # window background, rgb(0.055, 0.055, 0.06)-CARD = '#1a1a1c' # a card's fill (the launcher's "surface"), rgb(0.10, 0.10, 0.11)-CARD_EDGE = '#2c2c2e' # a card's hairline: white at 8% over the surface-TEXT = '#ebebeb' # white at 92%, as the launcher's button labels-MUTED = '#91949c' # the launcher's "unbuilt" grey-PATH = '#6f7178' # a filesystem path in a dependency row: dimmer than prose, so the eye- # reads the hint beside it first (the report asked for exactly this)-HINT = '#a8aab0' # a hint or explanation: a step brighter than the path it sits next to-CREAM = '#fff0d6' # the accent: primary buttons, switches, the chosen choice-GREEN = '#40d678' # ok / done: the launcher's "ready"-ORANGE = '#ffc73d' # attention: the launcher's "building"-RED = '#ff6b66' # missing / failed: the launcher's destructive red+BG = '#000000'+SURFACE = '#141416'+CARD = '#1a1a1c'+CARD_HOVER = '#222225'+BORDER = '#2c2c2e'+CARD_EDGE = BORDER+DIVIDER = '#232326'++TEXT = '#f5f5f7'+MUTED = '#9e9ea6'+FAINT = '#73737a'+PATH = '#6f7178'+HINT = '#a8aab0'++ACCENT = '#fff0d6' # LauncherAccent.cream: rgb(1.0, 0.94, 0.84)+CREAM = ACCENT+ACCENT_HOVER = '#fff6e6'+ACCENT_PRESSED = '#e8d7ba'+ACCENT_DISABLED = '#3a3834'+ACCENT_INK = '#0d0d0f' # LauncherAccent.ink-# Controls, as white over the background at the launcher's opacities.-BTN = '#1b1b1c' # white 5.5%-BTN_HOVER = '#242425' # white 9%-BTN_PRESSED = '#2d2d2e' # white 13%-BTN_EDGE = '#262627' # white 10%-FIELD = '#161617' # an input: a touch above the background-TRACK = '#262627' # a slider or progress track: white 10%+GREEN = '#52d97a' # LauncherTone.ready+AMBER = '#ffbd38' # LauncherTone.caution+ORANGE = AMBER+RED = '#ff6161' # LauncherTone.danger+NEUTRAL_DOT = '#73737a' # LauncherTone.muted-MONO = 'Menlo, Consolas, monospace'+BTN = '#1b1b1c'+BTN_HOVER = '#242425'+BTN_PRESSED = '#2d2d2e'+BTN_EDGE = '#262627'+FIELD = '#161617'+TRACK = '#262627'+MONO = '"Cascadia Mono", "Consolas", "SF Mono", "Menlo", monospace'-def _font_file():+def _font_file() -> str | None:"""Manrope.ttf: in the bundle's `fonts` folder in a frozen build (build-qt.yml adds it), in- the repository's frontend/fonts, the copy the Mac app embeds, in a source run."""+ the repository's frontend/fonts in a source run."""if getattr(sys, 'frozen', False):base = getattr(sys, '_MEIPASS', os.path.dirname(sys.executable))- candidates = [os.path.join(base, 'fonts', 'Manrope.ttf'),- os.path.join(os.path.dirname(sys.executable), 'fonts', 'Manrope.ttf')]+ candidates = [+ os.path.join(base, 'fonts', 'Manrope.ttf'),+ os.path.join(os.path.dirname(sys.executable), 'fonts', 'Manrope.ttf'),+ ]else:here = os.path.dirname(os.path.abspath(__file__))candidates = [os.path.join(here, '..', '..', 'frontend', 'fonts', 'Manrope.ttf')]@@ -52,175 +59,335 @@ def _font_file():def load_font() -> str:- """Registers Manrope with Qt and returns its family name, or '' (keep the system font)- when the file is missing or Qt rejects it."""+ """Registers Manrope with Qt and returns its family name, or '' when unavailable."""path = _font_file()if path is None:return ''from PySide6.QtGui import QFontDatabasefid = QFontDatabase.addApplicationFont(path)families = QFontDatabase.applicationFontFamilies(fid) if fid >= 0 else []- # The TTF's legacy family name is "Manrope ExtraLight" (a variable font), so prefer the- # "Manrope" family the stylesheet and Qt's matching use, and fall back to what Qt reports.if 'Manrope' in families:return 'Manrope'return families[0] if families else ''-STYLE = f"""-QMainWindow, QDialog, QScrollArea, QWidget#body {{+STYLESHEET = f"""+QMainWindow, QWidget#root {{background: {BG};+ color: {TEXT};+ font-family: "Manrope", "Segoe UI", "Inter", -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;+ font-size: 13px;}}-QWidget {{+QDialog {{+ background: #141416;color: {TEXT};- font-size: 9pt; /* pt, not px: a handheld at 150% scaling keeps readable text and a window that fits */+ font-family: "Manrope", "Segoe UI", "Inter", -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;+ font-size: 13px;}}-QLabel {{+QScrollArea {{background: transparent;+ border: none;}}-QScrollArea > QWidget > QWidget {{- background: {BG};+ background: transparent;+}}+QScrollBar:vertical {{+ background: transparent;+ width: 8px;+ margin: 4px 2px 4px 0px;+}}+QScrollBar::handle:vertical {{+ background: rgba(255, 255, 255, 0.18);+ min-height: 28px;+ border-radius: 3px;+}}+QScrollBar::handle:vertical:hover {{+ background: rgba(255, 255, 255, 0.30);+}}+QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical,+QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {{+ background: none;+ height: 0px;+}}+QScrollBar:horizontal {{+ background: transparent;+ height: 8px;+ margin: 0px 4px 2px 4px;+}}+QScrollBar::handle:horizontal {{+ background: rgba(255, 255, 255, 0.18);+ min-width: 28px;+ border-radius: 3px;+}}+QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal,+QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {{+ background: none;+ width: 0px;}}--/* ---- cards: a plain frame, the title is a label inside it ---- */QFrame#card {{background: {CARD};- border: 1px solid {CARD_EDGE};+ border: 1px solid {BORDER};+ border-radius: 14px;+}}+QFrame#subcard {{+ background: #141416;+ border: 1px solid #262629;border-radius: 10px;}}--/* ---- buttons: white 5.5% on the background, a 10% hairline, radius 9 ---- */+QFrame#failureCard {{+ background: #221618;+ border: 1px solid #5c2b2f;+ border-radius: 14px;+}}+QFrame#bannerCard {{+ background: #1c1b18;+ border: 1px solid #3d3526;+ border-radius: 12px;+}}+QFrame#divider {{+ background: {DIVIDER};+ border: none;+ max-height: 1px;+ min-height: 1px;+}}+QFrame#topBar {{+ background: {BG};+ border-bottom: 1px solid #161618;+}}+QFrame#activityBar {{+ background: #0d0d0f;+ border-top: 1px solid #1f1f22;+}}+QLabel {{+ background: transparent;+ color: {TEXT};+}}+QLabel#pageTitle {{+ font-size: 36px;+ font-weight: 800;+ color: {TEXT};+}}+QLabel#pageNote {{+ font-size: 14px;+ color: {MUTED};+}}+QLabel#sectionTitle {{+ font-size: 14px;+ font-weight: 600;+ color: {MUTED};+}}+QLabel#sectionFoot {{+ font-size: 12px;+ color: {FAINT};+}}+QLabel#rowTitle {{+ font-size: 13px;+ font-weight: 600;+ color: {TEXT};+}}+QLabel#muted {{+ color: {MUTED};+ font-size: 12px;+}}+QLabel#faint {{+ color: {FAINT};+ font-size: 11px;+}}+QLabel#mono {{+ color: {MUTED};+ font-family: "Cascadia Mono", "Consolas", "SF Mono", "Menlo", monospace;+ font-size: 11.5px;+}}QPushButton {{- background: {BTN};- border: 1px solid {BTN_EDGE};- border-radius: 9px;- padding: 4px 7px; /* compact: a 7-inch panel must fit the whole form */+ background: rgba(255, 255, 255, 0.08);color: {TEXT};+ border: 1px solid rgba(255, 255, 255, 0.13);+ border-radius: 9px;+ padding: 6px 14px;font-weight: 600;+ font-size: 12.5px;+}}+QPushButton:hover {{+ background: rgba(255, 255, 255, 0.13);+ border-color: rgba(255, 255, 255, 0.22);+}}+QPushButton:pressed {{+ background: rgba(255, 255, 255, 0.06);+}}+QPushButton:disabled {{+ background: rgba(255, 255, 255, 0.03);+ color: #55555a;+ border-color: rgba(255, 255, 255, 0.05);+}}+QPushButton#creamPill {{+ background: {ACCENT};+ color: {ACCENT_INK};+ border: none;+ border-radius: 18px;+ padding: 7px 18px;+ font-size: 13px;+ font-weight: 700;+}}+QPushButton#creamPill:hover {{+ background: {ACCENT_HOVER};+}}+QPushButton#creamPill:pressed {{+ background: {ACCENT_PRESSED};+}}+QPushButton#creamPill:disabled {{+ background: {ACCENT_DISABLED};+ color: #7c7972;}}-QPushButton:hover {{ background: {BTN_HOVER}; }}-QPushButton:pressed {{ background: {BTN_PRESSED}; }}-QPushButton:disabled {{ color: #5a5b60; background: {BTN}; border-color: #1e1e1f; }}--/* the primary action: cream fill, dark text */QPushButton#primary {{- background: {CREAM};- border: 1px solid {CREAM};- color: {BG};- font-size: 10pt;+ background: {ACCENT};+ color: {ACCENT_INK};+ border: none;+ border-radius: 22px;+ padding: 11px 26px;+ font-size: 14px;font-weight: 700;- padding: 6px 16px;}}-QPushButton#primary:hover {{ background: #fff6e6; border-color: #fff6e6; }}-QPushButton#primary:pressed {{ background: #e8d9bf; border-color: #e8d9bf; }}-QPushButton#primary:disabled {{ background: #2a2822; border-color: #2a2822; color: #6d6a62; }}--/* a stop or destructive action: the secondary button in red, as the build bar's Stop */-QPushButton#danger {{- background: {BTN};- border: 1px solid #a14a48;- color: {RED};- font-size: 10pt;- font-weight: 600;- padding: 6px 16px;+QPushButton#primary:hover {{+ background: {ACCENT_HOVER};}}-QPushButton#danger:hover {{ background: {BTN_HOVER}; }}--/* ---- labels ---- */-QLabel#title {{ font-size: 17pt; font-weight: 800; background: transparent; }}-QLabel#subtitle {{ color: {MUTED}; font-size: 9pt; background: transparent; }}-QLabel#note {{ color: {HINT}; font-size: 8pt; background: transparent; }}-QLabel#mono {{ color: {PATH}; font-family: {MONO}; font-size: 8pt; background: transparent; }}-QLabel#ok {{ color: {GREEN}; font-weight: 600; background: transparent; }}-QLabel#warn {{ color: {ORANGE}; font-weight: 600; }}-QLabel#bad {{ color: {RED}; font-weight: 600; background: transparent; }}-QLabel#rowname {{ font-size: 10pt; background: transparent; }}-QLabel#footer {{ color: {MUTED}; font-size: 8pt; padding: 4px 2px; background: transparent; }}--/* ---- the log ---- */-QTextEdit {{- background: {FIELD};- border: 1px solid {CARD_EDGE};- border-radius: 10px;- padding: 8px;- color: #b9bbc1;- font-family: {MONO};- font-size: 8pt;- selection-background-color: #5a5445;- selection-color: {TEXT};+QPushButton#primary:pressed {{+ background: {ACCENT_PRESSED};}}--/* ---- progress ---- */-QProgressBar {{- background: {TRACK};+QPushButton#primary:disabled {{+ background: #252422;+ color: #6b6862;+}}+QPushButton#heroPlay {{+ background: {ACCENT};+ color: {ACCENT_INK};border: none;- border-radius: 4px;- height: 7px;- text-align: center;- color: transparent;+ border-radius: 25px;+ padding: 12px 28px;+ font-size: 15px;+ font-weight: 800;}}-QProgressBar::chunk {{- background: {GREEN};- border-radius: 4px;+QPushButton#heroPlay:hover {{+ background: {ACCENT_HOVER};}}--/* ---- scrollbars ---- */-QScrollBar:vertical {{+QPushButton#heroPlay:disabled {{+ background: rgba(255, 255, 255, 0.12);+ color: rgba(255, 255, 255, 0.40);+}}+QPushButton#heroSecondary {{+ background: rgba(20, 20, 22, 0.72);+ color: {TEXT};+ border: 1px solid rgba(255, 255, 255, 0.20);+ border-radius: 21px;+ padding: 9px 18px;+ font-size: 13px;+ font-weight: 600;+}}+QPushButton#heroSecondary:hover {{+ background: rgba(38, 38, 42, 0.88);+ border-color: rgba(255, 255, 255, 0.32);+}}+QPushButton#danger {{+ background: rgba(255, 97, 97, 0.15);+ color: {RED};+ border: 1px solid rgba(255, 97, 97, 0.35);+ border-radius: 9px;+ padding: 6px 14px;+ font-weight: 600;+}}+QPushButton#danger:hover {{+ background: rgba(255, 97, 97, 0.25);+}}+QPushButton#ghost {{background: transparent;- width: 10px;- margin: 0;+ color: {MUTED};+ border: none;+ border-radius: 8px;+ padding: 5px 10px;+ font-weight: 600;}}-QScrollBar::handle:vertical {{- background: #34343a;- border-radius: 5px;- min-height: 30px;+QPushButton#ghost:hover {{+ background: rgba(255, 255, 255, 0.07);+ color: {TEXT};}}-QScrollBar::handle:vertical:hover {{ background: #46464d; }}-QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{ height: 0; }}-QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {{ background: transparent; }}-QScrollBar:horizontal {{+QPushButton#navTab {{background: transparent;- height: 10px;- margin: 0;+ color: rgba(255, 255, 255, 0.62);+ border: none;+ border-radius: 9px;+ padding: 7px 16px;+ font-size: 13px;+ font-weight: 500;}}-QScrollBar::handle:horizontal {{- background: #34343a;- border-radius: 5px;- min-width: 30px;+QPushButton#navTab:hover {{+ color: rgba(255, 255, 255, 0.88);+ background: rgba(255, 255, 255, 0.05);}}-QScrollBar::handle:horizontal:hover {{ background: #46464d; }}-QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {{ width: 0; }}-QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {{ background: transparent; }}--/* ---- dialogs inherit the dark look ---- */-QFileDialog, QMessageBox, QInputDialog {{ background: {BG}; }}-QLineEdit {{- background: {FIELD};- border: 1px solid {BTN_EDGE};+QPushButton#navTabActive {{+ background: rgba(255, 255, 255, 0.10);+ color: #ffffff;+ border: none;border-radius: 9px;- padding: 5px 9px;+ padding: 7px 16px;+ font-size: 13px;+ font-weight: 700;+}}+QLineEdit#searchField {{+ background: rgba(255, 255, 255, 0.07);color: {TEXT};- selection-background-color: #5a5445;- selection-color: {TEXT};+ border: 1px solid rgba(255, 255, 255, 0.12);+ border-radius: 16px;+ padding: 5px 14px;+ font-size: 12.5px;}}-QLineEdit:focus {{ border-color: {CREAM}; }}--/* ---- menus and tooltips ---- */-QMenu {{- background: {CARD};- border: 1px solid {CARD_EDGE};+QLineEdit#searchField:focus {{+ border-color: {ACCENT};+ background: rgba(255, 255, 255, 0.10);+}}+QComboBox#launcherDropdown {{+ background: rgba(255, 255, 255, 0.06);+ color: {TEXT};+ border: 1px solid rgba(255, 255, 255, 0.14);border-radius: 9px;- padding: 6px;+ padding: 6px 12px;+ font-size: 13px;+ font-weight: 500;+ min-width: 160px;}}-QMenu::item {{ padding: 6px 14px; border-radius: 7px; }}-QMenu::item:selected {{ background: {BTN_PRESSED}; }}-QMenu::item:disabled {{ color: #5a5b60; }}-QMenu::separator {{ height: 1px; background: {CARD_EDGE}; margin: 4px 6px; }}-QToolTip {{- background: {CARD};+QComboBox#launcherDropdown:hover {{+ background: rgba(255, 255, 255, 0.10);+}}+QComboBox#launcherDropdown::drop-down {{+ border: none;+ width: 24px;+}}+QComboBox QAbstractItemView {{+ background: #1f1f23;color: {TEXT};- border: 1px solid {CARD_EDGE};- padding: 4px 6px;+ border: 1px solid {BORDER};+ selection-background-color: {ACCENT};+ selection-color: {ACCENT_INK};+ padding: 4px;+}}+QPlainTextEdit {{+ background: #0d0d0f;+ color: #c7c7cc;+ border: 1px solid #242428;+ border-radius: 10px;+ padding: 10px;+ font-family: "Cascadia Mono", "Consolas", "SF Mono", "Menlo", monospace;+ font-size: 11.5px;+}}+QProgressBar {{+ background: rgba(255, 255, 255, 0.10);+ border: none;+ border-radius: 3px;+ max-height: 6px;+ min-height: 6px;+}}+QProgressBar::chunk {{+ background: {ACCENT};+ border-radius: 3px;}}"""++STYLE = STYLESHEETdiff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.pyindex 39813f17..036263b7 100644--- a/frontend-qt/nspb_qt/ui.py+++ b/frontend-qt/nspb_qt/ui.py@@ -1,820 +1,2172 @@-"""The window: header, repository, inputs, dependencies, build progress, log.--The layout follows the SwiftUI app section for section, so a user who has seen one recognises-the other: rounded cards on a dark background, a coloured dot per row, monospaced paths.-"""+"""Main window mirroring the Mac SwiftUI launcher (Library / Builds / Settings + Hero + Sheets)."""from __future__ import annotations+import osfrom pathlib import Path-from PySide6.QtCore import Qt, QUrl-from PySide6.QtGui import QDesktopServices, QFontDatabase+from PySide6.QtCore import QTimer, QUrl, Qt+from PySide6.QtGui import QDesktopServices, QDragEnterEvent, QDropEvent, QFontfrom PySide6.QtWidgets import (- QFileDialog, QFrame, QGridLayout, QHBoxLayout, QLabel, QMainWindow,- QProgressBar, QPushButton, QScrollArea, QSizePolicy, QTextEdit, QVBoxLayout, QWidget,+ QApplication,+ QComboBox,+ QFileDialog,+ QFrame,+ QHBoxLayout,+ QLabel,+ QLineEdit,+ QMainWindow,+ QMenu,+ QMessageBox,+ QPlainTextEdit,+ QProgressBar,+ QPushButton,+ QScrollArea,+ QSizePolicy,+ QStackedWidget,+ QVBoxLayout,+ QWidget,)+from . import build_failure as bf+from . import features as featfrom . import inputs+from . import library as libfrom . import platform_util as pu-from .model import DepState, Model-from .style import CARD_EDGE, GREEN, MUTED, ORANGE, RED+from . import style++APP_VERSION = '1.1.0'+from .i18n import Lang+from .model import Dep, DepState, Model+from .sheets import CheatsDialog, DeleteGameDialog, FreeSpaceDialog, OnboardingDialog+from .widgets import (+ CardGroup,+ CardPageHeading,+ DropOverlayWidget,+ GameCardWidget,+ HeroBannerWidget,+ LauncherSegmented,+ LauncherSwitch,+ StatusDot,+ make_divider,+)+++def _dot(color: str) -> QLabel:+ d = QLabel()+ d.setFixedSize(8, 8)+ d.setStyleSheet(f'background: {color}; border-radius: 4px;')+ return d+++def _set_dot(d: QLabel, color: str) -> None:+ d.setStyleSheet(f'background: {color}; border-radius: 4px;')class MainWindow(QMainWindow):def __init__(self, model: Model) -> None:super().__init__()self.m = model- self.setWindowTitle('NS Port Builder')- # Size to the screen, not to a fixed 1000x980: on a handheld's 1280x800 panel a fixed- # height puts the footer below the screen edge and the window cannot be shrunk enough to- # reach it. Fit within 90% of the available area and let the scroll area do the rest.- avail = self.screen().availableGeometry() if self.screen() else None- if avail is not None:- # Use most of the panel: a 1280x800 handheld at 150% has only ~853x533 logical pixels,- # so the margins must be small and the height is what matters.- self.resize(min(900, int(avail.width() * 0.98)), min(900, int(avail.height() * 0.96)))- else:- self.resize(900, 800)- self.setMinimumSize(420, 300) # the scroll area carries everything below this- self._mono = QFontDatabase.systemFont(QFontDatabase.FixedFont)+ self.m.ask_folder = lambda title: QFileDialog.getExistingDirectory(+ self, title, str(Path.home())+ )+ self.m.ask_file = self._ask_metal_archive+ self.setWindowTitle(f'NX2Apple v{APP_VERSION}')+ self.resize(1080, 800)+ self.setMinimumSize(820, 440)+ self.setAcceptDrops(True)+ self.setStyleSheet(style.STYLESHEET)++ self._current_page = 'builds'+ self._failed = False+ self._library_filter = 'owned' # 'owned' or 'built'+ self._search_query = ''+ self._drive_folder = ''+ self._options_expanded = True+ self._deps_expanded = Trueroot = QWidget()+ root.setObjectName('root')self.setCentralWidget(root)- outer = QVBoxLayout(root)- outer.setContentsMargins(0, 0, 0, 0)- outer.setSpacing(0)-- scroll = QScrollArea()- scroll.setWidgetResizable(True)- scroll.setFrameShape(QFrame.NoFrame)- # kept so a failed build can scroll the log into view: the message says "see the log- # below", and on a window shorter than about 600 px the log sits below the fold (issue #52)- self.scroll = scroll- body = QWidget()- body.setObjectName('body')- self.body = QVBoxLayout(body)- # (widget, string key) pairs re-set on every refresh: anything built once here would- # otherwise keep its start-up language after the toggle (the half-Chinese report)- self._translatable: list[tuple[QLabel, str]] = []- self.body.setContentsMargins(12, 10, 12, 10)- self.body.setSpacing(8)- scroll.setWidget(body)- outer.addWidget(scroll, 1)-- self._build_header()- self._build_repository()- self._build_inputs()- self._build_deps()- self._build_progress()- self._build_log()- outer.addWidget(self._separator())- self._build_footer()+ root_col = QVBoxLayout(root)+ root_col.setContentsMargins(0, 0, 0, 0)+ root_col.setSpacing(0)++ # 1. Top Navigation Bar (64px)+ self.top_bar = self._build_top_bar()+ root_col.addWidget(self.top_bar)++ # 2. Engine Sync / Failure Banner (below top bar)+ self.engine_banner = self._build_engine_banner()+ root_col.addWidget(self.engine_banner)+ # 3. Main Stacked Pages+ # `self.scroll` is the ONLY QScrollArea in MainWindow (hosting both Builds and Settings+ # containers), so `w.findChild(QScrollArea)` always returns `self.scroll`.+ self.stack = QStackedWidget()+ self.scroll = QScrollArea()+ self.scroll.setWidgetResizable(True)+ self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)+ scroll_body = QWidget()+ self.scroll_col = QVBoxLayout(scroll_body)+ self.scroll_col.setContentsMargins(0, 0, 0, 0)+ self.scroll_col.setSpacing(0)++ self.builds_page = self._build_builds_page()+ self.settings_page = self._build_settings_page()+ self.scroll_col.addWidget(self.builds_page)+ self.scroll_col.addWidget(self.settings_page)+ self.scroll.setWidget(scroll_body)++ self.library_page = self._build_library_page()++ self.stack.addWidget(self.scroll) # index 0: Scrollable workspace (Builds / Settings)+ self.stack.addWidget(self.library_page) # index 1: Full-bleed Library showcase+ root_col.addWidget(self.stack, 1)++ # 4. Bottom Global Activity Bar+ self.activity_bar = self._build_activity_bar()+ root_col.addWidget(self.activity_bar)++ # 5. Full-window drag & drop overlay+ self.drop_overlay = DropOverlayWidget(self.m.t('drop.hint'), root)++ # Connect model signalsself.m.depsChanged.connect(self._refresh_deps)self.m.repoChanged.connect(self._refresh_all)self.m.stagesChanged.connect(self._refresh_stages)- self.m.logAppended.connect(self._append_log)self.m.runningChanged.connect(self._refresh_running)+ self.m.logAppended.connect(self._append_log)self.m.finished.connect(self._on_finished)+ self.m.appUpdateFound.connect(self._on_app_update)+ self.m.libraryChanged.connect(self._refresh_library)++ if self.m.log_path:+ self._append_log(self.m.t('log.at', str(self.m.log_path)) + '\n\n')++ self._switch_page('builds')self._refresh_all()- self.m.ask_folder = lambda title: self._ask_folder(title)- self.m.ask_file = lambda title: self._ask_file(title)- self.m.check_deps()+ for g in self.m.library.games:+ self.m.artwork.request_banner_async(g.title_id)- # ---------------------------------------------------------------- header+ self._init_timer = QTimer(self)+ self._init_timer.setSingleShot(True)+ self._init_timer.timeout.connect(self.m.check_deps)+ self._init_timer.start(50)++ # ================================================================ Top Bar++ def _build_top_bar(self) -> QFrame:+ bar = QFrame()+ bar.setObjectName('topBar')+ bar.setFixedHeight(64)+ row = QHBoxLayout(bar)+ row.setContentsMargins(28, 0, 28, 0)+ row.setSpacing(12)++ # Brand+ brand_row = QHBoxLayout()+ brand_row.setSpacing(8)+ self.title_label = QLabel('NX2Apple')+ self.title_label.setStyleSheet('font-size: 24px; font-weight: 800; color: #ffffff;')+ self.sub_label = QLabel('— by nxnative')+ self.sub_label.setObjectName('faint')+ brand_row.addWidget(self.title_label)+ brand_row.addWidget(self.sub_label)+ row.addLayout(brand_row)++ row.addStretch(1)++ # Navigation tabs: Library / Builds / Settings+ nav_wrap = QHBoxLayout()+ nav_wrap.setSpacing(4)+ self.nav_btns: dict[str, QPushButton] = {}+ for page_id in ('library', 'builds', 'settings'):+ btn = QPushButton(self.m.t('nav.' + page_id))+ btn.setCursor(Qt.PointingHandCursor)+ btn.clicked.connect(lambda _=False, p=page_id: self._switch_page(p))+ self.nav_btns[page_id] = btn+ nav_wrap.addWidget(btn)+ row.addLayout(nav_wrap)- def _build_header(self) -> None:- row = QHBoxLayout()- row.setSpacing(8)row.addStretch(1)++ # Trailing controls: Search input + New Build + Update pill + Language toggle+ self.search_input = QLineEdit()+ self.search_input.setObjectName('searchField')+ self.search_input.setPlaceholderText(self.m.t('library.search'))+ self.search_input.setFixedWidth(180)+ self.search_input.setClearButtonEnabled(True)+ self.search_input.textChanged.connect(self._on_search_changed)+ row.addWidget(self.search_input)++ self.new_build_btn = QPushButton('+ ' + self.m.t('library.newBuild'))+ self.new_build_btn.setCursor(Qt.PointingHandCursor)+ self.new_build_btn.clicked.connect(lambda: self._switch_page('builds'))+ row.addWidget(self.new_build_btn)++ self.update_btn = QPushButton('')+ self.update_btn.setObjectName('creamPill')+ self.update_btn.hide()+ row.addWidget(self.update_btn)+self.lang_btn = QPushButton(self.m.lang.toggle_label)- self.lang_btn.clicked.connect(self._toggle_lang)- row.addWidget(self.lang_btn, 0, Qt.AlignTop)- self.body.addLayout(row)+ self.lang_btn.setFixedWidth(92)+ self.lang_btn.clicked.connect(self.m.toggle_lang)+ row.addWidget(self.lang_btn)++ return bar- # ---------------------------------------------------------------- cards+ def _switch_page(self, page_id: str) -> None:+ self._current_page = page_id+ if page_id == 'library':+ self.stack.setCurrentIndex(1)+ else:+ self.builds_page.setVisible(page_id == 'builds')+ self.settings_page.setVisible(page_id == 'settings')+ self.stack.setCurrentIndex(0)+ self.scroll.verticalScrollBar().setValue(0)+ for pid, btn in self.nav_btns.items():+ btn.setObjectName('navTabActive' if pid == page_id else 'navTab')+ btn.style().unpolish(btn)+ btn.style().polish(btn)+ self.search_input.setVisible(page_id == 'library')+ self.new_build_btn.setVisible(page_id != 'builds')+ if page_id == 'library':+ self._refresh_library()++ # ================================================================ Engine Banner- def _card(self, title_key: str, note_key: str = '') -> tuple[QFrame, QVBoxLayout]:- # title/note are registered for re-translation: the language toggle rebuilds nothing, it- # re-sets text — and a card title built once at start-up stayed English after the toggle- # (the report's half-Chinese interface).+ def _build_engine_banner(self) -> QFrame:box = QFrame()- box.setObjectName('card')- lay = QVBoxLayout(box)- lay.setContentsMargins(12, 10, 12, 10)- lay.setSpacing(6)- head = QHBoxLayout()- head.setSpacing(6)- t = QLabel(self.m.t(title_key))- t.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)- f = t.font()- f.setBold(True)- f.setPointSize(13)- t.setFont(f)- head.addWidget(t)- n = None- if note_key:- n = QLabel(self.m.t(note_key))- n.setObjectName('note')- head.addWidget(n)- head.addStretch(1)- lay.addLayout(head)- self._translatable.append((t, title_key))- if n is not None:- self._translatable.append((n, note_key))- self.body.addWidget(box)- return box, lay-- def _build_repository(self) -> None:- box, lay = self._card('repo.title', 'repo.note')- self.repo_box = box+ box.setObjectName('bannerCard')+ box.setContentsMargins(28, 8, 28, 0)+ col = QVBoxLayout(box)+ col.setContentsMargins(16, 12, 16, 12)+ col.setSpacing(6)+ self.engine_sync_label = QLabel()+ self.engine_sync_label.setWordWrap(True)+ col.addWidget(self.engine_sync_label)+ self.engine_fail_what = QLabel()+ self.engine_fail_what.setStyleSheet('font-weight: 700;')+ self.engine_fail_what.setWordWrap(True)+ col.addWidget(self.engine_fail_what)+ self.engine_fail_next = QLabel()+ self.engine_fail_next.setObjectName('muted')+ self.engine_fail_next.setWordWrap(True)+ col.addWidget(self.engine_fail_next)row = QHBoxLayout()- self.repo_dot = QLabel('●')- self.repo_dot.setFixedWidth(14)- row.addWidget(self.repo_dot)- self.repo_path_label = QLabel('')- self.repo_path_label.setObjectName('mono')- self.repo_path_label.setTextInteractionFlags(Qt.TextSelectableByMouse)- self.repo_path_label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred) # long paths shrink, the buttons stay on screen- self.repo_path_label.setMinimumWidth(60)- row.addWidget(self.repo_path_label, 1)- self.choose_btn = QPushButton(self.m.t('repo.choose'))- self._translatable.append((self.choose_btn, 'repo.choose'))- self.choose_btn.clicked.connect(self._choose_repo)- row.addWidget(self.choose_btn)- lay.addLayout(row)- # A machine without a clone gets Download; a clone gets one update button (fetch, then- # fast-forward if there is anything to take — see Model.update_repo).- actions = QHBoxLayout()- actions.setSpacing(8)- self.download_btn = QPushButton(self.m.t('repo.download'))- self._translatable.append((self.download_btn, 'repo.download'))- self.download_btn.clicked.connect(lambda: self.m.clone_repo())- self.update_btn = QPushButton(self.m.t('repo.update'))- self._translatable.append((self.update_btn, 'repo.update'))- self.update_btn.clicked.connect(self.m.update_repo)- for b in (self.download_btn, self.update_btn):- actions.addWidget(b)- actions.addStretch(1)- lay.addLayout(actions)- self.repo_status = QLabel('')- self.repo_status.setObjectName('note')- lay.addWidget(self.repo_status)- # The engine's online sync (first start, after updates): a status line while it runs, and its failure row with Try again.- self.engine_status = QLabel('')- self.engine_status.setObjectName('note')- self.engine_status.setWordWrap(True)- self.engine_status.hide()- lay.addWidget(self.engine_status)- self.engine_failure_box = QFrame()- self.engine_failure_box.setObjectName('card')- fbox = QVBoxLayout(self.engine_failure_box)- fbox.setContentsMargins(12, 8, 12, 8)- fbox.setSpacing(4)- self.engine_failure_what = QLabel('')- self.engine_failure_what.setWordWrap(True)- self.engine_failure_what.setStyleSheet(f'color: {ORANGE}; font-weight: 600;')- self.engine_failure_next = QLabel('')- self.engine_failure_next.setWordWrap(True)- self.engine_failure_next.setObjectName('note')- self.engine_retry_btn = QPushButton(self.m.t('fail.retry'))- self._translatable.append((self.engine_retry_btn, 'fail.retry'))- self.engine_retry_btn.clicked.connect(self.m.retry_engine_sync)- retry_row = QHBoxLayout()- retry_row.addWidget(self.engine_retry_btn)- retry_row.addStretch(1)- fbox.addWidget(self.engine_failure_what)- fbox.addWidget(self.engine_failure_next)- fbox.addLayout(retry_row)- self.engine_failure_box.hide()- lay.addWidget(self.engine_failure_box)-- def _show_engine_sync(self) -> None:- """The status line while tools/engine.py sync runs, or its failure row (what happened, what to do, Try again)."""- self.engine_status.setVisible(self.m.engine_syncing)- self.engine_status.setText(self.m.t('engine.syncing') if self.m.engine_syncing else '')+ self.engine_retry_btn = QPushButton()+ self.engine_retry_btn.clicked.connect(lambda: self.m.sync_engine())+ row.addWidget(self.engine_retry_btn)+ row.addStretch(1)+ col.addLayout(row)+ box.hide()+ return box++ def _refresh_engine_banner(self) -> None:f = self.m.engine_failure- if f is None or self.m.engine_syncing:- self.engine_failure_box.hide()+ if self.m.engine_syncing:+ self.engine_sync_label.setText(self.m.t('engine.syncing'))+ self.engine_sync_label.show()+ self.engine_fail_what.hide()+ self.engine_fail_next.hide()+ self.engine_retry_btn.hide()+ self.engine_banner.show()+ elif f is not None:+ self.engine_sync_label.hide()+ self.engine_fail_what.setText(self.m.t(f.what_key))+ self.engine_fail_next.setText(self.m.t(f.next_key))+ self.engine_retry_btn.setText(self.m.t('fail.retry'))+ self.engine_fail_what.show()+ self.engine_fail_next.show()+ self.engine_retry_btn.show()+ self.engine_banner.show()+ else:+ self.engine_banner.hide()++ # ================================================================ Page 0: Library++ def _build_library_page(self) -> QWidget:+ page = QWidget()+ lay = QVBoxLayout(page)+ lay.setContentsMargins(0, 0, 0, 0)+ lay.setSpacing(0)++ self.lib_stack = QStackedWidget()++ # 0A: Empty Library Welcome State (mirrors emptyLibrary in LauncherView+Library.swift)+ empty = QWidget()+ ecol = QVBoxLayout(empty)+ ecol.setContentsMargins(40, 60, 40, 60)+ ecol.setSpacing(14)+ ecol.addStretch(1)++ icon_lbl = QLabel('🎮')+ icon_lbl.setAlignment(Qt.AlignCenter)+ icon_lbl.setStyleSheet('font-size: 46px;')+ ecol.addWidget(icon_lbl)++ self.lib_welcome_title = QLabel(self.m.t('library.welcome'))+ self.lib_welcome_title.setAlignment(Qt.AlignCenter)+ self.lib_welcome_title.setStyleSheet('font-size: 40px; font-weight: 800; color: #ffffff;')+ ecol.addWidget(self.lib_welcome_title)++ self.lib_welcome_note = QLabel(self.m.t('library.welcomeNote'))+ self.lib_welcome_note.setObjectName('pageNote')+ self.lib_welcome_note.setAlignment(Qt.AlignCenter)+ self.lib_welcome_note.setWordWrap(True)+ ecol.addWidget(self.lib_welcome_note)+ ecol.addSpacing(10)++ btn_row = QHBoxLayout()+ btn_row.addStretch(1)+ self.lib_first_build_btn = QPushButton('+ ' + self.m.t('library.firstBuild'))+ self.lib_first_build_btn.setObjectName('primary')+ self.lib_first_build_btn.setCursor(Qt.PointingHandCursor)+ self.lib_first_build_btn.clicked.connect(lambda: self._switch_page('builds'))+ btn_row.addWidget(self.lib_first_build_btn)++ self.lib_choose_folder_btn = QPushButton(self.m.t('library.chooseFolder'))+ self.lib_choose_folder_btn.setCursor(Qt.PointingHandCursor)+ self.lib_choose_folder_btn.clicked.connect(self._pick_library_folder)+ btn_row.addWidget(self.lib_choose_folder_btn)+ btn_row.addStretch(1)+ ecol.addLayout(btn_row)+ ecol.addStretch(1)+ self.lib_stack.addWidget(empty)++ # 0B: Populated Library (Hero showcase + Collection horizontal strip)+ pop = QWidget()+ pcol = QVBoxLayout(pop)+ pcol.setContentsMargins(0, 0, 0, 0)+ pcol.setSpacing(0)++ self.hero = HeroBannerWidget()+ self.hero.primaryClicked.connect(self._on_hero_primary)+ self.hero.manageClicked.connect(self._show_manage_menu)+ pcol.addWidget(self.hero, 1)++ # Collection section below Hero+ coll_wrap = QWidget()+ ccol = QVBoxLayout(coll_wrap)+ ccol.setContentsMargins(36, 14, 36, 20)+ ccol.setSpacing(12)++ chead = QHBoxLayout()+ chead.setSpacing(14)+ self.coll_title_lbl = QLabel(self.m.t('library.collection'))+ self.coll_title_lbl.setStyleSheet('font-size: 18px; font-weight: 800;')+ chead.addWidget(self.coll_title_lbl)++ self.coll_filter_seg = LauncherSegmented(+ [('owned', self.m.t('filter.owned')), ('built', self.m.t('filter.built'))],+ selected='owned',+ )+ self.coll_filter_seg.changed.connect(self._on_library_filter_changed)+ chead.addWidget(self.coll_filter_seg)++ self.coll_count_lbl = QLabel('')+ self.coll_count_lbl.setObjectName('muted')+ chead.addWidget(self.coll_count_lbl)+ chead.addStretch(1)++ self.rescan_lib_btn = QPushButton(self.m.t('library.rescan'))+ self.rescan_lib_btn.setObjectName('ghost')+ self.rescan_lib_btn.clicked.connect(self._rescan_library)+ chead.addWidget(self.rescan_lib_btn)++ scroll_left_btn = QPushButton('‹')+ scroll_left_btn.setFixedSize(30, 30)+ scroll_left_btn.setStyleSheet('padding: 0px; font-size: 16px; font-weight: 700;')+ scroll_left_btn.clicked.connect(lambda: self._scroll_collection(-1))+ scroll_right_btn = QPushButton('›')+ scroll_right_btn.setFixedSize(30, 30)+ scroll_right_btn.setStyleSheet('padding: 0px; font-size: 16px; font-weight: 700;')+ scroll_right_btn.clicked.connect(lambda: self._scroll_collection(1))+ chead.addWidget(scroll_left_btn)+ chead.addWidget(scroll_right_btn)+ ccol.addLayout(chead)++ self._coll_offset = 0+ self.coll_strip = QWidget()+ self.coll_strip.setFixedHeight(176)+ self.coll_strip_layout = QHBoxLayout(self.coll_strip)+ self.coll_strip_layout.setContentsMargins(0, 4, 0, 4)+ self.coll_strip_layout.setSpacing(18)+ ccol.addWidget(self.coll_strip)++ pcol.addWidget(coll_wrap)+ self.lib_stack.addWidget(pop)++ lay.addWidget(self.lib_stack, 1)+ return page++ def _filtered_games(self) -> list[lib.LibraryGame]:+ games = list(self.m.library.games)+ if self._library_filter == 'built':+ games = [g for g in games if g.has_any_build]+ if self._search_query:+ q = self._search_query.lower()+ games = [g for g in games if q in g.name.lower() or q in g.title_id.lower()]+ return games++ def _refresh_library(self) -> None:+ self.lib_welcome_title.setText(self.m.t('library.welcome'))+ self.lib_welcome_note.setText(self.m.t('library.welcomeNote'))+ self.lib_first_build_btn.setText('+ ' + self.m.t('library.firstBuild'))+ self.lib_choose_folder_btn.setText(self.m.t('library.chooseFolder'))+ self.coll_title_lbl.setText(self.m.t('library.collection'))+ self.coll_filter_seg.set_items(+ [('owned', self.m.t('filter.owned')), ('built', self.m.t('filter.built'))],+ selected=self._library_filter,+ )+ self.rescan_lib_btn.setText(self.m.t('library.rescan'))++ if not self.m.library.games:+ self.lib_stack.setCurrentIndex(0)return- self.engine_failure_what.setText(self.m.t(f.what_key))- self.engine_failure_next.setText(self.m.t(f.next_key))- self.engine_failure_box.show()-- def _build_inputs(self) -> None:- box, lay = self._card('data.title', 'data.note')- self.data_box = box- self.folder_label = QLabel(self.m.t('data.folderHint'))- self.folder_label.setObjectName('mono')- lay.addWidget(self.folder_label)- grid = QGridLayout()- grid.setHorizontalSpacing(8)- grid.setVerticalSpacing(4)- grid.setColumnStretch(2, 1)- self.input_rows: dict[str, tuple[QLabel, QLabel]] = {}- specs = [('base', 'data.base', False), ('update', 'data.update', True),- ('dlc', 'data.dlc', True), ('keys', 'data.keys', False)]- for i, (key, l10n, optional) in enumerate(specs):- dot = QLabel('○')- dot.setFixedWidth(14)- name = QLabel(self.m.t(l10n))- name.setFixedWidth(110)- self._translatable.append((name, l10n))- val = QLabel('—')- val.setObjectName('mono')- val.setTextInteractionFlags(Qt.TextSelectableByMouse)- val.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred) # filenames are long; the Choose button must stay visible- btn = QPushButton(self.m.t('data.choose'))- self._translatable.append((btn, 'data.choose'))- btn.setFixedWidth(72)- btn.clicked.connect(lambda _=False, k=key: self._choose_input(k))- grid.addWidget(dot, i, 0)- grid.addWidget(name, i, 1)- grid.addWidget(val, i, 2)- grid.addWidget(btn, i, 3)- self.input_rows[key] = (dot, val)- lay.addLayout(grid)- row = QHBoxLayout()- row.addStretch(1)- pick = QPushButton(self.m.t('data.pickFolder'))- self._translatable.append((pick, 'data.pickFolder'))- pick.clicked.connect(self._pick_folder)- row.addWidget(pick)- lay.addLayout(row)-- def _build_deps(self) -> None:- box, lay = self._card('dep.title')- self.deps_box = box- head = QHBoxLayout()- self.deps_summary = QLabel('')- head.addWidget(self.deps_summary)- head.addStretch(1)- self.install_all_btn = QPushButton(self.m.t('dep.installAll'))- self._translatable.append((self.install_all_btn, 'dep.installAll'))- self.install_all_btn.clicked.connect(self.m.install_all_missing)- head.addWidget(self.install_all_btn)- recheck = QPushButton(self.m.t('dep.recheck'))- self._translatable.append((recheck, 'dep.recheck'))- recheck.clicked.connect(self.m.check_deps)- head.addWidget(recheck)- self.deps_toggle = QPushButton(self.m.t('dep.hide'))- self._translatable.append((self.deps_toggle, 'dep.hide'))- self.deps_toggle.clicked.connect(self._toggle_deps)- head.addWidget(self.deps_toggle)- lay.addLayout(head)- self.deps_container = QVBoxLayout()- self.deps_container.setSpacing(3)- lay.addLayout(self.deps_container)- # Open by default, like the Mac's panel (open while anything is missing); remembered for- # the next start either way.- self.deps_open = self.m.settings_value('depsExpanded')- self._apply_deps_open()-- def _toggle_deps(self) -> None:- self.deps_open = not self.deps_open- self.m.settings_set('depsExpanded', self.deps_open)- self._apply_deps_open()-- def _apply_deps_open(self) -> None:- for i in range(self.deps_container.count()):- if w := self.deps_container.itemAt(i).widget():- w.setVisible(self.deps_open)- self.deps_toggle.setText(self.m.t('dep.hide' if self.deps_open else 'dep.show'))- self._translatable = [(w, k) if k != 'dep.hide' and w is not self.deps_toggle else (w, 'dep.hide' if self.deps_open else 'dep.show')- for w, k in self._translatable]-- def _build_progress(self) -> None:- box, lay = self._card('prog.title')- self.progress_box = box- self.progress_box.setVisible(False)- self.overall = QProgressBar()- self.overall.setTextVisible(False)- lay.addWidget(self.overall)- self.stages_container = QVBoxLayout()- self.stages_container.setSpacing(3)- lay.addLayout(self.stages_container)-- def _build_log(self) -> None:- head = QHBoxLayout()- head.setSpacing(6)- self.log_path_label = QLabel('')- self.log_path_label.setObjectName('note')- self.log_path_label.setTextInteractionFlags(Qt.TextSelectableByMouse)- self.log_path_label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred)- head.addWidget(self.log_path_label, 1)- self.export_btn = QPushButton(self.m.t('log.export'))- self._translatable.append((self.export_btn, 'log.export'))- self.export_btn.clicked.connect(self._export_log)- head.addWidget(self.export_btn)- self.body.addLayout(head)- self.log = QTextEdit()- self.log.setReadOnly(True)- self.log.setFont(self._mono)- self.log.setPlaceholderText(self.m.t('log.placeholder'))- self.log.setMinimumHeight(90)- self.log.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)- self.body.addWidget(self.log, 1)- def _build_footer(self) -> None:- wrap = QWidget()- outer = QVBoxLayout(wrap)- outer.setContentsMargins(0, 0, 0, 0)- outer.setSpacing(2)- row = QHBoxLayout()- row.setContentsMargins(12, 6, 12, 4)- row.setSpacing(10)+ self.lib_stack.setCurrentIndex(1)+ filtered = self._filtered_games()+ self.coll_count_lbl.setText(self.m.t('library.gameCount', len(filtered)))++ sel = self.m.library.selected+ if sel not in filtered and filtered:+ sel = filtered[0]+ self.m.library.select(sel.title_id)++ if sel:+ if self.m.running and self.m.build_key.upper() == sel.title_id.upper():+ st_text = self.m.t('library.building')+ st_color = style.AMBER+ p_label = self.m.t('library.viewBuild')+ p_en = True+ elif sel.has_ipa or sel.has_archive:+ st_text = self.m.t('library.readyIOS')+ st_color = style.GREEN+ p_label = self.m.t('install.reveal')+ p_en = True+ else:+ st_text = self.m.t('library.notBuilt')+ st_color = style.NEUTRAL_DOT+ p_label = self.m.t('build.startGame')+ p_en = not self.m.running++ sub_parts = [sel.title_id]+ if sel.has_ipa:+ sub_parts.append(sel.ipa_path)+ elif sel.inputs.get('base'):+ sub_parts.append(sel.inputs['base'][0])++ art = self.m.artwork.image_path(sel.title_id, self.m.engine_path)+ self.hero.set_data(+ title_id=sel.title_id,+ title=sel.name,+ subtitle=' · '.join(sub_parts),+ status_text=st_text,+ status_color=st_color,+ primary_label=p_label,+ primary_enabled=p_en,+ manage_label=self.m.t('library.manage'),+ image_path=art,+ is_switch2=sel.is_switch2(self.m.engine_path),+ switch2_label=self.m.t('switch2.badge'),+ )++ # Rebuild horizontal strip+ while self.coll_strip_layout.count():+ it = self.coll_strip_layout.takeAt(0)+ if it.widget():+ it.widget().deleteLater()++ if not filtered:+ no_lbl = QLabel(self.m.t('library.noResults'))+ no_lbl.setObjectName('muted')+ self.coll_strip_layout.addWidget(no_lbl)+ else:+ for g in filtered:+ dot_c = style.GREEN if g.has_any_build else style.NEUTRAL_DOT+ art = self.m.artwork.image_path(g.title_id, self.m.engine_path)+ card = GameCardWidget(+ title_id=g.title_id,+ title=g.name,+ image_path=art,+ selected=(sel is not None and g.title_id == sel.title_id),+ dot_color=dot_c,+ is_switch2=g.is_switch2(self.m.engine_path),+ switch2_label=self.m.t('switch2.badge'),+ )+ card.clicked.connect(self._on_card_selected)+ card.doubleClicked.connect(self._on_card_double_clicked)+ self.coll_strip_layout.addWidget(card)+ self.coll_strip_layout.addStretch(1)++ def _on_card_selected(self, title_id: str) -> None:+ self.m.library.select(title_id)+ self._refresh_library()++ def _on_card_double_clicked(self, title_id: str) -> None:+ self.m.library.select(title_id)+ g = self.m.library.selected+ if g:+ self.m.load_game_from_library(g)+ self._switch_page('builds')++ def _on_hero_primary(self) -> None:+ g = self.m.library.selected+ if not g:+ return+ if self.m.running and self.m.build_key.upper() == g.title_id.upper():+ self._switch_page('builds')+ return+ if g.has_ipa:+ pu.reveal(g.ipa_path)+ elif g.has_archive:+ pu.reveal(g.archive_path)+ else:+ self.m.load_game_from_library(g)+ self._switch_page('builds')++ def _show_manage_menu(self, anchor: QWidget) -> None:+ g = self.m.library.selected+ if not g:+ return+ menu = QMenu(self)+ menu.setStyleSheet(+ f'QMenu {{ background: #1c1c1f; color: {style.TEXT}; border: 1px solid {style.BORDER}; '+ f'border-radius: 10px; padding: 6px; }} '+ f'QMenu::item {{ padding: 7px 18px; border-radius: 6px; }} '+ f'QMenu::item:selected {{ background: rgba(255,255,255,0.12); }}'+ )++ act_build = menu.addAction(self.m.t('library.buildAgain') if g.has_any_build else self.m.t('build.startGame'))+ act_build.triggered.connect(lambda: (self.m.load_game_from_library(g), self._switch_page('builds')))++ act_cheats = menu.addAction(self.m.t('cheats.menu'))+ act_cheats.triggered.connect(lambda: CheatsDialog(self.m, g, self).exec())++ act_art = menu.addAction(self.m.t('library.changeArtwork'))+ act_art.triggered.connect(lambda: self._pick_custom_artwork(g))++ if self.m.artwork.has_custom(g.title_id):+ act_reset_art = menu.addAction(self.m.t('library.resetArtwork'))+ act_reset_art.triggered.connect(lambda: (self.m.artwork.clear_custom(g.title_id), self._refresh_library()))++ target_reveal = g.ipa_path if g.has_ipa else (g.archive_path if g.has_archive else ((g.inputs.get('base') or [''])[0]))+ if target_reveal and os.path.exists(target_reveal):+ act_reveal = menu.addAction(self.m.t('install.reveal'))+ act_reveal.triggered.connect(lambda: pu.reveal(target_reveal))++ act_free = menu.addAction(self.m.t('free.menu'))+ act_free.triggered.connect(lambda: FreeSpaceDialog(self.m, g, self).exec())++ menu.addSeparator()++ act_remove = menu.addAction(self.m.t('library.remove'))+ act_remove.triggered.connect(lambda: (self.m.library.remove(g.title_id), self._refresh_library()))++ act_delete = menu.addAction(self.m.t('delete.menu'))+ act_delete.triggered.connect(lambda: self._delete_game_dialog(g))++ menu.exec(anchor.mapToGlobal(anchor.rect().bottomLeft()))++ def _pick_custom_artwork(self, game: lib.LibraryGame) -> None:+ f, _ = QFileDialog.getOpenFileName(+ self,+ self.m.t('library.changeArtwork'),+ '',+ 'Images (*.png *.jpg *.jpeg *.webp)',+ )+ if f:+ self.m.artwork.set_custom(game.title_id, f)+ self._refresh_library()++ def _delete_game_dialog(self, game: lib.LibraryGame) -> None:+ dlg = DeleteGameDialog(self.m, game, self)+ dlg.exec()+ if dlg.confirmed:+ self._refresh_library()++ def _on_library_filter_changed(self, flt: str) -> None:+ self._library_filter = flt+ self._refresh_library()++ def _on_search_changed(self, text: str) -> None:+ self._search_query = text.strip()+ if self._current_page == 'library':+ self._refresh_library()++ def _scroll_collection(self, direction: int) -> None:+ filtered = self._filtered_games()+ if not filtered:+ return+ self._coll_offset = max(0, min(max(0, len(filtered) - 1), self._coll_offset + direction))+ self.m.library.select(filtered[self._coll_offset].title_id)+ self._refresh_library()++ def _pick_library_folder(self) -> None:+ d = QFileDialog.getExistingDirectory(+ self,+ self.m.t('library.folderTitle'),+ self.m.library.games_folder or str(Path.home()),+ )+ if d:+ self.m.library.set_games_folder(d, repo_path=self.m.engine_path, default_keys=self.m.keys_path)+ for g in self.m.library.games:+ self.m.artwork.request_banner_async(g.title_id)+ self._refresh_all()++ def _rescan_library(self) -> None:+ if not self.m.library.games_folder:+ self._pick_library_folder()+ return+ self.m.library.rescan_games_folder(repo_path=self.m.engine_path, default_keys=self.m.keys_path)+ for g in self.m.library.games:+ self.m.artwork.request_banner_async(g.title_id)+ self._refresh_library()++ # ================================================================ Page 1: Builds++ def _build_builds_page(self) -> QWidget:+ body = QWidget()+ self.body_col = QVBoxLayout(body)+ self.body_col.setContentsMargins(40, 28, 40, 36)+ self.body_col.setSpacing(20)++ # Page heading+ self.build_heading = CardPageHeading(self.m.t('build.heading'), self.m.t('build.intro'))+ self.body_col.addWidget(self.build_heading)++ # Setup Hint Card (shown when repo or required deps are not ready)+ self.setup_hint_card = self._build_setup_hint_card()+ self.body_col.addWidget(self.setup_hint_card)++ # Card 1: Game Files (FilesCard)+ self.files_group = self._build_files_card()+ self.body_col.addWidget(self.files_group)++ # Card 2: Play on / Target & BC texture option (TargetCard)+ self.target_group = self._build_target_card()+ self.body_col.addWidget(self.target_group)++ # Card 3: Install or Export / Shared App vs One-Game IPA + Drive Copy (InstallCard)+ self.install_group = self._build_install_card()+ self.body_col.addWidget(self.install_group)++ # Card 4: Action + BuildFailureCard + OutcomeCard+ self.action_group = self._build_action_card()+ self.body_col.addWidget(self.action_group)++ # Card 5: Progress Card+ self.stages_card = self._build_stages_card()+ self.body_col.addWidget(self.stages_card)++ # Card 6: Build Log Card (at the bottom of `self.scroll` so `test_build_failure.py` geometry checks pass)+ self.log_group = self._build_log_card()+ self.body_col.addWidget(self.log_group)++ self.body_col.addStretch(1)+ return body++ def _build_setup_hint_card(self) -> CardGroup:+ grp = CardGroup(title=self.m.t('section.setup'))+ r = QWidget()+ rl = QHBoxLayout(r)+ rl.setContentsMargins(18, 13, 18, 13)+ rl.setSpacing(12)+ self.setup_hint_dot = _dot(style.AMBER)+ rl.addWidget(self.setup_hint_dot)+ col = QVBoxLayout()+ col.setSpacing(2)+ self.setup_hint_title = QLabel(self.m.t('library.setupHint'))+ self.setup_hint_title.setObjectName('rowTitle')+ self.setup_hint_sub = QLabel('')+ self.setup_hint_sub.setObjectName('muted')+ self.setup_hint_sub.setWordWrap(True)+ col.addWidget(self.setup_hint_title)+ col.addWidget(self.setup_hint_sub)+ rl.addLayout(col, 1)+ self.setup_goto_btn = QPushButton(self.m.t('nav.settings'))+ self.setup_goto_btn.setObjectName('creamPill')+ self.setup_goto_btn.clicked.connect(lambda: self._switch_page('settings'))+ rl.addWidget(self.setup_goto_btn)+ grp.add_row(r)+ return grp++ def _build_files_card(self) -> CardGroup:+ grp = CardGroup(title=self.m.t('section.files'), footer=self.m.t('msg.workdirHint'))++ # Row 1: Game folder CTA (cream capsule button)+ r_folder = QWidget()+ rf_lay = QHBoxLayout(r_folder)+ rf_lay.setContentsMargins(18, 14, 18, 14)+ rf_lay.setSpacing(12)+ self.folder_cta_dot = _dot(style.NEUTRAL_DOT)+ rf_lay.addWidget(self.folder_cta_dot)+ fcol = QVBoxLayout()+ fcol.setSpacing(2)+ self.folder_cta_title = QLabel(self.m.t('build.folderCTA') + ' · ' + self.m.t('data.note'))+ self.folder_cta_title.setObjectName('rowTitle')+ self.folder_cta_sub = QLabel(self.m.t('build.folderNote') + ' (' + self.m.t('data.folderHint') + ')')+ self.folder_cta_sub.setObjectName('muted')+ self.folder_cta_sub.setWordWrap(True)+ fcol.addWidget(self.folder_cta_title)+ fcol.addWidget(self.folder_cta_sub)+ rf_lay.addLayout(fcol, 1)+ self.pick_folder_btn = QPushButton(self.m.t('data.pickFolder'))+ self.pick_folder_btn.setObjectName('creamPill')+ self.pick_folder_btn.setFixedWidth(184)+ self.pick_folder_btn.clicked.connect(self._pick_game_dir)+ rf_lay.addWidget(self.pick_folder_btn)+ grp.add_row(r_folder)+ grp.add_divider()++ self.input_rows: dict[str, dict] = {}++ # Row 2 & 3: Required slots (base, keys)+ for idx, (key, title_key, req, multi) in enumerate([+ ('base', 'data.base', True, False),+ ('keys', 'data.keys', True, False),+ ]):+ if idx > 0:+ grp.add_divider()+ grp.add_row(self._make_input_slot_row(key, title_key, req, multi))++ # KeyCheck live verification row (under prod.keys)+ self.keycheck_row = QWidget()+ kc_lay = QHBoxLayout(self.keycheck_row)+ kc_lay.setContentsMargins(38, 4, 18, 10)+ kc_lay.setSpacing(8)+ self.keycheck_dot = _dot(style.GREEN)+ self.keycheck_lbl = QLabel('')+ self.keycheck_lbl.setObjectName('muted')+ self.keycheck_lbl.setWordWrap(True)+ kc_lay.addWidget(self.keycheck_dot)+ kc_lay.addWidget(self.keycheck_lbl, 1)+ self.keycheck_row.hide()+ grp.add_row(self.keycheck_row)+ grp.add_divider()++ # Row 4: Disclosure for Updates & DLC (optional)+ disc_head = QWidget()+ dh_lay = QHBoxLayout(disc_head)+ dh_lay.setContentsMargins(18, 10, 18, 10)+ self.opt_toggle_btn = QPushButton('▾ ' + self.m.t('build.options'))+ self.opt_toggle_btn.setObjectName('ghost')+ self.opt_toggle_btn.clicked.connect(self._toggle_optional_inputs)+ dh_lay.addWidget(self.opt_toggle_btn)+ dh_lay.addStretch(1)+ grp.add_row(disc_head)++ self.opt_container = QWidget()+ opt_col = QVBoxLayout(self.opt_container)+ opt_col.setContentsMargins(0, 0, 0, 0)+ opt_col.setSpacing(0)+ opt_col.addWidget(self._make_input_slot_row('update', 'data.update', False, False))+ opt_col.addWidget(self._make_input_slot_row('dlc', 'data.dlc', False, True))+ grp.add_row(self.opt_container)+ grp.add_divider()++ # Row 5: Output folder (build.saveTo)+ out_row = QWidget()+ or_lay = QHBoxLayout(out_row)+ or_lay.setContentsMargins(18, 12, 18, 12)+ or_lay.setSpacing(12)+ or_lay.addWidget(_dot(style.NEUTRAL_DOT))+ ocol = QVBoxLayout()+ ocol.setSpacing(2)+ self.out_title_lbl = QLabel(self.m.t('build.saveTo'))+ self.out_title_lbl.setObjectName('rowTitle')+ self.out_label = QLabel(self.m.t('build.saveDefault'))+ self.out_label.setObjectName('mono')+ ocol.addWidget(self.out_title_lbl)+ ocol.addWidget(self.out_label)+ or_lay.addLayout(ocol, 1)+ self.out_clear_btn = QPushButton(self.m.t('data.clear'))+ self.out_clear_btn.setObjectName('ghost')+ self.out_clear_btn.clicked.connect(self._clear_out_dir)+ self.out_clear_btn.hide()+ or_lay.addWidget(self.out_clear_btn)+ self.out_btn = QPushButton(self.m.t('build.outDir'))+ self.out_btn.setFixedWidth(184)+ self.out_btn.clicked.connect(self._pick_out_dir)+ or_lay.addWidget(self.out_btn)+ grp.add_row(out_row)++ return grp++ def _make_input_slot_row(self, key: str, title_key: str, req: bool, multi: bool) -> QWidget:+ w = QWidget()+ r = QHBoxLayout(w)+ r.setContentsMargins(18, 11, 18, 11)+ r.setSpacing(12)+ dot = _dot(style.NEUTRAL_DOT)+ r.addWidget(dot)+ col = QVBoxLayout()+ col.setSpacing(2)+ title = QLabel(self.m.t(title_key))+ title.setObjectName('rowTitle')+ path = QLabel()+ path.setObjectName('mono')+ path.setWordWrap(True)+ col.addWidget(title)+ col.addWidget(path)+ r.addLayout(col, 1)++ clear = QPushButton(self.m.t('data.clear'))+ clear.setObjectName('ghost')+ clear.clicked.connect(lambda _=False, k=key: self._clear_input(k))+ r.addWidget(clear)++ choose = QPushButton(self.m.t('data.choose'))+ choose.setFixedWidth(184)+ choose.clicked.connect(lambda _=False, k=key, m=multi: self._pick_input(k, m))+ r.addWidget(choose)++ self.input_rows[key] = {+ 'dot': dot,+ 'title': title,+ 'title_key': title_key,+ 'path': path,+ 'clear': clear,+ 'choose': choose,+ 'req': req,+ }+ return w++ def _toggle_optional_inputs(self) -> None:+ self._options_expanded = not self._options_expanded+ self.opt_container.setVisible(self._options_expanded)+ arrow = '▾' if self._options_expanded else '▸'+ self.opt_toggle_btn.setText(f"{arrow} {self.m.t('build.options')}")++ def _build_target_card(self) -> CardGroup:+ grp = CardGroup(title=self.m.t('section.target'))++ # Platform row+ r_plat = QWidget()+ rp_lay = QHBoxLayout(r_plat)+ rp_lay.setContentsMargins(18, 12, 18, 12)+ rp_lay.setSpacing(12)+ rp_lay.addWidget(_dot(style.GREEN))+ pcol = QVBoxLayout()+ pcol.setSpacing(2)+ self.target_title_lbl = QLabel(self.m.t('build.ios'))+ self.target_title_lbl.setObjectName('rowTitle')+ self.target_hint = QLabel(self.m.t('build.iosNote'))+ self.target_hint.setObjectName('muted')+ self.target_hint.setWordWrap(True)+ pcol.addWidget(self.target_title_lbl)+ pcol.addWidget(self.target_hint)+ rp_lay.addLayout(pcol, 1)++ self.target_btn = QPushButton()+ self.target_btn.clicked.connect(self._toggle_target)+ if pu.IS_WIN:+ self.target_btn.hide()+ rp_lay.addWidget(self.target_btn)+ grp.add_row(r_plat)+ grp.add_divider()++ # Older devices BC texture CPU decode row (opt.bc)+ r_bc = QWidget()+ rbc_lay = QHBoxLayout(r_bc)+ rbc_lay.setContentsMargins(18, 12, 18, 12)+ rbc_lay.setSpacing(12)+ rbc_lay.addWidget(_dot(style.NEUTRAL_DOT))+ bccol = QVBoxLayout()+ bccol.setSpacing(2)+ self.bc_title_lbl = QLabel(self.m.t('opt.bc'))+ self.bc_title_lbl.setObjectName('rowTitle')+ self.bc_note_lbl = QLabel(self.m.t('opt.bc.note'))+ self.bc_note_lbl.setObjectName('muted')+ self.bc_note_lbl.setWordWrap(True)+ bccol.addWidget(self.bc_title_lbl)+ bccol.addWidget(self.bc_note_lbl)+ rbc_lay.addLayout(bccol, 1)+ self.bc_switch = LauncherSwitch(self.m.bc_on_cpu)+ self.bc_switch.toggled.connect(self._on_bc_toggled)+ rbc_lay.addWidget(self.bc_switch)+ grp.add_row(r_bc)++ return grp++ def _on_bc_toggled(self, checked: bool) -> None:+ self.m.bc_on_cpu = checked++ def _build_install_card(self) -> CardGroup:+ grp = CardGroup(title=self.m.t('dev.section'))++ # Row 1: What the IPA holds (Shared app vs One game, all inside)+ r_kind = QWidget()+ rk_lay = QHBoxLayout(r_kind)+ rk_lay.setContentsMargins(18, 12, 18, 12)+ rk_lay.setSpacing(12)+ rk_lay.addWidget(_dot(style.GREEN))+ kcol = QVBoxLayout()+ kcol.setSpacing(2)+ self.ipa_kind_title = QLabel(self.m.t('shell.ipaKind'))+ self.ipa_kind_title.setObjectName('rowTitle')+ self.ipa_kind_note = QLabel(self.m.t('shell.ipaSharedNote'))+ self.ipa_kind_note.setObjectName('muted')+ self.ipa_kind_note.setWordWrap(True)+ kcol.addWidget(self.ipa_kind_title)+ kcol.addWidget(self.ipa_kind_note)+ rk_lay.addLayout(kcol, 1)++ self.ipa_kind_seg = LauncherSegmented(+ [+ ('shared', self.m.t('shell.ipaShared')),+ ('oneGame', self.m.t('shell.ipaOneGame')),+ ],+ selected=self.m.ipa_kind,+ )+ self.ipa_kind_seg.changed.connect(self._on_ipa_kind_changed)+ rk_lay.addWidget(self.ipa_kind_seg)+ grp.add_row(r_kind)+ grp.add_divider()++ # Step 1: Export IPA+ r_s1 = QWidget()+ rs1_lay = QHBoxLayout(r_s1)+ rs1_lay.setContentsMargins(18, 11, 18, 11)+ s1_col = QVBoxLayout()+ self.step1_title = QLabel('① ' + self.m.t('shell.step1Title'))+ self.step1_title.setObjectName('rowTitle')+ self.step1_sub = QLabel(self.m.t('shell.step1Sub'))+ self.step1_sub.setObjectName('muted')+ self.step1_sub.setWordWrap(True)+ s1_col.addWidget(self.step1_title)+ s1_col.addWidget(self.step1_sub)+ rs1_lay.addLayout(s1_col, 1)+ grp.add_row(r_s1)+ grp.add_divider()++ # Step 2: Install with your own tool (AltStore / SideStore)+ r_s2 = QWidget()+ rs2_lay = QHBoxLayout(r_s2)+ rs2_lay.setContentsMargins(18, 11, 18, 11)+ s2_col = QVBoxLayout()+ self.step2_title = QLabel('② ' + self.m.t('shell.step2Title'))+ self.step2_title.setObjectName('rowTitle')+ self.step2_sub = QLabel(self.m.t('shell.step2Sub'))+ self.step2_sub.setObjectName('muted')+ self.step2_sub.setWordWrap(True)+ s2_col.addWidget(self.step2_title)+ s2_col.addWidget(self.step2_sub)+ rs2_lay.addLayout(s2_col, 1)+ grp.add_row(r_s2)++ # Step 3: Send game data to drive or folder (shown when shared app mode)+ self.step3_container = QWidget()+ s3_outer = QVBoxLayout(self.step3_container)+ s3_outer.setContentsMargins(0, 0, 0, 0)+ s3_outer.setSpacing(0)+ s3_outer.addWidget(make_divider())++ r_s3 = QWidget()+ rs3_lay = QHBoxLayout(r_s3)+ rs3_lay.setContentsMargins(18, 11, 18, 11)+ rs3_lay.setSpacing(10)+ s3_col = QVBoxLayout()+ self.step3_title = QLabel('③ ' + self.m.t('shell.step3Title') + ' · ' + self.m.t('shell.whereDrive'))+ self.step3_title.setObjectName('rowTitle')+ self.step3_sub = QLabel(self.m.t('shell.copyExternalNote'))+ self.step3_sub.setObjectName('muted')+ self.step3_sub.setWordWrap(True)+ s3_col.addWidget(self.step3_title)+ s3_col.addWidget(self.step3_sub)+ rs3_lay.addLayout(s3_col, 1)++ self.drive_choose_btn = QPushButton(self.m.t('shell.driveChoose'))+ self.drive_choose_btn.clicked.connect(self._pick_drive_folder)+ rs3_lay.addWidget(self.drive_choose_btn)++ self.drive_copy_btn = QPushButton(self.m.t('shell.driveCopy'))+ self.drive_copy_btn.setObjectName('creamPill')+ self.drive_copy_btn.clicked.connect(self._copy_archive_to_drive)+ rs3_lay.addWidget(self.drive_copy_btn)+ s3_outer.addWidget(r_s3)+ grp.add_row(self.step3_container)++ return grp++ def _on_ipa_kind_changed(self, kind: str) -> None:+ self.m.ipa_kind = kind+ self._refresh_install_card()++ def _refresh_install_card(self) -> None:+ self.install_group.set_title(self.m.t('dev.section'))+ self.ipa_kind_title.setText(self.m.t('shell.ipaKind'))+ self.ipa_kind_seg.set_items(+ [+ ('shared', self.m.t('shell.ipaShared')),+ ('oneGame', self.m.t('shell.ipaOneGame')),+ ],+ selected=self.m.ipa_kind,+ )+ one = self.m.ipa_kind == 'oneGame'+ self.ipa_kind_note.setText(self.m.t('shell.ipaOneGameNote' if one else 'shell.ipaSharedNote'))+ self.step1_title.setText('① ' + self.m.t('shell.step1Title'))+ self.step1_sub.setText(self.m.t('shell.oneGameSub' if one else 'shell.step1Sub'))+ self.step2_title.setText('② ' + self.m.t('shell.step2Title'))+ self.step2_sub.setText(self.m.t('shell.oneGameStep2Sub' if one else 'shell.step2Sub'))+ self.step3_title.setText('③ ' + self.m.t('shell.step3Title') + ' · ' + self.m.t('shell.whereDrive'))+ self.drive_choose_btn.setText(self.m.t('shell.driveChoose'))+ self.drive_copy_btn.setText(self.m.t('shell.driveCopy'))+ self.step3_container.setVisible(not one)+ has_arch = bool(self.m.archive_path and os.path.isdir(self.m.archive_path))+ self.drive_copy_btn.setEnabled(has_arch and bool(self._drive_folder))++ def _pick_drive_folder(self) -> None:+ d = QFileDialog.getExistingDirectory(self, self.m.t('shell.driveChoose'), self._drive_folder or str(Path.home()))+ if d:+ self._drive_folder = d+ self.step3_sub.setText(d)+ self._refresh_install_card()++ def _copy_archive_to_drive(self) -> None:+ if not self.m.archive_path or not self._drive_folder:+ return+ tid = self.m.build_key+ ok, info = lib.DriveCopy.copy_to_folder(self.m.archive_path, self._drive_folder, tid)+ if ok:+ self.step3_sub.setText(self.m.t('shell.driveDone', info, self.m.t('ios.ui.gameData')))+ else:+ self.step3_sub.setText(self.m.t('shell.driveFailed', info))++ def _build_action_card(self) -> CardGroup:+ grp = CardGroup()+ r = QWidget()+ act = QHBoxLayout(r)+ act.setContentsMargins(18, 14, 18, 14)+ act.setSpacing(12)+self.build_btn = QPushButton(self.m.t('build.start'))self.build_btn.setObjectName('primary')- self.build_btn.setMinimumWidth(110)+ self.build_btn.setMinimumWidth(190)self.build_btn.clicked.connect(self._build_clicked)- row.addWidget(self.build_btn)+ act.addWidget(self.build_btn)+self.footer = QLabel('')- self.footer.setObjectName('footer')- row.addWidget(self.footer, 1)- # Output target. A Mac app only exists on macOS (dm/mac/pack_app.py), so the choice is- # hidden elsewhere rather than shown and rejected.- if not pu.IS_WIN:- self.target_btn = QPushButton(self.m.t('target.ios'))- self.target_btn.setToolTip(self.m.t('target.tip'))- self.target_btn.clicked.connect(self._toggle_target)- row.addWidget(self.target_btn)- self.out_btn = QPushButton(self.m.t('build.outDir'))- self._translatable.append((self.out_btn, 'build.outDir'))- self.out_btn.clicked.connect(self._choose_out)- row.addWidget(self.out_btn)- # the output folder silently decides where the build cache lives — the report changed it- # and lost a finished build; say it here, all the time- hint = QLabel(self.m.t('msg.workdirHint'))- hint.setObjectName('note')- hint.setWordWrap(True)- outer.addLayout(row)- self._build_failure_box(outer)- outer.addWidget(hint)- self._translatable.append((hint, 'msg.workdirHint'))- self.centralWidget().layout().addWidget(wrap)-- def _build_failure_box(self, outer: QVBoxLayout) -> None:- """After a known early stop of the script: what happened, the next step, and its button."""+ self.footer.setObjectName('muted')+ self.footer.setWordWrap(True)+ self.footer.setTextInteractionFlags(Qt.TextSelectableByMouse)+ act.addWidget(self.footer, 1)++ self.reveal_ipa_btn = QPushButton('IPA')+ self.reveal_ipa_btn.clicked.connect(lambda: pu.reveal(self.m.ipa_path))+ self.reveal_ipa_btn.hide()+ act.addWidget(self.reveal_ipa_btn)++ self.reveal_arc_btn = QPushButton('romfs.img')+ self.reveal_arc_btn.clicked.connect(lambda: pu.reveal(self.m.archive_path))+ self.reveal_arc_btn.hide()+ act.addWidget(self.reveal_arc_btn)++ self.reveal_app_btn = QPushButton('.app')+ self.reveal_app_btn.clicked.connect(lambda: pu.reveal(self.m.mac_app_path))+ self.reveal_app_btn.hide()+ act.addWidget(self.reveal_app_btn)++ grp.add_row(r)++ # BuildFailureCard (shown on a known early stop)self.failure_box = QFrame()- self.failure_box.setObjectName('card')- box = QVBoxLayout(self.failure_box)- box.setContentsMargins(12, 8, 12, 8)- box.setSpacing(4)- self.failure_what = QLabel('')+ self.failure_box.setObjectName('failureCard')+ self.failure_box.setContentsMargins(14, 8, 14, 14)+ fcol = QVBoxLayout(self.failure_box)+ fcol.setContentsMargins(16, 14, 16, 14)+ fcol.setSpacing(6)+ self.failure_title = QLabel()+ self.failure_title.setObjectName('sectionTitle')+ fcol.addWidget(self.failure_title)+ self.failure_what = QLabel()+ self.failure_what.setStyleSheet('font-weight: 700;')self.failure_what.setWordWrap(True)- self.failure_what.setStyleSheet(f'color: {ORANGE}; font-weight: 600;')- self.failure_next = QLabel('')+ fcol.addWidget(self.failure_what)+ self.failure_next = QLabel()+ self.failure_next.setObjectName('muted')self.failure_next.setWordWrap(True)- self.failure_next.setObjectName('note')- buttons = QHBoxLayout()- self.failure_fix_btn = QPushButton('')+ fcol.addWidget(self.failure_next)+ frow = QHBoxLayout()+ frow.setSpacing(8)+ self.failure_folder_btn = QPushButton()+ self.failure_folder_btn.clicked.connect(self._open_failure_folder)+ frow.addWidget(self.failure_folder_btn)+ self.failure_fix_btn = QPushButton()self.failure_fix_btn.clicked.connect(self._fix_failure)- self.failure_anyway_btn = QPushButton(self.m.t('fail.buildAnyway'))+ frow.addWidget(self.failure_fix_btn)+ self.failure_anyway_btn = QPushButton()+ self.failure_anyway_btn.setObjectName('danger')self.failure_anyway_btn.clicked.connect(self._build_anyway)- buttons.addWidget(self.failure_fix_btn)- buttons.addWidget(self.failure_anyway_btn)- buttons.addStretch(1)- box.addWidget(self.failure_what)- box.addWidget(self.failure_next)- box.addLayout(buttons)+ frow.addWidget(self.failure_anyway_btn)+ frow.addStretch(1)+ fcol.addLayout(frow)self.failure_box.hide()- outer.addWidget(self.failure_box)+ grp.add_row(self.failure_box)- _FIX_BUTTONS = {'translator': 'fail.translator.button', 'zbic': 'fail.zbic.button', 'iosSDK': 'fail.iosSDK.button',- 'keys': 'fail.keys.button', 'keysOld': 'fail.keys.button', 'severalGames': 'fail.showFolder', 'noTitleID': 'fail.showFolder',- 'diskFull': 'fail.showFolder'}+ return grp- def _show_failure(self) -> None:- f = self.m.failure- if f is None or self.m.running:- self.failure_box.hide()- return- self.failure_what.setText(self.m.failure_what(f))- self.failure_next.setText(self.m.t(f.next_key))- fix = self._FIX_BUTTONS.get(f.kind)- self.failure_fix_btn.setVisible(fix is not None)- if fix:- self.failure_fix_btn.setText(self.m.t(fix))- self.failure_anyway_btn.setVisible(f.flag is not None)- self.failure_anyway_btn.setText(self.m.t('fail.buildAnyway'))- self.failure_box.show()+ def _build_stages_card(self) -> CardGroup:+ grp = CardGroup(title=self.m.t('prog.title'))+ wrap = QWidget()+ self.stages_col = QVBoxLayout(wrap)+ self.stages_col.setContentsMargins(18, 12, 18, 12)+ self.stages_col.setSpacing(8)+ grp.add_row(wrap)+ grp.hide()+ return grp- def _fix_failure(self) -> None:- f = self.m.failure- if f is None:- return- if f.kind in ('keys', 'keysOld'):- self._choose_input('keys') # the same picker as the keys row- elif f.kind in ('severalGames', 'noTitleID', 'diskFull'):- folder = self.m.failure_folder(f)- if folder:- QDesktopServices.openUrl(QUrl.fromLocalFile(folder))- else:- self.m.fix_failure(f)+ def _build_log_card(self) -> CardGroup:+ grp = CardGroup(title=self.m.t('build.log'))+ head = QWidget()+ hl = QHBoxLayout(head)+ hl.setContentsMargins(18, 10, 18, 6)+ self.log_label = QLabel(self.m.t('build.log'))+ self.log_label.setObjectName('rowTitle')+ hl.addWidget(self.log_label)+ hl.addStretch(1)+ self.export_log_btn = QPushButton(self.m.t('log.export'))+ self.export_log_btn.setObjectName('ghost')+ self.export_log_btn.clicked.connect(self._export_log)+ hl.addWidget(self.export_log_btn)+ grp.add_row(head)- def _build_anyway(self) -> None:- """Asks first: the dialog states the risk. Nothing is armed until the player agrees."""- if self.m.running or not self.m.override.request(self.m.failure):- return- from PySide6.QtWidgets import QMessageBox- risk = self.m.t(f'fail.{self.m.failure.kind}.risk')- yes = QMessageBox.question(self, self.m.t('fail.confirm.title'), risk,- QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)- if yes != QMessageBox.Yes:- self.m.override.cancel()- return- if self.m.override.confirm():- self._build_clicked()+ log_wrap = QWidget()+ lw = QVBoxLayout(log_wrap)+ lw.setContentsMargins(14, 4, 14, 14)+ self.log = QPlainTextEdit()+ self.log.setReadOnly(True)+ self.log.setPlaceholderText(self.m.t('log.placeholder'))+ self.log.setMinimumHeight(200)+ lw.addWidget(self.log)+ grp.add_row(log_wrap)+ return grp++ def _export_log(self) -> None:+ f, _ = QFileDialog.getSaveFileName(self, self.m.t('log.export'), 'nx2apple-build.log', 'Log files (*.log *.txt)')+ if f:+ try:+ Path(f).write_text(self.log.toPlainText(), encoding='utf-8')+ self._append_log(self.m.t('log.exported', f) + '\n')+ except OSError as e:+ self._append_log(self.m.t('log.exportFail', str(e)) + '\n')++ # ================================================================ Page 2: Settings++ def _build_settings_page(self) -> QWidget:+ sbody = QWidget()+ scol = QVBoxLayout(sbody)+ scol.setContentsMargins(40, 28, 40, 36)+ scol.setSpacing(22)++ self.settings_heading = CardPageHeading(self.m.t('settings.heading'), self.m.t('settings.note'))+ scol.addWidget(self.settings_heading)++ # 1. Library Card (section.library)+ self.settings_lib_group = CardGroup(title=self.m.t('section.library'))+ r_lib = QWidget()+ rl_lay = QHBoxLayout(r_lib)+ rl_lay.setContentsMargins(18, 13, 18, 13)+ rl_lay.setSpacing(12)+ self.lib_folder_dot = _dot(style.NEUTRAL_DOT)+ rl_lay.addWidget(self.lib_folder_dot)+ lcol = QVBoxLayout()+ lcol.setSpacing(2)+ self.lib_folder_title = QLabel(self.m.t('library.folderTitle'))+ self.lib_folder_title.setObjectName('rowTitle')+ self.lib_folder_path_lbl = QLabel(self.m.t('library.folderUnset'))+ self.lib_folder_path_lbl.setObjectName('mono')+ self.lib_folder_hint_lbl = QLabel(self.m.t('library.folderHint'))+ self.lib_folder_hint_lbl.setObjectName('muted')+ self.lib_folder_hint_lbl.setWordWrap(True)+ lcol.addWidget(self.lib_folder_title)+ lcol.addWidget(self.lib_folder_path_lbl)+ lcol.addWidget(self.lib_folder_hint_lbl)+ rl_lay.addLayout(lcol, 1)++ self.settings_rescan_btn = QPushButton(self.m.t('library.rescan'))+ self.settings_rescan_btn.clicked.connect(self._rescan_library)+ rl_lay.addWidget(self.settings_rescan_btn)++ self.settings_lib_choose_btn = QPushButton(self.m.t('library.chooseFolder'))+ self.settings_lib_choose_btn.setFixedWidth(184)+ self.settings_lib_choose_btn.clicked.connect(self._pick_library_folder)+ rl_lay.addWidget(self.settings_lib_choose_btn)+ self.settings_lib_group.add_row(r_lib)+ scol.addWidget(self.settings_lib_group)++ # 2. Build Tools Card (section.tools: Repo + Deps + Diagnostics)+ self.tools_group = self._build_tools_card()+ scol.addWidget(self.tools_group)++ # 3. App Card (section.app: 13-Language Dropdown + Notify + Setup Wizard + Version)+ self.app_group = self._build_app_card()+ scol.addWidget(self.app_group)++ scol.addStretch(1)+ return sbody++ def _build_tools_card(self) -> CardGroup:+ grp = CardGroup(title=self.m.t('section.tools'))- @staticmethod- def _separator() -> QFrame:- line = QFrame()- line.setFrameShape(QFrame.HLine)- line.setStyleSheet(f'color: {CARD_EDGE};')- return line+ # Row 1: Project repository+ r_repo = QWidget()+ repo_col = QVBoxLayout(r_repo)+ repo_col.setContentsMargins(18, 14, 18, 14)+ repo_col.setSpacing(8)- # ---------------------------------------------------------------- refresh+ r1 = QHBoxLayout()+ r1.setSpacing(10)+ self.repo_dot = _dot(style.NEUTRAL_DOT)+ r1.addWidget(self.repo_dot)+ self.repo_title = QLabel(self.m.t('repo.title'))+ self.repo_title.setObjectName('rowTitle')+ r1.addWidget(self.repo_title)+ self.repo_sub = QLabel(self.m.t('repo.note'))+ self.repo_sub.setObjectName('muted')+ r1.addWidget(self.repo_sub, 1)+ self.clone_btn = QPushButton(self.m.t('repo.download'))+ self.clone_btn.setObjectName('creamPill')+ self.clone_btn.clicked.connect(lambda: self.m.clone_repo())+ r1.addWidget(self.clone_btn)+ self.repo_btn = QPushButton(self.m.t('repo.choose'))+ self.repo_btn.clicked.connect(self._pick_repo)+ r1.addWidget(self.repo_btn)+ repo_col.addLayout(r1)++ self.repo_path_label = QLabel()+ self.repo_path_label.setObjectName('mono')+ self.repo_path_label.setWordWrap(True)+ repo_col.addWidget(self.repo_path_label)++ self.repo_hint_label = QLabel()+ self.repo_hint_label.setObjectName('muted')+ self.repo_hint_label.setWordWrap(True)+ self.repo_hint_label.setOpenExternalLinks(True)+ repo_col.addWidget(self.repo_hint_label)++ r2 = QHBoxLayout()+ r2.setSpacing(8)+ self.repo_status_label = QLabel()+ self.repo_status_label.setObjectName('muted')+ r2.addWidget(self.repo_status_label, 1)+ self.check_upd_btn = QPushButton(self.m.t('repo.update'))+ self.check_upd_btn.clicked.connect(self.m.update_repo)+ r2.addWidget(self.check_upd_btn)+ repo_col.addLayout(r2)+ grp.add_row(r_repo)+ grp.add_divider()++ # Row 2: Device dependencies+ r_deps = QWidget()+ deps_col = QVBoxLayout(r_deps)+ deps_col.setContentsMargins(18, 14, 18, 14)+ deps_col.setSpacing(10)++ dh = QHBoxLayout()+ dh.setSpacing(10)+ self.deps_dot = _dot(style.NEUTRAL_DOT)+ dh.addWidget(self.deps_dot)+ self.deps_title = QLabel(self.m.t('dep.title'))+ self.deps_title.setObjectName('rowTitle')+ dh.addWidget(self.deps_title)+ self.deps_summary = QLabel(self.m.t('dep.checking'))+ self.deps_summary.setObjectName('muted')+ dh.addWidget(self.deps_summary, 1)+ self.install_all_btn = QPushButton(self.m.t('dep.installAll'))+ self.install_all_btn.setObjectName('creamPill')+ self.install_all_btn.clicked.connect(self.m.install_all_missing)+ dh.addWidget(self.install_all_btn)+ self.recheck_btn = QPushButton(self.m.t('dep.recheck'))+ self.recheck_btn.clicked.connect(self.m.check_deps)+ dh.addWidget(self.recheck_btn)+ self.deps_toggle_btn = QPushButton(self.m.t('dep.hide'))+ self.deps_toggle_btn.setObjectName('ghost')+ self.deps_toggle_btn.clicked.connect(self._toggle_deps_expanded)+ dh.addWidget(self.deps_toggle_btn)+ deps_col.addLayout(dh)++ self.deps_rows_host = QWidget()+ self.deps_rows = QVBoxLayout(self.deps_rows_host)+ self.deps_rows.setContentsMargins(0, 4, 0, 0)+ self.deps_rows.setSpacing(8)+ deps_col.addWidget(self.deps_rows_host)+ grp.add_row(r_deps)+ grp.add_divider()++ # Row 3: Copy Diagnostics (diag.title / diag.copy)+ r_diag = QWidget()+ rd_lay = QHBoxLayout(r_diag)+ rd_lay.setContentsMargins(18, 12, 18, 12)+ rd_lay.setSpacing(12)+ rd_lay.addWidget(_dot(style.GREEN))+ dcol = QVBoxLayout()+ dcol.setSpacing(2)+ self.diag_title_lbl = QLabel(self.m.t('diag.title'))+ self.diag_title_lbl.setObjectName('rowTitle')+ self.diag_note_lbl = QLabel(self.m.t('diag.note'))+ self.diag_note_lbl.setObjectName('muted')+ self.diag_note_lbl.setWordWrap(True)+ dcol.addWidget(self.diag_title_lbl)+ dcol.addWidget(self.diag_note_lbl)+ rd_lay.addLayout(dcol, 1)+ self.diag_btn = QPushButton(self.m.t('diag.copy'))+ self.diag_btn.setFixedWidth(184)+ self.diag_btn.clicked.connect(self._copy_diagnostics)+ rd_lay.addWidget(self.diag_btn)+ grp.add_row(r_diag)++ return grp++ def _copy_diagnostics(self) -> None:+ report = feat.Diagnostics.format_report(+ app_version=APP_VERSION,+ repo_path=self.m.repo_path,+ deps=self.m.deps,+ last_log=self.log.toPlainText(),+ )+ cb = QApplication.clipboard()+ if cb:+ cb.setText(report)+ self.diag_btn.setText(self.m.t('diag.copied'))+ QTimer.singleShot(2000, lambda: self.diag_btn.setText(self.m.t('diag.copy')))++ def _toggle_deps_expanded(self) -> None:+ self._deps_expanded = not self._deps_expanded+ self.deps_rows_host.setVisible(self._deps_expanded)+ self.deps_toggle_btn.setText(self.m.t('dep.hide' if self._deps_expanded else 'dep.show'))++ def _build_app_card(self) -> CardGroup:+ grp = CardGroup(title=self.m.t('section.app'))++ # Row 1: Language 13-language dropdown+ r_lang = QWidget()+ rl_lay = QHBoxLayout(r_lang)+ rl_lay.setContentsMargins(18, 12, 18, 12)+ rl_lay.addWidget(_dot(style.GREEN))+ self.app_lang_lbl = QLabel(self.m.t('settings.language'))+ self.app_lang_lbl.setObjectName('rowTitle')+ rl_lay.addWidget(self.app_lang_lbl, 1)++ self.lang_combo = QComboBox()+ self.lang_combo.setObjectName('launcherDropdown')+ self.lang_combo.setFixedWidth(184)+ for lg in Lang.all():+ self.lang_combo.addItem(lg.name, lg.code)+ curr_idx = next((i for i, lg in enumerate(Lang.all()) if lg.code == self.m.lang.code), 0)+ self.lang_combo.setCurrentIndex(curr_idx)+ self.lang_combo.currentIndexChanged.connect(self._on_lang_combo_changed)+ rl_lay.addWidget(self.lang_combo)+ grp.add_row(r_lang)+ grp.add_divider()++ # Row 2: Notify when a build ends+ r_notif = QWidget()+ rn_lay = QHBoxLayout(r_notif)+ rn_lay.setContentsMargins(18, 12, 18, 12)+ rn_lay.addWidget(_dot(style.NEUTRAL_DOT))+ ncol = QVBoxLayout()+ ncol.setSpacing(2)+ self.notif_title_lbl = QLabel(self.m.t('settings.notify'))+ self.notif_title_lbl.setObjectName('rowTitle')+ self.notif_note_lbl = QLabel(self.m.t('settings.notifyNote'))+ self.notif_note_lbl.setObjectName('muted')+ self.notif_note_lbl.setWordWrap(True)+ ncol.addWidget(self.notif_title_lbl)+ ncol.addWidget(self.notif_note_lbl)+ rn_lay.addLayout(ncol, 1)+ notif_on = self.m.settings_value('notifyOnComplete', True)+ self.notif_switch = LauncherSwitch(bool(notif_on))+ self.notif_switch.toggled.connect(lambda v: self.m.settings_set('notifyOnComplete', v))+ rn_lay.addWidget(self.notif_switch)+ grp.add_row(r_notif)+ grp.add_divider()++ # Row 3: Run setup again (OnboardingDialog)+ r_setup = QWidget()+ rs_lay = QHBoxLayout(r_setup)+ rs_lay.setContentsMargins(18, 12, 18, 12)+ rs_lay.addWidget(_dot(style.NEUTRAL_DOT))+ scol = QVBoxLayout()+ scol.setSpacing(2)+ self.setup_row_title = QLabel(self.m.t('settings.setup'))+ self.setup_row_title.setObjectName('rowTitle')+ self.setup_row_note = QLabel(self.m.t('settings.setupNote'))+ self.setup_row_note.setObjectName('muted')+ self.setup_row_note.setWordWrap(True)+ scol.addWidget(self.setup_row_title)+ scol.addWidget(self.setup_row_note)+ rs_lay.addLayout(scol, 1)+ self.run_onboarding_btn = QPushButton(self.m.t('settings.setupBtn'))+ self.run_onboarding_btn.setFixedWidth(184)+ self.run_onboarding_btn.clicked.connect(self._open_onboarding)+ rs_lay.addWidget(self.run_onboarding_btn)+ grp.add_row(r_setup)+ grp.add_divider()++ # Row 4: App Version+ r_ver = QWidget()+ rv_lay = QHBoxLayout(r_ver)+ rv_lay.setContentsMargins(18, 12, 18, 12)+ rv_lay.addWidget(_dot(style.GREEN))+ self.ver_title_lbl = QLabel(self.m.t('app.version', APP_VERSION))+ self.ver_title_lbl.setObjectName('rowTitle')+ rv_lay.addWidget(self.ver_title_lbl, 1)+ self.ver_status_lbl = QLabel(self.m.t('app.upToDate'))+ self.ver_status_lbl.setObjectName('muted')+ rv_lay.addWidget(self.ver_status_lbl)+ grp.add_row(r_ver)++ return grp++ def _on_lang_combo_changed(self, idx: int) -> None:+ code = self.lang_combo.itemData(idx)+ if code and code != self.m.lang.code:+ self.m.set_lang(Lang(str(code)))++ def _open_onboarding(self) -> None:+ OnboardingDialog(self.m, self).exec()+ self._refresh_all()++ # ================================================================ Bottom Activity Bar++ def _build_activity_bar(self) -> QFrame:+ bar = QFrame()+ bar.setObjectName('activityBar')+ bar.setFixedHeight(44)+ row = QHBoxLayout(bar)+ row.setContentsMargins(28, 0, 28, 0)+ row.setSpacing(12)++ self.act_dot = StatusDot(style.NEUTRAL_DOT, size=7)+ row.addWidget(self.act_dot)++ self.act_title = QLabel(self.m.t('library.localNote'))+ self.act_title.setStyleSheet('font-size: 12px; font-weight: 600;')+ row.addWidget(self.act_title)++ self.act_detail = QLabel('')+ self.act_detail.setObjectName('muted')+ row.addWidget(self.act_detail, 1)++ self.act_progress = QProgressBar()+ self.act_progress.setRange(0, 100)+ self.act_progress.setFixedWidth(160)+ self.act_progress.hide()+ row.addWidget(self.act_progress)++ self.act_view_btn = QPushButton(self.m.t('library.viewBuild'))+ self.act_view_btn.setObjectName('ghost')+ self.act_view_btn.clicked.connect(lambda: self._switch_page('builds'))+ self.act_view_btn.hide()+ row.addWidget(self.act_view_btn)++ self.act_stop_btn = QPushButton(self.m.t('btn.stop'))+ self.act_stop_btn.setObjectName('danger')+ self.act_stop_btn.clicked.connect(self.m.cancel_build)+ self.act_stop_btn.hide()+ row.addWidget(self.act_stop_btn)++ return bar++ def _refresh_activity_bar(self) -> None:+ if self.m.running:+ self.act_dot.set_color(style.AMBER)+ self.act_title.setText(self.m.t('activity.ios' if self.m.target == 'ios' else 'activity.mac'))+ curr_stage = next((s for s in self.m.stages if s.state == 'running'), None)+ done_cnt = sum(1 for s in self.m.stages if s.state == 'done')+ total_cnt = max(7, len(self.m.stages))+ pct = int(min(95, (done_cnt * 100) // total_cnt))+ self.act_detail.setText(f"{curr_stage.name}: {curr_stage.detail}" if curr_stage else '')+ self.act_progress.setValue(pct)+ self.act_progress.show()+ self.act_view_btn.setText(self.m.t('library.viewBuild'))+ self.act_view_btn.setVisible(self._current_page != 'builds')+ self.act_stop_btn.setText(self.m.t('btn.stop'))+ self.act_stop_btn.show()+ else:+ self.act_dot.set_color(style.GREEN if self.m.can_build else style.NEUTRAL_DOT)+ self.act_title.setText(self.m.t('library.localNote'))+ self.act_detail.setText(self.footer.text())+ self.act_progress.hide()+ self.act_view_btn.hide()+ self.act_stop_btn.hide()++ # ================================================================ Refresh Logicdef _refresh_all(self) -> None:+ t = self.m.tself.lang_btn.setText(self.m.lang.toggle_label)- # everything built once at start-up re-reads its string here: the language toggle emits- # repoChanged, and without this the card titles, the notes and the buttons kept their- # start-up language — the report's half-Chinese interface- for w, key in self._translatable:- w.setText(self.m.t(key))++ # Sync language dropdown without re-triggering signal+ self.lang_combo.blockSignals(True)+ curr_idx = next((i for i, lg in enumerate(Lang.all()) if lg.code == self.m.lang.code), 0)+ self.lang_combo.setCurrentIndex(curr_idx)+ self.lang_combo.blockSignals(False)++ # Navigation bar texts+ for pid, btn in self.nav_btns.items():+ btn.setText(t('nav.' + pid))+ self.search_input.setPlaceholderText(t('library.search'))+ self.new_build_btn.setText('+ ' + t('library.newBuild'))++ # Headings & Cards+ self.build_heading.set_text(t('build.heading'), t('build.intro'))+ self.files_group.set_title(t('section.files'))+ self.files_group.set_footer(t('msg.workdirHint'))+ self.folder_cta_title.setText(t('build.folderCTA') + ' · ' + t('data.note'))+ self.folder_cta_sub.setText(t('build.folderNote') + ' (' + t('data.folderHint') + ')')+ self.pick_folder_btn.setText(t('data.pickFolder'))+ arrow = '▾' if self._options_expanded else '▸'+ self.opt_toggle_btn.setText(f"{arrow} {t('build.options').replace('&', '&&')}")+ self.out_title_lbl.setText(t('build.saveTo'))+ self.out_btn.setText(t('build.outDir'))+ self.out_clear_btn.setText(t('data.clear'))++ self.target_group.set_title(t('section.target'))+ self.bc_title_lbl.setText(t('opt.bc'))+ self.bc_note_lbl.setText(t('opt.bc.note'))++ self.stages_card.set_title(t('prog.title'))+ self.log_group.set_title(t('build.log'))+ self.log_label.setText(t('build.log'))+ self.export_log_btn.setText(t('log.export'))+ self.log.setPlaceholderText(t('log.placeholder'))++ # Settings page texts+ self.settings_heading.set_text(t('settings.heading'), t('settings.note'))+ self.settings_lib_group.set_title(t('section.library'))+ self.lib_folder_title.setText(t('library.folderTitle'))+ self.lib_folder_path_lbl.setText(self.m.library.games_folder or t('library.folderUnset'))+ self.lib_folder_hint_lbl.setText(t('library.folderHint'))+ _set_dot(self.lib_folder_dot, style.GREEN if self.m.library.games_folder else style.NEUTRAL_DOT)+ self.settings_rescan_btn.setText(t('library.rescan'))+ self.settings_lib_choose_btn.setText(t('library.chooseFolder'))++ self.tools_group.set_title(t('section.tools'))+ self.repo_title.setText(t('repo.title'))+ self.repo_sub.setText(t('repo.note'))+ self.clone_btn.setText(t('repo.download'))+ self.repo_btn.setText(t('repo.choose'))+ self.check_upd_btn.setText(t('repo.update'))+ self.deps_title.setText(t('dep.title'))+ self.recheck_btn.setText(t('dep.recheck'))+ self.deps_toggle_btn.setText(t('dep.hide' if self._deps_expanded else 'dep.show'))+ self.install_all_btn.setText(t('dep.installAll'))+ self.diag_title_lbl.setText(t('diag.title'))+ self.diag_note_lbl.setText(t('diag.note'))+ self.diag_btn.setText(t('diag.copy'))++ self.app_group.set_title(t('section.app'))+ self.app_lang_lbl.setText(t('settings.language'))+ self.notif_title_lbl.setText(t('settings.notify'))+ self.notif_note_lbl.setText(t('settings.notifyNote'))+ self.setup_row_title.setText(t('settings.setup'))+ self.setup_row_note.setText(t('settings.setupNote'))+ self.run_onboarding_btn.setText(t('settings.setupBtn'))+ self.ver_title_lbl.setText(t('app.version', APP_VERSION))+ self.ver_status_lbl.setText(t('app.upToDate'))++ self._refresh_engine_banner()+ self._refresh_repo()+ self._refresh_deps()+ self._refresh_inputs()+ self._refresh_target()+ self._refresh_install_card()+ self._refresh_stages()+ self._refresh_running()self._show_failure()- self._show_engine_sync()- full = (pu.short_path(self.m.repo_path) if self.m.repo_ok- else (self.m.repo_path or self.m.t('repo.notFound')))- self.repo_path_label.setText(full)- self.repo_path_label.setToolTip(full) # the full path on hover when elided- if self.m.repo_ok:- self.repo_dot.setStyleSheet(f'color: {GREEN};')- self.repo_status.setText(self.m.repo_status or- (self.m.t('repo.ok') if self.m.repo_is_git else self.m.t('repo.noGit')))+ self._refresh_library()+ self._refresh_activity_bar()++ def _refresh_repo(self) -> None:+ t = self.m.t+ ok = self.m.repo_ok+ busy = self.m.repo_busy+ _set_dot(self.repo_dot, style.GREEN if ok else style.RED)+ self.repo_path_label.setText(self.m.repo_path if ok else t('repo.notFound'))+ self.clone_btn.setVisible(not ok)+ self.clone_btn.setEnabled(not busy and not self.m.running)+ self.repo_btn.setEnabled(not busy and not self.m.running)+ if not ok:+ url = 'https://github.com/LNPANDY/NX2Apple'+ self.repo_hint_label.setText(+ f'{t("repo.firstHint")}<br>{t("repo.manualHint")} '+ f'<a href="{url}" style="color:{style.ACCENT};">{url}</a>{t("repo.manualHint2")}'+ )+ self.repo_hint_label.show()else:- self.repo_dot.setStyleSheet(f'color: {RED};')- self.repo_status.setText(self.m.repo_status or self.m.t('repo.firstHint'))- # Download when there is no usable checkout; one update button when there is a git one.- self.download_btn.setVisible(not self.m.repo_ok)- self.update_btn.setVisible(self.m.repo_ok and self.m.repo_is_git)- busy = self.m.repo_busy or self.m.running- for b in (self.download_btn, self.update_btn, self.choose_btn):- b.setEnabled(not busy)- self.engine_retry_btn.setEnabled(not self.m.engine_syncing)- if getattr(self.m, 'log_path', None):- self.log_path_label.setText(self.m.t('log.at', str(self.m.log_path)))- self._refresh_inputs()- self._refresh_deps()+ self.repo_hint_label.hide()+ is_git = self.m.repo_is_git+ self.check_upd_btn.setVisible(is_git)+ self.check_upd_btn.setEnabled(not busy and not self.m.running)+ self.repo_status_label.setText(self.m.repo_status or (t('repo.ok') if ok else ''))+ self.repo_status_label.setVisible(bool(self.m.repo_status or ok))++ def _refresh_deps(self) -> None:+ t = self.m.t+ while self.deps_rows.count():+ item = self.deps_rows.takeAt(0)+ if item.widget():+ item.widget().deleteLater()++ if not self.m.deps_checked:+ _set_dot(self.deps_dot, style.NEUTRAL_DOT)+ self.deps_summary.setText(t('dep.checking'))+ self.install_all_btn.hide()+ self._refresh_running()+ return+ if not self.m.deps:+ _set_dot(self.deps_dot, style.RED)+ self.deps_summary.setText(t('dep.checkFailed'))+ self.install_all_btn.hide()+ self._refresh_running()+ return++ req_missing = sum(1 for d in self.m.deps if not d.ok and d.required)+ opt_missing = sum(1 for d in self.m.deps if not d.ok and not d.required)+ fixable = any(not d.ok and d.install for d in self.m.deps)+ any_busy = any(d.installing for d in self.m.deps)+ if req_missing == 0 and opt_missing == 0:+ _set_dot(self.deps_dot, style.GREEN)+ self.deps_summary.setText(t('dep.allReady'))+ elif req_missing == 0:+ _set_dot(self.deps_dot, style.GREEN)+ self.deps_summary.setText(t('dep.onlyOptional', opt_missing))+ elif opt_missing:+ _set_dot(self.deps_dot, style.AMBER)+ self.deps_summary.setText(t('dep.missingOptional', req_missing, opt_missing))+ else:+ _set_dot(self.deps_dot, style.AMBER)+ self.deps_summary.setText(t('dep.missing', req_missing))+ self.install_all_btn.setVisible(fixable)+ self.install_all_btn.setEnabled(not any_busy)++ for d in self.m.deps:+ self.deps_rows.addWidget(self._make_dep_row(d))++ self._refresh_running()++ def _make_dep_row(self, d: Dep) -> QFrame:+ t = self.m.t+ f = QFrame()+ f.setObjectName('subcard')+ outer = QVBoxLayout(f)+ outer.setContentsMargins(12, 10, 12, 10)+ outer.setSpacing(6)++ r = QHBoxLayout()+ r.setSpacing(10)+ color = style.GREEN if d.ok else (style.NEUTRAL_DOT if not d.required else+ (style.AMBER if d.state is DepState.OLD else style.RED))+ r.addWidget(_dot(color))+ col = QVBoxLayout()+ col.setSpacing(2)+ title = QLabel(t(d.title_key))+ title.setStyleSheet('font-weight: 600;')+ detail = self._format_dep_detail(d)+ sub = QLabel(detail or t(d.hint_key))+ sub.setObjectName('mono' if d.ok else 'muted')+ sub.setWordWrap(True)+ sub.setOpenExternalLinks(True)+ col.addWidget(title)+ col.addWidget(sub)+ r.addLayout(col, 1)++ if not d.ok and d.install:+ b = QPushButton(t('dep.installing') if d.installing else t('dep.install'))+ b.setEnabled(not d.installing)+ b.clicked.connect(lambda _=False, dep=d: self.m.install_dep(dep))+ r.addWidget(b)+ elif not d.ok and d.id == 'xcode':+ b = QPushButton(t('dep.openAppStore'))+ b.clicked.connect(lambda: QDesktopServices.openUrl(+ QUrl('macappstore://apps.apple.com/app/id497799835')))+ r.addWidget(b)+ if d.pick_key:+ label_key = 'dep.pick.metal' if d.pick_key == 'metal_dir' else 'dep.pick'+ pb = QPushButton(t(label_key))+ pb.setEnabled(not d.installing)+ pb.clicked.connect(lambda _=False, dep=d: self.m.pick_dep_folder(dep))+ r.addWidget(pb)+ outer.addLayout(r)++ guide_key = {'ios_sdk': 'dep.guide.iossdk', 'metal': 'dep.guide.metal'}.get(d.id)+ if not d.ok and guide_key:+ guide = QLabel(t(guide_key))+ guide.setObjectName('muted')+ guide.setWordWrap(True)+ guide.setOpenExternalLinks(True)+ guide.setContentsMargins(18, 2, 4, 0)+ outer.addWidget(guide)++ if not d.ok and (d.last_error or d.fix_hint):+ msg = (d.last_error + ' — ' if d.last_error else '') + (t(d.fix_hint) if d.fix_hint else '')+ err = QLabel(msg)+ err.setWordWrap(True)+ err.setStyleSheet(f'color: {style.AMBER}; font-size: 11px;')+ err.setContentsMargins(18, 2, 4, 0)+ outer.addWidget(err)+ return f++ def _format_dep_detail(self, d: Dep) -> str:+ if d.detail == 'dep.xcode.noSDK':+ return self.m.t('dep.xcode.noSDK')+ if d.detail.startswith('dep.python.old:'):+ ver = d.detail.split(':', 1)[1]+ return self.m.t('dep.python.old', ver, f'{pu.MIN_PYTHON[0]}.{pu.MIN_PYTHON[1]}')+ if d.detail.startswith('dep.python.missing:'):+ py = d.detail.split(':', 1)[1]+ return self.m.t('dep.python.missing', py)+ if d.detail.startswith('dep.python.notFound:'):+ need = d.detail.split(':', 1)[1]+ return self.m.t('dep.python.notFound', need, need)+ if d.detail.startswith('dep.python.none:'):+ found = d.detail.split(':', 1)[1]+ return self.m.t('dep.python.none', found)+ if d.detail.startswith('dep.metal.other:'):+ _, got, tested = d.detail.split(':', 2)+ return self.m.t('dep.metal.other', got, tested)+ return d.detaildef _refresh_inputs(self) -> None:- self.folder_label.setText(pu.short_path(self.m.game_dir) if self.m.game_dir- else self.m.t('data.folderHint'))- vals = {'base': self.m.base_path, 'update': self.m.update_path, 'keys': self.m.keys_path}- for key, (dot, val) in self.input_rows.items():+ t = self.m.t+ folder = self.m.game_folder+ problem = self.m.game_folder_problem+ values = {+ 'base': self.m.base_path,+ 'update': self.m.update_path,+ 'dlc': (t('data.files', len(self.m.dlc_paths)) ++ ', '.join(Path(p).name for p in self.m.dlc_paths)) if self.m.dlc_paths else '',+ 'keys': self.m.keys_path,+ }+ empty_label = {+ 'base': t('data.notSelected'),+ 'update': t('data.notSelectedOptional'),+ 'dlc': t('data.notSelectedDlc'),+ 'keys': t('data.notSelected'),+ }++ _set_dot(self.folder_cta_dot, style.GREEN if (folder or self.m.base_path) else style.NEUTRAL_DOT)++ for key, widgets in self.input_rows.items():+ widgets['title'].setText(t(widgets['title_key']))+ widgets['clear'].setText(t('data.clear'))folder_text = self.m.input_row_text(key)- if folder_text is not None: # a game folder or a NUP: what it holds, and no keys needed- dot.setText('●')- dot.setStyleSheet(f'color: {GREEN};')- val.setText(folder_text)- val.setStyleSheet(f'color: {MUTED};')- continue- if key == 'base' and self.m.game_folder_problem: # refused: the reason, on the base row- dot.setText('✕')- dot.setStyleSheet(f'color: {RED};')- val.setText(self.m.game_folder_problem)- val.setStyleSheet(f'color: {ORANGE};')- continue- if key == 'dlc':- n = len(self.m.dlc_paths)- text = (Path(self.m.dlc_paths[0]).name + (f' +{n - 1}' if n > 1 else '')) if n else ''- set_, optional = bool(n), True- else:- v = vals.get(key, '')- text, set_, optional = (Path(v).name if v else ''), bool(v), key == 'update'- if set_:- dot.setText('●')- dot.setStyleSheet(f'color: {GREEN};')- val.setText(text)- val.setStyleSheet(f'color: {MUTED};')+ if problem and key == 'base':+ widgets['path'].setText(problem)+ widgets['path'].setObjectName('muted')+ _set_dot(widgets['dot'], style.RED)+ widgets['clear'].setVisible(True)+ widgets['choose'].setText(t('data.choose'))+ widgets['choose'].setVisible(True)+ elif folder is not None and folder_text is not None:+ has_val = key == 'base' or (key == 'update' and folder.newest_update is not None) or (key == 'dlc' and bool(folder.dlc))+ widgets['path'].setText(folder_text)+ widgets['path'].setObjectName('mono' if has_val else 'muted')+ _set_dot(widgets['dot'], style.GREEN if has_val else style.NEUTRAL_DOT)+ widgets['clear'].setVisible(key == 'base')+ widgets['choose'].setVisible(False)else:- dot.setText('○' if optional else '✕')- dot.setStyleSheet(f'color: {MUTED if optional else RED};')- val.setText(self.m.t('data.notSelectedOptional') if optional else self.m.t('data.notSelected'))- val.setStyleSheet(f'color: {MUTED if optional else ORANGE};')- self._refresh_running()-- @staticmethod- def _esc(text: str) -> str:- # The failure line is tool output; keep it out of the rich-text parser.- return (text.replace('&', '&').replace('<', '<').replace('>', '>'))+ v = values[key]+ widgets['path'].setText(v if v else empty_label[key])+ widgets['path'].setObjectName('mono' if v else 'muted')+ _set_dot(widgets['dot'],+ style.GREEN if v else (style.AMBER if widgets['req'] else style.NEUTRAL_DOT))+ widgets['clear'].setVisible(bool(v))+ widgets['choose'].setText(t('data.change') if v else t('data.choose'))+ widgets['choose'].setVisible(True)+ widgets['path'].style().unpolish(widgets['path'])+ widgets['path'].style().polish(widgets['path'])- def _refresh_deps(self) -> None:- while self.deps_container.count():- item = self.deps_container.takeAt(0)- if w := item.widget():- w.deleteLater()- for d in self.m.deps:- row = QWidget()- h = QHBoxLayout(row)- h.setContentsMargins(0, 0, 0, 0)- h.setSpacing(6)- # An optional tool that is missing reads as a muted ○, not a red ✕: it does not block- # the build in front of the player, and the red row made a complete Metal toolchain look- # broken (the report's screenshot: spirv-cross and glslangValidator, both OpenGL-only).- optional_missing = not d.ok and not getattr(d, 'required', True)- mark = QLabel('●' if d.ok else ('◐' if d.state is DepState.OLD else ('○' if optional_missing else '✕')))- mark.setFixedWidth(14)- mark.setStyleSheet(f'color: {GREEN if d.ok else (MUTED if optional_missing else (ORANGE if d.state is DepState.OLD else RED))};')- h.addWidget(mark)- name = QLabel(self.m.t(d.title_key))- name.setFixedWidth(140)- h.addWidget(name)- detail = d.detail- if detail.startswith('dep.'):- if ':' in detail:- key, arg = detail.split(':', 1)- detail = self.m.t(key, arg)- else:- detail = self.m.t(detail)- elif detail:- detail = pu.short_path(detail)- # A long detail (the link probe's three-attempt report) would be elided to nothing on- # one line: it moves into its own wrapped block under the row, where it is readable.- if len(detail) > 140 or '\n' in detail:- head = QLabel(detail[:120] + '…')- head.setObjectName('mono')- head.setTextInteractionFlags(Qt.TextSelectableByMouse)- h.addWidget(head, 1)- note = QLabel(detail)- note.setObjectName('mono')- note.setWordWrap(True)- note.setTextInteractionFlags(Qt.TextSelectableByMouse)- note.setContentsMargins(20, 0, 0, 4)- self.deps_container.addWidget(row)- self.deps_container.addWidget(note)- continue- lab = QLabel(detail)- lab.setObjectName('mono')- lab.setTextInteractionFlags(Qt.TextSelectableByMouse)- lab.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred)- lab.setToolTip(detail)- h.addWidget(lab, 1)- if not d.ok:- if d.install:- btn = QPushButton(self.m.t('dep.install'))- btn.setEnabled(not d.installing)- btn.clicked.connect(lambda _=False, dep=d: self.m.install_dep(dep))- h.addWidget(btn)- if d.pick_key:- # Apple-licensed pieces cannot be downloaded by the app: Choose points at a- # copy the user already has — an unpacked folder, or (Metal) the downloaded- # zip, which the app unpacks and remembers.- pick = QPushButton(self.m.t('dep.pick.metal' if d.pick_key == 'metal_dir' else 'dep.pick'))- pick.clicked.connect(lambda _=False, dep=d: self.m.pick_dep_folder(dep))- h.addWidget(pick)- if not d.install and not d.pick_key:- hint = QLabel(self.m.t(d.hint_key))- hint.setObjectName('note')- hint.setOpenExternalLinks(True) # the Windows hints carry download links- h.addWidget(hint)- self.deps_container.addWidget(row)- # Why the last install failed and what to do: the tool's own line under the row, the- # fix under it (Mac parity). Cleared when the row installs successfully.- if not d.ok and (d.last_error or d.fix_hint):- note = QLabel(('<br>' if d.last_error and d.fix_hint else '')- + (self._esc(d.last_error) if d.last_error else '')- + ('<br>' + self.m.t(d.fix_hint) if d.fix_hint else ''))- note.setObjectName('note')- note.setOpenExternalLinks(True)- note.setContentsMargins(20, 0, 0, 4)- self.deps_container.addWidget(note)- for d in self.m.deps:- if not d.ok and not d.install and d.id == 'ios_sdk':- guide = QLabel(self.m.t('dep.guide.iossdk'))- guide.setObjectName('note')- guide.setOpenExternalLinks(True)- guide.setContentsMargins(20, 0, 0, 4)- self.deps_container.addWidget(guide)- elif not d.ok and not d.install and d.id == 'metal':- guide = QLabel(self.m.t('dep.guide.metal'))- guide.setObjectName('note')- guide.setOpenExternalLinks(True)- guide.setContentsMargins(20, 0, 0, 4)- self.deps_container.addWidget(guide)- if self.m.deps_checked:- if not self.m.deps:- # The check produced no rows at all, which means it failed — never report that as- # "all ready" (see Model.all_deps_ok) or as "0 missing".- self.deps_summary.setText('⚠ ' + self.m.t('dep.checkFailed'))- self.deps_summary.setStyleSheet(f'color: {RED}; font-weight: 600;')- elif self.m.all_deps_ok:- # Every required row passed, so the build may start. An optional tool that is not installed- # (glslangValidator for OpenGL games, spirv-cross) is said, but it is not a problem.- optional = sum(1 for d in self.m.deps if not d.ok and not d.required)- self.deps_summary.setText(self.m.t('dep.onlyOptional', optional) if optional- else '● ' + self.m.t('dep.allReady'))- self.deps_summary.setStyleSheet(f'color: {GREEN}; font-weight: 600;')+ # Live KeyCheck status when both base and keys are selected+ if folder is None and self.m.base_path and self.m.keys_path and os.path.isfile(self.m.base_path) and os.path.isfile(self.m.keys_path):+ verdict = feat.KeyCheck.check(+ self.m.keys_path,+ self.m.base_path,+ self.m.update_path,+ self.m.dlc_paths,+ )+ if verdict.kind == 'fits':+ _set_dot(self.keycheck_dot, style.GREEN)+ self.keycheck_lbl.setText(t('keycheck.fits'))+ elif verdict.kind == 'unreadableKeys':+ _set_dot(self.keycheck_dot, style.RED)+ self.keycheck_lbl.setText(t('keycheck.unreadable'))+ elif verdict.kind == 'missingHeaderKey':+ _set_dot(self.keycheck_dot, style.RED)+ self.keycheck_lbl.setText(t('keycheck.noHeaderKey'))+ elif verdict.kind == 'wrongHeaderKey':+ _set_dot(self.keycheck_dot, style.RED)+ part_name = t('keycheck.part.' + (verdict.part or 'base'))+ self.keycheck_lbl.setText(t('keycheck.wrongHeaderKey', part_name))+ elif verdict.kind == 'missingKey':+ _set_dot(self.keycheck_dot, style.AMBER)+ part_name = t('keycheck.part.' + (verdict.part or 'base'))+ msg = t('keycheck.tooOld', part_name, verdict.key)+ if verdict.firmware:+ msg += ' ' + t('keycheck.firmware', verdict.firmware)+ self.keycheck_lbl.setText(msg)else:- # Required only: an optional tool or one that only some titles need was counted here, so a- # machine that could build the game in front of it read "缺 3 项" and looked broken.- n = sum(1 for d in self.m.deps if not d.ok and d.required)- optional = sum(1 for d in self.m.deps if not d.ok and not d.required)- self.deps_summary.setText(self.m.t('dep.missingOptional', n, optional) if optional- else self.m.t('dep.missing', n))- self.deps_summary.setStyleSheet(f'color: {RED}; font-weight: 600;')+ _set_dot(self.keycheck_dot, style.NEUTRAL_DOT)+ self.keycheck_lbl.setText(t('keycheck.cannotCheck', verdict.reason))+ self.keycheck_row.show()else:- self.deps_summary.setText(self.m.t('dep.checking'))- self.deps_summary.setStyleSheet(f'color: {MUTED};')- missing_installable = [d for d in self.m.deps if not d.ok and d.install]- self.install_all_btn.setVisible(bool(missing_installable))- self.install_all_btn.setEnabled(bool(missing_installable) and- not any(d.installing for d in self.m.deps))+ self.keycheck_row.hide()++ self.out_label.setText(self.m.out_dir or t('build.saveDefault'))+ self.out_clear_btn.setVisible(bool(self.m.out_dir))self._refresh_running()- def _refresh_stages(self) -> None:- while self.stages_container.count():- item = self.stages_container.takeAt(0)- if w := item.widget():- w.deleteLater()- if not self.m.stages:- self.progress_box.setVisible(False)+ def _refresh_target(self) -> None:+ t = self.m.t+ ios = self.m.target == 'ios'+ self.target_title_lbl.setText(t('build.ios') if ios else t('build.mac'))+ self.target_btn.setText(t('target.ios' if ios else 'target.mac'))+ self.target_btn.setToolTip(t('target.tip'))+ self.target_hint.setText(t('target.hint.ios' if ios else 'target.hint.mac'))++ def _toggle_target(self) -> None:+ if self.m.running or pu.IS_WIN:return- self.progress_box.setVisible(True)+ self.m.target = 'mac-app' if self.m.target == 'ios' else 'ios'+ self._refresh_target()++ def _refresh_stages(self) -> None:+ while self.stages_col.count():+ item = self.stages_col.takeAt(0)+ if item.widget():+ item.widget().deleteLater()+ self.stages_card.setVisible(bool(self.m.stages))for st in self.m.stages:- row = QWidget()- h = QHBoxLayout(row)- h.setContentsMargins(0, 0, 0, 0)- h.setSpacing(6)- mark = {'done': '●', 'running': '◐', 'failed': '✕'}.get(st.state, '○')- colour = {'done': GREEN, 'failed': RED}.get(st.state, MUTED)- lab = QLabel(mark)- lab.setFixedWidth(14)- lab.setStyleSheet(f'color: {colour};')- h.addWidget(lab)+ r = QHBoxLayout()+ r.setSpacing(8)+ color = {+ 'done': style.GREEN,+ 'running': style.AMBER,+ 'failed': style.RED,+ }.get(st.state, style.NEUTRAL_DOT)+ r.addWidget(_dot(color))name = QLabel(st.name)- h.addWidget(name, 0)if st.state == 'running':- bar = QProgressBar()- bar.setTextVisible(False)- bar.setFixedWidth(150)- bar.setRange(0, 0)- h.addWidget(bar)- det = QLabel(st.detail)- det.setObjectName('mono')- h.addWidget(det, 1)- self.stages_container.addWidget(row)- done = sum(1 for s in self.m.stages if s.state == 'done')- self.overall.setRange(0, len(self.m.stages))- self.overall.setValue(done)+ name.setStyleSheet('font-weight: 700;')+ elif st.state != 'done':+ name.setObjectName('muted')+ r.addWidget(name)+ detail = QLabel(st.detail if st.state == 'running' else '')+ detail.setObjectName('mono')+ r.addWidget(detail, 1, Qt.AlignRight)+ w = QWidget()+ w.setLayout(r)+ self.stages_col.addWidget(w)+ self._refresh_activity_bar()def _refresh_running(self) -> None:- running = self.m.running- self.build_btn.setText(self.m.t('build.cancel') if running else self.m.t('build.start'))- self.build_btn.setObjectName('danger' if running else 'primary')+ t = self.m.t+ if self.m.running:+ self.build_btn.setText(t('build.cancel'))+ self.build_btn.setObjectName('danger')+ self.build_btn.setEnabled(True)+ else:+ self.build_btn.setText(t('build.start'))+ self.build_btn.setObjectName('primary')+ self.build_btn.setEnabled(self.m.can_build)+ if not self.m.can_build and not self._failed:+ if not self.m.repo_ok:+ why = t('status.chooseRepo')+ elif not self.m.deps_checked:+ why = t('status.checkingDeps')+ elif not self.m.all_deps_ok:+ why = t('status.installFirst')+ elif self.m.game_folder_problem:+ why = t('status.fixFolder')+ else:+ why = t('status.needInputs')+ self.footer.setText(why)+ elif self.m.can_build and not self.m.ipa_path and not self.m.mac_app_path and self.m.failure is None and not self._failed:+ self.footer.setText('')++ # SetupHintCard visibility on Builds page+ setup_needed = not self.m.repo_ok or (self.m.deps_checked and not self.m.all_deps_ok)+ self.setup_hint_card.setVisible(setup_needed)+ if setup_needed:+ self.setup_hint_title.setText(t('library.setupHint'))+ self.setup_hint_sub.setText(t('status.chooseRepo') if not self.m.repo_ok else t('status.installFirst'))+ self.setup_goto_btn.setText(t('nav.settings'))+self.build_btn.style().unpolish(self.build_btn)self.build_btn.style().polish(self.build_btn)- self.build_btn.setEnabled(running or self.m.can_build)- # Re-set on every refresh, and clear when a build runs (the build's own progress text- # takes the footer). "only when empty" wrote the start-up language once and never- # updated it — the footer was English after the toggle.- if running:- self.footer.setText('')- elif getattr(self, '_failed', False):- pass # a failure message stays until the next build: it was being replaced by- # the input reminder on the refresh that follows the failure (issue #52)- elif not self.m.deps_checked:- self.footer.setText(self.m.t('status.checkingDeps'))- elif not self.m.all_deps_ok:- self.footer.setText(self.m.t('status.installFirst'))- elif not self.m.repo_ok:- self.footer.setText(self.m.t('status.chooseRepo'))- elif not (self.m.game_folder is not None or (self.m.base_path and self.m.keys_path)):- # what can_build asks for: a game folder, or the base package and the keys- self.footer.setText(self.m.t('status.needInputs'))- elif not self.footer.text() or self.footer.text() in (- self.m.t('status.needInputs'), self.m.t('status.chooseRepo'),- self.m.t('status.checkingDeps'), self.m.t('status.installFirst')):- self.footer.setText('')+ self._refresh_activity_bar()def _append_log(self, s: str) -> None:- self.log.moveCursor(self.log.textCursor().MoveOperation.End)- self.log.insertPlainText(s)- self.log.moveCursor(self.log.textCursor().MoveOperation.End)- # The script marks a shader-chain bump with this tag: the cached libraries cannot be- # reused and this build recompiles them. A popup, not a log line — the report's question- # ("why is it building shaders again, the artifacts are on the drive") came from exactly- # this moment passing unnoticed. Once per build: the log chunks arrive in pieces.- if '[NOTE] chain-changed' in s and not getattr(self, '_chain_note_shown', False):- self._chain_note_shown = True- from PySide6.QtWidgets import QMessageBox- QMessageBox.information(self, 'NS Port Builder', self.m.t('msg.chainChanged'))+ c = self.log.textCursor()+ c.movePosition(c.MoveOperation.End)+ c.insertText(s)+ self.log.setTextCursor(c)+ self.log.ensureCursorVisible()def _on_finished(self, ok: bool, note: str) -> None:+ t = self.m.t+ self._failed = not okif ok:- msg = note or self.m.t('msg.done')- if self.m.ipa_path:- msg += ' ' + self.m.t('msg.ipaAt', self.m.ipa_path)- if self.m.archive_path:- msg += ' ' + self.m.t('msg.archiveAt', self.m.archive_path)- self.footer.setStyleSheet(f'color: {GREEN};')+ out = self.m.mac_app_path or self.m.ipa_path+ self.footer.setText(note or (t('status.output', out) if out else t('msg.done')))else:- msg = note or self.m.t('msg.buildFailed')- self.footer.setStyleSheet(f'color: {RED};')- self.footer.setText(msg)- self._failed = not ok- self._show_failure()- if not ok:- # The message points at the log, so put it in view rather than trusting the window to- # be tall enough. ensureWidgetVisible also handles the scroll area's own margin.+ self.footer.setText(note or t('msg.buildFailed'))+ if self._current_page != 'builds':+ self._switch_page('builds')self.scroll.ensureWidgetVisible(self.log, 0, 0)- self.log.setFocus(Qt.OtherFocusReason)- self._refresh_running()+ self._show_failure()+ self.reveal_ipa_btn.setToolTip(t('msg.ipaAt', self.m.ipa_path) if self.m.ipa_path else '')+ self.reveal_arc_btn.setToolTip(t('msg.archiveAt', self.m.archive_path) if self.m.archive_path else '')+ self.reveal_ipa_btn.setVisible(bool(self.m.ipa_path) and Path(self.m.ipa_path).exists())+ self.reveal_arc_btn.setVisible(bool(self.m.archive_path) and Path(self.m.archive_path).exists())+ self.reveal_app_btn.setVisible(bool(self.m.mac_app_path) and Path(self.m.mac_app_path).exists())+ self._refresh_install_card()+ self._refresh_library()+ self._refresh_activity_bar()- # ---------------------------------------------------------------- actions+ if self.m.settings_value('notifyOnComplete', True) and not self.isActiveWindow():+ QApplication.beep()- def _toggle_lang(self) -> None:- self.m.toggle_lang()- self._refresh_all()+ # ================================================================ Failure Card Actions- def _build_clicked(self) -> None:- if self.m.running:- self.m.cancel_build()- else:- self.footer.setText('')- self.footer.setStyleSheet('')- self._failed = False+ def _show_failure(self) -> None:+ t = self.m.t+ f = self.m.failure+ if f is None or f.kind == bf.UNKNOWN or self.m.running:self.failure_box.hide()- self.m.start_build()+ return+ self.failure_title.setText(t('fail.section'))+ self.failure_what.setText(self.m.failure_what(f))+ self.failure_next.setText(t(f.next_key))+ folder = self.m.failure_folder(f)+ self.failure_folder_btn.setText(t('fail.showFolder'))+ self.failure_folder_btn.setVisible(+ f.kind in (bf.NO_TITLE_ID, bf.SEVERAL_GAMES, bf.DISK_FULL, bf.CLOUD_FOLDER) and bool(folder))+ fix_key = {+ bf.KEYS: 'fail.keys.button',+ bf.CLOUD_FOLDER: 'fail.cloudFolder.button',+ bf.TRANSLATOR: 'fail.translator.button',+ bf.ZBIC: 'fail.zbic.button',+ bf.IOS_SDK: 'fail.iosSDK.button',+ }.get(f.kind)+ if fix_key and (f.kind != bf.IOS_SDK or not pu.IS_WIN):+ self.failure_fix_btn.setText(t(fix_key))+ self.failure_fix_btn.show()+ else:+ self.failure_fix_btn.hide()+ self.failure_anyway_btn.setText(t('fail.buildAnyway'))+ self.failure_anyway_btn.setVisible(bool(f.flag))+ self.failure_box.show()- def _ask_folder(self, title: str) -> str:- d = QFileDialog.getExistingDirectory(self, title)- return d or ''+ def _open_failure_folder(self) -> None:+ if self.m.failure:+ folder = self.m.failure_folder(self.m.failure)+ if folder:+ pu.reveal(folder)- def _ask_file(self, title: str) -> str:- d, _ = QFileDialog.getOpenFileName(self, title, '', 'Metal tools zip (*.zip)')- return d or ''+ def _fix_failure(self) -> None:+ f = self.m.failure+ if f is None:+ return+ if f.kind == bf.KEYS:+ self._pick_input('keys', False)+ elif f.kind == bf.CLOUD_FOLDER:+ self._pick_out_dir()+ else:+ self.m.fix_failure(f)- def _choose_repo(self) -> None:- d = QFileDialog.getExistingDirectory(self, self.m.t('repo.pickMessage'))- if d:- self.m.repo_path = d- self.m.repoChanged.emit()+ def _build_anyway(self) -> None:+ if not self.m.override.request(self.m.failure):+ return+ f = self.m.override.confirming+ assert f is not None+ ans = QMessageBox.question(+ self,+ self.m.t('fail.confirm.title'),+ self.m.t(f'fail.{f.kind}.risk'),+ QMessageBox.Yes | QMessageBox.Cancel,+ QMessageBox.Cancel,+ )+ if ans == QMessageBox.Yes and self.m.override.confirm():+ self._build_clicked()+ else:+ self.m.override.cancel()- def _pick_folder(self) -> None:- d = QFileDialog.getExistingDirectory(self, self.m.t('data.pickFolder'))- if d:- self.m.scan_game_dir(d)+ def _on_app_update(self, tag: str, url: str) -> None:+ self.update_btn.setText(self.m.t('app.updateBtn', tag))+ self.update_btn.setToolTip(url)+ try:+ self.update_btn.clicked.disconnect()+ except (RuntimeError, TypeError):+ pass+ self.update_btn.clicked.connect(lambda: QDesktopServices.openUrl(QUrl(url)))+ self.update_btn.show()- def _choose_input(self, key: str) -> None:- path, _ = QFileDialog.getOpenFileName(self, self.m.t('data.choose'))- if not path:- return- if key == 'base' and inputs.is_game_folder_candidate(path): # a .nup file- self.m.take_game_folder(path)+ # ================================================================ File Pickers & Build Trigger++ def _ask_metal_archive(self, title: str) -> str:+ picked, _ = QFileDialog.getOpenFileName(+ self, title, str(Path.home() / 'Downloads'),+ 'Metal Developer Tools (*.zip *.exe *.msi);;All files (*)')+ if picked:+ return picked+ return QFileDialog.getExistingDirectory(self, title, str(Path.home()))++ def _pick_repo(self) -> None:+ d = QFileDialog.getExistingDirectory(+ self, self.m.t('repo.pickMessage'), self.m.repo_path or str(Path.home()))+ if not d:return- self.m.leave_game_folder() # picking packages leaves the game-folder mode- if key == 'base':- self.m.base_path = path- elif key == 'update':- self.m.update_path = path- elif key == 'keys':- self.m.keys_path = path+ if self.m.is_repo(d):+ self.m.repo_path = d+ self.m.sync_engine()+ self._refresh_repo()+ self._refresh_running()else:- if path not in self.m.dlc_paths:- self.m.dlc_paths.append(path)- self.m.repoChanged.emit()+ QMessageBox.warning(self, self.m.t('repo.title'), self.m.t('repo.notRepo', d))- def _export_log(self) -> None:- """Save the log to a file the user picks, defaulting to the Desktop.-- The window's log is also written to disk as it grows (m.model.log_path); this is for- sending a copy somewhere, e.g. attaching it to an issue from a handheld where copying text- out of the window is awkward.- """- default = str(Path.home() / 'Desktop' / 'ns-port-builder-log.txt')- path, _ = QFileDialog.getSaveFileName(self, self.m.t('log.export'), default,- 'Text (*.txt);;All files (*)')- if not path:+ def _pick_game_dir(self) -> None:+ d = QFileDialog.getExistingDirectory(+ self, self.m.t('data.pickFolder'), self.m.game_dir or self.m.library.games_folder or str(Path.home()))+ if not d:return- try:- Path(path).write_text(self.log.toPlainText(), encoding='utf-8')- self.footer.setText(self.m.t('log.exported', path))- self.footer.setStyleSheet(f'color: {GREEN};')- except OSError as e:- self.footer.setText(self.m.t('log.exportFail', str(e)))- self.footer.setStyleSheet(f'color: {RED};')+ self.m.scan_game_dir(d)+ if not self.m.base_path and self.m.game_folder is None and not self.m.game_folder_problem:+ QMessageBox.information(self, self.m.t('data.title'), self.m.t('data.noBase'))+ elif self.m.base_path:+ g = self.m.library.remember_inputs(+ base_path=self.m.base_path,+ update_path=self.m.update_path,+ dlc_paths=self.m.dlc_paths,+ keys_path=self.m.keys_path,+ output_dir=self.m.out_dir,+ repo_path=self.m.engine_path,+ )+ if g:+ self.m.artwork.request_banner_async(g.title_id)- def _toggle_target(self) -> None:- """Switch between an iPhone IPA and a Mac app (macOS only)."""- self.m.target = 'mac-app' if self.m.target == 'ios' else 'ios'- self.target_btn.setText(self.m.t('target.mac' if self.m.target == 'mac-app' else 'target.ios'))- self.footer.setText(self.m.t('target.hint.mac' if self.m.target == 'mac-app' else 'target.hint.ios'))- self.footer.setStyleSheet('')+ def _pick_input(self, key: str, multi: bool) -> None:+ start = self.m.game_dir or (str(Path(self.m.base_path).parent) if self.m.base_path else str(Path.home()))+ if key == 'keys':+ f, _ = QFileDialog.getOpenFileName(+ self, 'prod.keys', start, 'Keys (prod.keys *.keys *);;All files (*)')+ if f:+ self.m.keys_path = f+ elif multi:+ fs, _ = QFileDialog.getOpenFileNames(+ self, 'DLC', start, 'Switch dumps (*.nsp *.xci *.nsz *.xcz)')+ if fs:+ self.m.leave_game_folder()+ self.m.dlc_paths = fs+ else:+ flt = 'Switch games (*.nsp *.xci *.nsz *.xcz *.nup)' if key == 'base' else 'Switch dumps (*.nsp *.xci *.nsz *.xcz)'+ f, _ = QFileDialog.getOpenFileName(self, key, start, flt)+ if f:+ if key == 'base' and inputs.is_game_folder_candidate(f):+ self.m.take_game_folder(f)+ return+ self.m.leave_game_folder()+ setattr(self.m, f'{key}_path', f)+ self._refresh_inputs()- def _choose_out(self) -> None:- d = QFileDialog.getExistingDirectory(self, self.m.t('build.outDir'))+ def _clear_input(self, key: str) -> None:+ if key == 'base' and (self.m.game_folder is not None or self.m.game_folder_problem):+ self.m.leave_game_folder()+ elif key == 'dlc':+ self.m.dlc_paths = []+ else:+ setattr(self.m, f'{key}_path', '')+ self._refresh_inputs()++ def _pick_out_dir(self) -> None:+ d = QFileDialog.getExistingDirectory(+ self, self.m.t('build.outDir'), self.m.out_dir or str(Path.home()))if d:self.m.out_dir = d- self._refresh_all()+ self._refresh_inputs()++ def _clear_out_dir(self) -> None:+ self.m.out_dir = ''+ self._refresh_inputs()++ def _build_clicked(self) -> None:+ if self.m.running:+ self.m.cancel_build()+ return+ self._failed = False+ self.reveal_ipa_btn.hide()+ self.reveal_arc_btn.hide()+ self.reveal_app_btn.hide()+ self.footer.setText('')+ self.m.start_build()++ # ================================================================ Full-Window Drag & Drop++ def resizeEvent(self, event) -> None:+ super().resizeEvent(event)+ if hasattr(self, 'drop_overlay') and self.centralWidget():+ self.drop_overlay.setGeometry(self.centralWidget().rect())++ def dragEnterEvent(self, event: QDragEnterEvent) -> None:+ if event.mimeData().hasUrls():+ event.acceptProposedAction()+ self.drop_overlay.set_hint(self.m.t('drop.hint'))+ self.drop_overlay.setGeometry(self.centralWidget().rect())+ self.drop_overlay.raise_()+ self.drop_overlay.show()++ def dragLeaveEvent(self, _event) -> None:+ self.drop_overlay.hide()++ def dropEvent(self, event: QDropEvent) -> None:+ self.drop_overlay.hide()+ urls = event.mimeData().urls()+ paths = [u.toLocalFile() for u in urls if u.isLocalFile()]+ if not paths:+ return+ event.acceptProposedAction()++ pkg_files: list[Path] = []+ for p in paths:+ if os.path.isdir(p):+ self.m.scan_game_dir(p)+ self._switch_page('builds')+ self._refresh_all()+ return+ low = os.path.basename(p).lower()+ if low == 'prod.keys' or low.endswith('.keys'):+ self.m.keys_path = p+ elif low.endswith('.nup'):+ self.m.take_game_folder(p)+ elif os.path.splitext(low)[1] in inputs.GAME_SUFFIXES:+ pkg_files.append(Path(p))++ if pkg_files:+ self.m.leave_game_folder()+ classified = inputs.classify(pkg_files)+ if classified.get('base'):+ self.m.base_path = str(classified['base'])+ if classified.get('update'):+ self.m.update_path = str(classified['update'])+ if classified.get('dlc'):+ self.m.dlc_paths = [str(x) for x in classified['dlc']]++ if self.m.base_path:+ g = self.m.library.remember_inputs(+ base_path=self.m.base_path,+ update_path=self.m.update_path,+ dlc_paths=self.m.dlc_paths,+ keys_path=self.m.keys_path,+ output_dir=self.m.out_dir,+ repo_path=self.m.engine_path,+ )+ if g:+ self.m.artwork.request_banner_async(g.title_id)++ self._switch_page('builds')+ self._refresh_all()diff --git a/frontend-qt/nspb_qt/widgets.py b/frontend-qt/nspb_qt/widgets.pynew file mode 100644index 00000000..9d5ab37e--- /dev/null+++ b/frontend-qt/nspb_qt/widgets.py@@ -0,0 +1,610 @@+"""Custom QPainter widgets and card primitives mirroring the Mac SwiftUI launcher."""+from __future__ import annotations++from typing import Callable++from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal+from PySide6.QtGui import (+ QColor,+ QFont,+ QFontMetrics,+ QLinearGradient,+ QMouseEvent,+ QPainter,+ QPainterPath,+ QPen,+ QPixmap,+)+from PySide6.QtWidgets import (+ QFrame,+ QHBoxLayout,+ QLabel,+ QPushButton,+ QSizePolicy,+ QVBoxLayout,+ QWidget,+)++from . import style+++class StatusDot(QWidget):+ """A 7px status indicator circle (LauncherTone)."""++ def __init__(self, color: str = style.NEUTRAL_DOT, size: int = 8, parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self._color = color+ self._size = size+ self.setFixedSize(size + 4, size + 4)++ def set_color(self, color: str) -> None:+ if self._color != color:+ self._color = color+ self.update()++ def paintEvent(self, _event) -> None:+ p = QPainter(self)+ p.setRenderHint(QPainter.Antialiasing)+ p.setPen(Qt.NoPen)+ p.setBrush(QColor(self._color))+ off = 2.0+ p.drawEllipse(QRectF(off, off, self._size, self._size))+++class LauncherSwitch(QWidget):+ """Pill toggle switch matching SwiftUI's LauncherSwitchStyle (40x24, cream track when on)."""++ toggled = Signal(bool)++ def __init__(self, checked: bool = False, parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self._checked = bool(checked)+ self.setFixedSize(42, 24)+ self.setCursor(Qt.PointingHandCursor)++ def isChecked(self) -> bool:+ return self._checked++ def setChecked(self, val: bool) -> None:+ val = bool(val)+ if self._checked != val:+ self._checked = val+ self.update()++ def mouseReleaseEvent(self, event: QMouseEvent) -> None:+ if event.button() == Qt.LeftButton and self.isEnabled():+ self._checked = not self._checked+ self.update()+ self.toggled.emit(self._checked)++ def paintEvent(self, _event) -> None:+ p = QPainter(self)+ p.setRenderHint(QPainter.Antialiasing)+ rect = QRectF(1, 1, self.width() - 2, self.height() - 2)+ radius = rect.height() / 2.0++ if not self.isEnabled():+ track = QColor(255, 255, 255, 20)+ knob = QColor(255, 255, 255, 90)+ elif self._checked:+ track = QColor(style.ACCENT)+ knob = QColor(style.ACCENT_INK)+ else:+ track = QColor(255, 255, 255, 36)+ knob = QColor(255, 255, 255, 230)++ p.setPen(QPen(QColor(255, 255, 255, 25 if not self._checked else 0), 1.0))+ p.setBrush(track)+ p.drawRoundedRect(rect, radius, radius)++ knob_d = 18.0+ knob_y = (self.height() - knob_d) / 2.0+ knob_x = (self.width() - knob_d - 3.0) if self._checked else 3.0+ p.setPen(Qt.NoPen)+ p.setBrush(knob)+ p.drawEllipse(QRectF(knob_x, knob_y, knob_d, knob_d))+++class LauncherSegmented(QWidget):+ """Capsule segmented control matching SwiftUI's LauncherSegmented (cream active pill)."""++ changed = Signal(str)++ def __init__(self, items: list[tuple[str, str]] | None = None, selected: str = '', parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self._items: list[tuple[str, str]] = list(items or [])+ self._selected = selected or (self._items[0][0] if self._items else '')+ self.setFixedHeight(34)+ self.setCursor(Qt.PointingHandCursor)+ self._recalc_width()++ def set_items(self, items: list[tuple[str, str]], selected: str | None = None) -> None:+ self._items = list(items)+ if selected is not None:+ self._selected = selected+ elif self._items and all(k != self._selected for k, _ in self._items):+ self._selected = self._items[0][0]+ self._recalc_width()+ self.update()++ def selected(self) -> str:+ return self._selected++ def set_selected(self, key: str) -> None:+ if self._selected != key:+ self._selected = key+ self.update()++ def _recalc_width(self) -> None:+ fm = QFontMetrics(self.font())+ total = 8+ for _, label in self._items:+ total += max(68, fm.horizontalAdvance(label) + 28)+ self.setFixedWidth(max(120, total))++ def mouseReleaseEvent(self, event: QMouseEvent) -> None:+ if event.button() != Qt.LeftButton or not self.isEnabled() or not self._items:+ return+ n = len(self._items)+ seg_w = (self.width() - 6.0) / n+ idx = int((event.position().x() - 3.0) // seg_w)+ idx = max(0, min(n - 1, idx))+ key = self._items[idx][0]+ if key != self._selected:+ self._selected = key+ self.update()+ self.changed.emit(key)++ def paintEvent(self, _event) -> None:+ p = QPainter(self)+ p.setRenderHint(QPainter.Antialiasing)+ outer = QRectF(0.5, 0.5, self.width() - 1.0, self.height() - 1.0)+ p.setPen(QPen(QColor(255, 255, 255, 26), 1.0))+ p.setBrush(QColor(255, 255, 255, 13))+ p.drawRoundedRect(outer, outer.height() / 2.0, outer.height() / 2.0)++ if not self._items:+ return+ n = len(self._items)+ seg_w = (self.width() - 6.0) / n+ for i, (key, label) in enumerate(self._items):+ r = QRectF(3.0 + i * seg_w, 3.0, seg_w, self.height() - 6.0)+ active = key == self._selected+ if active:+ p.setPen(Qt.NoPen)+ p.setBrush(QColor(style.ACCENT))+ p.drawRoundedRect(r, r.height() / 2.0, r.height() / 2.0)+ p.setPen(QColor(style.ACCENT_INK))+ f = QFont(self.font())+ f.setBold(True)+ p.setFont(f)+ else:+ p.setPen(QColor(255, 255, 255, 190))+ f = QFont(self.font())+ f.setBold(False)+ p.setFont(f)+ p.drawText(r, Qt.AlignCenter, label)+++class CardPageHeading(QWidget):+ """Large page heading + optional subtitle note (CardPageHeading in LauncherCard.swift)."""++ def __init__(self, title: str = '', note: str = '', parent: QWidget | None = None) -> None:+ super().__init__(parent)+ lay = QVBoxLayout(self)+ lay.setContentsMargins(0, 0, 0, 4)+ lay.setSpacing(6)+ self.title_label = QLabel(title)+ self.title_label.setObjectName('pageTitle')+ self.note_label = QLabel(note)+ self.note_label.setObjectName('pageNote')+ self.note_label.setWordWrap(True)+ lay.addWidget(self.title_label)+ lay.addWidget(self.note_label)+ self.note_label.setVisible(bool(note))++ def set_text(self, title: str, note: str = '') -> None:+ self.title_label.setText(title)+ self.note_label.setText(note)+ self.note_label.setVisible(bool(note))+++class CardGroup(QWidget):+ """Rounded dark card with optional section header and footer (CardGroup in LauncherCard.swift)."""++ def __init__(self, title: str = '', footer: str = '', parent: QWidget | None = None) -> None:+ super().__init__(parent)+ outer = QVBoxLayout(self)+ outer.setContentsMargins(0, 0, 0, 0)+ outer.setSpacing(8)++ self.header_row = QHBoxLayout()+ self.header_row.setContentsMargins(4, 0, 4, 0)+ self.title_label = QLabel(title)+ self.title_label.setObjectName('sectionTitle')+ self.header_row.addWidget(self.title_label)+ self.header_row.addStretch(1)+ outer.addLayout(self.header_row)+ self.title_label.setVisible(bool(title))++ self.card = QFrame()+ self.card.setObjectName('card')+ self.body_layout = QVBoxLayout(self.card)+ self.body_layout.setContentsMargins(0, 2, 0, 2)+ self.body_layout.setSpacing(0)+ outer.addWidget(self.card)++ self.footer_label = QLabel(footer)+ self.footer_label.setObjectName('sectionFoot')+ self.footer_label.setWordWrap(True)+ self.footer_label.setContentsMargins(4, 0, 4, 0)+ outer.addWidget(self.footer_label)+ self.footer_label.setVisible(bool(footer))++ def set_title(self, title: str) -> None:+ self.title_label.setText(title)+ self.title_label.setVisible(bool(title))++ def set_footer(self, footer: str) -> None:+ self.footer_label.setText(footer)+ self.footer_label.setVisible(bool(footer))++ def add_row(self, widget: QWidget) -> None:+ self.body_layout.addWidget(widget)++ def add_divider(self) -> QFrame:+ div_wrap = QWidget()+ h = QHBoxLayout(div_wrap)+ h.setContentsMargins(18, 0, 18, 0)+ d = QFrame()+ d.setObjectName('divider')+ h.addWidget(d)+ self.body_layout.addWidget(div_wrap)+ return d+++def make_divider() -> QFrame:+ d = QFrame()+ d.setObjectName('divider')+ return d+++def _fallback_gradient_colors(title_id: str) -> tuple[QColor, QColor]:+ h = 0+ for ch in (title_id or '0100'):+ h = (h * 31 + ord(ch)) & 0xFFFFFFFF+ palettes = [+ (QColor('#1e293b'), QColor('#0f172a')),+ (QColor('#31102f'), QColor('#13071e')),+ (QColor('#14332a'), QColor('#091914')),+ (QColor('#3b2314'), QColor('#1a0f08')),+ (QColor('#1f243d'), QColor('#0c0e1a')),+ (QColor('#2d1b36'), QColor('#120b18')),+ ]+ return palettes[h % len(palettes)]+++class HeroBannerWidget(QWidget):+ """Full-bleed Hero showcase for the selected game (mirrors LauncherView+Library.swift hero)."""++ primaryClicked = Signal()+ manageClicked = Signal(QWidget)++ def __init__(self, parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self.setMinimumHeight(330)+ self.setMaximumHeight(410)+ self._pixmap: QPixmap | None = None+ self._image_path: str = ''+ self._title_id: str = ''+ self._title_text: str = ''+ self._status_text: str = ''+ self._status_color: str = style.NEUTRAL_DOT+ self._is_switch2: bool = False+ self._switch2_text: str = 'Switch 2'++ lay = QVBoxLayout(self)+ lay.setContentsMargins(36, 28, 36, 28)+ lay.setSpacing(10)+ lay.addStretch(1)++ # Status + Switch 2 badge row+ status_row = QHBoxLayout()+ status_row.setSpacing(8)+ self.dot = StatusDot(style.GREEN, size=8)+ self.status_lbl = QLabel('')+ self.status_lbl.setStyleSheet('font-size: 11.5px; font-weight: 700; color: rgba(255,255,255,0.82); letter-spacing: 0.6px;')+ self.sw2_badge = QLabel('Switch 2')+ self.sw2_badge.setStyleSheet(+ f'background: rgba(255, 240, 214, 0.16); color: {style.ACCENT}; '+ f'border: 1px solid rgba(255, 240, 214, 0.42); border-radius: 9px; '+ f'padding: 2px 9px; font-size: 11px; font-weight: 700;'+ )+ self.sw2_badge.hide()+ status_row.addWidget(self.dot)+ status_row.addWidget(self.status_lbl)+ status_row.addWidget(self.sw2_badge)+ status_row.addStretch(1)+ lay.addLayout(status_row)++ # Giant game title+ self.title_lbl = QLabel('')+ self.title_lbl.setWordWrap(True)+ self.title_lbl.setStyleSheet('font-size: 38px; font-weight: 800; color: #ffffff;')+ lay.addWidget(self.title_lbl)++ # Subtitle (Title ID / output note)+ self.sub_lbl = QLabel('')+ self.sub_lbl.setObjectName('mono')+ self.sub_lbl.setStyleSheet('font-size: 12px; color: rgba(255,255,255,0.58);')+ lay.addWidget(self.sub_lbl)+ lay.addSpacing(6)++ # Action bar: primary capsule CTA + Manage button+ act_row = QHBoxLayout()+ act_row.setSpacing(12)+ self.primary_btn = QPushButton('')+ self.primary_btn.setObjectName('heroPlay')+ self.primary_btn.setMinimumWidth(196)+ self.primary_btn.setFixedHeight(50)+ self.primary_btn.setCursor(Qt.PointingHandCursor)+ self.primary_btn.clicked.connect(self.primaryClicked.emit)++ self.manage_btn = QPushButton('⋯')+ self.manage_btn.setObjectName('heroSecondary')+ self.manage_btn.setFixedHeight(42)+ self.manage_btn.setCursor(Qt.PointingHandCursor)+ self.manage_btn.clicked.connect(lambda: self.manageClicked.emit(self.manage_btn))++ act_row.addWidget(self.primary_btn)+ act_row.addWidget(self.manage_btn)+ act_row.addStretch(1)+ lay.addLayout(act_row)++ def set_data(+ self,+ title_id: str,+ title: str,+ subtitle: str,+ status_text: str,+ status_color: str,+ primary_label: str,+ primary_enabled: bool,+ manage_label: str,+ image_path: str | None,+ is_switch2: bool = False,+ switch2_label: str = 'Switch 2',+ ) -> None:+ self._title_id = title_id+ self._title_text = title+ self.title_lbl.setText(title)+ self.sub_lbl.setText(subtitle)+ self.status_lbl.setText(status_text.upper())+ self.dot.set_color(status_color)+ self.primary_btn.setText(primary_label)+ self.primary_btn.setEnabled(primary_enabled)+ self.manage_btn.setText(f'⋯ {manage_label}')+ self.sw2_badge.setText(switch2_label)+ self.sw2_badge.setVisible(is_switch2)++ new_img = image_path or ''+ if new_img != self._image_path:+ self._image_path = new_img+ if new_img:+ pm = QPixmap(new_img)+ self._pixmap = pm if not pm.isNull() else None+ else:+ self._pixmap = None+ self.update()++ def paintEvent(self, _event) -> None:+ p = QPainter(self)+ p.setRenderHint(QPainter.Antialiasing)+ p.setRenderHint(QPainter.SmoothPixmapTransform)+ w, h = float(self.width()), float(self.height())+ rect = QRectF(0, 0, w, h)++ if self._pixmap and not self._pixmap.isNull():+ pw, ph = float(self._pixmap.width()), float(self._pixmap.height())+ scale = max(w / max(1.0, pw), h / max(1.0, ph))+ sw, sh = pw * scale, ph * scale+ sx = (w - sw) * 0.5+ sy = (h - sh) * 0.25+ p.drawPixmap(QRectF(sx, sy, sw, sh), self._pixmap, QRectF(0, 0, pw, ph))+ else:+ c1, c2 = _fallback_gradient_colors(self._title_id)+ bg = QLinearGradient(0, 0, w, h)+ bg.setColorAt(0.0, c1)+ bg.setColorAt(1.0, c2)+ p.fillRect(rect, bg)+ # Subtle decorative monogram on the right+ if self._title_text:+ p.save()+ f = QFont(self.font())+ f.setPixelSize(160)+ f.setBold(True)+ p.setFont(f)+ p.setPen(QColor(255, 255, 255, 14))+ p.drawText(QRectF(w * 0.45, 10, w * 0.5, h - 20), Qt.AlignRight | Qt.AlignVCenter, self._title_text[:2].upper())+ p.restore()++ # Vertical gradient (matching LauncherView+Library.swift heroScrim)+ vg = QLinearGradient(0, 0, 0, h)+ vg.setColorAt(0.0, QColor(0, 0, 0, 46))+ vg.setColorAt(0.45, QColor(0, 0, 0, 115))+ vg.setColorAt(0.85, QColor(0, 0, 0, 232))+ vg.setColorAt(1.0, QColor(0, 0, 0, 255))+ p.fillRect(rect, vg)++ # Left readability scrim (580px wide)+ hg = QLinearGradient(0, 0, min(w, 620.0), 0)+ hg.setColorAt(0.0, QColor(0, 0, 0, 165))+ hg.setColorAt(1.0, QColor(0, 0, 0, 0))+ p.fillRect(QRectF(0, 0, min(w, 620.0), h), hg)+++class GameCardWidget(QWidget):+ """16:9 game card in the Collection strip (mirrors gameCard in LauncherView+Library.swift)."""++ clicked = Signal(str)+ doubleClicked = Signal(str)++ CARD_W = 228+ ART_H = 128+ TOTAL_H = 166++ def __init__(+ self,+ title_id: str,+ title: str,+ image_path: str | None,+ selected: bool,+ dot_color: str,+ is_switch2: bool = False,+ switch2_label: str = 'Switch 2',+ parent: QWidget | None = None,+ ) -> None:+ super().__init__(parent)+ self.title_id = title_id+ self.title = title+ self.selected = selected+ self.dot_color = dot_color+ self.is_switch2 = is_switch2+ self.switch2_label = switch2_label+ self._hovered = False+ self._pixmap: QPixmap | None = None+ if image_path:+ pm = QPixmap(image_path)+ if not pm.isNull():+ self._pixmap = pm+ self.setFixedSize(self.CARD_W, self.TOTAL_H)+ self.setCursor(Qt.PointingHandCursor)++ def enterEvent(self, _event) -> None:+ self._hovered = True+ self.update()++ def leaveEvent(self, _event) -> None:+ self._hovered = False+ self.update()++ def mouseReleaseEvent(self, event: QMouseEvent) -> None:+ if event.button() == Qt.LeftButton:+ self.clicked.emit(self.title_id)++ def mouseDoubleClickEvent(self, event: QMouseEvent) -> None:+ if event.button() == Qt.LeftButton:+ self.doubleClicked.emit(self.title_id)++ def paintEvent(self, _event) -> None:+ p = QPainter(self)+ p.setRenderHint(QPainter.Antialiasing)+ p.setRenderHint(QPainter.SmoothPixmapTransform)++ art_rect = QRectF(2.0, 2.0, self.CARD_W - 4.0, self.ART_H)+ path = QPainterPath()+ path.addRoundedRect(art_rect, 12.0, 12.0)++ p.save()+ p.setClipPath(path)+ if self._pixmap and not self._pixmap.isNull():+ pw, ph = float(self._pixmap.width()), float(self._pixmap.height())+ scale = max(art_rect.width() / max(1.0, pw), art_rect.height() / max(1.0, ph))+ sw, sh = pw * scale, ph * scale+ sx = art_rect.x() + (art_rect.width() - sw) * 0.5+ sy = art_rect.y() + (art_rect.height() - sh) * 0.5+ p.drawPixmap(QRectF(sx, sy, sw, sh), self._pixmap, QRectF(0, 0, pw, ph))+ else:+ c1, c2 = _fallback_gradient_colors(self.title_id)+ grad = QLinearGradient(art_rect.topLeft(), art_rect.bottomRight())+ grad.setColorAt(0.0, c1)+ grad.setColorAt(1.0, c2)+ p.fillRect(art_rect, grad)+ # Fallback title inside art+ f = QFont(self.font())+ f.setPixelSize(15)+ f.setBold(True)+ p.setFont(f)+ p.setPen(QColor(255, 255, 255, 210))+ p.drawText(art_rect.adjusted(14, 14, -14, -14), Qt.AlignBottom | Qt.AlignLeft | Qt.TextWordWrap, self.title)++ # Top-right status dot pill+ p.setPen(Qt.NoPen)+ p.setBrush(QColor(0, 0, 0, 150))+ p.drawEllipse(QRectF(art_rect.right() - 22, art_rect.top() + 8, 14, 14))+ p.setBrush(QColor(self.dot_color))+ p.drawEllipse(QRectF(art_rect.right() - 19, art_rect.top() + 11, 8, 8))++ # Top-left Switch 2 badge if applicable+ if self.is_switch2:+ f = QFont(self.font())+ f.setPixelSize(10)+ f.setBold(True)+ p.setFont(f)+ fm = QFontMetrics(f)+ bw = fm.horizontalAdvance(self.switch2_label) + 12+ brect = QRectF(art_rect.left() + 8, art_rect.top() + 8, bw, 18)+ p.setBrush(QColor(13, 13, 15, 200))+ p.setPen(QPen(QColor(style.ACCENT), 1.0))+ p.drawRoundedRect(brect, 9.0, 9.0)+ p.setPen(QColor(style.ACCENT))+ p.drawText(brect, Qt.AlignCenter, self.switch2_label)+ p.restore()++ # Border around art+ if self.selected:+ p.setPen(QPen(QColor(style.ACCENT), 2.2))+ elif self._hovered:+ p.setPen(QPen(QColor(255, 255, 255, 95), 1.4))+ else:+ p.setPen(QPen(QColor(255, 255, 255, 28), 1.0))+ p.setBrush(Qt.NoBrush)+ p.drawRoundedRect(art_rect, 12.0, 12.0)++ # Title below art+ f = QFont(self.font())+ f.setPixelSize(12)+ f.setBold(self.selected)+ p.setFont(f)+ p.setPen(QColor('#ffffff') if (self.selected or self._hovered) else QColor(255, 255, 255, 175))+ fm = QFontMetrics(f)+ elided = fm.elidedText(self.title, Qt.ElideRight, self.CARD_W - 8)+ text_rect = QRectF(4.0, self.ART_H + 8.0, self.CARD_W - 8.0, 18.0)+ p.drawText(text_rect, Qt.AlignLeft | Qt.AlignVCenter, elided)++ # Cream indicator bar under selected card+ if self.selected:+ p.setPen(Qt.NoPen)+ p.setBrush(QColor(style.ACCENT))+ p.drawRoundedRect(QRectF(4.0, self.TOTAL_H - 5.0, 28.0, 3.0), 1.5, 1.5)+++class DropOverlayWidget(QWidget):+ """Full-window drag-and-drop overlay matching GameFilesDropOverlay in SwiftUI."""++ def __init__(self, hint_text: str = '', parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self.hint_text = hint_text+ self.setAttribute(Qt.WA_TransparentForMouseEvents, True)+ self.hide()++ def set_hint(self, text: str) -> None:+ self.hint_text = text+ self.update()++ def paintEvent(self, _event) -> None:+ p = QPainter(self)+ p.setRenderHint(QPainter.Antialiasing)+ p.fillRect(self.rect(), QColor(0, 0, 0, 185))+ box = QRectF(self.rect()).adjusted(36, 36, -36, -36)+ pen = QPen(QColor(style.ACCENT), 2.0, Qt.DashLine)+ p.setPen(pen)+ p.setBrush(QColor(26, 26, 28, 210))+ p.drawRoundedRect(box, 20.0, 20.0)++ f = QFont(self.font())+ f.setPixelSize(18)+ f.setBold(True)+ p.setFont(f)+ p.setPen(QColor(style.ACCENT))+ p.drawText(box, Qt.AlignCenter, self.hint_text)diff --git a/frontend-qt/tests/test_swift_parity.py b/frontend-qt/tests/test_swift_parity.pynew file mode 100644index 00000000..ea807b6d--- /dev/null+++ b/frontend-qt/tests/test_swift_parity.py@@ -0,0 +1,269 @@+"""Unit tests for Mac Swift parity features in the Windows/Qt front end:+KeyCheck (AES-128-XTS NCA header verification), CheatFiles, GameLibrary,+BuildFolder (FreeSpace), GameDeletion, DriveCopy, Diagnostics, and the 3-page UI.+"""+from __future__ import annotations++import os+import struct+import sys+import tempfile+import unittest+import zipfile+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / 'frontend-qt'))+os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')++from nspb_qt import features as feat+from nspb_qt import library as lib+from nspb_qt.i18n import Lang+++def _encrypt_nca_sector(plain: bytes, sector: int, key1: bytes, key2: bytes) -> bytes:+ """Encrypt a 0x200-byte sector with Nintendo Switch AES-128-XTS to build real PFS0/NCA test fixtures."""+ rk1 = feat._expand_key_128(key1)+ rk2 = feat._expand_key_128(key2)+ tweak = list(feat._aes128_encrypt_block(sector.to_bytes(16, 'big'), rk2))+ out = bytearray(len(plain))+ for off in range(0, len(plain), 16):+ xored = bytes(plain[off + i] ^ tweak[i] for i in range(16))+ enc = feat._aes128_encrypt_block(xored, rk1)+ for i in range(16):+ out[off + i] = enc[i] ^ tweak[i]+ carry = 0+ for i in range(16):+ nxt = (tweak[i] >> 7) & 1+ tweak[i] = ((tweak[i] << 1) | carry) & 0xFF+ carry = nxt+ if carry:+ tweak[0] ^= 0x87+ return bytes(out)+++def _make_pfs0_nsp(path: Path, header_key: bytes, key_gen: int = 0x0E, with_ticket: bool = False) -> None:+ """Build a valid PFS0 (.nsp) containing a 0x400-byte NCA3 header encrypted with AES-128-XTS."""+ plain_sector1 = bytearray(0x200)+ plain_sector1[0:4] = b'NCA3'+ plain_sector1[0x06] = 2+ plain_sector1[0x07] = 0 # application key area+ plain_sector1[0x20] = key_gen+ if with_ticket:+ plain_sector1[0x30:0x40] = b'\x01' * 16 # non-zero rights ID++ enc_sector1 = _encrypt_nca_sector(bytes(plain_sector1), 1, header_key[:16], header_key[16:32])+ nca_data = (b'\x00' * 0x200) + enc_sector1++ files: list[tuple[str, bytes]] = [('0000000000000001.nca', nca_data)]+ if with_ticket:+ tik = bytearray(0x2A0)+ tik[0x285] = key_gen+ files.append(('01007ef00011e000.tik', bytes(tik)))++ str_tab = bytearray()+ entries = bytearray()+ data_blob = bytearray()+ for name, content in files:+ soff = len(str_tab)+ str_tab.extend(name.encode('utf-8') + b'\x00')+ entries.extend(struct.pack('<QQII', len(data_blob), len(content), soff, 0))+ data_blob.extend(content)+ while len(str_tab) % 16 != 0:+ str_tab.append(0)++ head = b'PFS0' + struct.pack('<III', len(files), len(str_tab), 0)+ path.write_bytes(head + bytes(entries) + bytes(str_tab) + bytes(data_blob))+++class KeyCheckTests(unittest.TestCase):+ def setUp(self) -> None:+ self.tmp = tempfile.TemporaryDirectory()+ self.dir = Path(self.tmp.name)+ self.hk = bytes.fromhex('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f')++ def tearDown(self) -> None:+ self.tmp.cleanup()++ def test_valid_keys_fit_encrypted_nsp(self) -> None:+ nsp = self.dir / 'Game [01007EF00011E000].nsp'+ _make_pfs0_nsp(nsp, self.hk, key_gen=0x0E) # 0x0E -> gen index 0x0D (13)+ keys = self.dir / 'prod.keys'+ keys.write_text(+ f'header_key = {self.hk.hex()}\n'+ f'master_key_0d = {"aa" * 16}\n',+ encoding='utf-8',+ )+ v = feat.KeyCheck.check(str(keys), str(nsp))+ self.assertEqual(v.kind, 'fits')++ def test_wrong_header_key_is_caught(self) -> None:+ nsp = self.dir / 'Game [01007EF00011E000].nsp'+ _make_pfs0_nsp(nsp, self.hk, key_gen=0x0E)+ keys = self.dir / 'prod.keys'+ keys.write_text(+ f'header_key = {"ff" * 32}\n'+ f'master_key_0d = {"aa" * 16}\n',+ encoding='utf-8',+ )+ v = feat.KeyCheck.check(str(keys), str(nsp))+ self.assertEqual(v.kind, 'wrongHeaderKey')+ self.assertEqual(v.part, 'base')++ def test_missing_newer_generation_key_reports_firmware(self) -> None:+ nsp = self.dir / 'Game [01007EF00011E000].nsp'+ _make_pfs0_nsp(nsp, self.hk, key_gen=0x14, with_ticket=True) # 0x14 -> gen 0x13 (19.0.0)+ keys = self.dir / 'prod.keys'+ keys.write_text(+ f'header_key = {self.hk.hex()}\n'+ f'master_key_00 = {"aa" * 16}\n',+ encoding='utf-8',+ )+ v = feat.KeyCheck.check(str(keys), str(nsp))+ self.assertEqual(v.kind, 'missingKey')+ self.assertEqual(v.key, 'master_key_13')+ self.assertEqual(v.firmware, '19.0.0')+++class CheatFilesTests(unittest.TestCase):+ def setUp(self) -> None:+ self.tmp = tempfile.TemporaryDirectory()+ self.dir = Path(self.tmp.name)++ def tearDown(self) -> None:+ self.tmp.cleanup()++ def test_parse_and_toggle_cheats(self) -> None:+ bid = '0123456789ABCDEF'+ txt = self.dir / f'{bid}.txt'+ txt.write_text(+ '{Master Code}\n04000000 00112233 44556677\n\n'+ '[60 FPS]\n04000000 00AABBCC 00000001\n\n'+ '[Broken Cheat]\nNOT_HEX 123\n',+ encoding='utf-8',+ )+ master_on, files = feat.CheatFiles.load_folder(str(self.dir), '01007EF00011E000')+ self.assertTrue(master_on)+ self.assertEqual(len(files), 1)+ cheats = files[0].cheats+ self.assertEqual(len(cheats), 3)+ self.assertTrue(cheats[0].is_master and cheats[0].is_valid)+ self.assertTrue(cheats[1].is_valid and cheats[1].runs_once)+ self.assertFalse(cheats[2].is_valid)++ feat.CheatFiles.set_cheat_enabled(str(self.dir), bid, '60 FPS', True)+ _, files2 = feat.CheatFiles.load_folder(str(self.dir), '01007EF00011E000')+ self.assertIn('60 FPS', files2[0].enabled)++ feat.CheatFiles.set_master(str(self.dir), '01007EF00011E000', False)+ master_on2, _ = feat.CheatFiles.load_folder(str(self.dir), '01007EF00011E000')+ self.assertFalse(master_on2)++ def test_read_build_id_from_ipa(self) -> None:+ ipa = self.dir / 'test.ipa'+ with zipfile.ZipFile(ipa, 'w') as zf:+ zf.writestr('Payload/Game.app/main.fixups.tsv', '# BUILD_ID\tabcdef01234567890000\n')+ bid = feat.CheatFiles.read_build_id(ipa_path=str(ipa))+ self.assertEqual(bid, 'ABCDEF0123456789')+++class LibraryAndSpaceTests(unittest.TestCase):+ def setUp(self) -> None:+ self.tmp = tempfile.TemporaryDirectory()+ self.dir = Path(self.tmp.name)++ def tearDown(self) -> None:+ self.tmp.cleanup()++ def test_discover_games_and_free_space(self) -> None:+ games_dir = self.dir / 'games_root'+ sub = games_dir / 'Celeste'+ sub.mkdir(parents=True)+ (sub / 'Celeste [0100F7B00BB5C000].nsp').write_bytes(b'1234')+ (sub / 'Celeste Update [0100F7B00BB5C800][v65536].nsp').write_bytes(b'5678')+ (games_dir / 'prod.keys').write_text('header_key = ' + '00' * 32, encoding='utf-8')++ library = lib.GameLibrary(state_dir=self.dir / 'state')+ library.set_games_folder(str(games_dir))+ self.assertEqual(len(library.games), 1)+ g = library.games[0]+ self.assertEqual(g.title_id, '0100F7B00BB5C000')+ self.assertTrue(g.has_inputs)++ # Create a build folder with freeable parts and a kept save+ bf = Path(g.work_dir)+ (bf / g.title_id).mkdir(parents=True)+ (bf / g.title_id / 'data.bin').write_bytes(b'x' * 4096)+ (bf / 'shaders').mkdir(parents=True)+ (bf / 'shaders' / 'lib.metallib').write_bytes(b'y' * 2048)+ (bf / 'run').mkdir(parents=True)+ (bf / 'run' / 'save.dat').write_bytes(b's' * 512)++ rep = lib.BuildFolder.inspect(str(bf), g.title_id)+ parts = {it.part: it.bytes for it in rep.items}+ self.assertEqual(parts.get('extracted'), 4096)+ self.assertEqual(parts.get('shaders'), 2048)+ self.assertEqual(rep.kept_bytes, 512)++ freed, failed = lib.BuildFolder.remove(rep, {'extracted'})+ self.assertEqual(freed, 4096)+ self.assertEqual(failed, [])+ self.assertTrue((bf / 'run' / 'save.dat').is_file())+++class ParityWindowTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ from PySide6.QtWidgets import QApplication+ cls.app = QApplication.instance() or QApplication([])++ def _delete(self, m, w) -> None:+ from PySide6.QtCore import QEvent+ w.close()+ w.deleteLater()+ m.deleteLater()+ self.app.sendPostedEvents(None, QEvent.DeferredDelete)+ self.app.processEvents()++ def test_three_page_navigation_and_controls(self) -> None:+ from unittest import mock+ from nspb_qt.model import Model+ from nspb_qt.ui import MainWindow++ p = mock.patch.object(Model, 'check_deps', lambda self: None)+ p.start()+ self.addCleanup(p.stop)+ m = Model()+ m.lang = Lang('en')+ w = MainWindow(m)+ self.addCleanup(self._delete, m, w)+ w.resize(1080, 760)+ w.show()+ self.app.processEvents()++ # Navigate across Library, Builds, Settings+ w._switch_page('library')+ self.assertEqual(w._current_page, 'library')+ w._switch_page('settings')+ self.assertEqual(w._current_page, 'settings')+ w._switch_page('builds')+ self.assertEqual(w._current_page, 'builds')++ # Toggle BC texture decode and One-Game IPA mode+ w.bc_switch.setChecked(True)+ w._on_bc_toggled(True)+ self.assertTrue(m.bc_on_cpu)++ w._on_ipa_kind_changed('oneGame')+ self.assertEqual(m.ipa_kind, 'oneGame')+ self.assertTrue(w.step3_container.isHidden())++ w._on_ipa_kind_changed('shared')+ self.assertEqual(m.ipa_kind, 'shared')+ self.assertFalse(w.step3_container.isHidden())++ w.close()+++if __name__ == '__main__':+ unittest.main()