Skip to content

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

Folder scan reads bare title IDs, rows refuse files that do not fit

v0lumehi823ca8b9c9dc
diff --git a/frontend-qt/nspb_qt/inputs.py b/frontend-qt/nspb_qt/inputs.py
new file mode 100644
index 00000000..f6d0a045
--- /dev/null
+++ b/frontend-qt/nspb_qt/inputs.py
@@ -0,0 +1,81 @@
+"""Sorting a folder's game files into base, update and DLC by the title ID in their names.
+The same rules as the Mac launcher's BuildModel.classify, so both front ends agree."""
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+GAME_SUFFIXES = ('.nsp', '.xci', '.nsz', '.xcz')
+
+_BRACKET_ID = re.compile(r'\[([0-9A-Fa-f]{16})\]')
+# a bare ID that starts with 01, as a token: start of the name or after _ space - . ( [
+_BARE_ID = re.compile(r'(?:^|[_ \-.(\[])(01[0-9A-Fa-f]{14})(?![0-9A-Fa-f])')
+_BRACKET_VERSION = re.compile(r'\[v(\d+)\]')
+_TOKEN_VERSION = re.compile(r'(?:^|[_ ])v(\d+)(?=$|[_ .\-)\]])')
+
+
+def title_id(name: str) -> int | None:
+ """The title ID in a file name: [0100F2C0115B6000] first, else a bare 16-digit ID like
+ 01007EF00011E000_v0_420d1c5034ab.nsp."""
+ m = _BRACKET_ID.search(name) or _BARE_ID.search(name)
+ return int(m.group(1), 16) if m else None
+
+
+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)
+ return int(m.group(1)) if m else 0
+
+
+def owner(tid: int) -> int:
+ """The base game's title ID a title ID belongs to: 0x000 base, 0x800 its update, else add-on content."""
+ low = tid & 0xFFF
+ if low == 0:
+ return tid
+ return tid & ~0xFFF if low == 0x800 else (tid & ~0xFFF) - 0x1000
+
+
+def classify(files: list[Path]) -> dict:
+ """{'base', 'update', 'dlc', 'update_count'} for a list of files. Names without a title ID fall back
+ to the older [upd] / [dlc] / 'update' / 'addon' markers, and count as a base game only when no file
+ with a title ID is one. Update and DLC files of another game than the chosen base are left out."""
+ bases: list[tuple[int, Path]] = []
+ updates: list[tuple[int, Path, int]] = []
+ dlcs: list[Path] = []
+ unnamed: list[Path] = []
+ for f in files:
+ name = f.name
+ if name.startswith('._') or f.suffix.lower() not in GAME_SUFFIXES:
+ continue
+ try:
+ size = f.stat().st_size
+ except OSError:
+ continue
+ if size <= 0: # an incomplete download leaves empty files
+ continue
+ tid = title_id(name)
+ if tid is None:
+ low = name.lower()
+ if '[upd]' in low or 'update' in low:
+ updates.append((0, f, update_version(name)))
+ elif '[dlc]' in low or 'addon' in low:
+ dlcs.append(f)
+ else:
+ unnamed.append(f)
+ continue
+ kind = tid & 0xFFF
+ if kind == 0:
+ bases.append((size, f))
+ elif kind == 0x800:
+ updates.append((tid, f, update_version(name)))
+ else:
+ dlcs.append(f)
+ base = max(bases, key=lambda b: b[0])[1] if bases else (unnamed[0] if unnamed else None)
+ base_tid = title_id(base.name) if base else None
+ if base_tid is not None:
+ app = base_tid & ~0xFFF
+ updates = [u for u in updates if u[0] == 0 or owner(u[0]) == app]
+ dlcs = [d for d in dlcs if (title_id(d.name) is None or owner(title_id(d.name)) == app)]
+ newest = max(updates, key=lambda u: u[2]) if updates else None
+ return {'base': base, 'update': newest[1] if newest else None,
+ 'dlc': sorted(dlcs), 'update_count': len(updates)}
diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.py
index 16b05870..3871095a 100644
--- a/frontend-qt/nspb_qt/model.py
+++ b/frontend-qt/nspb_qt/model.py
@@ -17,6 +17,7 @@ from PySide6.QtCore import QSettings, Q_ARG, QMetaObject, QObject, Qt, QThread,
from . import build_failure as bf
from . import input_staging
+from . import inputs
from . import platform_util as pu
from .i18n import Lang
from .localization import t
@@ -994,13 +995,10 @@ class Model(QObject):
elif p.is_dir():
files += [q for q in sorted(p.iterdir()) if q.is_file()]
self.keys_path = next((str(f) for f in files if f.name.lower() == 'prod.keys'), self.keys_path)
- nsps = [f for f in files if f.suffix.lower() in ('.nsp', '.xci', '.nsz', '.xcz')]
- updates = [f for f in nsps if '[upd]' in f.name.lower() or 'update' in f.name.lower()]
- dlcs = [f for f in nsps if '[dlc]' in f.name.lower() or 'addon' in f.name.lower()]
- bases = [f for f in nsps if f not in updates and f not in dlcs]
- self.base_path = str(bases[0]) if bases else ''
- self.update_path = str(updates[0]) if updates else ''
- self.dlc_paths = [str(f) for f in dlcs]
+ found = inputs.classify(files)
+ self.base_path = str(found['base']) if found['base'] else ''
+ self.update_path = str(found['update']) if found['update'] else ''
+ self.dlc_paths = [str(f) for f in found['dlc']]
self.repoChanged.emit()
@property
@@ -1276,13 +1274,5 @@ class Model(QObject):
@staticmethod
def _title_id(nsp: str) -> int | None:
- """The title ID from a dump's file name: the 16 hex digits in [0100…], which every
- dumper puts there."""
- import re
- m = re.search(r'\[([0-9A-Fa-f]{16})\]', Path(nsp).name)
- if not m:
- return None
- try:
- return int(m.group(1), 16)
- except ValueError:
- return None
+ """The title ID from a dump's file name: bracketed [0100…] or a bare 16-digit ID."""
+ return inputs.title_id(Path(nsp).name)
diff --git a/frontend-qt/tests/test_inputs.py b/frontend-qt/tests/test_inputs.py
new file mode 100644
index 00000000..54859c8f
--- /dev/null
+++ b/frontend-qt/tests/test_inputs.py
@@ -0,0 +1,78 @@
+"""Sorting a game folder by the title ID in the file names (issue #237), the same cases as the Mac
+launcher's DropFilesTests."""
+from __future__ import annotations
+
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / 'frontend-qt'))
+
+from nspb_qt import inputs # noqa: E402
+
+
+class InputsTests(unittest.TestCase):
+ def setUp(self):
+ self._tmp = tempfile.TemporaryDirectory()
+ self.dir = Path(self._tmp.name)
+
+ def tearDown(self):
+ self._tmp.cleanup()
+
+ def make(self, name: str, size: int = 16) -> Path:
+ p = self.dir / name
+ p.write_bytes(b'x' * size)
+ return p
+
+ def test_reporter_folder(self):
+ base = self.make('01007EF00011E000_v0_420d1c5034ab.nsp', 64)
+ old = self.make('01007EF00011E800_v1048576_48d51e6d7ff4.nsp')
+ new = self.make('01007EF00011E800_v1114112_038ff9df0888.nsp')
+ d1 = self.make('01007EF00011F001_v196608_8a46aae731b8.nsp')
+ d2 = self.make('01007EF00011F002_v196608_193e5731baf2.nsp')
+ found = inputs.classify([d2, old, base, d1, new])
+ self.assertEqual(found['base'], base)
+ self.assertEqual(found['update'], new)
+ self.assertEqual(found['dlc'], [d1, d2])
+ self.assertEqual(found['update_count'], 2)
+
+ def test_bracket_names_still_work(self):
+ base = self.make('Game [0100000000010000][v0].nsp', 64)
+ upd = self.make('Game [0100000000010800][v131072].nsp')
+ dlc = self.make('Game DLC [0100000000011001].nsp')
+ self.make('Game [0100000000010000].xci').write_bytes(b'') # unfinished download
+ found = inputs.classify(sorted(self.dir.iterdir()))
+ self.assertEqual((found['base'], found['update'], found['dlc']), (base, upd, [dlc]))
+
+ def test_title_id_and_version_tokens(self):
+ self.assertEqual(inputs.title_id('Game [0100F2C0115B6000][v0].nsp'), 0x0100F2C0115B6000)
+ self.assertEqual(inputs.title_id('Game 0100AAAA00000000 [0100F2C0115B6000].nsp'), 0x0100F2C0115B6000)
+ self.assertEqual(inputs.title_id('Game (01007EF00011E000).nsp'), 0x01007EF00011E000)
+ self.assertIsNone(inputs.title_id('0200000000000000_v0.nsp'))
+ self.assertIsNone(inputs.title_id('x01007EF00011E000.nsp'))
+ self.assertIsNone(inputs.title_id('01007EF00011E0001.nsp'))
+ self.assertEqual(inputs.update_version('Game [v65536] _v1.nsp'), 65536)
+ self.assertEqual(inputs.update_version('01007EF00011E800_v1114112_038ff9df0888.nsp'), 1114112)
+ self.assertEqual(inputs.update_version('Game v131072.nsp'), 131072)
+ self.assertEqual(inputs.update_version('game.nsp'), 0)
+
+ def test_other_games_are_left_out(self):
+ base = self.make('01007EF00011E000_v0_a.nsp', 64)
+ upd = self.make('01007EF00011E800_v1_b.nsp')
+ self.make('0100AAAA00000800_v9_c.nsp')
+ self.make('0100AAAA00001001_v0_d.nsp')
+ found = inputs.classify(sorted(self.dir.iterdir()))
+ self.assertEqual((found['base'], found['update'], found['dlc']), (base, upd, []))
+
+ def test_names_without_ids_keep_the_old_markers(self):
+ base = self.make('game.nsp', 64)
+ upd = self.make('game [UPD].nsp')
+ dlc = self.make('game [DLC].nsp')
+ found = inputs.classify(sorted(self.dir.iterdir()))
+ self.assertEqual((found['base'], found['update'], found['dlc']), (base, upd, [dlc]))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index 1c6a23ac..f72a1cc5 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -68,14 +68,22 @@ struct Slot: Identifiable {
let optional: Bool
var paths: [String] = []
var problem: String = ""
+ /// A finished sentence shown beside the file name (the update row: which of several updates was taken).
+ var note: String = ""
var ok: Bool { paths.contains { FileManager.default.fileExists(atPath: $0) } }
/// `problem` holds either a finished message or a key + arguments, resolved by the model
/// (it needs the current language, which a struct cannot read).
var problemText: String { problem }
func summary(_ t: (String) -> String) -> String {
if !problem.isEmpty { return problem.hasPrefix("data.") ? t(problem) : problem }
- if paths.isEmpty { return optional ? t("data.notSelectedOptional") : t("data.notSelected") }
- if paths.count == 1 { return (paths[0] as NSString).lastPathComponent }
+ if paths.isEmpty {
+ if kind == .dlc { return t("data.notSelectedDlc") }
+ return optional ? t("data.notSelectedOptional") : t("data.notSelected")
+ }
+ if paths.count == 1 {
+ let name = (paths[0] as NSString).lastPathComponent
+ return note.isEmpty ? name : name + "\n" + note
+ }
return String(format: t("data.files"), paths.count) + paths.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
}
}
@@ -915,7 +923,7 @@ final class BuildModel: ObservableObject {
gameDir = folder
let found = Self.classify(Self.inputFiles(in: folder))
updateSlot("base") { $0.paths = found.base.map { [$0] } ?? []; $0.problem = found.base == nil ? "data.noBase" : "" }
- updateSlot("update") { $0.paths = found.update.map { [$0] } ?? []; $0.problem = "" }
+ updateSlot("update") { $0.paths = found.update.map { [$0] } ?? []; $0.problem = ""; $0.note = updateNote(found) }
updateSlot("dlc") { $0.paths = found.dlc; $0.problem = "" }
updateSlot("keys") { $0.paths = found.keys.map { [$0] } ?? []; $0.problem = "" }
if !found.anyGame {
@@ -929,7 +937,19 @@ final class BuildModel: ObservableObject {
var update: String?
var dlc: [String] = []
var keys: String?
+ /// How many updates the files held and the version of the one taken (the newest), for the update row's note.
+ var updateCount = 0
+ var updateVersion = 0
var anyGame: Bool { base != nil || update != nil || !dlc.isEmpty }
+ static func == (a: Self, b: Self) -> Bool {
+ a.base == b.base && a.update == b.update && a.dlc == b.dlc && a.keys == b.keys
+ }
+ }
+
+ /// The update row's note when the files held several updates: which one was taken and why one is enough.
+ func updateNote(_ found: FoundInputs) -> String {
+ guard found.update != nil, found.updateCount > 1 else { return "" }
+ return String(format: t("data.updateNewest"), found.updateVersion, found.updateCount)
}
/// The files under a folder, pruning the build folders this pipeline itself writes so a rescan is not slow.
@@ -970,7 +990,7 @@ final class BuildModel: ObservableObject {
guard ["nsp", "xci", "nsz", "xcz"].contains((low as NSString).pathExtension) else { continue }
let size = (try? FileManager.default.attributesOfItem(atPath: path))?[.size] as? Int ?? 0
guard size > 0 else { continue } // an incomplete download leaves 0-byte files behind
- guard let tid = titleID(name) else { continue } // a name without [title ID] cannot be classified
+ guard let tid = titleID(name) else { continue } // a name without a title ID cannot be classified
switch tid & 0xFFF {
case 0: base.append((path, size))
case 0x800: update.append((path, size, updateVersion(name)))
@@ -979,19 +999,70 @@ final class BuildModel: ObservableObject {
}
// several bases happen when a folder holds a repack beside the original: the largest wins
found.base = base.sorted { $0.1 > $1.1 }.first?.0
- // several updates: the newest [vN] is the one a profile would pack
- found.update = update.sorted { $0.2 > $1.2 }.first?.0
+ // a folder that holds other games too: only the update and add-on content of the chosen base game count
+ if let app = found.base.flatMap({ titleID(($0 as NSString).lastPathComponent) }).map({ $0 & ~0xFFF }) {
+ update = update.filter { titleID(($0.0 as NSString).lastPathComponent).map(owner) == app }
+ dlc = dlc.filter { titleID(($0 as NSString).lastPathComponent).map(owner) == app }
+ }
+ // several updates: the newest version is the one a profile would pack (an update contains the earlier ones)
+ let newest = update.sorted { $0.2 > $1.2 }.first
+ found.update = newest?.0
+ found.updateCount = update.count
+ found.updateVersion = newest?.2 ?? 0
found.dlc = dlc.sorted()
return found
}
- /// The [vN] in a file name, 0 when absent — used to pick the newest of several updates.
+ /// The base game's title ID (low 12 bits clear) a title ID belongs to, as build_ipa_from_nsp.py reads it:
+ /// 0x000 is a base game, 0x800 its update, anything else add-on content in the block above the base.
+ nonisolated static func owner(_ tid: UInt64) -> UInt64 {
+ let low = tid & 0xFFF
+ return low == 0 ? tid : (low == 0x800 ? tid & ~0xFFF : (tid & ~0xFFF) - 0x1000)
+ }
+
+ /// Why a file does not fit the row it was put in, judged by the title ID in its name.
+ enum RowMismatch: Equatable { case notBase(UInt64), notUpdate(UInt64), notDLC(UInt64), otherGame }
+
+ /// A file whose name carries no title ID fits every row (the build script reads the ID from the package).
+ /// `base` is the selected base game's file name, when it carries one.
+ nonisolated static func rowMismatch(_ kind: InputKind, name: String, base: String?) -> RowMismatch? {
+ guard kind != .keys, let tid = titleID(name) else { return nil }
+ let low = tid & 0xFFF
+ switch kind {
+ case .base: if low != 0 { return .notBase(tid) }
+ case .update: if low != 0x800 { return .notUpdate(tid) }
+ case .dlc: if low == 0 || low == 0x800 { return .notDLC(tid) }
+ case .keys: break
+ }
+ if kind != .base, let b = base.flatMap(titleID), owner(tid) != b & ~0xFFF { return .otherGame }
+ return nil
+ }
+
+ /// The row's message for a rejected file, as a finished sentence in the current language.
+ func rowProblemText(_ mismatch: RowMismatch, name: String) -> String {
+ func hex(_ tid: UInt64) -> String { String(format: "%016llX", tid) }
+ switch mismatch {
+ case .notBase(let tid): return String(format: t("data.rowNotBase"), name, hex(tid))
+ case .notUpdate(let tid): return String(format: t("data.rowNotUpdate"), name, hex(tid))
+ case .notDLC(let tid): return String(format: t("data.rowNotDLC"), name, hex(tid))
+ case .otherGame: return String(format: t("data.rowOtherGame"), name)
+ }
+ }
+
+ /// The version in a file name, 0 when absent: `[v65536]` first, then the `_v65536` / ` v65536` token the
+ /// eShop-style names use (`01007EF00011E800_v1114112_038ff9df0888.nsp`). Picks the newest of several updates.
nonisolated static func updateVersion(_ name: String) -> Int {
- guard let re = try? NSRegularExpression(pattern: #"\[v(\d+)\]"#) else { return 0 }
+ for pattern in [#"\[v(\d+)\]"#, #"(?:^|[_ ])v(\d+)(?=$|[_ .\-)\]])"#] {
+ if let v = firstGroup(pattern, in: name), let n = Int(v) { return n }
+ }
+ return 0
+ }
+
+ nonisolated private static func firstGroup(_ pattern: String, in name: String) -> String? {
+ guard let re = try? NSRegularExpression(pattern: pattern) else { return nil }
let ns = name as NSString
- guard let m = re.firstMatch(in: name, range: NSRange(location: 0, length: ns.length)),
- let v = Int(ns.substring(with: m.range(at: 1))) else { return 0 }
- return v
+ guard let m = re.firstMatch(in: name, range: NSRange(location: 0, length: ns.length)) else { return nil }
+ return ns.substring(with: m.range(at: 1))
}
/// What the Choose… dialog of a row offers. The compressed NSZ / XCZ are accepted by the build
@@ -1010,24 +1081,47 @@ final class BuildModel: ObservableObject {
p.canChooseFiles = true
p.allowsMultipleSelection = (kind == .dlc)
p.allowedFileTypes = Self.allowedFileTypes(for: kind)
+ switch kind {
+ case .dlc:
+ p.message = t("data.dlcPanelMessage")
+ p.prompt = t("data.dlcPanelPrompt")
+ case .update: p.message = t("data.updatePanelMessage")
+ default: break
+ }
guard p.runModal() == .OK, !p.urls.isEmpty else { return }
+ take(picked: p.urls.map(\.path), kind: kind)
+ }
+
+ /// Files chosen for one row: those that fit it are taken, the first that does not is named on the row
+ /// and left out (it is not moved to another row: the row the user chose stays as they set it).
+ func take(picked: [String], kind: InputKind) {
let id = kind == .base ? "base" : kind == .update ? "update" : kind == .dlc ? "dlc" : "keys"
- let picked = p.urls.map(\.path)
+ let baseName = kind == .base ? nil : (basePath as NSString).lastPathComponent
+ var fitting: [String] = [], problem = ""
+ for path in picked {
+ let name = (path as NSString).lastPathComponent
+ if let why = Self.rowMismatch(kind, name: name, base: baseName) {
+ if problem.isEmpty { problem = rowProblemText(why, name: name) }
+ } else { fitting.append(path) }
+ }
updateSlot(id) { s in
- s.paths = kind == .dlc ? Array(Set(s.paths + picked)).sorted() : Array(picked.prefix(1))
- s.problem = ""
+ if !fitting.isEmpty {
+ s.paths = kind == .dlc ? Array(Set(s.paths + fitting)).sorted() : Array(fitting.prefix(1))
+ s.note = ""
+ }
+ s.problem = problem
}
- if kind == .base, !picked.isEmpty { gameDir = (picked[0] as NSString).deletingLastPathComponent }
+ if kind == .base, let first = fitting.first { gameDir = (first as NSString).deletingLastPathComponent }
}
func clear(_ id: String) { updateSlot(id) { $0.paths = []; $0.problem = "" } }
- /// The title ID in a file name: [0100F2C0115B6000]
+ /// The title ID in a file name: `[0100F2C0115B6000]` first, else a bare 16-digit ID that starts with 01 as a token
+ /// (start of the name or after `_`, space, `-`, `.`, `(`, `[`), like `01007EF00011E000_v0_420d1c5034ab.nsp`.
nonisolated static func titleID(_ name: String) -> UInt64? {
- guard let re = try? NSRegularExpression(pattern: #"\[([0-9A-Fa-f]{16})\]"#) else { return nil }
- let ns = name as NSString
- guard let m = re.firstMatch(in: name, range: NSRange(location: 0, length: ns.length)) else { return nil }
- return UInt64(ns.substring(with: m.range(at: 1)), radix: 16)
+ let found = firstGroup(#"\[([0-9A-Fa-f]{16})\]"#, in: name)
+ ?? firstGroup(#"(?:^|[_ \-.(\[])(01[0-9A-Fa-f]{14})(?![0-9A-Fa-f])"#, in: name)
+ return found.flatMap { UInt64($0, radix: 16) }
}
var repoOK: Bool { Self.isRepo(repoPath) }
diff --git a/frontend/Sources/NSPortBuilder/DropFiles.swift b/frontend/Sources/NSPortBuilder/DropFiles.swift
index e8b4e1b1..49186977 100644
--- a/frontend/Sources/NSPortBuilder/DropFiles.swift
+++ b/frontend/Sources/NSPortBuilder/DropFiles.swift
@@ -14,8 +14,21 @@ extension BuildModel {
return FileManager.default.fileExists(atPath: p, isDirectory: &d) && d.boolValue
}
if paths.count == 1, isFolder(paths[0]) { scan(folder: paths[0]); return }
- let found = Self.classify(paths.flatMap { isFolder($0) ? Self.inputFiles(in: $0) : [$0] })
+ var found = Self.classify(paths.flatMap { isFolder($0) ? Self.inputFiles(in: $0) : [$0] })
+ // update and add-on files of another game than the base (the dropped one, else the one already chosen)
+ let baseName = (found.base ?? (basePath.isEmpty ? nil : basePath)).map { ($0 as NSString).lastPathComponent }
+ var rejected: [InputKind: String] = [:]
+ func fits(_ path: String, _ kind: InputKind) -> Bool {
+ let name = (path as NSString).lastPathComponent
+ guard let why = Self.rowMismatch(kind, name: name, base: baseName) else { return true }
+ if rejected[kind] == nil { rejected[kind] = rowProblemText(why, name: name) }
+ return false
+ }
+ if let u = found.update, !fits(u, .update) { found.update = nil }
+ found.dlc = found.dlc.filter { fits($0, .dlc) }
slots = Self.merged(slots, with: found)
+ for (kind, text) in rejected { updateSlot(kind == .update ? "update" : "dlc") { $0.problem = text } }
+ if found.update != nil { updateSlot("update") { $0.note = updateNote(found) } }
if let base = found.base { gameDir = (base as NSString).deletingLastPathComponent }
}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 8c625f6a..cc2957a1 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -613,6 +613,19 @@ enum L10n {
"data.noBase": ("这个文件夹里没有本体 NSP([xxxx…000])",
"No base game NSP in this folder ([xxxx…000])"),
"data.noNsp": ("这个文件夹里没有 NSP/XCI", "No NSP/XCI in this folder"),
+ "data.notSelectedDlc": ("未选择(可选,可一次选择多个文件)", "Not selected (optional, several files can be selected)"),
+ "data.updateNewest": ("v%d,共 %d 个更新中最新的一个。更新包含之前所有更新的内容。",
+ "v%d, the newest of %d. An update contains the earlier ones."),
+ "data.rowNotBase": ("%@ 不是本体(标题 ID %@)。本体的标题 ID 以 000 结尾。",
+ "%@ is not a base game (title ID %@). A base game's title ID ends in 000."),
+ "data.rowNotUpdate": ("%@ 不是更新(标题 ID %@)。更新的标题 ID 以 800 结尾。",
+ "%@ is not an update (title ID %@). An update's title ID ends in 800."),
+ "data.rowNotDLC": ("%@ 不是 DLC(标题 ID %@)。DLC 的标题 ID 不以 000 或 800 结尾。",
+ "%@ is not DLC (title ID %@). DLC does not end in 000 or 800. Those are the base game and its update."),
+ "data.rowOtherGame": ("%@ 属于另一个游戏,不是所选的本体。", "%@ belongs to another game than the selected base game."),
+ "data.dlcPanelMessage": ("选择一个或多个 DLC 文件(按住 ⌘ 点按可多选)", "Select one or more DLC files (hold ⌘ and click to select several)"),
+ "data.dlcPanelPrompt": ("添加 DLC", "Add DLC"),
+ "data.updatePanelMessage": ("选择最新的更新。更新包含之前所有更新的内容。", "Select the newest update. An update contains the earlier ones."),
// ---- dependencies ----
// ---- Qt front end (frontend-qt): keys the SwiftUI app does not use yet ----
@@ -1413,6 +1426,15 @@ enum L10n {
"data.choose": "Välj …",
"data.change": "Ändra …",
"data.noNsp": "Ingen NSP/XCI i den här mappen",
+ "data.notSelectedDlc": "Inte vald (valfri, flera filer kan väljas)",
+ "data.updateNewest": "v%d, den senaste av %d. En uppdatering innehåller de tidigare.",
+ "data.rowNotBase": "%@ är inte ett grundspel (titel-id %@). Ett grundspels titel-id slutar på 000.",
+ "data.rowNotUpdate": "%@ är inte en uppdatering (titel-id %@). En uppdatering har ett titel-id som slutar på 800.",
+ "data.rowNotDLC": "%@ är inte DLC (titel-id %@). DLC slutar inte på 000 eller 800, de är grundspelet och uppdateringen.",
+ "data.rowOtherGame": "%@ hör till ett annat spel än det valda grundspelet.",
+ "data.dlcPanelMessage": "Välj en eller flera DLC-filer (håll ⌘ och klicka för att välja flera)",
+ "data.dlcPanelPrompt": "Lägg till DLC",
+ "data.updatePanelMessage": "Välj den senaste uppdateringen. En uppdatering innehåller de tidigare.",
"build.start": "Starta bygget",
"notify.doneTitle": "%@ är byggt",
"notify.failedTitle": "%@ kunde inte byggas",
diff --git a/frontend/Tests/NSPortBuilderTests/DropFilesTests.swift b/frontend/Tests/NSPortBuilderTests/DropFilesTests.swift
index 9b10e6aa..a5e80a5f 100644
--- a/frontend/Tests/NSPortBuilderTests/DropFilesTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/DropFilesTests.swift
@@ -46,6 +46,110 @@ final class DropFilesTests: XCTestCase {
XCTAssertFalse(BuildModel.FoundInputs(keys: keys).anyGame)
}
+ /// The names from issue #237: the title ID bare at the start of the name, the version as a `_vN` token.
+ func testBareTitleIDNamesAreClassified() throws {
+ let base = try file("01007EF00011E000_v0_420d1c5034ab.nsp", size: 64)
+ let old = try file("01007EF00011E800_v1048576_48d51e6d7ff4.nsp")
+ let new = try file("01007EF00011E800_v1114112_038ff9df0888.nsp")
+ let dlc1 = try file("01007EF00011F001_v196608_8a46aae731b8.nsp")
+ let dlc2 = try file("01007EF00011F002_v196608_193e5731baf2.nsp")
+ let found = BuildModel.classify([dlc2, old, base, dlc1, new])
+ XCTAssertEqual(found, BuildModel.FoundInputs(base: base, update: new, dlc: [dlc1, dlc2]))
+ XCTAssertEqual(found.updateCount, 2)
+ XCTAssertEqual(found.updateVersion, 1114112)
+ // bracket names keep working, and win when a name has both
+ XCTAssertEqual(BuildModel.titleID("Game [0100F2C0115B6000][v0].nsp"), 0x0100F2C0115B6000)
+ XCTAssertEqual(BuildModel.titleID("Game 0100AAAA00000000 [0100F2C0115B6000].nsp"), 0x0100F2C0115B6000)
+ XCTAssertEqual(BuildModel.updateVersion("Game [v65536] _v1.nsp"), 65536)
+ XCTAssertEqual(BuildModel.updateVersion("Game v131072.nsp"), 131072)
+ XCTAssertEqual(BuildModel.updateVersion("01007EF00011E800_v1114112_038ff9df0888.nsp"), 1114112)
+ XCTAssertEqual(BuildModel.updateVersion("game.nsp"), 0)
+ // token separators, and only IDs that look like Switch title IDs
+ XCTAssertEqual(BuildModel.titleID("Game (01007EF00011E000).nsp"), 0x01007EF00011E000)
+ XCTAssertEqual(BuildModel.titleID("Game-01007EF00011E000.nsp"), 0x01007EF00011E000)
+ XCTAssertNil(BuildModel.titleID("0200000000000000_v0.nsp"))
+ XCTAssertNil(BuildModel.titleID("x01007EF00011E000.nsp"), "not a token")
+ XCTAssertNil(BuildModel.titleID("01007EF00011E0001.nsp"), "17 digits")
+ // another game's update and DLC in the same folder are not taken for this base
+ let other = try file("0100AAAA00000800_v65536_aaaaaaaaaaaa.nsp")
+ let otherDLC = try file("0100AAAA00001001_v0_bbbbbbbbbbbb.nsp")
+ XCTAssertEqual(BuildModel.classify([base, new, dlc1, other, otherDLC]).update, new)
+ XCTAssertEqual(BuildModel.classify([base, new, dlc1, other, otherDLC]).dlc, [dlc1])
+ }
+
+ func testRowChecks() throws {
+ let base = "01007EF00011E000_v0_420d1c5034ab.nsp"
+ let update = "01007EF00011E800_v1114112_038ff9df0888.nsp"
+ let dlc = "01007EF00011F001_v196608_8a46aae731b8.nsp"
+ func check(_ kind: InputKind, _ name: String, _ b: String? = base) -> BuildModel.RowMismatch? {
+ BuildModel.rowMismatch(kind, name: name, base: b)
+ }
+ XCTAssertNil(check(.update, update))
+ XCTAssertNil(check(.dlc, dlc))
+ XCTAssertNil(check(.base, base, nil))
+ XCTAssertEqual(check(.dlc, update), .notDLC(0x01007EF00011E800), "the reporter's update in the DLC row")
+ XCTAssertEqual(check(.update, dlc), .notUpdate(0x01007EF00011F001))
+ XCTAssertEqual(check(.dlc, base), .notDLC(0x01007EF00011E000))
+ XCTAssertEqual(check(.update, base), .notUpdate(0x01007EF00011E000))
+ XCTAssertEqual(check(.base, update, nil), .notBase(0x01007EF00011E800))
+ XCTAssertEqual(check(.base, dlc, nil), .notBase(0x01007EF00011F001))
+ XCTAssertEqual(check(.update, "0100AAAA00000800_v1.nsp"), .otherGame)
+ XCTAssertEqual(check(.dlc, "0100AAAA00001001_v1.nsp"), .otherGame)
+ XCTAssertNil(check(.update, "0100AAAA00000800_v1.nsp", nil), "no base chosen yet")
+ XCTAssertNil(check(.dlc, "game.nsp"), "no title ID in the name: the build script reads it from the package")
+ XCTAssertNil(check(.keys, "prod.keys"))
+ }
+
+ func testPickedFilesThatDoNotFitTheRowAreNotTaken() throws {
+ let m = BuildModel()
+ let base = try file("01007EF00011E000_v0_420d1c5034ab.nsp")
+ let update = try file("01007EF00011E800_v1114112_038ff9df0888.nsp")
+ let dlc1 = try file("01007EF00011F001_v196608_8a46aae731b8.nsp")
+ let dlc2 = try file("01007EF00011F002_v196608_193e5731baf2.nsp")
+ m.take(picked: [base], kind: .base)
+ m.take(picked: [update], kind: .dlc)
+ XCTAssertEqual(m.dlcPaths, [])
+ XCTAssertFalse(m.slot("dlc").problem.isEmpty)
+ XCTAssertTrue(m.slot("dlc").problem.contains("01007EF00011E800"))
+ m.take(picked: [dlc2, update, dlc1], kind: .dlc)
+ XCTAssertEqual(m.dlcPaths, [dlc1, dlc2], "the files that fit are taken, the update is named on the row")
+ XCTAssertFalse(m.slot("dlc").problem.isEmpty)
+ m.take(picked: [dlc1], kind: .update)
+ XCTAssertEqual(m.updatePath, "")
+ m.take(picked: [update], kind: .update)
+ XCTAssertEqual(m.updatePath, update)
+ XCTAssertEqual(m.slot("update").problem, "")
+ // a file of another game
+ let foreign = try file("0100AAAA00000800_v65536_aaaaaaaaaaaa.nsp")
+ m.take(picked: [foreign], kind: .update)
+ XCTAssertEqual(m.updatePath, update, "the earlier choice stays")
+ XCTAssertFalse(m.slot("update").problem.isEmpty)
+ // dropped, the same checks apply
+ let foreignDLC = try file("0100AAAA00001001_v0_bbbbbbbbbbbb.nsp")
+ m.take(dropped: [foreignDLC])
+ XCTAssertEqual(m.dlcPaths, [dlc1, dlc2])
+ XCTAssertFalse(m.slot("dlc").problem.isEmpty)
+ }
+
+ func testTheUpdateRowSaysWhichOfSeveralUpdatesItTook() throws {
+ let folder = temporary.appendingPathComponent("reporter")
+ _ = try file("01007EF00011E000_v0_420d1c5034ab.nsp", size: 64, in: "reporter")
+ _ = try file("01007EF00011E800_v1048576_48d51e6d7ff4.nsp", in: "reporter")
+ let new = try file("01007EF00011E800_v1114112_038ff9df0888.nsp", in: "reporter")
+ _ = try file("01007EF00011F001_v196608_8a46aae731b8.nsp", in: "reporter")
+ _ = try file("01007EF00011F002_v196608_193e5731baf2.nsp", in: "reporter")
+ let m = BuildModel()
+ m.lang = .en
+ m.scan(folder: folder.path)
+ XCTAssertEqual(m.updatePath, new)
+ XCTAssertEqual(m.dlcPaths.count, 2)
+ XCTAssertEqual(m.slot("update").note, "v1114112, the newest of 2. An update contains the earlier ones.")
+ XCTAssertTrue(m.slot("update").summary(m.t).contains("the newest of 2"))
+ XCTAssertFalse(m.slot("update").note.contains(";"))
+ XCTAssertTrue(m.slot("dlc").summary(m.t).hasPrefix("2 files"))
+ XCTAssertTrue(BuildModel().slot("dlc").summary(m.t).contains("several files"))
+ }
+
func testDroppedFilesJoinWhatIsAlreadyChosen() throws {
let m = BuildModel()
let base = try file("Game [0100000000010000].nsp", in: "base")