Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Launcher: drop game files, a folder or prod.keys onto the Builds page (issue #68)
v0lumehi87b96c977ab8
diff --git a/frontend/README.md b/frontend/README.mdindex 5a1cfcb9..692dbed0 100644--- a/frontend/README.md+++ b/frontend/README.md@@ -16,7 +16,9 @@ writes them as PNG (from a copy of your library, with example paths), and## Build game1. Select **Build game** and choose the folder containing one game's files, or- pick the base game and `prod.keys` separately.+ pick the base game and `prod.keys` separately. Dropping NSP, NSZ or XCI files,+ a folder or `prod.keys` onto the page does the same: they are sorted into base+ game, update and DLC by the title ID in their names, as a chosen folder is.2. Add an update or DLC under **Updates & add-on content** when needed.3. Choose **This Mac** or **iPhone / iPad**, then **Build game**.diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 26c3e95a..e4a1fe10 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -609,9 +609,29 @@ final class BuildModel: ObservableObject {/// pruning the build folders this pipeline itself writes so a rescan is not slow.func scan(folder: String) {gameDir = folder- let fm = FileManager.default- var base: [(String, Int)] = [], update: [(String, Int, Int)] = [], dlc: [String] = []+ 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("dlc") { $0.paths = found.dlc; $0.problem = "" }+ updateSlot("keys") { $0.paths = found.keys.map { [$0] } ?? []; $0.problem = "" }+ if !found.anyGame {+ updateSlot("base") { $0.problem = "data.noNsp" }+ }+ }++ /// What a set of files holds for the four slots (`classify`).+ struct FoundInputs: Equatable {+ var base: String?+ var update: String?+ var dlc: [String] = []var keys: String?+ var anyGame: Bool { base != nil || update != nil || !dlc.isEmpty }+ }++ /// The files under a folder, pruning the build folders this pipeline itself writes so a rescan is not slow.+ nonisolated static func inputFiles(in folder: String) -> [String] {+ let fm = FileManager.default+ var files: [String] = []var seen = 0let enumerator = fm.enumerator(atPath: folder)while let rel = enumerator?.nextObject() as? String {@@ -628,32 +648,36 @@ final class BuildModel: ObservableObject {if low == "archive" || low == "xcode" || low.hasSuffix("_build") || low.hasSuffix("_survey") { enumerator?.skipDescendants() }continue}- if keys == nil && (low == "prod.keys" || low.hasSuffix(".keys")) { keys = path; continue }- guard low.hasSuffix(".nsp") || low.hasSuffix(".xci") else { continue }- let size = (try? fm.attributesOfItem(atPath: path))?[.size] as? Int ?? 0+ files.append(path)+ }+ return files+ }++ /// NSP/XCI (and their compressed NSZ/XCZ) sorted by the title ID in the file name, plus the first prod.keys.+ /// Shared by Choose game folder and files dropped on the Builds page.+ nonisolated static func classify(_ files: [String]) -> FoundInputs {+ var base: [(String, Int)] = [], update: [(String, Int, Int)] = [], dlc: [String] = []+ var found = FoundInputs()+ for path in files {+ let name = (path as NSString).lastPathComponent+ let low = name.lowercased()+ if found.keys == nil && (low == "prod.keys" || low.hasSuffix(".keys")) { found.keys = path; continue }+ guard ["nsp", "xci", "nsz", "xcz"].contains((low as NSString).pathExtension) else { continue }+ let size = (try? FileManager.default.attributesOfItem(atPath: path))?[.size] as? Int ?? 0guard size > 0 else { continue } // an incomplete download leaves 0-byte files behind- guard let tid = Self.titleID(name) else { continue } // a name without [title ID] cannot be classified+ guard let tid = titleID(name) else { continue } // a name without [title ID] cannot be classifiedswitch tid & 0xFFF {case 0: base.append((path, size))- case 0x800: update.append((path, size, Self.updateVersion(name)))+ case 0x800: update.append((path, size, updateVersion(name)))default: dlc.append(path)}}// several bases happen when a folder holds a repack beside the original: the largest wins- updateSlot("base") {- $0.paths = base.sorted { $0.1 > $1.1 }.prefix(1).map(\.0)- $0.problem = base.isEmpty ? "data.noBase" : ""- }+ found.base = base.sorted { $0.1 > $1.1 }.first?.0// several updates: the newest [vN] is the one a profile would pack- updateSlot("update") {- $0.paths = update.sorted { $0.2 > $1.2 }.prefix(1).map(\.0)- $0.problem = ""- }- updateSlot("dlc") { $0.paths = dlc.sorted(); $0.problem = "" }- updateSlot("keys") { $0.paths = keys.map { [$0] } ?? []; $0.problem = "" }- if base.isEmpty && update.isEmpty && dlc.isEmpty {- updateSlot("base") { $0.problem = "data.noNsp" }- }+ found.update = update.sorted { $0.2 > $1.2 }.first?.0+ found.dlc = dlc.sorted()+ return found}/// The [vN] in a file name, 0 when absent — used to pick the newest of several updates.@@ -1816,6 +1840,7 @@ struct BuilderView: View {.onChange(of: padFocus.focused) { id in // a controller's focus on this page scrolls into viewif let id, id.hasPrefix("set.") { withAnimation(.easeInOut(duration: 0.2)) { proxy.scrollTo(id, anchor: .center) } }}+ .modifier(GameFilesDrop(enabled: !settings && !m.running, label: m.t("drop.hint")) { m.take(dropped: $0) }) // DropFiles.swift}.buttonStyle(LauncherSecondaryButtonStyle())}diff --git a/frontend/Sources/NSPortBuilder/DropFiles.swift b/frontend/Sources/NSPortBuilder/DropFiles.swiftnew file mode 100644index 00000000..e8b4e1b1--- /dev/null+++ b/frontend/Sources/NSPortBuilder/DropFiles.swift@@ -0,0 +1,95 @@+import SwiftUI+import UniformTypeIdentifiers++// Game files dropped on the Builds page (issue #68): NSP, NSZ and XCI files, a folder, prod.keys, in any+// mix. They are sorted into the slots by the same classification as Choose game folder+// (BuildModel.classify), so a drop and a picked folder never disagree about what is the update.++extension BuildModel {+ /// One dropped folder is the same as choosing it; anything else (files, several folders, a mix) is added to+ /// what is already chosen: a slot the drop has something for is replaced, add-on content is added to.+ func take(dropped paths: [String]) {+ func isFolder(_ p: String) -> Bool {+ var d: ObjCBool = false+ 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] })+ slots = Self.merged(slots, with: found)+ if let base = found.base { gameDir = (base as NSString).deletingLastPathComponent }+ }++ /// The slots after a drop of `found`. Nothing usable in it leaves the slots as they were, but says so on an empty base row.+ nonisolated static func merged(_ slots: [Slot], with found: FoundInputs) -> [Slot] {+ slots.map { s in+ var s = s+ switch s.id {+ case "base":+ if let base = found.base { s.paths = [base]; s.problem = "" }+ else if !found.anyGame && found.keys == nil && s.paths.isEmpty { s.problem = "data.noNsp" }+ case "update": if let update = found.update { s.paths = [update]; s.problem = "" }+ case "dlc": if !found.dlc.isEmpty { s.paths = Array(Set(s.paths + found.dlc)).sorted(); s.problem = "" }+ case "keys": if let keys = found.keys { s.paths = [keys]; s.problem = "" }+ default: break+ }+ return s+ }+ }+}++/// The Builds page as a drop target: a highlight while files are dragged over it, the files to the model when dropped.+struct GameFilesDrop: ViewModifier {+ let enabled: Bool+ let label: String+ let onDrop: ([String]) -> Void+ @State private var targeted: Bool++ /// `targeted` starts the highlight on (visual QA renders it without a drag).+ init(enabled: Bool, label: String, targeted: Bool = false, onDrop: @escaping ([String]) -> Void) {+ self.enabled = enabled; self.label = label; self.onDrop = onDrop+ _targeted = State(initialValue: targeted)+ }++ func body(content: Content) -> some View {+ content+ .overlay {+ if targeted && enabled {+ // the page dimmed under the label, so the label reads wherever it lands+ ZStack {+ RoundedRectangle(cornerRadius: 18)+ .fill(LauncherPalette.background.opacity(0.72))+ .overlay(RoundedRectangle(cornerRadius: 18).strokeBorder(LauncherPalette.cream.opacity(0.8),+ style: StrokeStyle(lineWidth: 2, dash: [8, 6])))+ Label(label, systemImage: "square.and.arrow.down")+ .font(.manrope(15, .semibold)).foregroundStyle(.black)+ .padding(.horizontal, 20).padding(.vertical, 12)+ .background(LauncherPalette.cream, in: Capsule())+ }+ .padding(12)+ .allowsHitTesting(false)+ }+ }+ .onDrop(of: [.fileURL], isTargeted: $targeted) { providers in+ guard enabled else { return false }+ Self.paths(from: providers) { onDrop($0) }+ return true+ }+ }++ /// The file URLs of a drop, delivered on the main queue once all have loaded.+ static func paths(from providers: [NSItemProvider], then done: @escaping ([String]) -> Void) {+ let group = DispatchGroup()+ let lock = NSLock()+ var paths: [String] = []+ for p in providers where p.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) {+ group.enter()+ _ = p.loadDataRepresentation(forTypeIdentifier: UTType.fileURL.identifier) { data, _ in+ if let data, let url = URL(dataRepresentation: data, relativeTo: nil), url.isFileURL {+ lock.lock(); paths.append(url.path); lock.unlock()+ }+ group.leave()+ }+ }+ group.notify(queue: .main) { if !paths.isEmpty { done(paths) } }+ }+}diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 4454dd15..3284c67f 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -416,6 +416,7 @@ enum L10n {"msg.stagingFailed": ("无法在暂存文件夹里建立链接(文件在不同磁盘?)","Could not create links in the staging folder (files on different volumes?)"),"msg.stagedFromSharedFolder": ("文件夹里还有其他游戏:只把选中的这个游戏(%@)临时复制出去构建", "The folder holds other games: building from a temporary copy of this one (%@)"),+ "drop.hint": ("松开以添加:NSP、NSZ、XCI 文件,文件夹或 prod.keys", "Drop to add: NSP, NSZ or XCI files, a folder, prod.keys"),"msg.launchFailed": ("无法启动构建脚本:%@", "Could not start the build script: %@"),"msg.repoInvalid": ("仓库路径无效:%@——用上方的「选择仓库…」指向本项目的 clone","Invalid repository path: %@ — use Choose repository… above to point at your clone"),diff --git a/frontend/Tests/NSPortBuilderTests/DropFilesTests.swift b/frontend/Tests/NSPortBuilderTests/DropFilesTests.swiftnew file mode 100644index 00000000..d019cf97--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/DropFilesTests.swift@@ -0,0 +1,118 @@+import XCTest+import SwiftUI+@testable import NSPortBuilder++/// Files dropped on the Builds page (issue #68), sorted by the same classification as Choose game folder.+final class DropFilesTests: XCTestCase {+ private var temporary: URL!++ override func setUpWithError() throws {+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-drop-" + UUID().uuidString)+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)+ }++ override func tearDownWithError() throws { try FileManager.default.removeItem(at: temporary) }++ /// A stand-in file of `size` bytes (the classification skips empty ones, as an unfinished download leaves).+ @discardableResult private func file(_ name: String, size: Int = 16, in folder: String = "") throws -> String {+ let dir = folder.isEmpty ? temporary! : temporary.appendingPathComponent(folder)+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ let path = dir.appendingPathComponent(name).path+ FileManager.default.createFile(atPath: path, contents: Data(repeating: 0, count: size))+ return path+ }++ func testADroppedMixedSetIsSortedByTitleID() throws {+ let base = try file("Game [0100000000010000][v0].nsp", size: 64)+ let repack = try file("Game [0100000000010000].nsz", size: 32)+ let old = try file("Game [0100000000010800][v65536].nsp")+ let new = try file("Game [0100000000010800][v131072].nsz")+ let dlc1 = try file("Game DLC [0100000000011001].nsp"), dlc2 = try file("Game DLC [0100000000011002].xci")+ let keys = try file("prod.keys")+ let unfinished = try file("Game [0100000000010000].xci", size: 0)+ let unnamed = try file("game.nsp"), text = try file("readme.txt")+ let found = BuildModel.classify([dlc2, text, old, repack, unfinished, base, keys, new, unnamed, dlc1])+ XCTAssertEqual(found, BuildModel.FoundInputs(base: base, update: new, dlc: [dlc1, dlc2], keys: keys),+ "the largest base, the newest update, every add-on sorted, the keys")+ XCTAssertEqual(BuildModel.classify([text, unnamed]), BuildModel.FoundInputs())+ XCTAssertFalse(BuildModel.FoundInputs(keys: keys).anyGame)+ }++ func testDroppedFilesJoinWhatIsAlreadyChosen() throws {+ let m = BuildModel()+ let base = try file("Game [0100000000010000].nsp", in: "base")+ let dlc1 = try file("Game DLC [0100000000011001].nsp", in: "dlc")+ m.take(dropped: [base, dlc1])+ XCTAssertEqual(m.basePath, base)+ XCTAssertEqual(m.gameDir, (base as NSString).deletingLastPathComponent)+ let update = try file("Game [0100000000010800][v65536].nsp", in: "update")+ let dlc2 = try file("Game DLC [0100000000011002].nsp", in: "dlc")+ let keys = try file("prod.keys", in: "keys")+ m.take(dropped: [update, dlc2, keys])+ XCTAssertEqual(m.basePath, base, "a drop without a base game keeps the chosen one")+ XCTAssertEqual(m.updatePath, update)+ XCTAssertEqual(m.dlcPaths, [dlc1, dlc2], "add-on content is added to")+ XCTAssertEqual(m.keysPath, keys)+ XCTAssertEqual(m.gameDir, (base as NSString).deletingLastPathComponent)++ // nothing usable: the slots stay; a note only on an empty base row+ m.take(dropped: [try file("cover.jpg")])+ XCTAssertEqual(m.basePath, base)+ XCTAssertEqual(m.slot("base").problem, "")+ let empty = BuildModel()+ empty.take(dropped: [try file("notes.txt")])+ XCTAssertEqual(empty.slot("base").problem, "data.noNsp")+ }++ func testOneDroppedFolderIsTheSameAsChoosingIt() throws {+ let base = try file("Game [0100000000010000].nsp", in: "Game/Base")+ let update = try file("Game [0100000000010800][v65536].nsp", in: "Game/Update")+ let keys = try file("prod.keys", in: "Game")+ try file("Game [0100000000010800][v999999].nsp", in: "Game/0100000000010000_build") // the pipeline's own folder is pruned+ let folder = temporary.appendingPathComponent("Game").path+ let m = BuildModel()+ m.take(dropped: [folder])+ XCTAssertEqual(m.gameDir, folder)+ XCTAssertEqual(m.basePath, base)+ XCTAssertEqual(m.updatePath, update)+ XCTAssertEqual(m.keysPath, keys)++ // a folder with a file beside it: the folder's files and the file, added to what is chosen+ let other = BuildModel()+ let dlc = try file("Game DLC [0100000000011001].nsp", in: "elsewhere")+ other.take(dropped: [folder, dlc])+ XCTAssertEqual(other.basePath, base)+ XCTAssertEqual(other.dlcPaths, [dlc])+ XCTAssertEqual(other.gameDir, (base as NSString).deletingLastPathComponent)+ }++ // MARK: Visual QA (matched by --filter testRenderLauncherForVisualQA)++ @MainActor func testRenderLauncherForVisualQADropHighlight() throws {+ guard let directory = ProcessInfo.processInfo.environment["NX_LAUNCHER_CAPTURE_DIR"] else { throw XCTSkip("Set NX_LAUNCHER_CAPTURE_DIR to capture native views") }+ let output = URL(fileURLWithPath: directory)+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)+ NSApplication.shared.setActivationPolicy(.accessory)+ let oldOutput = UserDefaults.standard.object(forKey: "buildOutputDirectory")+ defer { UserDefaults.standard.set(oldOutput, forKey: "buildOutputDirectory") }+ let model = BuildModel()+ model.lang = .en+ model.outDir = temporary.path+ model.depsChecked = true+ model.deps = [BuildModel.Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]+ let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))+ // the page as a drag shows it: the highlight drawn over the Builds page+ let page = BuilderView(m: model, library: library).environmentObject(PadFocus())+ .modifier(GameFilesDrop(enabled: true, label: model.t("drop.hint"), targeted: true) { _ in })+ .frame(width: 1100, height: 760).background(LauncherPalette.background).environment(\.colorScheme, .dark)+ let host = NSHostingView(rootView: page)+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 760), styleMask: [.titled], backing: .buffered, defer: false)+ window.contentView = host+ window.orderFront(nil)+ RunLoop.main.run(until: Date().addingTimeInterval(0.5))+ let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))+ host.cacheDisplay(in: host.bounds, to: rep)+ try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent("build-drop.png"))+ window.orderOut(nil)+ }+}