diff --git a/.github/workflows/build-qt.yml b/.github/workflows/build-qt.yml index 934bb2cbb..564d9956d 100644 --- a/.github/workflows/build-qt.yml +++ b/.github/workflows/build-qt.yml @@ -38,6 +38,15 @@ jobs: - name: Generate the localisation table run: python frontend-qt/gen_localization.py + # The build packages ride in the zip: the venv step then installs from disk (--no-index), + # so a fresh machine needs no PyPI round-trip for lz4/capstone/fonttools/nsz. The runner's + # Python is the version these wheels target (3.12), matching the interpreter the app + # installs for its venv. + # Exact versions, wheels only: the zip ships these to players, so the supply is pinned + # (hash-locking the full closure can follow the Mac bundled-Python pattern if wanted). + - name: Download the venv wheels + run: "python -m pip download --only-binary=:all: lz4==4.4.5 capstone==5.0.9 fonttools==4.68.0 zbic==1.0.1.post1 backports.zstd==1.8.0 nsz==5.0.0 -d frontend-qt/wheels" + - name: Build working-directory: frontend-qt shell: bash @@ -123,6 +132,7 @@ jobs: shell: bash run: | cd frontend-qt/dist + cp -r ../wheels "NS Port Builder/wheels" powershell -Command "Compress-Archive -Path 'NS Port Builder' -DestinationPath '../NS-Port-Builder-qt-windows-x64.zip'" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.py index 4c47c19d5..eb9c96073 100644 --- a/frontend-qt/nspb_qt/localization.py +++ b/frontend-qt/nspb_qt/localization.py @@ -684,7 +684,11 @@ 'dep.show': ('展开', 'Show', 'Show', 'Einblenden'), 'dep.pick': ('选择文件夹…', 'Choose folder…', 'Choose folder…', 'Ordner wählen …'), 'dep.pick.ios_sdk.title': ('选择 iPhoneOS SDK 文件夹', 'Choose the iPhoneOS SDK folder', 'Choose the iPhoneOS SDK folder', 'Ordner des iPhoneOS SDK wählen'), - 'dep.pick.metal_dir.title': ('选择 Metal Developer Tools 文件夹', 'Choose the Metal Developer Tools folder', 'Choose the Metal Developer Tools folder', 'Ordner der Metal Developer Tools wählen'), + 'dep.pick.metal_dir.title': ('选择 Metal Developer Tools(下载的 zip 或解压后的文件夹)', 'Choose Metal Developer Tools (the downloaded zip, or the unpacked folder)', 'Välj Metal Developer Tools (den nedladdade zip-filen eller den uppackade mappen)', 'Metal Developer Tools wählen (die geladene Zip oder der entpackte Ordner)'), + 'dep.pick.metal': ('选择 zip / 文件夹…', 'Choose zip / folder…', 'Välj zip / mapp …', 'Zip / Ordner wählen …'), + 'dep.metal.unpacking': ('正在解压 %@…', 'Unpacking %@…', 'Packar upp %@ …', '%@ wird entpackt …'), + 'dep.metal.done': ('Metal Developer Tools 已安装:%@', 'Metal Developer Tools installed: %@', 'Metal Developer Tools installerat: %@', 'Metal Developer Tools installiert: %@'), + 'dep.pick.metal.invalid': ('“%@”里没有 metal.exe(需要 bin\\metal.exe 或 ios\\bin\\metal.exe):确认下载的是 “Metal Developer Tools for Windows”。', 'No metal.exe inside "%@" (needs bin\\metal.exe or ios\\bin\\metal.exe): check that the download is "Metal Developer Tools for Windows".', 'Ingen metal.exe i ”%@” (kräver bin\\metal.exe eller ios\\bin\\metal.exe): kontrollera att nedladdningen är ”Metal Developer Tools for Windows”.', 'Keine metal.exe in „%@“ (benötigt bin\\metal.exe oder ios\\bin\\metal.exe): Prüfe, ob der Download „Metal Developer Tools for Windows“ ist.'), 'dep.pick.saved': ('已记住:%@', 'Remembered: %@', 'Remembered: %@', 'Gemerkt: %@'), 'dep.pick.iossdk.saved': ('SDK 已记住:%@', 'SDK remembered: %@', 'SDK remembered: %@', 'SDK gemerkt: %@'), 'dep.pick.iossdk.version': ('SDK 版本:%@', 'SDK version: %@', 'SDK version: %@', 'SDK-Version: %@'), @@ -707,6 +711,10 @@ 'dep.fix.brewMissing': ('没装 Homebrew:从 brew.sh 安装(安装程序会要你的密码),再点「重新检测」。', 'Homebrew is not installed: install it from brew.sh (the installer asks for your password), then press Check again.', 'Homebrew är inte installerat. Installera från brew.sh. Installationsprogrammet ber om ditt lösenord. Välj sedan ”Kontrollera igen”.', 'Homebrew ist nicht installiert: Installiere es von brew.sh (das Installationsprogramm fragt nach deinem Passwort) und tippe dann auf „Erneut prüfen“.'), 'dep.fix.xcodeLicense': ('Xcode 的许可协议还没接受:运行 sudo xcodebuild -license accept。', "Xcode's license is not accepted yet: run sudo xcodebuild -license accept.", 'Xcodes licensavtal är inte godkänt. Kör sudo xcodebuild -license accept.', 'Die Lizenz von Xcode ist noch nicht akzeptiert: Führe sudo xcodebuild -license accept aus.'), 'dep.fix.network': ('下载失败了:检查网络(代理或 VPN 可能拦住了 Homebrew 的域名),再试一次。', "The download failed: check the network (a proxy or VPN can block Homebrew's hosts) and try again.", 'Hämtningen misslyckades. Kontrollera nätverket; proxy eller VPN kan blockera Homebrews domäner. Försök sedan igen.', 'Der Download ist fehlgeschlagen: Prüfe das Netzwerk (ein Proxy oder VPN kann die Server von Homebrew blockieren) und versuche es erneut.'), + 'dep.git.downloading': ('正在下载 PortableGit(SDK 下载需要它,约 45 MB)…', 'Downloading PortableGit (the SDK download needs it, about 45 MB)…', 'Hämtar PortableGit (SDK-nedladdningen behöver den, cirka 45 MB) …', 'PortableGit wird geladen (die SDK-Installation braucht es, rund 45 MB) …'), + 'dep.git.done': ('PortableGit 已安装:%@', 'PortableGit installed: %@', 'PortableGit installerat: %@', 'PortableGit installiert: %@'), + 'dep.fix.nonascii': ('SDK 所在路径含非英文字符(比如用户名里的中文):ld64.lld 在 Windows 上可能因此打不开 SDK 文件。把整个 SDK 文件夹拷到一个纯英文路径(如 C:\\NSPB\\sdk),然后在依赖面板用「选择文件夹…」指向它。', "The SDK path contains non-ASCII characters (a Chinese username, for example): ld64.lld on Windows may fail to open it. Copy the whole SDK folder to an ASCII-only path (e.g. C:\\NSPB\\sdk) and point the dependencies panel's Choose folder… at it.", 'SDK-sökvägen innehåller icke-ASCII-tecken (ett kinesiskt användarnamn till exempel): ld64.lld på Windows kan därför misslyckas med att öppna SDK-filerna. Kopiera hela SDK-mappen till en sökväg med bara ASCII (till exempel C:\\NSPB\\sdk) och peka beroendepanelens ”Välj mapp …” på den.', 'Der SDK-Pfad enthält Nicht-ASCII-Zeichen (etwa ein chinesischer Benutzername): ld64.lld öffnet die SDK-Dateien unter Windows deshalb womöglich nicht. Kopiere den ganzen SDK-Ordner auf einen reinen ASCII-Pfad (z. B. C:\\NSPB\\sdk) und wähle ihn im Abhängigkeiten-Panel unter „Ordner wählen …“.'), + 'dep.row.log': ('依赖 %@:[%@] %@', 'dependency %@: [%@] %@', 'beroende %@: [%@] %@', 'Abhängigkeit %@: [%@] %@'), 'dep.fix.diskspace': ('磁盘空间不足:清理后(SDK 和工具链解压需要数 GB)再点「安装」。', 'The disk is full: free some space (the SDK and toolchains unpack to several GB) and press Install again.', 'The disk is full: free some space (the SDK and toolchains unpack to several GB) and press Install again.', 'Das Volume ist voll: Gib Speicherplatz frei (das SDK und die Toolchains entpacken sich auf mehrere GB) und tippe erneut auf „Installieren“.'), 'dep.fix.log': ('完整输出在 Mac/iPhone 选择下面的日志里。', 'The full output is in the log under the Mac/iPhone choice.', 'Fullständig utdata finns i loggen under Mac/iPhone-valet.', 'Die vollständige Ausgabe steht im Protokoll unter der Auswahl Mac/iPhone.'), 'dep.python.missing': ('%@ 缺包', '%@ is missing packages', '%@ saknar paket', 'Bei %@ fehlen Pakete'), diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.py index 0d8e30108..c45256a9b 100644 --- a/frontend-qt/nspb_qt/model.py +++ b/frontend-qt/nspb_qt/model.py @@ -83,6 +83,9 @@ class Model(QObject): #: 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. ask_folder: Callable[[str], str] | None = None + #: Same, for a file ('Metal Developer Tools*.zip' the user downloaded from Apple). + ask_file: Callable[[str], str] | None = None + _metal_zip: Path | None = None def __init__(self) -> None: super().__init__() @@ -347,6 +350,16 @@ def _check_deps(self) -> None: d.last_error, d.fix_hint = p.last_error, p.fix_hint self.deps = deps + # The panel can only show one row at a time; the log keeps every detail, so a report sent + # from a handheld always carries the full probe text (the truncated link row is why this + # exists). + for d in deps: + if not d.ok and d.detail: + # three placeholders, three args: a mismatch makes t() fall back to the raw + # "dependency %@: [%@] %@" line (the report's log had it six times) + name = d.title_key.replace('dep.', '').replace('.hint', '') + self.log(self.t('dep.row.log', name, d.state.value, + d.detail.replace('\n', ' | ')) + '\n') if not pu.IS_WIN: # On Windows `_windows_deps` already set python_path (the interpreter the app # installed, which find_python without its candidates cannot see) and dotnet_path @@ -388,7 +401,7 @@ def _windows_deps(self, deps: list[Dep]) -> list[Dep]: from .win import toolchain as wtc # local import: macOS never loads it out: list[Dep] = [] - probes = wtc.check_all(deep=True) + probes = wtc.check_all(deep=True, t=self.t) # t: the failure summaries' hint keys reach the panel translated # Re-do the Python row now that the toolchain can speak: the interpreter this app # installed for itself is not on PATH and not in Program Files, so the row built before @@ -794,9 +807,27 @@ def work() -> None: elif what == 'ios_sdk': self.log(self.t('dep.iossdk.downloading') + '\n') from .win import sdk_fetch as sf + # clone_sdk runs git, which a fresh machine has none of: the app installs + # PortableGit itself (per-user, no installer) instead of sending the player + # to git-scm.com — the report's SDK row failed three times on exactly that. + if not (wtc.git_exe() or shutil.which('git')): + self.log(self.t('dep.git.downloading') + '\n') + from .win import fetch as wf + git = wf.install_git(log=lambda s: self.log(str(s) + '\n')) + self.log(self.t('dep.git.done', str(git)) + '\n') path = sf.clone_sdk(log=lambda s: self.log(str(s) + '\n')) self.log(self.t('dep.iossdk.done', str(path)) + '\n') ok = True + elif what == 'metal_zip': + # Apple's tools are Apple-ID-gated: the browser download is the licensed + # path, the app does the unpack and remembers the folder. + self.log(self.t('dep.metal.unpacking', self._metal_zip.name) + '\n') + from .win import fetch as wf + dest = wf.install_metal_from_zip(self._metal_zip, + log=lambda s: self.log(str(s) + '\n')) + wtc.save_config('metal_dir', str(dest)) + self.log(self.t('dep.metal.done', str(dest)) + '\n') + ok = True else: self.log(f'unknown Windows install target: {what}\n') except Exception as e: @@ -846,6 +877,19 @@ def pick_dep_folder(self, dep: Dep) -> None: if not dep.pick_key: return from .win import toolchain as wtc + if dep.pick_key == 'metal_dir': + # The Metal zip is a file, not a folder: the ask_file callback (the window's file + # dialog filters *.zip) takes the browser download straight away. An already + # unpacked folder is equally accepted. + ask_file = self.ask_file + if ask_file is None: + return + picked = ask_file(self.t('dep.pick.metal_dir.title')) + if not picked: + return + if picked.lower().endswith('.zip'): + return self.install_metal_zip(Path(picked)) + return self._save_metal_folder(Path(picked)) ask = self.ask_folder if ask is None: return # no window attached (tests): nothing to ask with @@ -869,6 +913,29 @@ def pick_dep_folder(self, dep: Dep) -> None: self.log(self.t('dep.pick.saved', folder) + '\n') self.check_deps() + def _save_metal_folder(self, folder: Path) -> None: + """A folder the user already unpacked: validate the two layouts metal_dir() accepts.""" + from .win import toolchain as wtc + if not (folder / 'bin' / 'metal.exe').is_file() and \ + not (folder / 'ios' / 'bin' / 'metal.exe').is_file(): + self.log(self.t('dep.pick.metal.invalid', str(folder)) + '\n') + return + wtc.save_config('metal_dir', str(folder)) + self.log(self.t('dep.pick.saved', str(folder)) + '\n') + self.check_deps() + + def install_metal_zip(self, zip_path: Path) -> None: + """Unpack the Apple zip the player downloaded and remember the folder (the one manual + dependency on Windows: Apple-ID-gated, so the app cannot fetch it itself).""" + if not zip_path.is_file(): + self.log(self.t('dep.pick.metal.invalid', str(zip_path)) + '\n') + return + self._metal_zip = zip_path + dep = next((d for d in self.deps if d.id == 'metal'), None) + if dep is None: + return + self._install_win(dep, 'metal_zip') + def _progress_logger(self, label: str): """A progress callback that logs at 5% steps, not on every chunk. @@ -889,6 +956,26 @@ def report(done: int, total: int) -> None: return report + @staticmethod + def bundled_wheels() -> Path | None: + """The wheel folder shipped in the Windows zip (`wheels/` beside the exe). + + The build packages (lz4, capstone, fonttools, nsz, backports.zstd) are downloaded by the + release workflow at packaging time, so the venv step installs from disk with no network + and no PyPI — the same "the app carries it" promise the Mac's bundled CPython makes. + Source runs have no such folder and fall back to PyPI. + """ + base = getattr(sys, '_MEIPASS', None) or Path(sys.executable).parent + w = Path(base) / 'wheels' + return w if w.is_dir() and any(w.glob('*.whl')) else None + + @staticmethod + def _pip_args(pkgs: list[str], wheels: Path | None) -> list[str]: + """pip's arguments: offline from the bundled wheels when they cover the packages.""" + if wheels: + return ['install', '--no-index', '--find-links', str(wheels)] + pkgs + return ['install'] + pkgs + def _make_venv(self, base: str) -> bool: """Create or reuse the app's venv and install the build packages into it.""" vpy = pu.venv_python() @@ -929,9 +1016,12 @@ def _make_venv(self, base: str) -> bool: pkgs = ['lz4', 'capstone', 'fonttools', 'zbic', 'nsz'] if ver < (3, 14): pkgs.insert(4, 'backports.zstd') - self.log(f'$ {vpy} -m pip install {" ".join(pkgs)}\n') + wheels = self.bundled_wheels() + args = self._pip_args(pkgs, wheels) + self.log(f'$ {vpy} -m pip {" ".join(args)}' + + ('' if wheels else ' (from PyPI)') + '\n') try: - p = subprocess.Popen([vpy, '-m', 'pip', 'install'] + pkgs, stdout=subprocess.PIPE, + p = subprocess.Popen([vpy, '-m', 'pip'] + args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors='replace', env=pu.child_env(), **pu.no_window_kwargs()) assert p.stdout is not None @@ -969,10 +1059,18 @@ def install_all_missing(self) -> None: def run_all() -> None: try: - attempted: set[str] = set() + # attempted is keyed by (id, fix): an id may legitimately come back in a later + # pass with a DIFFERENT fix — installing the Python interpreter turns its row + # into "pip install the packages", which is exactly the step install-all must + # then run (the report: only the interpreter was installed, the packages step + # needed a second click on the row). + attempted: dict[str, tuple] = {} while True: - rows = [d for d in self.deps if not d.ok and d.install - and d.id not in attempted] + def pending(d) -> bool: + if d.ok or not d.install: + return False + return attempted.get(d.id) != tuple(d.install) + rows = [d for d in self.deps if pending(d)] if not rows: break progressed = False @@ -980,7 +1078,9 @@ def run_all() -> None: live = next((r for r in self.deps if r.id == d.id), None) if live is None or live.ok or not live.install or live.installing: continue - attempted.add(live.id) + if attempted.get(live.id) == tuple(live.install): + continue + attempted[live.id] = tuple(live.install) self.log(f'--- {self.t(live.title_key)} ---\n') self.install_dep(live) progressed = True diff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.py index 219736fd4..df96ca02b 100644 --- a/frontend-qt/nspb_qt/ui.py +++ b/frontend-qt/nspb_qt/ui.py @@ -77,6 +77,8 @@ def __init__(self, model: Model) -> None: self.m.finished.connect(self._on_finished) 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() # ---------------------------------------------------------------- header @@ -539,6 +541,21 @@ def _refresh_deps(self) -> None: 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) @@ -553,8 +570,9 @@ def _refresh_deps(self) -> None: 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 (validated, remembered in toolchain.json). - pick = QPushButton(self.m.t('dep.pick')) + # 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: @@ -728,6 +746,14 @@ def _build_clicked(self) -> None: self.failure_box.hide() self.m.start_build() + def _ask_folder(self, title: str) -> str: + d = QFileDialog.getExistingDirectory(self, title) + return d or '' + + def _ask_file(self, title: str) -> str: + d, _ = QFileDialog.getOpenFileName(self, title, '', 'Metal tools zip (*.zip)') + return d or '' + def _choose_repo(self) -> None: d = QFileDialog.getExistingDirectory(self, self.m.t('repo.pickMessage')) if d: diff --git a/frontend-qt/nspb_qt/win/build_app.py b/frontend-qt/nspb_qt/win/build_app.py index 2d3dd8ffa..56a13535d 100644 --- a/frontend-qt/nspb_qt/win/build_app.py +++ b/frontend-qt/nspb_qt/win/build_app.py @@ -312,7 +312,7 @@ def link(clang: Path, sdk: Path, objs: list[Path], frameworks: list[str], out: P """Link the app, then prove the result is an unsigned iOS executable.""" args = [str(clang), '-target', f'arm64-apple-ios{deployment}', '-isysroot', str(sdk), '-fuse-ld=lld', '-fobjc-arc', '-o', str(out), *map(str, objs), - '-Wl,-rpath,@executable_path/Frameworks', '-lobjc', + '-Wl,-rpath,@executable_path/Frameworks', '-lobjc', '-lSystem', *[x for fw in frameworks for x in ('-framework', fw)], *embed_flags] if rt_obj: args.append(str(rt_obj)) diff --git a/frontend-qt/nspb_qt/win/fetch.py b/frontend-qt/nspb_qt/win/fetch.py index 55c449ac3..20b98f91d 100644 --- a/frontend-qt/nspb_qt/win/fetch.py +++ b/frontend-qt/nspb_qt/win/fetch.py @@ -558,3 +558,51 @@ def _download_unverified(url: str, dest: Path, log: Callable[[str], None], except (urllib.error.URLError, OSError) as e: tmp.unlink(missing_ok=True) raise DownloadError(f'download failed: {url}: {e}') from e + + +def install_metal_from_zip(zip_path: Path, dest: Path | None = None, + log: Callable[[str], None] | None = None) -> Path: + """Unpack a "Metal Developer Tools for Windows" zip the user downloaded from Apple, and + return the folder to write into `toolchain.json` as `metal_dir`. + + Apple's tools are Apple-ID-gated and cannot be downloaded by the app; the browser download + is the licensed path, and this is the app doing the unpack the user would otherwise do by + hand — into `tools_dir()`, the same place the other toolchains live, surviving app updates. + The zip is validated before anything is remembered: it must contain `metal.exe` (5.x/6.x in + `bin/`, 4.x in `ios/bin/`), matching `toolchain.metal_dir()`'s two accepted layouts. + """ + import zipfile as _zf + src = Path(zip_path) + if not src.is_file(): + raise DownloadError(f'{src} does not exist') + if log: + log(f'unpacking {src.name} …') + dest = Path(dest) if dest else tc.tools_dir() / 'metal-developer-tools' + staging = dest.parent / (dest.name + '-staging') + shutil.rmtree(staging, ignore_errors=True) + staging.mkdir(parents=True) + try: + with _zf.ZipFile(src) as z: + bad = [i.filename for i in z.infolist() if i.filename.startswith('/') or '..' in Path(i.filename).parts] + if bad: + raise DownloadError(f'unsafe paths inside {src.name}: {bad[:3]}') + z.extractall(staging) + except _zf.BadZipFile as e: + shutil.rmtree(staging, ignore_errors=True) + raise DownloadError(f'{src.name} is not a zip file ({e})') from e + + def has_metal(root: Path) -> bool: + return (root / 'bin' / 'metal.exe').is_file() or (root / 'ios' / 'bin' / 'metal.exe').is_file() + + roots = [staging] + [p for p in staging.iterdir() if p.is_dir()] # zip may or may not carry a top folder + hit = next((r for r in roots if has_metal(r)), None) + if hit is None: + shutil.rmtree(staging, ignore_errors=True) + raise DownloadError(f'{src.name} does not look like Metal Developer Tools ' + '(no metal.exe in bin/ or ios/bin/)') + shutil.rmtree(dest, ignore_errors=True) + hit.rename(dest) + shutil.rmtree(staging, ignore_errors=True) + if log: + log(f'Metal Developer Tools unpacked to {dest}') + return dest diff --git a/frontend-qt/nspb_qt/win/toolchain.py b/frontend-qt/nspb_qt/win/toolchain.py index 508f650a3..a7e650ac1 100644 --- a/frontend-qt/nspb_qt/win/toolchain.py +++ b/frontend-qt/nspb_qt/win/toolchain.py @@ -939,7 +939,38 @@ def probe_metal(sdk: Path) -> tuple[bool, str]: return True, f'{lib.stat().st_size} byte metallib for {tgt}' -def probe_link(sdk: Path) -> tuple[bool, str]: +def link_attempt_summary(r: subprocess.CompletedProcess) -> str: + """One failed strategy: the exit code plus the output's last lines (all of them, not just + one — '(no output)' alone was the report's whole diagnostic).""" + lines = (r.stderr or r.stdout or '').strip().splitlines() or ['(no output)'] + tail = ' | '.join(l.strip() for l in lines[-3:]) + return f'exit {r.returncode} (0x{r.returncode & 0xFFFFFFFF:08x}): {tail[:500]}' + + +def link_failure_summary(attempts: list[tuple[str, str, list[str]]], lld_line: str, + base: list[str], sdk: Path, + verbose: list[str] | None = None, + t=None) -> str: + """Every failed strategy, the linker's self-check, the exact command to try by hand, and — + when the SDK lives under a non-ASCII path — the one hint that has fixed this exact shape + before: ld64.lld's Windows port can fail to open narrow-char paths silently, while clang's + front end (the compile probe) handles them fine. `t` is the model's translator: the hint is + a localization key and must reach the panel translated, not as a raw key. + """ + parts = [f'link failed {len(attempts)} ways; ld64.lld self-check: {lld_line[:140]}'] + for how, summary, _cmd in attempts: + parts.append(f'{how}: {summary}') + parts.append('try by hand: ' + ' '.join([*base, '-fuse-ld=lld', '-o', '%TEMP%\\probe.exe', ''])) + try: + str(sdk).encode('ascii') + except UnicodeEncodeError: + if t: parts.append(t('dep.fix.nonascii')) + if verbose: + parts.append('verbose: ' + ' | '.join(verbose)) + return ' — '.join(parts) + + +def probe_link(sdk: Path, t=None) -> tuple[bool, str]: """Link a tiny executable for iOS and check it is an arm64 MH_EXECUTE with an iOS platform. Only the linker and the SDK's stubs are exercised, not the game's own code: an undefined @@ -962,6 +993,16 @@ def probe_link(sdk: Path) -> tuple[bool, str]: if v.returncode != 0: return False, (f'{lld.name} does not run by itself (exit {v.returncode}): {lld_line[:200]}' ' — reinstall LLVM-MinGW') + # The link needs libSystem's stub from the SDK that a hollow or partial download lacks; its + # absence reads as "undefined symbol: puts" (libc) at link time while the COMPILE probe + # stays green (it needs headers only). Name it before blaming the linker. iOS executables + # use LC_MAIN, so a real SDK ships no crt*.o at all — checking for one rejected complete SDKs. + missing = [n for n, there in ( + ('usr/lib/libSystem.tbd', (sdk / 'usr' / 'lib' / 'libSystem.tbd').is_file()), + ) if not there] + if missing: + return False, (f'SDK is missing {", ".join(missing)}: the download is incomplete — ' + 're-download the SDK in the app, or use the xip route (doctor --sdk-xip)') src = '#include \nint main(void) { puts("probe"); return 0; }\n' with ascii_temp_dir('nspb-link-') as td: @@ -971,41 +1012,40 @@ def probe_link(sdk: Path) -> tuple[bool, str]: target = f'-target arm64-apple-ios{IOS_DEPLOYMENT}'.split() base = [str(clang), *target, '-isysroot', str(sdk)] - def run(extra: list[str], env: dict[str, str] | None) -> subprocess.CompletedProcess: + # Strategies, in order: the build's own shape first (build_app.link drives the linker + # with -fuse-ld=lld and the linker's folder on PATH — if the probe cannot link that way, + # neither can the build), then naming the linker directly, then -B as clang's last + # resort. Each failure is kept; all three failing produces the full report. + attempts: list[tuple[str, str, list[str]]] = [] # (strategy, summary, command) + for how, extra, env in ( + ('fuse-ld (build-style)', ['-fuse-ld=lld'], None), + ('ld-path', ['-fuse-ld=lld', f'--ld-path={lld}'], None), + ('-B dir', [f'-B{lld.parent}', '-fuse-ld=lld'], None), + # Apple's driver adds libSystem itself; a cross driver that does not leaves + # every libc symbol undefined (the report: puts). Name it explicitly. + ('explicit -lSystem', ['-fuse-ld=lld', '-lSystem'], None)): + run_env = dict(os.environ) # a child on Windows needs the full env (SystemRoot etc.) + if extra[:1] == ['-fuse-ld=lld'] and how.startswith('fuse-ld'): + run_env['PATH'] = str(lld.parent) + os.pathsep + run_env.get('PATH', '') cmd = [*base, *extra, '-o', str(out), str(c)] - return subprocess.run(cmd, capture_output=True, text=True, timeout=180, - env=env, **no_window()) - - def summary(r: subprocess.CompletedProcess) -> str: - # the exit code is the evidence: 0xC0000135 (STATUS_DLL_NOT_FOUND) reads as "a DLL is - # missing", not "the linker is bad"; an empty stream pair stays honest as (no output) - tail = ((r.stderr or r.stdout or '').strip().splitlines() or ['(no output)'])[-1] - return f'exit {r.returncode} (0x{r.returncode & 0xFFFFFFFF:08x}): {tail[:400]}' - - # Strategy 1 — the build's own shape (build_app.link): -fuse-ld=lld and the linker's - # folder on PATH. If the machine's PATH handling differs from the probe's assumptions, - # this is what the build would do, so it is the first thing to try. - env = dict(os.environ) # a child on Windows needs the full env (SystemRoot etc.) - env['PATH'] = str(lld.parent) + os.pathsep + env.get('PATH', '') - r = run(['-fuse-ld=lld'], env) - if r.returncode == 0: - how = 'fuse-ld (build-style)' - else: - first = summary(r) - # Strategy 2 — name the linker directly (--ld-path), bypassing every lookup. - r = run(['-fuse-ld=lld', f'--ld-path={lld}'], dict(os.environ)) + r = subprocess.run(cmd, capture_output=True, text=True, timeout=180, + env=run_env, **no_window()) if r.returncode == 0: - how = 'ld-path' - else: - second = summary(r) - # Strategy 3 — -fuse-ld=full or the absolute path as -B: clang's last resort - r = run([f'-B{lld.parent}', '-fuse-ld=lld'], dict(os.environ)) - if r.returncode == 0: - how = '-B dir' - else: - third = summary(r) - return False, (f'link failed 3 ways; ld64.lld self-check: {lld_line[:120]}; ' - f'fuse-ld {first}; ld-path {second}; -B {third}') + how_ok = how + break + attempts.append((how, link_attempt_summary(r), cmd)) + else: + # One more run, verbose: the driver's own link command, the runtime libs it adds + # (-lSystem, crt) and the library search paths — the three things that decide whether + # libc (puts) resolves. Capped, since -v prints hundreds of lines. + rv = subprocess.run([*base, '-fuse-ld=lld', '-v', '-o', str(out), str(c)], + capture_output=True, text=True, timeout=180, + env=dict(os.environ), **no_window()) + interesting = [l.strip() for l in (rv.stderr or rv.stdout or '').splitlines() + if any(k in l for k in ('-lSystem', 'crt', 'Library search', + 'ld64.lld', 'error'))][:12] + return False, link_failure_summary(attempts, lld_line, base, sdk, + verbose=interesting, t=t) try: data = out.read_bytes() except OSError as e: @@ -1020,7 +1060,7 @@ def summary(r: subprocess.CompletedProcess) -> str: plat = macho_platform(data) if plat is not None and plat != PLATFORM_IOS: return False, f'platform {plat} is not iOS ({PLATFORM_IOS})' - return True, f'arm64 MH_EXECUTE{"" if plat is None else f", platform {plat}"}, {len(data)} bytes ({how})' + return True, f'arm64 MH_EXECUTE{"" if plat is None else f", platform {plat}"}, {len(data)} bytes ({how_ok})' def macho_platform(data: bytes) -> int | None: @@ -1048,7 +1088,7 @@ def macho_platform(data: bytes) -> int | None: # ---------------------------------------------------------------- the whole picture -def check_all(deep: bool = False) -> list[Probe]: +def check_all(deep: bool = False, t=None) -> list[Probe]: """Every component, in the order the dependency panel shows them. `deep` adds the compile / link / Metal probes. They take a few seconds, so the panel runs @@ -1165,7 +1205,7 @@ def check_all(deep: bool = False) -> list[Probe]: # compiler); this one adds the SDK to the same probe shape the build uses ok, detail = probe_compile(sdk, clang) out.append(Probe('probe_compile', 'cross-compile probe', 'ok' if ok else 'wrong', detail)) - ok2, detail2 = probe_link(sdk) + ok2, detail2 = probe_link(sdk, t=t) out.append(Probe('probe_link', 'cross-link probe', 'ok' if ok2 else 'wrong', detail2)) if sdk and metal_ok: ok3, detail3 = probe_metal(sdk) diff --git a/frontend-qt/tests/test_win.py b/frontend-qt/tests/test_win.py index abbc500d3..cb9a8e14c 100644 --- a/frontend-qt/tests/test_win.py +++ b/frontend-qt/tests/test_win.py @@ -1684,11 +1684,140 @@ def test_the_strategy_order_is_build_style_first(self) -> None: 'the build\'s own invocation must be tried before --ld-path') self.assertLess(body.index('f\'--ld-path={lld}\''), body.index("f'-B{lld.parent}'"), '--ld-path before the -B fallback') - self.assertIn("env['PATH'] = str(lld.parent)", body, + self.assertIn("run_env['PATH'] = str(lld.parent)", body, 'the build-style try must put the linker folder on PATH (build_app.link does)') self.assertIn('does not run by itself', body, 'a linker that cannot start is its own message, before any strategy runs') + def test_the_failure_summary_names_everything_and_flags_a_non_ascii_sdk(self) -> None: + from nspb_qt.win import toolchain as tc + attempts = [('fuse-ld', 'exit 1 (0x00000001): (no output)', ['clang', '-fuse-ld=lld']), + ('ld-path', 'exit 1 (0x00000001): (no output)', ['clang', '--ld-path=x']), + ('-B dir', 'exit 1 (0x00000001): (no output)', ['clang', '-Bx'])] + plain = Path('C:/sdks/iPhoneOS26.0.sdk') + t = lambda key, *a: 'HINT:' + key # the model's translator, as ui.py receives it + summary = tc.link_failure_summary(attempts, 'LLD 23.1.4', ['clang'], plain, t=t) + for part in ('link failed 3 ways', 'LLD 23.1.4', 'fuse-ld:', 'ld-path:', '-B dir:', + 'try by hand:'): + self.assertIn(part, summary, part) + self.assertNotIn('dep.fix.nonascii', summary) + # The owner's machine: C:\Users\QC-北\... — the SDK itself sits under a non-ASCII path. + # The hint is a localization key: the panel must see it translated, never as the raw key. + nonascii = Path('C:/Users/QC-北/AppData/Local/NS Port Builder/sdks/iPhoneOS26.0.sdk') + hinted = tc.link_failure_summary(attempts, 'LLD 23.1.4', ['clang'], nonascii, t=t) + self.assertIn('HINT:dep.fix.nonascii', hinted) + self.assertNotIn(' — dep.fix.nonascii', hinted) + bare = tc.link_failure_summary(attempts, 'LLD 23.1.4', ['clang'], nonascii) + self.assertNotIn('dep.fix.nonascii', bare) + + +class VenvWheelsTest(unittest.TestCase): + """The build packages ride in the zip: the venv installs offline from wheels/ beside the + exe when it is there, and from PyPI exactly as before when it is not (source runs).""" + + @staticmethod + def _pip_args_fn(): + """model.py imports PySide6, which the CI test job deliberately does not install: run + the pure static function by extracting it from the source when Qt is absent.""" + try: + from nspb_qt import model as M + return M.Model._pip_args + except ImportError: + import ast + src = (QT / 'nspb_qt' / 'model.py').read_text() + tree = ast.parse(src) + fn = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) + and n.name == '_pip_args') + for n in ast.walk(fn): + ast.fix_missing_locations(n) + ns: dict = {} + exec(compile(ast.fix_missing_locations(ast.Module(body=[fn], type_ignores=[])), + '', 'exec'), ns) + return ns['_pip_args'] + + def test_offline_args_when_wheels_are_bundled(self) -> None: + args = self._pip_args_fn()(['lz4', 'nsz'], Path('C:/app/wheels')) + self.assertEqual(args, ['install', '--no-index', '--find-links', 'C:/app/wheels', 'lz4', 'nsz']) + + def test_pypi_args_when_not_bundled(self) -> None: + self.assertEqual(self._pip_args_fn()(['lz4'], None), ['install', 'lz4']) + + def test_the_log_row_string_takes_three_args(self) -> None: + from nspb_qt.i18n import Lang + from nspb_qt.localization import t + out = t('dep.row.log', Lang.EN, 'python', 'missing', 'C:/x | found') + self.assertEqual(out, 'dependency python: [missing] C:/x | found', 'the report log showed raw %@ placeholders') + self.assertTrue(t('dep.row.log', Lang.ZH, 'python', 'missing', 'd'), 'Chinese side is filled too') + + +class MetalPickFlowShapeTest(unittest.TestCase): + """The model wiring (source-shape, since model.py needs PySide6): the metal row asks for a + file, takes a zip to install_metal_zip, a folder to _save_metal_folder.""" + + def test_the_metal_row_routes_zip_and_folder(self) -> None: + src = (QT / 'nspb_qt' / 'model.py').read_text() + body = src[src.index("if dep.pick_key == 'metal_dir':"):] + self.assertIn('ask_file', body, 'the metal row must ask for a file (the zip)') + self.assertIn('install_metal_zip', body) + self.assertIn('_save_metal_folder', body) + self.assertIn("endswith('.zip')", body) + + +class MetalZipInstallTest(unittest.TestCase): + """The one manual dependency (Apple-ID-gated Metal tools) handed a downloaded zip: the app + unpacks, validates both shipped layouts, and refuses anything else.""" + + def setUp(self) -> None: + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + + @staticmethod + def _fake_tools(root: Path, layout: str) -> Path: + bin_ = root / ('ios/bin' if layout == '4.x' else 'bin') + bin_.mkdir(parents=True) + (bin_ / 'metal.exe').write_bytes(b'MZ') + (bin_ / 'metallib.exe').write_bytes(b'MZ') + return root + + def test_a_zip_with_the_tools_unpacks_to_the_tools_dir(self) -> None: + from nspb_qt.win import fetch as wf + tools = self.root / 'tools' + src = self._fake_tools(self.root / 'unpacked', '6.x') + zip_path = self.root / 'Metal Developer Tools 6.0.zip' + import zipfile + with zipfile.ZipFile(zip_path, 'w') as z: + for f in src.rglob('*'): + z.write(f, f.relative_to(src.parent)) + dest = wf.install_metal_from_zip(zip_path, dest=tools / 'metal-developer-tools') + self.assertTrue((dest / 'bin' / 'metal.exe').is_file()) + self.assertFalse((tools / 'metal-developer-tools-staging').exists(), 'staging is cleaned up') + + def test_a_4x_layout_zip_is_accepted_by_its_ios_folder(self) -> None: + from nspb_qt.win import fetch as wf + src = self._fake_tools(self.root / 'u4', '4.x') + zip_path = self.root / 'metal4.zip' + import zipfile + with zipfile.ZipFile(zip_path, 'w') as z: + for f in src.rglob('*'): + z.write(f, f.relative_to(src.parent)) + dest = wf.install_metal_from_zip(zip_path, dest=self.root / 'tools' / 'm4') + self.assertTrue((dest / 'ios' / 'bin' / 'metal.exe').is_file()) + + def test_a_zip_without_metal_exe_is_refused_and_leaves_nothing_behind(self) -> None: + from nspb_qt.win import fetch as wf + zip_path = self.root / 'not-metal.zip' + import zipfile + with zipfile.ZipFile(zip_path, 'w') as z: + (self.root / 'junk').mkdir() + (self.root / 'junk' / 'readme.txt').write_text('x', encoding='utf-8') + z.write(self.root / 'junk' / 'readme.txt', 'stuff/readme.txt') + tools = self.root / 'tools' + with self.assertRaises(wf.DownloadError): + wf.install_metal_from_zip(zip_path, dest=tools / 'm') + self.assertFalse((tools / 'm').exists()) + self.assertFalse((tools / 'm-staging').exists()) + class InstallFailureHintTest(unittest.TestCase): """The row's fix hint after a failed install (Mac parity: name the fix, not the traceback).""" diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift index 780b0ddfc..944074687 100644 --- a/frontend/Sources/NSPortBuilder/Localization.swift +++ b/frontend/Sources/NSPortBuilder/Localization.swift @@ -785,7 +785,11 @@ enum L10n { "dep.show": ("展开", "Show"), "dep.pick": ("选择文件夹…", "Choose folder…"), "dep.pick.ios_sdk.title": ("选择 iPhoneOS SDK 文件夹", "Choose the iPhoneOS SDK folder"), - "dep.pick.metal_dir.title": ("选择 Metal Developer Tools 文件夹", "Choose the Metal Developer Tools folder"), + "dep.pick.metal_dir.title": ("选择 Metal Developer Tools(下载的 zip 或解压后的文件夹)", "Choose Metal Developer Tools (the downloaded zip, or the unpacked folder)"), + "dep.pick.metal": ("选择 zip / 文件夹…", "Choose zip / folder…"), + "dep.metal.unpacking": ("正在解压 %@…", "Unpacking %@…"), + "dep.metal.done": ("Metal Developer Tools 已安装:%@", "Metal Developer Tools installed: %@"), + "dep.pick.metal.invalid": ("“%@”里没有 metal.exe(需要 bin\\metal.exe 或 ios\\bin\\metal.exe):确认下载的是 “Metal Developer Tools for Windows”。", "No metal.exe inside \"%@\" (needs bin\\metal.exe or ios\\bin\\metal.exe): check that the download is \"Metal Developer Tools for Windows\"."), "dep.pick.saved": ("已记住:%@", "Remembered: %@"), "dep.pick.iossdk.saved": ("SDK 已记住:%@", "SDK remembered: %@"), "dep.pick.iossdk.version": ("SDK 版本:%@", "SDK version: %@"), @@ -814,6 +818,11 @@ enum L10n { "Xcode's license is not accepted yet: run sudo xcodebuild -license accept."), "dep.fix.network": ("下载失败了:检查网络(代理或 VPN 可能拦住了 Homebrew 的域名),再试一次。", "The download failed: check the network (a proxy or VPN can block Homebrew's hosts) and try again."), + "dep.git.downloading": ("正在下载 PortableGit(SDK 下载需要它,约 45 MB)…", "Downloading PortableGit (the SDK download needs it, about 45 MB)…"), + "dep.git.done": ("PortableGit 已安装:%@", "PortableGit installed: %@"), + "dep.fix.nonascii": ("SDK 所在路径含非英文字符(比如用户名里的中文):ld64.lld 在 Windows 上可能因此打不开 SDK 文件。把整个 SDK 文件夹拷到一个纯英文路径(如 C:\\NSPB\\sdk),然后在依赖面板用「选择文件夹…」指向它。", + "The SDK path contains non-ASCII characters (a Chinese username, for example): ld64.lld on Windows may fail to open it. Copy the whole SDK folder to an ASCII-only path (e.g. C:\\NSPB\\sdk) and point the dependencies panel's Choose folder… at it."), + "dep.row.log": ("依赖 %@:[%@] %@", "dependency %@: [%@] %@"), "dep.fix.diskspace": ("磁盘空间不足:清理后(SDK 和工具链解压需要数 GB)再点「安装」。", "The disk is full: free some space (the SDK and toolchains unpack to several GB) and press Install again."), "dep.fix.log": ("完整输出在 Mac/iPhone 选择下面的日志里。", @@ -1758,6 +1767,15 @@ enum L10n { "msg.workdirHint": "Tips: ”Utdatamapp” är också platsen för byggcachen (utdatamapp/_build). Välj samma plats som förra bygget för att återanvända befintliga byggresurser, så körs inte uppackning och shaders igen. En ny plats börjar från början.", "msg.chainChanged": "Uppströmskoden uppdaterade kedjan för shaderöversättning. Tidigare shaderbibliotek kan inte återanvändas. Det här bygget återskapar dem med den nya översättaren, vilket bara sker en gång per version.", "dep.python.downloading": "Hämtar och installerar Python 3.12 … ungefär 26 MB, till appens egen mapp", + "dep.pick.metal_dir.title": "Välj Metal Developer Tools (den nedladdade zip-filen eller den uppackade mappen)", + "dep.pick.metal": "Välj zip / mapp …", + "dep.metal.unpacking": "Packar upp %@ …", + "dep.metal.done": "Metal Developer Tools installerat: %@", + "dep.pick.metal.invalid": "Ingen metal.exe i ”%@” (kräver bin\\metal.exe eller ios\\bin\\metal.exe): kontrollera att nedladdningen är ”Metal Developer Tools for Windows”.", + "dep.git.downloading": "Hämtar PortableGit (SDK-nedladdningen behöver den, cirka 45 MB) …", + "dep.git.done": "PortableGit installerat: %@", + "dep.fix.nonascii": "SDK-sökvägen innehåller icke-ASCII-tecken (ett kinesiskt användarnamn till exempel): ld64.lld på Windows kan därför misslyckas med att öppna SDK-filerna. Kopiera hela SDK-mappen till en sökväg med bara ASCII (till exempel C:\\NSPB\\sdk) och peka beroendepanelens ”Välj mapp …” på den.", + "dep.row.log": "beroende %@: [%@] %@", "prog.empty": "När bygget startar visas varje steg från skriptet här", "install.step2": "2\tKopiera hela romfs-mappen ovan till spelappens Dokument (appen Filer → På min iPhone → spelets namn)", "msg.installingNsz": "Det valda filformatet är komprimerat NSZ/XCZ. Installerar nsz i Python-miljön som används för bygget …", @@ -2603,6 +2621,15 @@ enum L10n { "fail.engineSync.next": "Tippe auf „Erneut versuchen“. Das Protokoll zeigt den Grund. Wenn es weiter fehlschlägt, melde es mit „Diagnose kopieren“ und dem Protokoll.", "dep.metal.other": "%@ (getestet: %@)", "dep.fix.metalPin": "Das ist nicht der Metal-Compiler, mit dem die Shader getestet wurden. Spiele mit NVN stoppen vor den Shader-Schritten. Installiere Xcode 27.1 (macOS 26.6 oder neuer) samt Metal-Toolchain.", + "dep.pick.metal_dir.title": "Metal Developer Tools wählen (die geladene Zip oder der entpackte Ordner)", + "dep.pick.metal": "Zip / Ordner wählen …", + "dep.metal.unpacking": "%@ wird entpackt …", + "dep.metal.done": "Metal Developer Tools installiert: %@", + "dep.pick.metal.invalid": "Keine metal.exe in „%@“ (benötigt bin\\metal.exe oder ios\\bin\\metal.exe): Prüfe, ob der Download „Metal Developer Tools for Windows“ ist.", + "dep.git.downloading": "PortableGit wird geladen (die SDK-Installation braucht es, rund 45 MB) …", + "dep.git.done": "PortableGit installiert: %@", + "dep.fix.nonascii": "Der SDK-Pfad enthält Nicht-ASCII-Zeichen (etwa ein chinesischer Benutzername): ld64.lld öffnet die SDK-Dateien unter Windows deshalb womöglich nicht. Kopiere den ganzen SDK-Ordner auf einen reinen ASCII-Pfad (z. B. C:\\NSPB\\sdk) und wähle ihn im Abhängigkeiten-Panel unter „Ordner wählen …“.", + "dep.row.log": "Abhängigkeit %@: [%@] %@", "msg.exitCode": "Exit-Code %d", "msg.stagingFailed": "Im Staging-Ordner konnten keine Links erstellt werden (Dateien auf verschiedenen Volumes?)", "msg.stagedFromSharedFolder": "Der Ordner enthält weitere Spiele: Es wird aus einer temporären Kopie dieses Spiels gebaut (%@)",