Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

Give every game its own work folder when the file name has no title ID

v0lumehi0d7869270eac
diff --git a/frontend-qt/nspb_qt/inputs.py b/frontend-qt/nspb_qt/inputs.py
index f6d0a045..dd50dd5b 100644
--- a/frontend-qt/nspb_qt/inputs.py
+++ b/frontend-qt/nspb_qt/inputs.py
@@ -21,6 +21,22 @@ def title_id(name: str) -> int | None:
return int(m.group(1), 16) if m else None
+def build_key(path: str) -> str:
+ """The name of a game's work folder and output (<key>_build, <key>.app), the same rule as the Mac launcher's
+ buildKey: the title ID in the file name, else the cleaned file name stem plus a short FNV-1a hash of it. Two games
+ never share a folder (and its shader cache), the same file name always gets the same one (#382)."""
+ name = Path(path).name
+ tid = title_id(name)
+ if tid is not None:
+ return f'{tid:016X}'
+ stem = name.rsplit('.', 1)[0] if '.' in name else name
+ h = 2166136261
+ for byte in stem.encode('utf-8'):
+ h = ((h ^ byte) * 16777619) & 0xFFFFFFFF
+ clean = ''.join(c if (c.isascii() and (c.isalnum() or c in '-_')) else '_' for c in stem)[:40]
+ return f'{clean or "game"}-{h:08x}'
+
+
def update_version(name: str) -> int:
"""The version in a file name ([v65536], else a _v65536 or ' v65536' token), 0 when absent."""
m = _BRACKET_VERSION.search(name) or _TOKEN_VERSION.search(name)
diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.py
index c45256a9..4d0be5c0 100644
--- a/frontend-qt/nspb_qt/model.py
+++ b/frontend-qt/nspb_qt/model.py
@@ -1179,8 +1179,7 @@ class Model(QObject):
all_files = [self.base_path, self.update_path] + self.dlc_paths
dirs = {str(Path(f).parent) for f in all_files if f}
- tid = self._title_id(self.base_path)
- tid_hex = f'{tid:016X}' if tid else 'game'
+ tid_hex = inputs.build_key(self.base_path)
work_dir = str(Path(self.out_dir or base_dir, f'{tid_hex}_build'))
input_dir = base_dir
diff --git a/frontend-qt/tests/test_inputs.py b/frontend-qt/tests/test_inputs.py
index 54859c8f..752643b1 100644
--- a/frontend-qt/tests/test_inputs.py
+++ b/frontend-qt/tests/test_inputs.py
@@ -76,3 +76,26 @@ class InputsTests(unittest.TestCase):
if __name__ == '__main__':
unittest.main()
+
+
+class BuildKeyTests(unittest.TestCase):
+ """#382: no more `game_build` for every file name without a title ID. Same cases as the Mac BuildKeyTests."""
+
+ def test_title_id_name_keeps_its_folder(self):
+ self.assertEqual(inputs.build_key('/x/Game [01007EF00011E000][v0].nsp'), '01007EF00011E000')
+
+ def test_different_names_differ_same_name_repeats(self):
+ a, b = inputs.build_key('/x/Zelda.nsp'), inputs.build_key('/x/Mario.nsp')
+ self.assertNotEqual(a, b)
+ self.assertNotEqual(a, 'game')
+ self.assertEqual(a, inputs.build_key('/other/Zelda.nsp'))
+ self.assertTrue(a.startswith('Zelda-'))
+
+ def test_odd_characters_are_sanitized(self):
+ import re
+ for name in ('Pokémon: Sword ../.. §.nsp', '日本語.nsp', 'a b.nsp'):
+ self.assertRegex(inputs.build_key('/x/' + name), r'^[A-Za-z0-9_-]+$')
+ self.assertNotEqual(inputs.build_key('a b.nsp'), inputs.build_key('a_b.nsp'))
+
+ def test_matches_the_mac_hash(self):
+ self.assertEqual(inputs.build_key('Zelda.nsp'), 'Zelda-74c1008b')
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index 827021d5..b1500d5c 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -1202,6 +1202,22 @@ final class BuildModel: ObservableObject {
return found.flatMap { UInt64($0, radix: 16) }
}
+ /// The name of a game's work folder and output (`<key>_build`, `<key>.app`). The title ID in the file name when there
+ /// is one, so `<ID>_build` stays what the library looks for. Else the file name without its extension, cut to letters,
+ /// digits, `-` and `_`, plus a short hash of the full name: two games never share a folder (and so a shader cache),
+ /// the same file name always gets the same one (a rebuild reuses its cache). Never a constant.
+ nonisolated static func buildKey(_ path: String) -> String {
+ let name = (path as NSString).lastPathComponent // a bare ID is a token, so a "/" before it would hide it
+ if let id = titleID(name) { return String(format: "%016llX", id) }
+ let stem = (name as NSString).deletingPathExtension
+ var hash: UInt32 = 2166136261 // FNV-1a, stable across runs (Hashable is seeded per launch)
+ for byte in stem.utf8 { hash = (hash ^ UInt32(byte)) &* 16777619 }
+ let clean = String(stem.unicodeScalars.map { c in
+ c.isASCII && (CharacterSet.alphanumerics.contains(c) || c == "-" || c == "_") ? Character(c) : "_"
+ }).prefix(40)
+ return (clean.isEmpty ? "game" : String(clean)) + "-" + String(format: "%08x", hash)
+ }
+
var repoOK: Bool { Self.isRepo(repoPath) }
/// A clone has .git; a GitHub "Download ZIP" copy does not (everything builds, but there is
/// nothing to fetch or pull — the update buttons hide and the note says to re-download instead).
@@ -1277,7 +1293,7 @@ final class BuildModel: ObservableObject {
staged.append(baseDir + "/" + f)
}
}
- let tidHex = Self.titleID(basePath).map { String(format: "%016llX", $0) } ?? "game"
+ let tidHex = Self.buildKey(basePath)
let workDir = (outDir.isEmpty ? baseDir : outDir) + "/" + tidHex + "_build"
// The build's signing step refuses the attributes a cloud folder adds, after the long steps: stop here instead.
if cloudFolderCheck(workDir) {
@@ -1420,7 +1436,7 @@ final class BuildModel: ObservableObject {
self.cleanupStaging()
} else {
// The game's archive, then its framework into the one shared app on the device
- let tid = Self.titleID(self.basePath).map { String(format: "%016llX", $0) } ?? "game"
+ let tid = Self.buildKey(self.basePath)
let name = ((self.basePath as NSString).lastPathComponent as NSString).deletingPathExtension
self.packArchive(workDir: self.effectiveWorkDir) {
self.installShell(framework: ShellInstall.frameworkPath(workDir: self.effectiveWorkDir, titleID: tid),
@@ -1869,7 +1885,7 @@ final class BuildModel: ObservableObject {
// exposes on an external drive) then needs no renaming, and several games' folders can sit
// side by side in one app.
let gamesRoot = (outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir) + "/games"
- let tid = Self.titleID(basePath).map { String(format: "%016llX", $0) } ?? "game"
+ let tid = Self.buildKey(basePath)
// games/<id>/ holds romfs.img and aoc/ side by side: main.m's per-game lookup takes the
// image, and the host mounts DLC from aoc/<index>.img (hle_fs.c aoc_dir). One folder, which
// the user copies to the phone or keeps on an external drive as a whole.
diff --git a/frontend/Tests/NSPortBuilderTests/BuildKeyTests.swift b/frontend/Tests/NSPortBuilderTests/BuildKeyTests.swift
new file mode 100644
index 00000000..67a311ca
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/BuildKeyTests.swift
@@ -0,0 +1,36 @@
+import XCTest
+@testable import NSPortBuilder
+
+/// #382: a file name without a title ID used to give the work folder `game_build` and the app `game.app` for every game,
+/// so a second game hit the first one's shader cache. One key per game now.
+final class BuildKeyTests: XCTestCase {
+ func testNameWithTitleIDKeepsItsFolder() {
+ XCTAssertEqual(BuildModel.buildKey("/x/Game [01007EF00011E000][v0].nsp"), "01007EF00011E000")
+ XCTAssertEqual(BuildModel.buildKey("/x/01007ef00011e000_v0_420d1c5034ab.nsp"), "01007EF00011E000")
+ }
+
+ func testDifferentNamesWithoutIDGetDifferentKeys() {
+ let a = BuildModel.buildKey("/x/Zelda.nsp"), b = BuildModel.buildKey("/x/Mario.nsp")
+ XCTAssertNotEqual(a, b)
+ XCTAssertNotEqual(a, "game")
+ }
+
+ func testSameNameGivesTheSameKeyEveryTime() {
+ XCTAssertEqual(BuildModel.buildKey("/x/Zelda.nsp"), BuildModel.buildKey("/other/Zelda.nsp"))
+ XCTAssertEqual(BuildModel.buildKey("/x/Zelda.nsp"), BuildModel.buildKey("/x/Zelda.nsp"))
+ XCTAssertEqual(BuildModel.buildKey("/x/Zelda.nsp"), "Zelda-74c1008b") // the Qt front end gives the same key
+ }
+
+ func testOddCharactersAreSanitized() {
+ let k = BuildModel.buildKey("/x/Pokémon: Sword/Shield ../.. §.nsp")
+ XCTAssertNil(k.range(of: "[^A-Za-z0-9_-]", options: .regularExpression))
+ XCTAssertFalse(k.contains("/"))
+ XCTAssertNotEqual(BuildModel.buildKey("/x/a b.nsp"), BuildModel.buildKey("/x/a_b.nsp")) // same clean stem, different hash
+ XCTAssertNil(BuildModel.buildKey("/x/日本語.nsp").range(of: "[^A-Za-z0-9_-]", options: .regularExpression))
+ }
+
+ func testBuildFolderStillEndsInBuild() {
+ XCTAssertTrue((BuildModel.buildKey("/x/Zelda.nsp") + "_build").hasSuffix("_build"))
+ XCTAssertEqual(BuildModel.buildKey("/x/[0100F2C0115B6000].nsp") + "_build", "0100F2C0115B6000_build")
+ }
+}