Skip to content
20 changes: 12 additions & 8 deletions frontend-qt/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,15 @@ the bundle's `fonts` folder (`build-qt.yml`). If the file is missing the system

## What is not there yet

- **The Windows build path has run on a real Windows machine** — a handheld PC, which is where the
bug reports came from — through repository download, git auto-install and the LLVM / SDK / .NET
downloads. The compile, link, `Metal` compile and the final IPA on Windows have still not been
exercised end to end against a genuine LLVM-MinGW + iPhoneOS SDK + Metal Developer Tools
install. See [Windows build → Open risks](#open-risks).
- **The Windows build path remains experimental.** One Rhythm Heaven Groove 1.0.0 IPA built on
Windows installed and launched on an iPhone Air running iOS 27.0.1; Play started the game, and the
button mappings were correct. That IPA needed three local changes beyond this branch:
seedds/nxnative#591 (the Windows image reader), an updated `dmsh_chain.lock` with a regenerated
`DMSH_CHAIN` for this machine's SPIRV-Cross and Metal tools, and a two-line declaration of
`CMMotionManager.deviceMotionBody` because the Windows toolchain still ships `iPhoneOS26.0.sdk`.
SDK symlinks were materialized by hand. The current unmodified frontend is not yet verified end
to end; other games and longer-term performance remain unverified. See
[Windows build → Open risks](#open-risks).
- No self-update. Repository download and update buttons do exist (`Download repository`,
`Check for updates`, `Pull updates`), and they log what git is doing.
- No per-stage progress bar, no cancel-with-cleanup (cancel terminates the child).
Expand Down Expand Up @@ -268,9 +272,9 @@ the tool offers it. The IPA name and the RomFS archive come out where the macOS

## Open risks

The app's own toolchain discovery, downloads and repository handling have now run on a real
Windows machine (a handheld PC). These are the parts that still have not, and that only a full
build on Windows plus a device run can settle:
The frontend's setup has run on Windows, and one locally patched Windows build installed, launched
and started the game on an iPhone. That test does not settle these risks
for other games or for an unmodified checkout:

1. **Shader libraries on the device.** They come from the Windows Metal compiler, not Xcode's.
They must load and render on iOS 26+ (`newLibraryWithURL`). `own_compilers.py` accepts a
Expand Down
29 changes: 25 additions & 4 deletions frontend-qt/nspb_qt/win/build_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,25 @@ def _engine_root() -> str:
_IMPORT = re.compile(r'^\s*#\s*(?:import|include)\s*<(\w+)/', re.M)


#: Paths the pack step drops from the base app (a full IPA maps its RomFS back in as `romfs` or `romfs.img`).
PACK_SKIPS = ('Payload/DmIOS.app/msl', 'Payload/DmIOS.app/aoc',
'Payload/DmIOS.app/romfs', 'Payload/DmIOS.app/romfs.img')


def romfs_has(repo, romfs, marker: str) -> bool:
"""Whether the RomFS (a folder or an image file) holds `marker`, read through the engine's `romfs.Path`."""
tools = str(Path(repo) / 'dm' / 'tools')
if tools not in sys.path:
sys.path.insert(0, tools)
from romfs import Path as RomFSPath
return (RomFSPath(romfs) / marker).exists()


def romfs_resource(romfs) -> str:
"""The name a full IPA gives the RomFS: an image file is `romfs.img`, a folder is `romfs`."""
return 'romfs.img' if Path(romfs).is_file() else 'romfs'


def t(msg: str) -> None:
print(f'[{time.strftime("%H:%M:%S")}] {msg}', flush=True)

Expand Down Expand Up @@ -482,7 +501,7 @@ def main(argv: list[str] | None = None) -> int:
for m in mods:
if not ((patched / f'{m}.patched.bin').exists() and (patched / f'{m}.fixups.tsv').exists()):
die(f'no rewritten module {patched}/{m} (the rewrite step must run first)')
if not (romfs / marker).exists():
if not romfs_has(repo, romfs, marker):
die(f'no RomFS at {romfs} (missing {marker})')

name = env.get('DM_DISPLAY_NAME') or ''
Expand Down Expand Up @@ -673,7 +692,8 @@ def main(argv: list[str] | None = None) -> int:
t('add-on content: ' + ' '.join(sorted(p.name for p in aoc.iterdir())))
full = bool(env.get('DM_FULL_ROMFS'))
if full:
maps.append(f'Payload/DmIOS.app/romfs={romfs}')
resource = romfs_resource(romfs)
maps.append(f'Payload/DmIOS.app/{resource}={romfs}')
t('packing the full IPA with the RomFS (only sensible for small games)')
else:
t('packing a slim IPA without the RomFS (the game files come from Documents/romfs)')
Expand All @@ -682,8 +702,9 @@ def main(argv: list[str] | None = None) -> int:
pack = [sys.executable, str(repo / 'dm/ios/tools/pack_ipa.py'), str(out_ipa)]
if store:
pack += ['--store', ':'.join(store.split(':'))]
pack += ['--skip', 'Payload/DmIOS.app/msl', '--skip', 'Payload/DmIOS.app/aoc',
'--skip', 'Payload/DmIOS.app/romfs', *maps]
for skip in PACK_SKIPS:
pack += ['--skip', skip]
pack += maps
r = subprocess.run(pack, capture_output=True, text=True, errors='replace')
if r.returncode:
print(((r.stdout or '') + (r.stderr or ''))[-3000:], file=sys.stderr)
Expand Down
16 changes: 11 additions & 5 deletions frontend-qt/nspb_qt/win/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,18 +230,24 @@ def heap_check(repo_, d, patched, work, env, logs, g):
mod.heap_check = heap_check

# ---------------------------------------------------------------- the shader cache key
def toolchain_probe():
def toolchain_probe(repo_=None, env=None):
"""What the shader-stage cache keys record as "the compilers".

Upstream records `xcodebuild -version` and `spirv-cross --revision`. Here the Metal
compiler's own version is what actually changes the output, so it is recorded instead;
a Metal Tools upgrade then invalidates the cache, which is the behaviour we want.
Upstream records `xcodebuild -version` and fingerprints the SPIRV-Cross
executable returned by `spirv_cross(repo, env)`. Here the Metal compiler's
own version is what actually changes the output, so it is recorded instead;
a Metal Tools upgrade then invalidates the cache, which is the behaviour
we want. The SPIRV-Cross entry uses the upstream resolver as well, so the
cache follows `SPIRV_CROSS` (an explicit path or an executable on PATH),
not whichever `spirv-cross` happens to be found by a separate lookup.
"""
xc = [sys.executable, str(Path(__file__).resolve().parent / 'xcrun_shim.py')]
probes = [('cmd', [*xc, '-sdk', 'iphoneos', 'metal', '--version'])]
if os.environ.get('NSPB_MAC_METAL'):
probes.append(('cmd', [*xc, '-sdk', 'macosx', 'metal', '--version']))
probes.append(('cmd', ['spirv-cross', '--revision']))
if repo_ is None:
repo_ = Path(__file__).resolve().parents[3]
probes.append(('files', [mod.spirv_cross(repo_, env)]))
return tuple(probes)
mod.toolchain = toolchain_probe

Expand Down
4 changes: 4 additions & 0 deletions frontend-qt/nspb_qt/win/shim.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ def _map(args):
return _resolve(args[1:]) or [sys.executable, _XCRUN] + args[1:]
if base == 'dmsh_xlate' and '/dmsh_xlate_bin/' in head:
# an absolute path, not `which`: a .NET SDK the app installed is not on PATH
import toolchain as tc
dn = tc.dotnet_dir()
dotnet = str(dn / 'dotnet.exe') if dn else (shutil.which('dotnet') or 'dotnet')
return [dotnet, args[0] + '.dll'] + args[1:]
Expand Down Expand Up @@ -322,11 +323,14 @@ def build_env(base: dict[str, str] | None = None, python_exe: str | None = None)
p = tc.find_exe(name)
if p:
parts.append(str(p.parent))
if name == 'spirv-cross':
env.setdefault('SPIRV_CROSS', str(p))
# tc.dotnet_dir() first: it knows about the SDK the app installed for itself, which is not on
# PATH and not in Program Files. `which` alone missed it, so `dotnet build` and the shader
# translator failed on a machine that had just installed .NET through this app.
if dn := tc.dotnet_dir():
parts.append(str(dn))
env['DOTNET_ROOT'] = env['DOTNET_ROOT_X64'] = str(dn)
elif dn := shutil.which('dotnet'):
parts.append(str(Path(dn).parent))

Expand Down
7 changes: 5 additions & 2 deletions frontend-qt/nspb_qt/win/toolchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -986,8 +986,11 @@ def probe_link(sdk: Path, t=None) -> tuple[bool, str]:
# Step 0: run the linker by itself. A silent clang failure (the report: exit 1, no output on
# either stream) cannot say whether the linker is broken or clang's drive of it is, and the
# two have different fixes. lld --version is the smallest probe that separates them.
v = subprocess.run([str(lld), '--version'], capture_output=True, text=True, timeout=60,
**no_window())
try:
v = subprocess.run([str(lld), '--version'], capture_output=True, text=True, timeout=60,
**no_window())
except OSError as e:
return False, f'cannot run {lld.name}: {e}'
lld_self = (v.stdout or v.stderr or '').strip().splitlines()
lld_line = lld_self[0] if lld_self else f'exit {v.returncode}, no output'
if v.returncode != 0:
Expand Down
133 changes: 129 additions & 4 deletions frontend-qt/tests/test_win.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,16 @@ def test_explicit_target_is_not_duplicated(self) -> None:
got = xcrun_shim.metal_args('iphoneos', ['-target', 'air64-apple-ios26.0', '-c'])
self.assertEqual(got.count('-target'), 1)

def test_link_probe_reports_a_linker_failure(self) -> None:
# An unavailable linker should be reported by the doctor, not crash its probe.
with tempfile.TemporaryDirectory() as td, \
mock.patch.object(tc, 'llvm_tool', return_value=Path(td) / 'clang.exe'), \
mock.patch.object(tc, 'ensure_ld64_lld', return_value=(Path(td) / 'ld64.lld.exe', '')), \
mock.patch.object(tc.subprocess, 'run', side_effect=OSError('linker unavailable')):
ok, detail = tc.probe_link(Path(td))
self.assertFalse(ok)
self.assertIn('linker unavailable', detail)

def test_metal_tt_has_no_windows_tool(self) -> None:
# the pipeline archive is disabled here, and the caller relies on this being None
self.assertIsNone(tc.metal_tool('metal-tt'))
Expand Down Expand Up @@ -431,6 +441,58 @@ def test_without_icons_no_icon_keys(self) -> None:
self.assertNotIn('CFBundleIcons', p)


class RomfsPackTest(unittest.TestCase):
"""The RomFS can be a folder or an image file: marker check, resource name and pack skips."""

def setUp(self):
self._tmp = tempfile.TemporaryDirectory()
self.addCleanup(self._tmp.cleanup)
self.root = Path(self._tmp.name)
tools = self.root / 'repo' / 'dm' / 'tools'
tools.mkdir(parents=True)
# A stand-in for the engine's dm/tools/romfs.py: an image file is a text list of its entries.
(tools / 'romfs.py').write_text(
'from pathlib import Path as _P\n'
'class Path:\n'
' def __init__(self, p):\n'
' self.p = _P(p); self.rel = ""\n'
' def __truediv__(self, n):\n'
' o = Path(self.p); o.rel = n; return o\n'
' def exists(self):\n'
' if self.p.is_file():\n'
' return self.rel in self.p.read_text().split()\n'
' return (self.p / self.rel).exists()\n', encoding='utf-8')
self.repo = self.root / 'repo'
self._path = list(sys.path)
self.addCleanup(lambda: (sys.path.__setitem__(slice(None), self._path), sys.modules.pop('romfs', None)))
sys.modules.pop('romfs', None)

def test_marker_in_image_file(self):
img = self.root / 'RomFS.img'
img.write_text('graph/a.bin')
self.assertTrue(build_app.romfs_has(self.repo, img, 'graph/a.bin'))
self.assertFalse(build_app.romfs_has(self.repo, img, 'graph/b.bin'))

def test_marker_in_folder(self):
d = self.root / 'RomFS'
(d / 'graph').mkdir(parents=True)
(d / 'graph' / 'a.bin').write_bytes(b'')
self.assertTrue(build_app.romfs_has(self.repo, d, 'graph/a.bin'))
self.assertFalse(build_app.romfs_has(self.repo, d, 'graph/b.bin'))

def test_resource_name(self):
img = self.root / 'RomFS.img'
img.write_text('x')
d = self.root / 'RomFS'
d.mkdir()
self.assertEqual(build_app.romfs_resource(img), 'romfs.img')
self.assertEqual(build_app.romfs_resource(d), 'romfs')

def test_pack_skips_both_names(self):
self.assertIn('Payload/DmIOS.app/romfs', build_app.PACK_SKIPS)
self.assertIn('Payload/DmIOS.app/romfs.img', build_app.PACK_SKIPS)


class IpaModesTest(unittest.TestCase):
"""The zip mode fixer, which stands in for `pack_ipa.py --exec` (an upstream file we
must not edit)."""
Expand Down Expand Up @@ -548,6 +610,45 @@ def test_build_env_prepends_the_shim(self) -> None:
self.assertTrue(env['PYTHONPATH'].startswith(td))
self.assertEqual(env['PYTHONUTF8'], '1')

def test_build_env_passes_portable_dotnet_and_spirv_cross_to_children(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
dotnet = root / 'dotnet'
spirv = root / 'cross' / 'spirv-cross.exe'
def find(name):
return spirv if name == 'spirv-cross' else None
with mock.patch.object(shim, 'shim_dir', return_value=root / 'shim'), \
mock.patch.object(tc, 'dotnet_dir', return_value=dotnet), \
mock.patch.object(tc, 'find_exe', side_effect=find):
env = shim.build_env({'PATH': '', 'PYTHONPATH': ''}, python_exe=sys.executable)
self.assertEqual(env['DOTNET_ROOT'], str(dotnet))
self.assertEqual(env['DOTNET_ROOT_X64'], str(dotnet))
self.assertEqual(env['SPIRV_CROSS'], str(spirv))

def test_build_env_preserves_an_explicit_spirv_cross(self) -> None:
with tempfile.TemporaryDirectory() as td:
with mock.patch.object(shim, 'shim_dir', return_value=Path(td)), \
mock.patch.object(tc, 'find_exe', return_value=Path('detected-cross')):
env = shim.build_env({'PATH': '', 'SPIRV_CROSS': 'chosen-cross'},
python_exe=sys.executable)
self.assertEqual(env['SPIRV_CROSS'], 'chosen-cross')

@unittest.skipUnless(os.name == 'nt', 'Windows subprocess shim')
def test_translator_mapping_can_find_the_dotnet_module(self) -> None:
# The generated sitecustomize runs in child interpreters and must resolve dotnet there.
with tempfile.TemporaryDirectory() as td:
shim.install(Path(td), python_exe=sys.executable)
env = dict(os.environ, PYTHONPATH=td, NSPB_SHIM_OFF='')
script = ("import sitecustomize as s, toolchain\n"
"from pathlib import Path\n"
"toolchain.dotnet_dir = lambda: Path('portable-dotnet')\n"
"got = s._map(['x/dmsh_xlate_bin/dmsh_xlate', '--source-sha'])\n"
"assert got[0] == str(Path('portable-dotnet') / 'dotnet.exe'), got\n"
"assert got[1:] == ['x/dmsh_xlate_bin/dmsh_xlate.dll', '--source-sha'], got\n")
r = subprocess.run([sys.executable, '-c', script], env=env,
capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)


class DriverCliTest(unittest.TestCase):
"""Mac-only options are refused before any work starts."""
Expand Down Expand Up @@ -636,13 +737,36 @@ def test_check_prereqs_refuses_mac(self) -> None:
self.assertIn('need a Mac', str(ctx.exception))

def test_toolchain_probe_uses_the_windows_metal(self) -> None:
probes = self.mod.toolchain()
probes = self.mod.toolchain(self.repo, {})
self.assertTrue(probes)
joined = ' '.join(' '.join(p[1]) for p in probes if p[0] == 'cmd')
self.assertIn('xcrun_shim.py', joined)
self.assertIn('metal', joined)
self.assertNotIn('xcodebuild', joined)

def test_stage_key_fingerprints_the_selected_spirv_cross(self) -> None:
"""Switching SPIRV_CROSS must invalidate the shader-stage key."""
with tempfile.TemporaryDirectory() as td:
a = Path(td) / 'cross-a.exe'
b = Path(td) / 'cross-b.exe'
a.write_bytes(b'first')
b.write_bytes(b'second')

def files(probes):
return [p for kind, values in probes if kind == 'files' for p in values]

first = self.mod.toolchain(self.repo, {'SPIRV_CROSS': str(a), 'PATH': ''})
second = self.mod.toolchain(self.repo, {'SPIRV_CROSS': str(b), 'PATH': ''})
self.assertIn(a, files(first))
self.assertIn(b, files(second))
self.assertNotEqual(self.mod.fingerprint(('files', [a])),
self.mod.fingerprint(('files', [b])))
# The same selected path with changed executable contents must also
# change the key, or a rebuilt compiler would reuse the old library.
before = self.mod.fingerprint(('files', [a]))
a.write_bytes(b'changed')
self.assertNotEqual(before, self.mod.fingerprint(('files', [a])))

def test_tool_paths_are_replaced_not_extended(self) -> None:
"""On Windows the upstream macOS list must be gone.

Expand Down Expand Up @@ -1228,7 +1352,8 @@ def test_python_candidates_include_uvs_managed_interpreters(self) -> None:
shim.parent.mkdir(parents=True)
shim.write_text('#!/bin/sh\n')
with mock.patch.object(pu, 'IS_WIN', False), \
mock.patch.dict(os.environ, {'UV_PYTHON_INSTALL_DIR': str(store), 'HOME': td}):
mock.patch.dict(os.environ, {'UV_PYTHON_INSTALL_DIR': str(store), 'HOME': td,
'USERPROFILE': td}):
cands = pu.uv_pythons()
self.assertIn(str(exe), cands, "uv's store holds the real interpreter")
self.assertIn(str(shim), cands, "uv links a python3 shim in ~/.local/bin")
Expand Down Expand Up @@ -1678,7 +1803,7 @@ class LinkProbeStrategyTest(unittest.TestCase):
"""

def test_the_strategy_order_is_build_style_first(self) -> None:
src = (QT / 'nspb_qt' / 'win' / 'toolchain.py').read_text()
src = (QT / 'nspb_qt' / 'win' / 'toolchain.py').read_text(encoding='utf-8')
body = src[src.index('def probe_link'):]
self.assertLess(body.index("'-fuse-ld=lld'"), body.index('f\'--ld-path={lld}\''),
'the build\'s own invocation must be tried before --ld-path')
Expand Down Expand Up @@ -1830,7 +1955,7 @@ def test_network_disk_and_other_map_to_their_hints(self) -> None:
classify = M.Model._classify_install_failure
except ImportError:
import ast
src = (HERE.parent / 'nspb_qt' / 'model.py').read_text()
src = (HERE.parent / 'nspb_qt' / 'model.py').read_text(encoding='utf-8')
tree = ast.parse(src)
fn = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)
and n.name == '_classify_install_failure')
Expand Down
Loading