Skip to content

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

Mac launcher: export the shared app as an IPA and send the game data (#416)

v0lumehi8a71b119407e
diff --git a/frontend/Sources/NX2Apple/SaveDiscovery.swift b/frontend/Sources/NX2Apple/SaveDiscovery.swift
index c82cbe4f..5bda764c 100644
--- a/frontend/Sources/NX2Apple/SaveDiscovery.swift
+++ b/frontend/Sources/NX2Apple/SaveDiscovery.swift
@@ -2,29 +2,14 @@ import Foundation
import NXCore
import NXLauncher
-/// An app installed on a device, as `devicectl device info apps` lists it.
-struct InstalledApp: Equatable {
- let bundle: String
- let name: String
-}
-
/// Finding the game on the device itself, so the Saves sheet needs neither the launcher's install record nor the signed app
/// it cached (#250): a game exported as an IPA and signed by another tool (LCSign, Sideloadly, AltStore) has a data container
/// the Mac can read all the same, under whatever bundle ID that tool gave it.
enum SaveDiscovery {
- static func listCommand(device: String, json: String) -> [String] {
- ["device", "info", "apps", "--device", device, "--include-default-apps", "--include-removable-apps", "--json-output", json]
- }
+ static func listCommand(device: String, json: String) -> [String] { InstalledApps.listArguments(device: device, json: json) }
- /// `result.apps` of the listing. nil for JSON that cannot be read.
- static func parseApps(_ data: Data) -> [InstalledApp]? {
- guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
- let result = root["result"] as? [String: Any], let list = result["apps"] as? [[String: Any]] else { return nil }
- return list.compactMap { app in
- guard let bundle = app["bundleIdentifier"] as? String, !bundle.isEmpty else { return nil }
- return InstalledApp(bundle: bundle, name: app["name"] as? String ?? "")
- }
- }
+ /// `result.apps` of the listing (NXCore, shared with the shared app's data send). nil for JSON that cannot be read.
+ static func parseApps(_ data: Data) -> [InstalledApp]? { InstalledApps.parse(data) }
/// The apps on the device. A failure is the device's (not connected, locked, timed out), never "no apps".
static func apps(device: String, devicectl: DeviceControl, scratch: URL = FileManager.default.temporaryDirectory) throws -> [InstalledApp] {
diff --git a/frontend/Sources/NXCore/DeviceApps.swift b/frontend/Sources/NXCore/DeviceApps.swift
new file mode 100644
index 00000000..d255bfb2
--- /dev/null
+++ b/frontend/Sources/NXCore/DeviceApps.swift
@@ -0,0 +1,53 @@
+import Foundation
+
+/// An app installed on a device, as `devicectl device info apps` lists it.
+package struct InstalledApp: Equatable {
+ package let bundle: String
+ package let name: String
+
+ package init(bundle: String, name: String) { self.bundle = bundle; self.name = name }
+}
+
+/// The apps of a device (the Saves sheet's discovery and the shared app's data send both read them).
+package enum InstalledApps {
+ /// The arguments after `devicectl` (the Saves sheet's `DeviceControl` adds the tool).
+ package static func listArguments(device: String, json: String) -> [String] {
+ ["device", "info", "apps", "--device", device, "--include-default-apps", "--include-removable-apps", "--json-output", json]
+ }
+
+ /// `result.apps` of the listing. nil for JSON that cannot be read.
+ package static func parse(_ data: Data) -> [InstalledApp]? {
+ guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let result = root["result"] as? [String: Any], let list = result["apps"] as? [[String: Any]] else { return nil }
+ return list.compactMap { app in
+ guard let bundle = app["bundleIdentifier"] as? String, !bundle.isEmpty else { return nil }
+ return InstalledApp(bundle: bundle, name: app["name"] as? String ?? "")
+ }
+ }
+}
+
+extension ShellInstall {
+ /// The shared app's bundle ID. A sideloading tool may append a team ID or put a prefix before it.
+ package static let shellBundlePrefix = ShellLibrary.defaultBundleID
+
+ /// The copies of the shared app among a device's apps, by bundle ID so the order does not change between looks.
+ package static func shellApps(in apps: [InstalledApp]) -> [InstalledApp] {
+ apps.filter { $0.bundle.hasPrefix(shellBundlePrefix) }.sorted { $0.bundle < $1.bundle }
+ }
+
+ /// Why the game data could not be put into the app.
+ package enum DataFailure: Equatable {
+ /// The device has no app with this bundle ID.
+ case appNotFound
+ /// devicectl refused: an app not signed for development (get-task-allow), no permission, or anything else it says.
+ case refused
+ }
+
+ /// What a devicectl copy error means. Only a missing app is told apart. Everything else is a refusal, shown with devicectl's words.
+ package static func dataFailure(copyError text: String) -> DataFailure {
+ let lower = text.lowercased()
+ let missing = ["not installed", "no such app", "unknown app", "could not find the app", "couldn't find the app", "application not found",
+ "app not found", "no app with"]
+ return missing.contains { lower.contains($0) } ? .appNotFound : .refused
+ }
+}
diff --git a/frontend/Sources/NXCore/DriveCopy.swift b/frontend/Sources/NXCore/DriveCopy.swift
new file mode 100644
index 00000000..f36c00ea
--- /dev/null
+++ b/frontend/Sources/NXCore/DriveCopy.swift
@@ -0,0 +1,109 @@
+import Foundation
+
+/// The game data onto a drive or a folder of this Mac (LNPANDY/NX2Apple#416), for the iPhone's "Game data" folder. A plain file copy: no
+/// device and no signing. The shell finds a game's data in `<chosen folder>/<title ID>/` by name (GameCatalogue.swift, `DataLocator`:
+/// `holder(of: titleFolder)` accepts a `romfs.img` of the size the game's manifest names), and by scanning up to two levels for the
+/// image's identity, which the shell derives from the image itself (RomfsIdentity.swift). So `romfs.img` and the `aoc/` images the
+/// install copies go to `<folder>/<title ID>/`, the same files and relative paths as `Documents/games/<title ID>/`, and no sidecar file
+/// carries the identity.
+package enum DriveCopy {
+ /// What a drive says about itself.
+ package struct Volume: Equatable {
+ package var freeBytes: Int64
+ package var fileSystem: String // statfs's name: "apfs", "exfat", "msdos" (FAT32), "hfs", "ntfs"
+ package var readOnly: Bool
+
+ package init(freeBytes: Int64, fileSystem: String, readOnly: Bool) {
+ self.freeBytes = freeBytes; self.fileSystem = fileSystem; self.readOnly = readOnly
+ }
+ }
+
+ /// Why the copy stops before it starts.
+ package enum Problem: Equatable {
+ case readOnly
+ /// A FAT32 volume holds no file over 4 GB (4 GiB minus one byte). `largest` is the biggest file of the game's data.
+ case fat32(largest: Int64)
+ case noSpace(needed: Int64, free: Int64)
+ }
+
+ package static let fat32FileLimit: Int64 = 4_294_967_295
+
+ /// The name a player knows the file system by.
+ package static func fileSystemName(_ statfsName: String) -> String {
+ switch statfsName.lowercased() {
+ case "msdos": return "FAT32"
+ case "exfat": return "exFAT"
+ case "apfs": return "APFS"
+ case "hfs": return "Mac OS Extended"
+ case "ntfs": return "NTFS"
+ default: return statfsName.uppercased()
+ }
+ }
+
+ /// The volume that holds `path` (or the nearest folder above it that exists, for a folder the copy makes). nil when nothing answers.
+ package static func volume(at path: String, fm: FileManager = .default) -> Volume? {
+ var probe = path
+ while !fm.fileExists(atPath: probe), probe != "/", !probe.isEmpty { probe = (probe as NSString).deletingLastPathComponent }
+ var info = statfs()
+ guard statfs(probe, &info) == 0 else { return nil }
+ let name = withUnsafePointer(to: &info.f_fstypename) { $0.withMemoryRebound(to: CChar.self, capacity: Int(MFSTYPENAMELEN)) { String(cString: $0) } }
+ return Volume(freeBytes: Int64(info.f_bavail) * Int64(info.f_bsize), fileSystem: name, readOnly: info.f_flags & UInt32(MNT_RDONLY) != 0)
+ }
+
+ /// What stops the copy of `files` (relative path to size) onto `volume`, nil when it can go ahead. `have` is what the folder holds
+ /// already at the same size, which needs no room again. The order is the order a player can fix: read-only, then the file system,
+ /// then the space.
+ package static func problem(files: [String: Int64], have: [String: Int64] = [:], volume: Volume) -> Problem? {
+ if volume.readOnly { return .readOnly }
+ let largest = files.values.max() ?? 0
+ if fileSystemName(volume.fileSystem) == "FAT32", largest > fat32FileLimit { return .fat32(largest: largest) }
+ let needed = bytesToCopy(files: files, have: have)
+ return needed > volume.freeBytes ? .noSpace(needed: needed, free: volume.freeBytes) : nil
+ }
+
+ /// The bytes that still have to go over: files the target lacks or holds at another size.
+ package static func bytesToCopy(files: [String: Int64], have: [String: Int64]) -> Int64 {
+ files.reduce(Int64(0)) { $0 + (have[$1.key] == $1.value ? 0 : $1.value) }
+ }
+
+ /// `<chosen folder>/<title ID>`
+ package static func destination(folder: String, titleID: String) -> String { folder + "/" + titleID }
+
+ package enum CopyError: Error, Equatable { case cancelled }
+
+ /// Copies `files` (paths relative to `archive`) into `destination`. A file already there at the same size is left alone, so a
+ /// second run finishes a first that stopped. Each file is written under a temporary name and renamed when whole, so a drive pulled
+ /// out midway never leaves a cut-off `romfs.img` that looks complete. `progress` gets the bytes done and the total to copy.
+ package static func copy(archive: String, files: [String: Int64], to destination: String, chunk: Int = 8 << 20,
+ progress: (Int64, Int64) -> Void, cancelled: () -> Bool = { false }) throws {
+ let fm = FileManager.default
+ let have = ShellInstall.localFiles(in: destination)
+ let pending = files.filter { have[$0.key] != $0.value }.keys.sorted()
+ let total = pending.reduce(Int64(0)) { $0 + (files[$1] ?? 0) }
+ var done: Int64 = 0
+ progress(0, total)
+ for relative in pending {
+ if cancelled() { throw CopyError.cancelled }
+ let target = destination + "/" + relative, partial = target + ".partial"
+ try fm.createDirectory(atPath: (target as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
+ try? fm.removeItem(atPath: partial)
+ guard fm.createFile(atPath: partial, contents: nil) else {
+ throw CocoaError(.fileWriteUnknown, userInfo: [NSFilePathErrorKey: partial])
+ }
+ let input = try FileHandle(forReadingFrom: URL(fileURLWithPath: archive + "/" + relative))
+ let output = try FileHandle(forWritingTo: URL(fileURLWithPath: partial))
+ defer { try? input.close(); try? output.close() }
+ while true {
+ if cancelled() { try? fm.removeItem(atPath: partial); throw CopyError.cancelled }
+ guard let data = try input.read(upToCount: chunk), !data.isEmpty else { break }
+ try output.write(contentsOf: data)
+ done += Int64(data.count)
+ progress(done, total)
+ }
+ try output.close()
+ try? fm.removeItem(atPath: target)
+ try fm.moveItem(atPath: partial, toPath: target)
+ }
+ progress(total, total)
+ }
+}
diff --git a/frontend/Sources/NXCore/ShellExport.swift b/frontend/Sources/NXCore/ShellExport.swift
new file mode 100644
index 00000000..4e262670
--- /dev/null
+++ b/frontend/Sources/NXCore/ShellExport.swift
@@ -0,0 +1,195 @@
+import Foundation
+
+// The shared app as an unsigned IPA (LNPANDY/NX2Apple#416): no device and no signing team. The same project as the install
+// (build_shell.sh --prepare-xcode), built by xcodebuild with signing off, the executable signed ad-hoc to carry its entitlements
+// (as build_ipa.sh does for the one-game IPA), then zipped as Payload/<app>.app. A sideloading tool signs the result. The game data
+// stays out: the player copies romfs.img into the app's Documents/games/<title ID>/ after installing it.
+
+extension ShellInstall {
+ /// The IPA's file name.
+ package static let ipaName = "NX2Apple.ipa"
+
+ /// Everything the export writes lives in this folder of the shell root, apart from the project.
+ package static func exportFolder(root: String) -> String { root + "/export" }
+ package static func ipaPath(root: String) -> String { exportFolder(root: root) + "/" + ipaName }
+ /// Its own derived data: the unsigned build must not replace the signed app that an install, a reinstall and a re-sign use.
+ package static func exportDerivedData(root: String) -> String { exportFolder(root: root) + "/derived-data" }
+ package static func exportAppPath(root: String) -> String { exportDerivedData(root: root) + "/Build/Products/Release-iphoneos/" + appName }
+ /// The folder the app is copied into as `Payload/<app>.app` before it is zipped.
+ package static func exportStage(root: String) -> String { exportFolder(root: root) + "/stage" }
+
+ /// The shell project (prepared by the install's own script call) built for iOS with signing off, as build_shell.sh --build does.
+ /// `bundleID` is the one shell.json holds, so the IPA keeps the identifier of the install.
+ package static func exportBuildCommand(xcrun: String, root: String, bundleID: String) -> [String] {
+ [xcrun, "xcodebuild", "-project", projectFolder(root: root) + "/" + projectName, "-scheme", scheme,
+ "-configuration", "Release", "-destination", "generic/platform=iOS", "-derivedDataPath", exportDerivedData(root: root),
+ "PRODUCT_BUNDLE_IDENTIFIER=\(bundleID)", "CODE_SIGNING_ALLOWED=NO", "CODE_SIGNING_REQUIRED=NO", "CODE_SIGN_IDENTITY=", "build"]
+ }
+
+ /// The entitlements file `build_shell.sh --prepare-xcode` writes into the project (the Increased Memory Limit request).
+ package static func entitlementsPath(root: String) -> String { projectFolder(root: root) + "/Gen/DmShell.entitlements" }
+
+ /// An unsigned app has no signature to carry the entitlements, so a sideloader would lose the request. The executable gets an
+ /// ad-hoc signature that holds them, which the sideloader replaces and keeps the entitlements of (build_ipa.sh does the same).
+ package static func entitlementsCommand(app: String, entitlements: String) -> [String] {
+ ["/usr/bin/codesign", "--force", "--sign", "-", "--entitlements", entitlements, app + "/" + scheme]
+ }
+
+ /// codesign refuses a file with a resource fork or Finder information.
+ package static func cleanAttributesCommand(app: String) -> [String] { ["/usr/bin/xattr", "-cr", app + "/" + scheme] }
+
+ /// The IPA: the stage folder holds `Payload/<app>.app`, and ditto writes it with Payload as the root (see `BuildCommands.ipaCommand`).
+ package static func zipCommand(root: String) -> [String] {
+ BuildCommands.ipaCommand(payload: exportStage(root: root) + "/Payload", ipa: ipaPath(root: root))
+ }
+}
+
+extension ShellInstaller {
+ package static let exportBuildStageID = 1012, exportPackStageID = 1013
+
+ /// Steps 3 and 4 of the install, which the export shares: the library with this game, and the shell's project.
+ /// Exactly one of `failure` and (`library`, `env`) is set.
+ func prepareShell(framework: String, titleID: String, name: String)
+ -> (library: ShellLibrary?, env: [String: String]?, failure: Outcome?) {
+ // 3: the library
+ var library = ShellLibrary.load(root: root)
+ if !team.isEmpty { library.team = team } // the export has no team: keep the one an install stored
+ library.add(.init(titleID: titleID, name: name, framework: framework))
+ mirrorFrameworks(&library)
+ library.dropMissing()
+ // The 16:9 banner of the shell's library for every game in it (ShellHost reads <framework>/banner.<ext>, the square
+ // icon.png is the fallback): a game rebuilt since its last install gets its banner back too
+ for game in library.games {
+ let picked = game.titleID == titleID ? pickedArtwork : nil
+ if let banner = ShellInstall.placeBanner(titleID: game.titleID, framework: game.framework, banners: banners, picked: picked) {
+ log("banner: \(game.titleID) \(banner)\n")
+ }
+ }
+ do { try library.save(root: root) } catch {
+ return (nil, nil, Outcome(ok: false, message: fmt("shell.projectFailed", error.localizedDescription)))
+ }
+
+ // 4: the project
+ guard let package = ShellInstall.shellPackage(resources: resources, repo: repo) else {
+ let looked = ([resources, repo].compactMap { $0 }.filter { !$0.isEmpty }).map { $0 + "/frontend-ios" }.joined(separator: ", ")
+ return (nil, nil, Outcome(ok: false, message: fmt("shell.projectFailed", "no frontend-ios Swift package (Package.swift) in " + looked)))
+ }
+ var env = ShellInstall.projectEnvironment(root: root, frameworks: library.games.map(\.framework), bundleID: library.bundleID,
+ team: team, python: python, path: toolPath, home: NSHomeDirectory(), user: NSUserName(),
+ tmp: NSTemporaryDirectory(), package: package)
+ env.merge(BundledTools.environment(for: python)) { $1 }
+ let projectName = t("shell.projectStage")
+ begin(Self.projectStageID, projectName)
+ let project = run(ShellInstall.projectCommand(repo: repo), env: env, label: projectName, step: { _ in nil })
+ if project.status != 0 {
+ let why = ShellInstall.scriptFailure(project.output) ?? fmt("msg.exitCode", project.status)
+ end(Self.projectStageID, projectName, ok: false, detail: why)
+ return (nil, nil, Outcome(ok: false, message: fmt("shell.projectFailed", why)))
+ }
+ end(Self.projectStageID, projectName, ok: true)
+ return (library, env, nil)
+ }
+
+ /// The export: the library and the project, the unsigned build, the entitlements, the IPA. Needs no device and no team.
+ package func export(framework: String, titleID: String, name: String) -> Outcome {
+ let fm = FileManager.default
+ guard fm.fileExists(atPath: framework) else { return Outcome(ok: false, message: fmt("shell.noFramework", framework)) }
+ let prepared = prepareShell(framework: framework, titleID: titleID, name: name)
+ guard let library = prepared.library else { return prepared.failure! }
+
+ // The unsigned build, in the export's own derived data
+ let buildName = t("shell.exportBuildStage")
+ begin(Self.exportBuildStageID, buildName)
+ let built = run(ShellInstall.exportBuildCommand(xcrun: xcrun, root: root, bundleID: library.bundleID), env: nil, label: buildName,
+ step: BuildProgress.xcodeStep)
+ if built.status != 0 {
+ let why = built.lastError ?? fmt("msg.exitCode", built.status)
+ end(Self.exportBuildStageID, buildName, ok: false, detail: why)
+ return Outcome(ok: false, message: fmt("shell.exportFailed", why))
+ }
+ let app = ShellInstall.exportAppPath(root: root)
+ guard fm.fileExists(atPath: app) else {
+ end(Self.exportBuildStageID, buildName, ok: false, detail: app)
+ return Outcome(ok: false, message: fmt("dev.noProject", app))
+ }
+ // The Increased Memory Limit request rides in an ad-hoc signature of the executable. Without it the IPA still installs, and a
+ // game that needs the memory may run out of it, so a failure here is logged and does not stop the export.
+ let entitlements = ShellInstall.entitlementsPath(root: root)
+ if fm.fileExists(atPath: entitlements) {
+ _ = run(ShellInstall.cleanAttributesCommand(app: app), env: nil, label: buildName, step: { _ in nil })
+ let signed = run(ShellInstall.entitlementsCommand(app: app, entitlements: entitlements), env: nil, label: buildName, step: { _ in nil })
+ if signed.status != 0 { log("export: the entitlements could not be added to the app (a large game may run out of memory): \(signed.output)\n") }
+ } else {
+ log("export: no entitlements file at \(entitlements), the app asks for no Increased Memory Limit\n")
+ }
+ end(Self.exportBuildStageID, buildName, ok: true)
+
+ // The IPA: Payload/<app>.app in a stage folder, zipped
+ let packName = t("shell.exportPackStage")
+ begin(Self.exportPackStageID, packName)
+ let stage = ShellInstall.exportStage(root: root), ipa = ShellInstall.ipaPath(root: root)
+ do {
+ try? fm.removeItem(atPath: stage)
+ try? fm.removeItem(atPath: ipa)
+ try fm.createDirectory(atPath: stage + "/Payload", withIntermediateDirectories: true)
+ try fm.copyItem(atPath: app, toPath: stage + "/Payload/" + ShellInstall.appName)
+ } catch {
+ try? fm.removeItem(atPath: stage)
+ end(Self.exportPackStageID, packName, ok: false, detail: error.localizedDescription)
+ return Outcome(ok: false, message: fmt("shell.exportFailed", error.localizedDescription))
+ }
+ let zipped = run(ShellInstall.zipCommand(root: root), env: nil, label: packName, step: { _ in nil })
+ try? fm.removeItem(atPath: stage)
+ guard zipped.status == 0, fm.fileExists(atPath: ipa) else {
+ let why = zipped.lastError ?? fmt("msg.exitCode", zipped.status)
+ end(Self.exportPackStageID, packName, ok: false, detail: why)
+ return Outcome(ok: false, message: fmt("shell.exportFailed", why))
+ }
+ end(Self.exportPackStageID, packName, ok: true)
+ var outcome = Outcome(ok: true, message: fmt("shell.exportDone", ipa), bundleID: library.bundleID)
+ outcome.ipaPath = ipa
+ return outcome
+ }
+
+ /// The game data into the shared app that is installed already and signed by another tool (LNPANDY/NX2Apple#416). The app is found
+ /// on the device by its bundle ID prefix (a sideloading tool may add a team ID): none is `.appNotFound`, several come back in
+ /// `apps` for the player to choose from (`bundleID` then names the one). The copy is the install's own data step (listing, diff,
+ /// free space, the wired-or-Wi-Fi question, the copy). devicectl writes into an app container only for an app signed for development
+ /// (get-task-allow), so its refusal comes back as `.refused` with its own words in `detail`.
+ package func sendData(titleID: String, archive: String, bundleID: String? = nil) -> Outcome {
+ if let refused = pairingRefusal() { return refused }
+ var chosen = bundleID, name = ""
+ if chosen == nil {
+ let json = NSTemporaryDirectory() + "nspb-shell-apps-\(UUID().uuidString.prefix(8)).json"
+ defer { try? FileManager.default.removeItem(atPath: json) }
+ let listed = run([xcrun, "devicectl"] + InstalledApps.listArguments(device: device, json: json), env: nil, label: t("shell.sendStage"), step: { _ in nil })
+ guard listed.status == 0, let apps = InstalledApps.parse(FileManager.default.contents(atPath: json) ?? Data()) else {
+ return Outcome(ok: false, message: listed.lastError ?? fmt("msg.exitCode", listed.status))
+ }
+ let found = ShellInstall.shellApps(in: apps)
+ guard let first = found.first else {
+ var none = Outcome(ok: false, message: t("shell.sendNoApp"))
+ none.dataFailure = .appNotFound
+ return none
+ }
+ if found.count > 1 {
+ var several = Outcome(ok: false, message: t("shell.sendSeveral"))
+ several.apps = found
+ return several
+ }
+ chosen = first.bundle; name = first.name
+ }
+ var outcome = copyGameData(titleID: titleID, archive: archive, app: "", bundleID: chosen!,
+ outcome: Outcome(ok: true, message: "", bundleID: chosen!))
+ outcome.appName = name
+ if outcome.ok, !outcome.copySkipped, outcome.message.isEmpty || outcome.message == fmt("shell.dataAlready", deviceName) {
+ outcome.message = t("shell.sendDone")
+ }
+ if !outcome.ok, outcome.failure == .shellDataIncomplete {
+ outcome.dataFailure = ShellInstall.dataFailure(copyError: outcome.detail)
+ outcome.message = outcome.dataFailure == .appNotFound ? t("shell.sendNoApp") : t("shell.sendRefused")
+ outcome.failure = nil // the install's Retry card does not fit: nothing of the install ran
+ }
+ return outcome
+ }
+}
diff --git a/frontend/Sources/NXCore/ShellInstall.swift b/frontend/Sources/NXCore/ShellInstall.swift
index aacc35a0..5ffc6054 100644
--- a/frontend/Sources/NXCore/ShellInstall.swift
+++ b/frontend/Sources/NXCore/ShellInstall.swift
@@ -142,7 +142,7 @@ package enum ShellInstall {
/// The part of the build script's argument list that makes the game's framework instead of an Xcode project.
package static func buildArguments(workDir: String, team: String) -> [String] {
- ["--shell-framework", workDir + "/shell-framework", "--team-id", team]
+ ["--shell-framework", workDir + "/shell-framework"] + (team.isEmpty ? [] : ["--team-id", team])
}
// ---- 4: the project ----
@@ -262,7 +262,8 @@ package enum ShellInstall {
package static func localFiles(in archive: String) -> [String: Int64] {
let fm = FileManager.default
var found: [String: Int64] = [:]
- for case let path as String in fm.enumerator(atPath: archive) ?? FileManager.DirectoryEnumerator() {
+ guard let enumerator = fm.enumerator(atPath: archive) else { return found } // a folder that is not there holds nothing
+ for case let path as String in enumerator {
if path.split(separator: "/").contains(where: { $0.hasPrefix(".") }) { continue }
var isDirectory: ObjCBool = false
guard fm.fileExists(atPath: archive + "/" + path, isDirectory: &isDirectory), !isDirectory.boolValue,
@@ -370,6 +371,8 @@ package struct ShellInstaller {
/// player cancelled.
package var waiting: (Bool) -> Void = { _ in }
package var waitCancelled: () -> Bool = { false }
+ /// The bytes copied so far and the bytes to copy, told before each file and after it (the data send shows them).
+ package var copyProgress: (Int64, Int64) -> Void = { _, _ in }
/// Seconds between two looks at `devicectl list devices` while waiting for a cable.
package var pollInterval: TimeInterval = 4
/// Where the eShop banners are cached (ArtworkStore), read only: the game's goes into its framework for the shell's library.
@@ -386,6 +389,14 @@ package struct ShellInstaller {
package var message: String
package var step: BuildFailureClassifier.InstallStep? = nil // the failed device step, for the failure card
package var appPath = ""
+ /// The IPA of an export (ShellExport.swift).
+ package var ipaPath = ""
+ /// devicectl's own words for a copy that failed (the data copy of `sendData` shows them).
+ package var detail = ""
+ /// The data send: what the copy meant (`ShellExport.swift`), the copies of the shared app when there are several, the app's name.
+ package var dataFailure: ShellInstall.DataFailure? = nil
+ package var apps: [InstalledApp] = []
+ package var appName = ""
package var bundleID = ""
package var copied = 0
package var copySkipped = false
@@ -402,15 +413,15 @@ package struct ShellInstaller {
package static let projectStageID = 1010, signStageID = 1001, installStageID = 1002, copyStageID = 1003, checkStageID = 1011
- private func t(_ key: String) -> String { L10n.string(key, lang) }
- private func fmt(_ key: String, _ args: CVarArg...) -> String { String(format: t(key), arguments: args) }
+ func t(_ key: String) -> String { L10n.string(key, lang) }
+ func fmt(_ key: String, _ args: CVarArg...) -> String { String(format: t(key), arguments: args) }
- private struct ToolResult { var status: Int32; var output: String; var lastError: String? }
+ struct ToolResult { var status: Int32; var output: String; var lastError: String? }
/// The mirror in the shell folder is the primary copy of a game's framework: shell.json points there. A game whose
/// framework is in its build folder is mirrored now, so a game built before the mirror existed gets one too. A game whose
/// build folder is gone plays from the mirror it already has. A failed mirror is logged and the game keeps its build path.
- private func mirrorFrameworks(_ library: inout ShellLibrary) {
+ func mirrorFrameworks(_ library: inout ShellLibrary) {
let fm = FileManager.default
for i in library.games.indices {
let game = library.games[i]
@@ -436,42 +447,10 @@ package struct ShellInstaller {
}
// A device this Mac never paired is found out now, not after the signing: nothing is built for it
if let refused = pairingRefusal() { return refused }
- // 3: the library
- var library = ShellLibrary.load(root: root)
- library.team = team
- library.add(.init(titleID: titleID, name: name, framework: framework))
- mirrorFrameworks(&library)
- library.dropMissing()
- // The 16:9 banner of the shell's library for every game in it (ShellHost reads <framework>/banner.<ext>, the square
- // icon.png is the fallback): a game rebuilt since its last install gets its banner back too
- for game in library.games {
- let picked = game.titleID == titleID ? pickedArtwork : nil
- if let banner = ShellInstall.placeBanner(titleID: game.titleID, framework: game.framework, banners: banners, picked: picked) {
- log("banner: \(game.titleID) \(banner)\n")
- }
- }
- do { try library.save(root: root) } catch {
- return Outcome(ok: false, message: fmt("shell.projectFailed", error.localizedDescription))
- }
-
- // 4: the project
- guard let package = ShellInstall.shellPackage(resources: resources, repo: repo) else {
- let looked = ([resources, repo].compactMap { $0 }.filter { !$0.isEmpty }).map { $0 + "/frontend-ios" }.joined(separator: ", ")
- return Outcome(ok: false, message: fmt("shell.projectFailed", "no frontend-ios Swift package (Package.swift) in " + looked))
- }
- var env = ShellInstall.projectEnvironment(root: root, frameworks: library.games.map(\.framework), bundleID: library.bundleID,
- team: team, python: python, path: toolPath, home: NSHomeDirectory(), user: NSUserName(),
- tmp: NSTemporaryDirectory(), package: package)
- env.merge(BundledTools.environment(for: python)) { $1 }
+ // 3 and 4: the library and the project
+ let prepared = prepareShell(framework: framework, titleID: titleID, name: name)
+ guard var library = prepared.library, let env = prepared.env else { return prepared.failure! }
let projectName = t("shell.projectStage")
- begin(Self.projectStageID, projectName)
- let project = run(ShellInstall.projectCommand(repo: repo), env: env, label: projectName, step: { _ in nil })
- if project.status != 0 {
- let why = ShellInstall.scriptFailure(project.output) ?? fmt("msg.exitCode", project.status)
- end(Self.projectStageID, projectName, ok: false, detail: why)
- return Outcome(ok: false, message: fmt("shell.projectFailed", why))
- }
- end(Self.projectStageID, projectName, ok: true)
// 5: sign and build, with one retry under this team's own identifier
let signName = fmt("dev.signStage", deviceName)
@@ -541,7 +520,7 @@ package struct ShellInstaller {
}
/// The pairing steps as a failure when this Mac does not know the device, else nil.
- private func pairingRefusal() -> Outcome? {
+ func pairingRefusal() -> Outcome? {
guard connection() == .notPaired else { return nil }
return Outcome(ok: false, message: fmt("shell.notPaired", deviceName), failure: .devicePairing)
}
@@ -550,7 +529,7 @@ package struct ShellInstaller {
ShellInstall.connection(of: device, in: DeviceTools.devices(xcrun: xcrun, timeout: 20, runner: runner))
}
- private func copyGameData(titleID: String, archive: String, app: String, bundleID: String, outcome start: Outcome) -> Outcome {
+ func copyGameData(titleID: String, archive: String, app: String, bundleID: String, outcome start: Outcome) -> Outcome {
var outcome = start
let checkName = fmt("shell.checkStage", deviceName)
begin(Self.checkStageID, checkName)
@@ -602,7 +581,9 @@ package struct ShellInstaller {
}
let copyName = fmt("dev.copyStage", deviceName)
begin(Self.copyStageID, copyName)
+ var copiedBytes: Int64 = 0
for (i, path) in missing.enumerated() {
+ copyProgress(copiedBytes, needed)
stage(ShellStage(id: Self.copyStageID, name: copyName, state: .running, detail: "\(i + 1)/\(missing.count)",
percent: Double(i) / Double(missing.count) * 100))
let r = run(ShellInstall.copyCommand(xcrun: xcrun, device: device, bundleID: bundleID, titleID: titleID,
@@ -613,11 +594,15 @@ package struct ShellInstaller {
end(Self.copyStageID, copyName, ok: false, detail: why)
// The file that failed may be on the device in part. The next listing sees its size is not the local one and copies it
// again, so a Retry finishes the data. Nothing here marks the game as ready.
- return Outcome(ok: false, message: fmt("shell.copyIncomplete", deviceName, why), appPath: app, bundleID: bundleID, copied: i,
- failure: .shellDataIncomplete)
+ var incomplete = Outcome(ok: false, message: fmt("shell.copyIncomplete", deviceName, why), appPath: app, bundleID: bundleID, copied: i,
+ failure: .shellDataIncomplete)
+ incomplete.detail = why
+ return incomplete
}
outcome.copied = i + 1
+ copiedBytes += local[path] ?? 0
}
+ copyProgress(needed, needed)
end(Self.copyStageID, copyName, ok: true)
return outcome
}
@@ -637,14 +622,14 @@ package struct ShellInstaller {
sizeText: fmt("shell.copySize", ShellInstall.sizeText(bytes), files), connectionText: connectionText)
}
- private func begin(_ id: Int, _ name: String) { stage(ShellStage(id: id, name: name, state: .running)) }
- private func end(_ id: Int, _ name: String, ok: Bool, detail: String = "") {
+ func begin(_ id: Int, _ name: String) { stage(ShellStage(id: id, name: name, state: .running)) }
+ func end(_ id: Int, _ name: String, ok: Bool, detail: String = "") {
stage(ShellStage(id: id, name: name, state: ok ? .done : .failed, detail: detail, percent: ok ? 100 : nil))
}
/// One tool, blocking: its output lines go to `log`, the last error line is kept. `env` nil is the plain tool environment of the
/// per-game install (xcodebuild, devicectl).
- private func run(_ command: [String], env: [String: String]?, label: String,
+ func run(_ command: [String], env: [String: String]?, label: String,
step: (String) -> (detail: String, percent: Double?)?) -> ToolResult {
log("[\(label)] \(command.joined(separator: " "))\n")
var output = "", lastError: String?
diff --git a/frontend/Sources/NXLauncher/ExportSteps.swift b/frontend/Sources/NXLauncher/ExportSteps.swift
new file mode 100644
index 00000000..cb124881
--- /dev/null
+++ b/frontend/Sources/NXLauncher/ExportSteps.swift
@@ -0,0 +1,182 @@
+import SwiftUI
+import NXCore
+import NXModel
+
+/// The export of the shared app as an IPA, in three steps (LNPANDY/NX2Apple#416): export it, install it with another tool, send the
+/// game data. Shown by the Install card when its switch says "Export as IPA". Observes the build store (the steps' state) and the
+/// device store (the device and the place the data goes to).
+package struct ExportSteps: View {
+ @ObservedObject var build: BuildStore
+ @ObservedObject var devices: DeviceStore
+ @EnvironmentObject var loc: Localizer
+
+ package init(build: BuildStore, devices: DeviceStore) {
+ self.build = build
+ self.devices = devices
+ }
+
+ private var exported: Bool { !build.exportedIPAPath.isEmpty }
+ private var sentDone: Bool {
+ switch build.send { case .sent, .copied: return true; default: return false }
+ }
+ private var toDrive: Bool { devices.sendWhere == SendWhere.drive }
+ private var gameName: String { ((build.basePath as NSString).lastPathComponent as NSString).deletingPathExtension }
+
+ package var body: some View {
+ VStack(spacing: 0) {
+ step(1, done: exported, title: loc.t("shell.step1Title"),
+ sub: exported ? String(format: loc.t("shell.step1Done"), build.exportedIPAText) : loc.t("shell.step1Sub")) {
+ if exported {
+ Button(loc.t("shell.showInFinder")) { revealInFinder(build.exportedIPAPath) }
+ } else {
+ Button(loc.t("shell.step1Button")) { build.startBuild() }.disabled(!build.canBuild || build.running)
+ }
+ }
+ CardDivider()
+ step(2, done: sentDone, title: loc.t("shell.step2Title"), sub: loc.t("shell.step2Sub")) { EmptyView() }
+ CardDivider()
+ step(3, done: sentDone, title: loc.t("shell.step3Title"), sub: loc.t("shell.step3Sub")) {
+ LauncherSegmented(options: [(SendWhere.device, loc.t("shell.whereDevice")), (SendWhere.drive, loc.t("shell.whereDrive"))],
+ selection: devices.sendWhere) { devices.sendWhere = $0; build.refreshDrive() }
+ }
+ VStack(alignment: .leading, spacing: 10) {
+ if toDrive { driveBody } else { deviceBody }
+ }
+ .padding(.leading, 49).padding(.trailing, 18).padding(.bottom, 16)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .disabled(!exported && !sentDone)
+ .opacity(exported || sentDone ? 1 : 0.5)
+ }
+ }
+
+ // MARK: A step
+
+ private func step<Trailing: View>(_ number: Int, done: Bool, title: String, sub: String, @ViewBuilder trailing: () -> Trailing) -> some View {
+ HStack(spacing: 12) {
+ ZStack {
+ Circle().fill(done ? LauncherPalette.ready : Color.white.opacity(0.10)).frame(width: 25, height: 25)
+ if done { Image(systemName: "checkmark").font(.system(size: 11, weight: .bold)).foregroundStyle(.black) }
+ else { Text("\(number)").font(.manrope(12.5, .semibold)).foregroundStyle(.secondary) }
+ }
+ VStack(alignment: .leading, spacing: 3) {
+ Text(title).font(.manrope(14, .semibold)).fixedSize(horizontal: false, vertical: true)
+ Text(sub).font(.manrope(12.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer(minLength: 12)
+ trailing().launcherRowControls()
+ }
+ .padding(.horizontal, 18).padding(.vertical, 13)
+ .frame(minHeight: 52)
+ }
+
+ // MARK: To the device
+
+ private var connectionText: String {
+ guard let d = devices.devices.first(where: { $0.id == devices.installDevice }) else { return "" }
+ return d.wired ? "USB" : d.overNetwork ? "Wi-Fi" : ""
+ }
+
+ @ViewBuilder private var deviceBody: some View {
+ let options = [(value: "", label: loc.t("dev.none"))] + devices.devices.map { (value: $0.id, label: $0.name) }
+ HStack(spacing: 10) {
+ LauncherDropdown(options: options, selection: devices.installDevice, label: loc.t("dev.target")) { devices.installDevice = $0 }
+ .frame(width: 220)
+ if !connectionText.isEmpty { Text(connectionText).font(.mono(12)).foregroundStyle(.secondary) }
+ Button(loc.t("dev.refresh")) { _ = devices.refresh() }.buttonStyle(.plain).font(.manrope(13)).foregroundStyle(.secondary)
+ Spacer(minLength: 8)
+ Button { build.sendGameData() } label: { Label(loc.t("shell.sendButton"), systemImage: "arrow.up.circle") }
+ .buttonStyle(LauncherSecondaryButtonStyle()).disabled(!build.canSendToDevice).frame(width: LauncherControl.width)
+ }
+ deviceStatus
+ }
+
+ @ViewBuilder private var deviceStatus: some View {
+ switch build.send {
+ case .sending(let done, let total, let note):
+ progress(String(format: loc.t("shell.sendProgress"), gameName, ShellInstall.sizeText(done), ShellInstall.sizeText(total)) +
+ (note.isEmpty ? "" : " " + note), done: done, total: total)
+ case .sent:
+ note(loc.t("shell.sendDone"), LauncherPalette.ready)
+ case .appNotFound:
+ note(loc.t("shell.sendNoApp"), LauncherPalette.building)
+ case .chooseApp(let apps):
+ note(loc.t("shell.sendSeveral"), LauncherPalette.building)
+ ForEach(apps, id: \.bundle) { app in
+ Button(app.name.isEmpty ? app.bundle : app.name + " · " + app.bundle) { build.sendGameData(bundle: app.bundle) }
+ .buttonStyle(LauncherSecondaryButtonStyle())
+ }
+ case .refused(let detail):
+ note(loc.t("shell.sendRefused"), LauncherPalette.building)
+ HStack(spacing: 12) {
+ Button(loc.t("shell.sendShowData")) { build.showGameDataInFinder() }.buttonStyle(LauncherSecondaryButtonStyle())
+ Text(loc.t("shell.sendFinderSteps")).font(.manrope(12.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }
+ DisclosureGroup(loc.t("shell.sendDetails")) {
+ Text(detail).font(.mono(11.5)).foregroundStyle(.secondary).textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }.font(.manrope(12.5))
+ case .failed(let text):
+ note(text, LauncherPalette.building)
+ case .idle, .copying, .copied:
+ EmptyView()
+ }
+ }
+
+ // MARK: To a drive or folder
+
+ @ViewBuilder private var driveBody: some View {
+ HStack(spacing: 10) {
+ Text(devices.driveFolder.isEmpty ? loc.t("shell.driveNone") : build.shortPath(devices.driveFolder))
+ .font(devices.driveFolder.isEmpty ? .manrope(13) : .mono(12)).foregroundStyle(.secondary)
+ .lineLimit(1).truncationMode(.middle)
+ .padding(.horizontal, 12).padding(.vertical, 8)
+ .frame(maxWidth: 300, alignment: .leading)
+ .background(Color.white.opacity(0.05), in: RoundedRectangle(cornerRadius: 9))
+ Button(loc.t("shell.driveChoose")) { build.chooseDriveFolder() }.buttonStyle(LauncherSecondaryButtonStyle())
+ .frame(width: LauncherControl.width)
+ Spacer(minLength: 8)
+ Button(loc.t("shell.driveCopy")) { build.copyToDrive() }
+ .buttonStyle(LauncherSecondaryButtonStyle()).disabled(!build.canCopyToDrive).frame(width: LauncherControl.width)
+ }
+ driveStatus
+ }
+
+ private var gameDataRow: String { L10n.string("ios.ui.gameData", loc.lang) }
+
+ @ViewBuilder private var driveStatus: some View {
+ if case .copying(let done, let total) = build.send {
+ progress(String(format: loc.t("shell.driveProgress"), gameName, ShellInstall.sizeText(done), ShellInstall.sizeText(total)), done: done, total: total)
+ Button(loc.t("btn.stop")) { build.stopDriveCopy() }.buttonStyle(LauncherSecondaryButtonStyle())
+ } else if case .copied(let folder) = build.send {
+ note(String(format: loc.t("shell.driveDone"), build.shortPath((folder as NSString).deletingLastPathComponent), gameDataRow), LauncherPalette.ready)
+ } else if case .failed(let text) = build.send {
+ note(text, LauncherPalette.building)
+ } else if let state = build.drive {
+ switch state.problem {
+ case .fat32: note(loc.t("shell.driveFat32"), .red)
+ case .readOnly: note(loc.t("shell.driveReadOnly"), .red)
+ case .noSpace(let needed, let free):
+ note(String(format: loc.t("shell.driveNoSpace"), ShellInstall.sizeText(needed), ShellInstall.sizeText(free)), .red)
+ case nil:
+ if let volume = state.volume {
+ Text(String(format: loc.t("shell.driveNote"), ShellInstall.sizeText(state.needed), ShellInstall.sizeText(volume.freeBytes),
+ DriveCopy.fileSystemName(volume.fileSystem), gameDataRow))
+ .font(.manrope(12.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ }
+
+ // MARK: Pieces
+
+ private func note(_ text: String, _ color: Color) -> some View {
+ Text(text).font(.manrope(12.5)).foregroundStyle(color).fixedSize(horizontal: false, vertical: true)
+ }
+
+ private func progress(_ text: String, done: Int64, total: Int64) -> some View {
+ VStack(alignment: .leading, spacing: 6) {
+ ProgressView(value: total > 0 ? Double(done) / Double(total) : 0).progressViewStyle(.linear).tint(LauncherPalette.cream)
+ Text(text).font(.manrope(12.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }
+ }
+}
diff --git a/frontend/Sources/NXLauncher/InstallCard.swift b/frontend/Sources/NXLauncher/InstallCard.swift
index 5db3ca53..23714577 100644
--- a/frontend/Sources/NXLauncher/InstallCard.swift
+++ b/frontend/Sources/NXLauncher/InstallCard.swift
@@ -2,8 +2,9 @@ import SwiftUI
import NXCore
import NXModel
-/// Where an iPhone build goes: exported as an IPA (as before), or signed and installed on a paired device. Shown for the iPhone
-/// target only. Observes the device store, and the build store for the target and whether a build runs.
+/// Where an iPhone build goes: signed and installed on a paired device ("Install on device"), or exported as an unsigned IPA for
+/// another tool to sign, with the game data sent afterwards ("Export as IPA", ExportSteps). Shown for the iPhone target only. Observes the
+/// device store, and the build store for the target and whether a build runs.
package struct InstallCard: View {
@ObservedObject var devices: DeviceStore
@ObservedObject var build: BuildStore
@@ -15,7 +16,12 @@ package struct InstallCard: View {
}
package var body: some View {
- if build.target != BuildTarget.mac { card.disabled(build.running) }
+ if build.target != BuildTarget.mac { card.disabled(build.running && !sending) }
+ }
+
+ /// The copy of the game data runs on the build store's `running` flag too, and its own buttons must stay usable (Stop).
+ private var sending: Bool {
+ switch build.send { case .sending, .copying: return true; default: return false }
}
private var card: some View {
@@ -24,19 +30,32 @@ package struct InstallCard: View {
}
let teams = devices.teams.map { (value: $0.id, label: $0.label(personalTeam: loc.t("dev.personalTeam"))) }
let needsCertificate = devices.teams.first { $0.id == devices.signingTeam }.map { !$0.hasCertificate } ?? false
- return CardGroup(loc.t("dev.section"), footnote: devices.installDevice.isEmpty ? "" : (needsCertificate ? loc.t("dev.teamNoCert") + " " : "") + loc.t("dev.note")) {
- CardRow(loc.t("dev.target"), detail: devices.checked && devices.devices.isEmpty ? loc.t("dev.noDevices") : "") {
- if !devices.checked { ProgressView().controlSize(.small) }
- Button(loc.t("dev.refresh")) { _ = devices.refresh() }.buttonStyle(.plain).font(.manrope(13)).foregroundStyle(.secondary)
- LauncherDropdown(options: options, selection: devices.installDevice, label: loc.t("dev.target")) { devices.installDevice = $0 }
+ let footnote = devices.exportIPA ? ""
+ : devices.installDevice.isEmpty ? "" : (needsCertificate ? loc.t("dev.teamNoCert") + " " : "") + loc.t("dev.note")
+ return CardGroup(loc.t("dev.section"), footnote: footnote) {
+ // The two ways, a switch of their own: exporting is never chosen for the player (#416)
+ CardRow(loc.t("shell.modeTitle")) {
+ LauncherSegmented(options: [("install", loc.t("shell.modeInstall")), ("export", loc.t("shell.modeExport"))],
+ selection: devices.exportIPA ? "export" : "install") { devices.exportIPA = $0 == "export" }
+ .frame(width: 330)
}
- if !devices.installDevice.isEmpty {
- CardDivider()
- if teams.isEmpty {
- CardRow(loc.t("dev.team"), detail: loc.t("dev.noTeam"), dot: LauncherPalette.building) { EmptyView() }
- } else {
- CardRow(loc.t("dev.team")) {
- LauncherDropdown(options: teams, selection: devices.signingTeam, label: loc.t("dev.team")) { devices.signingTeam = $0 }
+ CardDivider()
+ if devices.exportIPA {
+ ExportSteps(build: build, devices: devices)
+ } else {
+ CardRow(loc.t("dev.target"), detail: devices.checked && devices.devices.isEmpty ? loc.t("dev.noDevices") : "") {
+ if !devices.checked { ProgressView().controlSize(.small) }
+ Button(loc.t("dev.refresh")) { _ = devices.refresh() }.buttonStyle(.plain).font(.manrope(13)).foregroundStyle(.secondary)
+ LauncherDropdown(options: options, selection: devices.installDevice, label: loc.t("dev.target")) { devices.installDevice = $0 }
+ }
+ if !devices.installDevice.isEmpty {
+ CardDivider()
+ if teams.isEmpty {
+ CardRow(loc.t("dev.team"), detail: loc.t("dev.noTeam"), dot: LauncherPalette.building) { EmptyView() }
+ } else {
+ CardRow(loc.t("dev.team")) {
+ LauncherDropdown(options: teams, selection: devices.signingTeam, label: loc.t("dev.team")) { devices.signingTeam = $0 }
+ }
}
}
}
diff --git a/frontend/Sources/NXModel/BuildStore+Export.swift b/frontend/Sources/NXModel/BuildStore+Export.swift
new file mode 100644
index 00000000..5b5ef35b
--- /dev/null
+++ b/frontend/Sources/NXModel/BuildStore+Export.swift
@@ -0,0 +1,28 @@
+import Foundation
+import Combine
+import NXCore
+
+// The shared app as an unsigned IPA (LNPANDY/NX2Apple#416). The steps are ShellInstaller.export (NXCore, ShellExport.swift): this
+// runs them off the main actor and shows what they leave. No device, no signing team, no game data copy.
+
+extension BuildStore {
+ /// Makes the IPA for a game whose framework is built: the shell's project with the frameworks of the games in its library, built
+ /// unsigned, zipped as Payload/<app>.app. The game's data stays where the archive step put it.
+ package func exportShell(framework: String, titleID: String, name: String) {
+ running = true
+ let installer = makeInstaller()
+ DispatchQueue.global(qos: .userInitiated).async {
+ let result = installer.export(framework: framework, titleID: titleID, name: name)
+ hop {
+ if self.stopping {
+ self.stopping = false; self.running = false
+ self.resetProgress(); self.doneNote = self.t("msg.stopped"); self.cleanupStaging()
+ return
+ }
+ guard result.ok else { self.finishInstall(result.message); return }
+ self.exportedIPAPath = result.ipaPath
+ self.finishInstall(nil, note: result.message)
+ }
+ }
+ }
+}
diff --git a/frontend/Sources/NXModel/BuildStore+Install.swift b/frontend/Sources/NXModel/BuildStore+Install.swift
index 23a47d74..31b2577c 100644
--- a/frontend/Sources/NXModel/BuildStore+Install.swift
+++ b/frontend/Sources/NXModel/BuildStore+Install.swift
@@ -7,15 +7,10 @@ import NXCore
extension BuildStore {
// MARK: Installing on a device
- /// Steps 4 to 7 of the shared app (ShellInstall.swift) for a game whose framework is built and whose archive is packed: the
- /// shell's project, signing, the install over the app that is already there, and the game data the device lacks.
- package func installShell(framework: String, titleID: String, name: String, archive: String, dataOnly: Bool = false) {
- running = true
- if dataOnly { failure = nil; done = false; doneNote = "" }
- shellRetry = (framework, titleID, name, archive)
+ /// The installer with this store's tools, log, stages and process hand-off wired in. The install and the export (BuildStore+Export.swift) share it.
+ func makeInstaller() -> ShellInstaller {
let python = deps.pythonPath.isEmpty ? Toolchain.findPython().path : deps.pythonPath
- let root = shellRoot
- var installer = ShellInstaller(xcrun: devices.xcrun, repo: repo.path, python: python, root: root, device: devices.installDevice, team: devices.signingTeam)
+ var installer = ShellInstaller(xcrun: devices.xcrun, repo: repo.path, python: python, root: shellRoot, device: devices.installDevice, team: devices.signingTeam)
installer.deviceName = devices.deviceName(devices.installDevice)
installer.lang = localizer.lang
installer.ownGroup = true
@@ -38,6 +33,17 @@ extension BuildStore {
installer.decideCopy = { plan in target.askCopy(plan) }
installer.waiting = { on in target.setWaiting(on) }
installer.waitCancelled = { target.waitCancelled }
+ return installer
+ }
+
+ /// Steps 4 to 7 of the shared app (ShellInstall.swift) for a game whose framework is built and whose archive is packed: the
+ /// shell's project, signing, the install over the app that is already there, and the game data the device lacks.
+ package func installShell(framework: String, titleID: String, name: String, archive: String, dataOnly: Bool = false) {
+ running = true
+ if dataOnly { failure = nil; done = false; doneNote = "" }
+ shellRetry = (framework, titleID, name, archive)
+ let installer = makeInstaller()
+ let target = devices
let device = devices.installDevice
DispatchQueue.global(qos: .userInitiated).async {
let result = dataOnly ? installer.installData(titleID: titleID, archive: archive)
diff --git a/frontend/Sources/NXModel/BuildStore+Run.swift b/frontend/Sources/NXModel/BuildStore+Run.swift
index f1f2b9d3..6f6aa8f7 100644
--- a/frontend/Sources/NXModel/BuildStore+Run.swift
+++ b/frontend/Sources/NXModel/BuildStore+Run.swift
@@ -8,7 +8,7 @@ extension BuildStore {
package func startBuild() {
guard !running else { return }
// The shared app needs a device this Mac knows. Found out here, before an hour of building, not after it.
- if target != BuildTarget.mac, !shellDeviceChecked {
+ if target != BuildTarget.mac, !shellDeviceChecked, !exportsShell {
guard installsDirectly else { doneNote = t("shell.needsDevice"); done = false; return }
verifyShellDevice()
return
@@ -19,7 +19,7 @@ extension BuildStore {
running = true; done = false; doneNote = ""; stages = []; log.clear(); chainNoteShown = false
failure = nil; confirmingOverride = nil
let override = takeOverrideFlag() // for this build only: the next one asks again
- installedOn = ""; installedAppPath = ""
+ installedOn = ""; installedAppPath = ""; exportedIPAPath = ""; send = .idle
guard repo.isRepo else {
fail(repo.path.isEmpty ? t("msg.repoInvalidEmpty") : String(format: t("msg.repoInvalid"), shortPath(repo.path)))
return
@@ -149,7 +149,7 @@ extension BuildStore {
args += ["-o", macAppPath]
} else {
// Only the game's framework: the one shared app is made and signed after the script (installShell)
- args += ShellInstall.buildArguments(workDir: workDir, team: devices.signingTeam)
+ args += ShellInstall.buildArguments(workDir: workDir, team: exportsShell ? "" : devices.signingTeam)
}
// The archive step packs whatever folder the build reported; without --work-dir that is the
// script's default, which is the same workDir unless a separate output folder was chosen.
@@ -215,7 +215,8 @@ extension BuildStore {
let name = ((self.basePath as NSString).lastPathComponent as NSString).deletingPathExtension
let fw = ShellInstall.frameworkPath(workDir: self.effectiveWorkDir, titleID: tid)
self.packArchive(workDir: self.effectiveWorkDir) {
- self.installShell(framework: fw, titleID: tid, name: name, archive: $0)
+ if self.exportsShell { self.exportShell(framework: fw, titleID: tid, name: name) }
+ else { self.installShell(framework: fw, titleID: tid, name: name, archive: $0) }
}
}
} else {
diff --git a/frontend/Sources/NXModel/BuildStore+Send.swift b/frontend/Sources/NXModel/BuildStore+Send.swift
new file mode 100644
index 00000000..afc83f6d
--- /dev/null
+++ b/frontend/Sources/NXModel/BuildStore+Send.swift
@@ -0,0 +1,167 @@
+import Foundation
+import Combine
+import NXCore
+
+// Step 3 of the export (LNPANDY/NX2Apple#416): the game data into the shared app on a device (the install's own copy step), or onto a
+// drive or folder of this Mac for the iPhone's Game data folder (DriveCopy). The IPA is signed and installed by another tool.
+
+/// Where step 3 stands. Every failure names the next step only.
+package enum DataSend: Equatable {
+ case idle
+ /// The copy to the device runs: `done` of `total` bytes, and the connection's note (cable or Wi-Fi) once it is known.
+ case sending(done: Int64, total: Int64, note: String)
+ /// The game data is in the app named `app`.
+ case sent(app: String)
+ /// The device lists no copy of the shared app: install the IPA first.
+ case appNotFound
+ /// Several copies of the shared app: the player picks one.
+ case chooseApp([InstalledApp])
+ /// devicectl refused. `detail` is its own text, for a bug report.
+ case refused(detail: String)
+ /// Anything else the copy said (the device is locked, not connected, out of space).
+ case failed(String)
+ /// The copy to the drive runs.
+ case copying(done: Int64, total: Int64)
+ /// The game data is on the drive, in this folder.
+ case copied(folder: String)
+}
+
+/// The chosen drive folder as the card shows it: its volume, the size the game data needs, and what stops the copy.
+package struct DriveState: Equatable {
+ package var volume: DriveCopy.Volume?
+ package var needed: Int64
+ package var problem: DriveCopy.Problem?
+
+ package init(volume: DriveCopy.Volume?, needed: Int64, problem: DriveCopy.Problem?) {
+ self.volume = volume; self.needed = needed; self.problem = problem
+ }
+}
+
+extension BuildStore {
+ /// The title ID of the game whose data the last build packed (the archive folder is named after it).
+ package var packedTitleID: String { archivePath.isEmpty ? "" : (archivePath as NSString).lastPathComponent }
+
+ /// Step 3 can run once a build packed the game's data and the IPA exists, and nothing else runs.
+ package var canSendGameData: Bool { !running && !archivePath.isEmpty && !exportedIPAPath.isEmpty }
+
+ /// The device button needs a device too, the drive button a folder without a problem.
+ package var canSendToDevice: Bool { canSendGameData && !devices.installDevice.isEmpty }
+ package var canCopyToDrive: Bool { canSendGameData && drive != nil && drive?.problem == nil && drive?.volume != nil }
+
+ /// The IPA's file name and size, for step 1.
+ package var exportedIPAText: String {
+ let size = ((try? FileManager.default.attributesOfItem(atPath: exportedIPAPath)[.size]) as? NSNumber)?.int64Value ?? 0
+ return (exportedIPAPath as NSString).lastPathComponent + (size > 0 ? ", " + ShellInstall.sizeText(size) : "")
+ }
+
+ // MARK: To the device
+
+ /// Finds the shared app on the device and copies the game data into it with the install's own data step. `bundle` is the copy
+ /// the player chose when the device has several.
+ package func sendGameData(bundle: String? = nil) {
+ guard canSendToDevice else { return }
+ running = true; done = false; doneNote = ""; failure = nil; stages = []
+ send = .sending(done: 0, total: 0, note: "")
+ var installer = makeInstaller()
+ let target = devices, device = devices.installDevice
+ let titleID = packedTitleID, archive = archivePath
+ // One click: no question. A device that is not connected cannot be copied to, the player is told instead.
+ installer.decideCopy = { [weak self] plan in
+ if plan.connection == .notConnected { return .skip }
+ hop { if case .sending(let done, let total, _) = self?.send { self?.send = .sending(done: done, total: total, note: plan.connectionText) } }
+ return .copy
+ }
+ installer.copyProgress = { [weak self] done, total in
+ hop {
+ guard let self, case .sending(_, _, let note) = self.send else { return }
+ self.send = .sending(done: done, total: total, note: note)
+ }
+ }
+ let ready = installer
+ DispatchQueue.global(qos: .userInitiated).async {
+ let result = ready.sendData(titleID: titleID, archive: archive, bundleID: bundle)
+ hop {
+ target.copyEnded()
+ self.running = false
+ if self.stopping {
+ self.stopping = false
+ self.resetProgress(); self.send = .idle; self.doneNote = self.t("msg.stopped")
+ return
+ }
+ if result.ok && !result.copySkipped {
+ self.send = .sent(app: result.appName.isEmpty ? "" : result.appName)
+ } else if result.copySkipped {
+ self.send = .failed(String(format: self.t("shell.copyNotConnected"), self.devices.deviceName(device)))
+ } else if !result.apps.isEmpty {
+ self.send = .chooseApp(result.apps)
+ } else if result.dataFailure == .appNotFound {
+ self.send = .appNotFound
+ } else if result.dataFailure == .refused {
+ self.send = .refused(detail: result.detail)
+ } else {
+ if let kind = result.failure { self.failure = BuildFailure(kind: kind, gameName: nil) }
+ self.send = .failed(result.message)
+ }
+ }
+ }
+ }
+
+ /// Opens the game's data folder in the Finder, for the way that needs no devicectl.
+ package func showGameDataInFinder() {
+ guard !archivePath.isEmpty else { return }
+ revealFolder(URL(fileURLWithPath: archivePath))
+ }
+
+ // MARK: To a drive or folder
+
+ /// The folder panel, then what the folder's volume says about the game data.
+ package func chooseDriveFolder() {
+ guard let folder = chooseFolder() else { return }
+ devices.driveFolder = folder
+ refreshDrive()
+ }
+
+ /// The volume of the chosen folder against the game data the copy still has to write.
+ package func refreshDrive() {
+ let folder = devices.driveFolder
+ guard !folder.isEmpty, !archivePath.isEmpty else { drive = nil; return }
+ let files = ShellInstall.localFiles(in: archivePath)
+ let have = ShellInstall.localFiles(in: DriveCopy.destination(folder: folder, titleID: packedTitleID))
+ let needed = DriveCopy.bytesToCopy(files: files, have: have)
+ guard let volume = DriveCopy.volume(at: folder) else { drive = DriveState(volume: nil, needed: needed, problem: nil); return }
+ drive = DriveState(volume: volume, needed: needed, problem: DriveCopy.problem(files: files, have: have, volume: volume))
+ }
+
+ /// A plain file copy of the game data into `<folder>/<title ID>/`, with progress.
+ package func copyToDrive() {
+ refreshDrive()
+ guard canCopyToDrive else { return }
+ running = true; done = false; doneNote = ""; failure = nil; stages = []
+ driveCancel.set(false)
+ send = .copying(done: 0, total: drive?.needed ?? 0)
+ let folder = devices.driveFolder, titleID = packedTitleID, archive = archivePath, cancel = driveCancel
+ let files = ShellInstall.localFiles(in: archive)
+ DispatchQueue.global(qos: .userInitiated).async {
+ let destination = DriveCopy.destination(folder: folder, titleID: titleID)
+ var failed: String?
+ do {
+ try DriveCopy.copy(archive: archive, files: files, to: destination,
+ progress: { done, total in hop { if case .copying = self.send { self.send = .copying(done: done, total: total) } } },
+ cancelled: { cancel.value })
+ } catch DriveCopy.CopyError.cancelled { failed = "" }
+ catch { failed = error.localizedDescription }
+ hop {
+ self.running = false
+ if let failed {
+ self.send = failed.isEmpty ? .idle : .failed(String(format: self.t("shell.driveFailed"), failed))
+ } else {
+ self.send = .copied(folder: destination)
+ self.refreshDrive()
+ }
+ }
+ }
+ }
+
+ /// Stop while the copy to the drive runs; the file in progress is dropped, the finished ones stay for the next run.
+ package func stopDriveCopy() { driveCancel.set(true) }
+}
diff --git a/frontend/Sources/NXModel/BuildStore.swift b/frontend/Sources/NXModel/BuildStore.swift
index 1560da75..615bbad3 100644
--- a/frontend/Sources/NXModel/BuildStore.swift
+++ b/frontend/Sources/NXModel/BuildStore.swift
@@ -32,6 +32,10 @@ package struct FilePick: Equatable {
/// The paired devices the last listing found.
var devices: [AppleDevice] { get }
var signingTeam: String { get }
+ /// The build exports the shared app as an IPA instead of installing it.
+ var exportIPA: Bool { get }
+ /// The folder the game data is copied to (a drive), empty when none is chosen.
+ var driveFolder: String { get set }
var xcrun: String { get }
var readTeams: @Sendable () -> [SigningTeam] { get }
func deviceName(_ udid: String) -> String
@@ -128,8 +132,12 @@ func hop(_ body: @escaping @MainActor () -> Void) {
// folder (romfs.img, aoc/) into its Documents, as a sideloaded copy has it. Without a device or a team the build stays an unsigned IPA, as before.
@Published package var installedOn = "" // the device the last build went to (its UDID)
@Published package var installedAppPath = "" // the signed app that went there
+ @Published package var exportedIPAPath = "" // the unsigned IPA of an export (#416)
+ @Published package var send: DataSend = .idle // step 3 of the export: the game data on its way (BuildStore+Send.swift)
+ @Published package var drive: DriveState? // the chosen folder's volume and what stops the copy (BuildStore+Send.swift)
var shellRetry: (framework: String, titleID: String, name: String, archive: String)?
var shellDeviceChecked = false
+ package let driveCancel = LockedFlag() // Stop of the copy to a drive (BuildStore+Send.swift)
// ---- The app's side: AppKit and the wiring, as closures ----
package var chooseKeys: (() -> Void)? // tests stand in for the file picker
@@ -187,6 +195,8 @@ func hop(_ body: @escaping @MainActor () -> Void) {
package func t(_ key: String) -> String { localizer.t(key) }
/// This iPhone build goes straight to a device.
+ /// An iPhone or iPad build that makes the shared app as an unsigned IPA (#416): no device, no team.
+ package var exportsShell: Bool { target != BuildTarget.mac && devices.exportIPA }
package var installsDirectly: Bool { target != BuildTarget.mac && !devices.installDevice.isEmpty && !devices.signingTeam.isEmpty }
/// Home shown as ~ (shorter in a one-line row, and it keeps the account name out of screenshots).
diff --git a/frontend/Sources/NXModel/DeviceStore.swift b/frontend/Sources/NXModel/DeviceStore.swift
index 3edfb222..491a6e95 100644
--- a/frontend/Sources/NXModel/DeviceStore.swift
+++ b/frontend/Sources/NXModel/DeviceStore.swift
@@ -2,6 +2,12 @@ import Foundation
import Combine
import NXCore
+/// The two places step 3 of the export sends the game data to.
+package enum SendWhere {
+ package static let device = "device"
+ package static let drive = "drive"
+}
+
/// The devices (LNPANDY/NX2Apple#387, step 7): the iPhones and iPads paired with this Mac, the teams it can sign for, the device and
/// the team the player chose to install on, and the copy flow of the shared app (the question before the game data goes over, and
/// the wait for a cable). It follows `AppUpdateStore` (`frontend/ARCHITECTURE.md`, "Stores").
@@ -18,6 +24,9 @@ import NXCore
@MainActor package final class DeviceStore: ObservableObject {
nonisolated package static let deviceKey = "installDevice"
nonisolated package static let teamKey = "signingTeam"
+ nonisolated package static let exportKey = "exportIPA"
+ nonisolated package static let sendWhereKey = "sendWhere"
+ nonisolated package static let driveFolderKey = "driveFolder"
@Published package var devices: [AppleDevice] = []
@Published package var teams: [SigningTeam] = []
@@ -31,6 +40,18 @@ import NXCore
@Published package var signingTeam: String {
didSet { defaults.set(signingTeam, forKey: Self.teamKey) }
}
+ /// The build makes the shared app as an unsigned IPA instead of installing it (#416). Needs no device and no team. Saved when it changes.
+ @Published package var exportIPA: Bool {
+ didSet { defaults.set(exportIPA, forKey: Self.exportKey) }
+ }
+ /// Where step 3 of the export sends the game data: `SendWhere.device` or `.drive`. Saved when it changes.
+ @Published package var sendWhere: String {
+ didSet { defaults.set(sendWhere, forKey: Self.sendWhereKey) }
+ }
+ /// The folder (a drive) the game data is copied to. Saved when it changes.
+ @Published package var driveFolder: String {
+ didSet { defaults.set(driveFolder, forKey: Self.driveFolderKey) }
+ }
/// The shared app's copy question: the size and the connection (nil: none is up).
@Published package private(set) var shellCopy: ShellCopyPlan?
/// Waiting for a cable before the game data goes over.
@@ -58,6 +79,9 @@ import NXCore
self.readTeams = readTeams ?? { DeviceTools.teams(runner: runner) }
self.installDevice = defaults.string(forKey: Self.deviceKey) ?? ""
self.signingTeam = defaults.string(forKey: Self.teamKey) ?? ""
+ self.exportIPA = defaults.bool(forKey: Self.exportKey)
+ self.sendWhere = defaults.string(forKey: Self.sendWhereKey) ?? SendWhere.device
+ self.driveFolder = defaults.string(forKey: Self.driveFolderKey) ?? ""
}
/// A device's name for a message, "iPhone" when this Mac has not listed it.
diff --git a/frontend/Tests/NX2AppleTests/ShellExportCaptureTests.swift b/frontend/Tests/NX2AppleTests/ShellExportCaptureTests.swift
new file mode 100644
index 00000000..ede4b2be
--- /dev/null
+++ b/frontend/Tests/NX2AppleTests/ShellExportCaptureTests.swift
@@ -0,0 +1,78 @@
+import XCTest
+import SwiftUI
+import AppKit
+@testable import NX2Apple
+@testable import NXCore
+import NXModel
+@testable import NXLauncher
+
+/// Visual QA of LNPANDY/NX2Apple#416 (matched by --filter testRenderExportStatesForVisualQA).
+final class ShellExportCaptureTests: XCTestCase {
+ /// The Install card in every state of the export, for the pull request's screenshots: ready, exported, sending, done, app not found,
+ /// refused, drive and FAT32. Also the card with the install flow, which the segmented switch changed.
+ @MainActor func testRenderExportStatesForVisualQA() 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)
+ let fm = FileManager.default
+ try fm.createDirectory(at: output, withIntermediateDirectories: true)
+ let lang = ProcessInfo.processInfo.environment["NX_CAPTURE_LANG"].flatMap { Lang.find($0) } ?? .en
+ let saved = ["buildTarget", "installDevice", "exportIPA", "sendWhere", "driveFolder", "shellRoot"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
+ defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
+ let ipa = fm.temporaryDirectory.appendingPathComponent("NX2Apple-capture-\(UUID().uuidString).ipa")
+ fm.createFile(atPath: ipa.path, contents: nil)
+ let handle = try FileHandle(forWritingTo: ipa)
+ try handle.truncate(atOffset: 1_200_000_000) // a sparse file of the size the card shows
+ try handle.close()
+ defer { try? fm.removeItem(at: ipa) }
+
+ let stores = LauncherStores(); let model = stores.build
+ stores.localizer.lang = lang
+ model.target = "ios"
+ model.slots[0].paths = ["/Games/Super Mario Odyssey [0100000000010000].nsp"]
+ stores.deviceStore.devices = [AppleDevice(id: "DEV-1", name: "Zijad’s iPhone", model: "iPhone 17 Pro", os: "27.0", reachable: true, transport: "wired")]
+ stores.deviceStore.checked = true
+ stores.deviceStore.installDevice = "DEV-1"
+ stores.deviceStore.sendWhere = SendWhere.device
+ func shot<V: View>(_ name: String, _ view: V) throws {
+ let framed = view.environmentObject(stores.localizer).padding(24).frame(width: 760).background(Color(white: 0.09)).environment(\.colorScheme, .dark)
+ NSApplication.shared.setActivationPolicy(.accessory)
+ let host = NSHostingView(rootView: framed)
+ host.frame = NSRect(origin: .zero, size: host.fittingSize)
+ let window = OffscreenWindow(size: host.frame.size)
+ window.contentView = host
+ window.orderFront(nil)
+ RunLoop.main.run(until: Date().addingTimeInterval(0.4))
+ host.layoutSubtreeIfNeeded()
+ 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("export-\(name)-\(lang.code).png"))
+ window.orderOut(nil)
+ }
+ func card() -> InstallCard { InstallCard(devices: stores.deviceStore, build: model) }
+
+ stores.deviceStore.exportIPA = false
+ try shot("0-install", card())
+ stores.deviceStore.exportIPA = true
+ try shot("1-ready", card())
+ model.exportedIPAPath = ipa.path
+ model.archivePath = "/Users/me/Games/0100000000010000_build/games/0100000000010000"
+ try shot("2-exported", card())
+ model.send = .sending(done: 3_100_000_000, total: 12_400_000_000,
+ note: L10n.string("shell.copyWired", lang).replacingOccurrences(of: "%@", with: "Zijad’s iPhone"))
+ try shot("3-sending", card())
+ model.send = .sent(app: "NX2Apple")
+ try shot("4-done", card())
+ model.send = .appNotFound
+ try shot("5-app-not-found", card())
+ model.send = .refused(detail: "ERROR: Failed to copy: the app does not allow access to its data container (get-task-allow). (com.apple.dt.CoreDeviceError error 7)")
+ try shot("6-refused", card())
+ model.send = .idle
+ stores.deviceStore.sendWhere = SendWhere.drive
+ stores.deviceStore.driveFolder = "/Volumes/GameDrive/Switch"
+ model.drive = DriveState(volume: DriveCopy.Volume(freeBytes: 412_000_000_000, fileSystem: "exfat", readOnly: false), needed: 12_400_000_000, problem: nil)
+ try shot("7-drive", card())
+ model.drive = DriveState(volume: DriveCopy.Volume(freeBytes: 412_000_000_000, fileSystem: "msdos", readOnly: false), needed: 12_400_000_000,
+ problem: .fat32(largest: 12_000_000_000))
+ try shot("8-fat32", card())
+ }
+}
diff --git a/frontend/Tests/NX2AppleTests/ShellExportTests.swift b/frontend/Tests/NX2AppleTests/ShellExportTests.swift
new file mode 100644
index 00000000..e202f29d
--- /dev/null
+++ b/frontend/Tests/NX2AppleTests/ShellExportTests.swift
@@ -0,0 +1,570 @@
+import XCTest
+import Combine
+@testable import NX2Apple
+@testable import NXCore
+import NXModel
+@testable import NXLauncher
+
+/// LNPANDY/NX2Apple#416: the shared app as an unsigned IPA. The commands are checked as pure functions. The export runs headless
+/// against a stand-in `xcrun` (xcodebuild only: it makes an app folder) and a stand-in build_shell.sh, while ditto, xattr and codesign
+/// are the system's. No test builds a real app, reaches a device or needs a signing team.
+@MainActor final class ShellExportTests: XCTestCase {
+ private var temporary: URL!
+ private let fm = FileManager.default
+ private let titleID = "0100535012974000"
+
+ override func setUpWithError() throws {
+ temporary = fm.temporaryDirectory.appendingPathComponent("nspb-export-" + UUID().uuidString)
+ try fm.createDirectory(at: temporary, withIntermediateDirectories: true)
+ }
+
+ override func tearDownWithError() throws { try fm.removeItem(at: temporary) }
+
+ private func path(_ parts: String...) -> String { parts.reduce(temporary.path) { $0 + "/" + $1 } }
+ private var state: String { path("state") }
+ private func write(_ file: String, _ text: String) throws {
+ try fm.createDirectory(atPath: (file as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
+ try text.write(toFile: file, atomically: true, encoding: .utf8)
+ }
+ private var calls: [String] { ((try? String(contentsOfFile: state + "/calls.txt", encoding: .utf8)) ?? "").split(separator: "\n").map(String.init) }
+
+ // ---- the commands ----
+
+ func testCommandsAreExact() {
+ let root = "/R/NX2Apple-shell"
+ XCTAssertEqual(ShellInstall.ipaPath(root: root), root + "/export/NX2Apple.ipa")
+ XCTAssertEqual(ShellInstall.exportAppPath(root: root), root + "/export/derived-data/Build/Products/Release-iphoneos/DmShell.app")
+ // not the install's derived data: the signed app of an install, a reinstall and a re-sign stays where it is
+ XCTAssertNotEqual(ShellInstall.exportDerivedData(root: root), ShellInstall.derivedData(root: root))
+ let build = ShellInstall.exportBuildCommand(xcrun: "/x", root: root, bundleID: "org.nxnative.shell")
+ XCTAssertEqual(build, ["/x", "xcodebuild", "-project", root + "/project/DmShell.xcodeproj", "-scheme", "DmShell", "-configuration", "Release",
+ "-destination", "generic/platform=iOS", "-derivedDataPath", root + "/export/derived-data",
+ "PRODUCT_BUNDLE_IDENTIFIER=org.nxnative.shell", "CODE_SIGNING_ALLOWED=NO", "CODE_SIGNING_REQUIRED=NO",
+ "CODE_SIGN_IDENTITY=", "build"])
+ // no team, no device, no provisioning
+ XCTAssertFalse(build.contains { $0.hasPrefix("DEVELOPMENT_TEAM") || $0 == "-allowProvisioningUpdates" || $0.hasPrefix("id=") })
+ XCTAssertEqual(ShellInstall.entitlementsPath(root: root), root + "/project/Gen/DmShell.entitlements")
+ XCTAssertEqual(ShellInstall.entitlementsCommand(app: "/a/DmShell.app", entitlements: "/e.plist"),
+ ["/usr/bin/codesign", "--force", "--sign", "-", "--entitlements", "/e.plist", "/a/DmShell.app/DmShell"])
+ XCTAssertEqual(ShellInstall.zipCommand(root: root),
+ ["/usr/bin/ditto", "-c", "-k", "--norsrc", "--keepParent", root + "/export/stage/Payload", root + "/export/NX2Apple.ipa"])
+ }
+
+ func testTheBuildScriptTakesNoTeamForAnExport() {
+ XCTAssertEqual(ShellInstall.buildArguments(workDir: "/W", team: ""), ["--shell-framework", "/W/shell-framework"])
+ XCTAssertEqual(ShellInstall.buildArguments(workDir: "/W", team: "T"), ["--shell-framework", "/W/shell-framework", "--team-id", "T"])
+ }
+
+ // ---- the stand-ins ----
+
+ /// xcodebuild only: it makes the unsigned app (an executable and one embedded framework) in the derived data it is given.
+ private func makeXcrun() throws -> String {
+ try fm.createDirectory(atPath: state, withIntermediateDirectories: true)
+ let xcrun = path("xcrun")
+ try """
+ #!/usr/bin/python3
+ import sys, os, json
+ a = sys.argv[1:]
+ open('\(state)/calls.txt', 'a').write(' '.join(a) + '\\n')
+ def val(flag): return a[a.index(flag) + 1] if flag in a else None
+ if a[0] == 'xcodebuild':
+ if os.path.exists('\(state)/xcode-fails'):
+ print('error: Build input file cannot be found: DmShell.m', flush=True)
+ sys.exit(65)
+ app = val('-derivedDataPath') + '/Build/Products/Release-iphoneos/DmShell.app'
+ os.makedirs(app + '/Frameworks/DmGame\(titleID).framework', exist_ok=True)
+ open(app + '/DmShell', 'w').write('not a real executable')
+ open(app + '/Info.plist', 'w').write('plist')
+ open(app + '/Frameworks/DmGame\(titleID).framework/DmGame\(titleID)', 'w').write('framework')
+ print('Build succeeded', flush=True)
+ elif a[:3] == ['devicectl', 'list', 'devices']:
+ json.dump({'info': {'outcome': 'success'}, 'result': {'devices': [{
+ 'hardwareProperties': {'udid': 'DEV-1', 'reality': 'physical', 'platform': 'iOS', 'marketingName': 'iPhone'},
+ 'deviceProperties': {'name': 'Z', 'osVersionNumber': '27.0'},
+ 'connectionProperties': {'pairingState': 'paired', 'tunnelState': 'connected', 'transportType': 'wired'}}]}}, open(val('--json-output'), 'w'))
+ elif a[:4] == ['devicectl', 'device', 'info', 'files']:
+ json.dump({'error': {'code': 6}, 'info': {'outcome': 'failed'}}, open(val('--json-output'), 'w')) # nothing on the device yet
+ sys.exit(1)
+ elif a[:4] == ['devicectl', 'device', 'copy', 'from']:
+ sys.exit(1) # no shell log
+ elif a[:4] == ['devicectl', 'device', 'copy', 'to']:
+ if os.path.exists('\(state)/refuse'):
+ print('ERROR: Failed to copy: the app does not allow access to its data container (get-task-allow). (com.apple.dt.CoreDeviceError error 7)', flush=True)
+ sys.exit(1)
+ print('Copied', flush=True)
+ elif a[:4] == ['devicectl', 'device', 'info', 'apps']:
+ src = '\(state)/apps.json'
+ if os.path.exists(src): open(val('--json-output'), 'w').write(open(src).read())
+ else: json.dump({'result': {'apps': []}}, open(val('--json-output'), 'w'))
+ else:
+ print('unexpected: ' + ' '.join(a), flush=True)
+ sys.exit(1)
+ """.write(toFile: xcrun, atomically: true, encoding: .utf8)
+ try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: xcrun)
+ return xcrun
+ }
+
+ /// A checkout with a stand-in build_shell.sh: it records its environment and writes the project with its entitlements file.
+ private func makeRepo(entitlements: Bool = true) throws -> String {
+ let repo = path("repo")
+ try write(repo + "/dm/ios/tools/build_shell.sh", """
+ #!/bin/bash
+ [ "$1" = "--prepare-xcode" ] || { echo "FAIL: no --prepare-xcode"; exit 1; }
+ mkdir -p "$SHELL_DIR/DmShell.xcodeproj" "$SHELL_DIR/Gen"
+ env | sort > "\(state)/shell-env.txt"
+ \(entitlements ? "echo '<plist/>' > \"$SHELL_DIR/Gen/DmShell.entitlements\"" : "true")
+ """)
+ try write(repo + "/frontend-ios/Package.swift", "// swift-tools-version: 5.9\n")
+ return repo
+ }
+
+ private struct Fixture { var xcrun: String, repo: String, framework: String, root: String }
+
+ private func makeFixture(entitlements: Bool = true) throws -> Fixture {
+ guard fm.isExecutableFile(atPath: "/usr/bin/python3") else { throw XCTSkip("System Python is required for the process fixture") }
+ let framework = path("work/shell-framework/DmGame\(titleID).framework")
+ try write(framework + "/game.manifest.json", "{}")
+ return Fixture(xcrun: try makeXcrun(), repo: try makeRepo(entitlements: entitlements), framework: framework, root: path("NX2Apple-shell"))
+ }
+
+ /// No device and no team: the installer is made the way the export needs it.
+ private func installer(_ f: Fixture) -> ShellInstaller {
+ var i = ShellInstaller(xcrun: f.xcrun, repo: f.repo, python: "/usr/bin/python3", root: f.root, device: "", team: "")
+ i.resources = nil
+ return i
+ }
+
+ private func entries(ofZip file: String) throws -> [String] {
+ let unzip = Process()
+ unzip.executableURL = URL(fileURLWithPath: "/usr/bin/unzip")
+ unzip.arguments = ["-Z1", file]
+ let pipe = Pipe()
+ unzip.standardOutput = pipe
+ try unzip.run()
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
+ unzip.waitUntilExit()
+ return String(decoding: data, as: UTF8.self).split(separator: "\n").map(String.init)
+ }
+
+ // ---- the export ----
+
+ func testExportMakesAnIPAWithPayloadAndTheFrameworksAndNeedsNoDeviceOrTeam() throws {
+ let f = try makeFixture()
+ let outcome = installer(f).export(framework: f.framework, titleID: titleID, name: "Test Game")
+ XCTAssertTrue(outcome.ok, outcome.message)
+ XCTAssertEqual(outcome.ipaPath, ShellInstall.ipaPath(root: f.root))
+ XCTAssertEqual(outcome.message, String(format: L10n.string("shell.exportDone", .en), outcome.ipaPath))
+ XCTAssertTrue(fm.fileExists(atPath: outcome.ipaPath))
+
+ let names = try entries(ofZip: outcome.ipaPath)
+ XCTAssertTrue(names.contains("Payload/DmShell.app/DmShell"), names.joined(separator: "\n"))
+ XCTAssertTrue(names.contains("Payload/DmShell.app/Frameworks/DmGame\(titleID).framework/DmGame\(titleID)"), names.joined(separator: "\n"))
+ XCTAssertTrue(names.allSatisfy { $0.hasPrefix("Payload/") && !$0.contains("__MACOSX") }, names.joined(separator: "\n"))
+
+ let xcodebuild = try XCTUnwrap(calls.first { $0.hasPrefix("xcodebuild") })
+ XCTAssertTrue(xcodebuild.contains("CODE_SIGNING_ALLOWED=NO") && xcodebuild.contains("-destination generic/platform=iOS"), xcodebuild)
+ XCTAssertFalse(xcodebuild.contains("DEVELOPMENT_TEAM") || xcodebuild.contains("-allowProvisioningUpdates"), xcodebuild)
+ XCTAssertFalse(calls.contains { $0.hasPrefix("devicectl") }, "no device is asked")
+ XCTAssertFalse(fm.fileExists(atPath: ShellInstall.derivedData(root: f.root)), "the install's derived data stays untouched")
+ XCTAssertFalse(fm.fileExists(atPath: ShellInstall.exportStage(root: f.root)), "the stage folder is removed")
+ // the project script gets an empty team (it falls back to its placeholder) and this game's framework
+ let env = try String(contentsOfFile: state + "/shell-env.txt", encoding: .utf8)
+ XCTAssertTrue(env.contains("\nDM_TEAM_ID=\n") || env.hasPrefix("DM_TEAM_ID=\n"), env)
+ XCTAssertTrue(env.contains("DM_SHELL_FRAMEWORKS=" + ShellInstall.mirroredFramework(root: f.root, titleID: titleID)), env)
+ XCTAssertEqual(ShellLibrary.load(root: f.root).games.map(\.titleID), [titleID])
+ }
+
+ func testExportKeepsTheTeamAnEarlierInstallStored() throws {
+ let f = try makeFixture()
+ var library = ShellLibrary()
+ library.team = "TEAM123456"
+ try library.save(root: f.root)
+ XCTAssertTrue(installer(f).export(framework: f.framework, titleID: titleID, name: "Test Game").ok)
+ XCTAssertEqual(ShellLibrary.load(root: f.root).team, "TEAM123456")
+ }
+
+ func testAnExportReplacesTheIPAOfTheLastOne() throws {
+ let f = try makeFixture()
+ try write(ShellInstall.ipaPath(root: f.root), "old")
+ let outcome = installer(f).export(framework: f.framework, titleID: titleID, name: "Test Game")
+ XCTAssertTrue(outcome.ok, outcome.message)
+ XCTAssertFalse(try entries(ofZip: outcome.ipaPath).isEmpty)
+ }
+
+ func testAFailingBuildReachesThePlayerAndLeavesNoIPA() throws {
+ let f = try makeFixture()
+ try write(state + "/xcode-fails", "")
+ let outcome = installer(f).export(framework: f.framework, titleID: titleID, name: "Test Game")
+ XCTAssertFalse(outcome.ok)
+ XCTAssertEqual(outcome.message, String(format: L10n.string("shell.exportFailed", .en), "error: Build input file cannot be found: DmShell.m"))
+ XCTAssertFalse(fm.fileExists(atPath: ShellInstall.ipaPath(root: f.root)))
+ }
+
+ func testAnAppWithoutEntitlementsFileStillExports() throws {
+ let f = try makeFixture(entitlements: false)
+ var logged = ""
+ var i = installer(f)
+ i.log = { logged += $0 }
+ let outcome = i.export(framework: f.framework, titleID: titleID, name: "Test Game")
+ XCTAssertTrue(outcome.ok, outcome.message)
+ XCTAssertTrue(logged.contains("no entitlements file"), logged)
+ }
+
+ func testAMissingFrameworkStopsBeforeAnyTool() throws {
+ let f = try makeFixture()
+ let outcome = installer(f).export(framework: path("nowhere.framework"), titleID: titleID, name: "Test Game")
+ XCTAssertFalse(outcome.ok)
+ XCTAssertTrue(calls.isEmpty)
+ XCTAssertFalse(fm.fileExists(atPath: state + "/shell-env.txt"))
+ }
+
+ // ---- step 3: the game data to the device ----
+
+ private func makeArchive() throws -> String {
+ let archive = path("out/games", titleID)
+ try write(archive + "/romfs.img", "0123456789")
+ try write(archive + "/aoc/1.img", "abcd")
+ return archive
+ }
+
+ /// The apps the stand-in device lists (`devicectl device info apps`).
+ private func listApps(_ apps: [(bundle: String, name: String)]) throws {
+ let list = apps.map { ["bundleIdentifier": $0.bundle, "name": $0.name] }
+ try JSONSerialization.data(withJSONObject: ["info": ["outcome": "success"], "result": ["apps": list]])
+ .write(to: URL(fileURLWithPath: state + "/apps.json"))
+ }
+
+ private func sender(_ f: Fixture) -> ShellInstaller {
+ var i = installer(f)
+ i.device = "DEV-1"
+ i.deviceName = "Z"
+ return i
+ }
+
+ func testTheShellAppIsFoundByItsBundleIDPrefix() {
+ let apps = [InstalledApp(bundle: "com.apple.mobilesafari", name: "Safari"),
+ InstalledApp(bundle: "org.nxnative.shell.ABC123", name: "NX2Apple"),
+ InstalledApp(bundle: "org.nxnative.0100535012974000", name: "Odyssey"),
+ InstalledApp(bundle: "org.nxnative.shell", name: "NX2Apple")]
+ XCTAssertEqual(ShellInstall.shellApps(in: apps).map(\.bundle), ["org.nxnative.shell", "org.nxnative.shell.ABC123"])
+ XCTAssertEqual(ShellInstall.shellApps(in: Array(apps.prefix(1))), [])
+ }
+
+ func testOneAppIsUsedWithoutAskingAndTheCopyGoesIntoItsContainer() throws {
+ let f = try makeFixture()
+ let archive = try makeArchive()
+ try listApps([("com.apple.mobilesafari", "Safari"), ("org.nxnative.shell.ABC123", "NX2Apple")])
+ var progress: [(Int64, Int64)] = []
+ var i = sender(f)
+ i.copyProgress = { progress.append(($0, $1)) }
+ let outcome = i.sendData(titleID: titleID, archive: archive)
+ XCTAssertTrue(outcome.ok, outcome.message)
+ XCTAssertEqual(outcome.message, L10n.string("shell.sendDone", .en))
+ XCTAssertEqual(outcome.appName, "NX2Apple")
+ XCTAssertEqual(outcome.bundleID, "org.nxnative.shell.ABC123")
+ let copies = calls.filter { $0.hasPrefix("devicectl device copy to") }
+ XCTAssertEqual(copies.count, 2)
+ for copy in copies {
+ XCTAssertTrue(copy.contains("--device DEV-1 ") && copy.contains("--domain-type appDataContainer --domain-identifier org.nxnative.shell.ABC123"), copy)
+ XCTAssertTrue(copy.contains("--destination Documents/games/\(titleID)/"), copy)
+ }
+ XCTAssertEqual(progress.last?.0, 14)
+ XCTAssertEqual(progress.last?.1, 14)
+ XCTAssertFalse(calls.contains { $0.hasPrefix("xcodebuild") }, "nothing is built or signed")
+ }
+
+ func testSeveralAppsAreAskedAboutAndNoneSaysToInstallFirst() throws {
+ let f = try makeFixture()
+ let archive = try makeArchive()
+ try listApps([("org.nxnative.shell", "NX2Apple"), ("org.nxnative.shell.ABC123", "NX2Apple")])
+ let several = sender(f).sendData(titleID: titleID, archive: archive)
+ XCTAssertFalse(several.ok)
+ XCTAssertEqual(several.apps.map(\.bundle), ["org.nxnative.shell", "org.nxnative.shell.ABC123"])
+ XCTAssertTrue(calls.filter { $0.hasPrefix("devicectl device copy") }.isEmpty, "nothing is copied before the player chooses")
+ // the chosen one
+ let chosen = sender(f).sendData(titleID: titleID, archive: archive, bundleID: "org.nxnative.shell.ABC123")
+ XCTAssertTrue(chosen.ok, chosen.message)
+ // none
+ try listApps([("com.apple.mobilesafari", "Safari")])
+ let none = sender(f).sendData(titleID: titleID, archive: archive)
+ XCTAssertFalse(none.ok)
+ XCTAssertEqual(none.dataFailure, .appNotFound)
+ XCTAssertEqual(none.message, L10n.string("shell.sendNoApp", .en))
+ }
+
+ func testARefusalKeepsDevicectlsWordsForTheDetails() throws {
+ let f = try makeFixture()
+ let archive = try makeArchive()
+ try listApps([("org.nxnative.shell", "NX2Apple")])
+ try write(state + "/refuse", "")
+ let outcome = sender(f).sendData(titleID: titleID, archive: archive)
+ XCTAssertFalse(outcome.ok)
+ XCTAssertEqual(outcome.dataFailure, .refused)
+ XCTAssertEqual(outcome.message, L10n.string("shell.sendRefused", .en))
+ XCTAssertTrue(outcome.detail.contains("get-task-allow"), outcome.detail)
+ XCTAssertNil(outcome.failure, "the install's Retry card does not fit")
+ }
+
+ /// The failure table: only a missing app is told apart, every other devicectl error is a refusal shown with its own words.
+ func testTheFailureTable() {
+ XCTAssertEqual(ShellInstall.dataFailure(copyError: "ERROR: The application is not installed on the device."), .appNotFound)
+ XCTAssertEqual(ShellInstall.dataFailure(copyError: "ERROR: No such app: org.nxnative.shell"), .appNotFound)
+ XCTAssertEqual(ShellInstall.dataFailure(copyError: "ERROR: Failed to copy: the app does not allow access to its data container (get-task-allow)."), .refused)
+ XCTAssertEqual(ShellInstall.dataFailure(copyError: "ERROR: Operation not permitted (NSPOSIXErrorDomain error 1)"), .refused)
+ XCTAssertEqual(ShellInstall.dataFailure(copyError: ""), .refused)
+ }
+
+ func testTheSendButtonsNeedTheIPAAndTheirPlace() throws {
+ let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
+ defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
+ let stores = LauncherStores(); let model = stores.build
+ stores.deviceStore.installDevice = "DEV-1"
+ model.archivePath = path("out/games", titleID)
+ XCTAssertFalse(model.canSendGameData, "step 3 waits for step 1")
+ model.exportedIPAPath = path("export/NX2Apple.ipa")
+ XCTAssertTrue(model.canSendToDevice)
+ XCTAssertEqual(model.packedTitleID, titleID)
+ stores.deviceStore.installDevice = ""
+ XCTAssertFalse(model.canSendToDevice)
+ XCTAssertFalse(model.canCopyToDrive, "no folder chosen")
+ model.running = true
+ XCTAssertFalse(model.canSendGameData)
+ }
+
+ @MainActor func testTheStoreSendsToTheDeviceItFoundTheAppOn() throws {
+ let f = try makeFixture()
+ let archive = try makeArchive()
+ try listApps([("org.nxnative.shell.ABC123", "NX2Apple")])
+ try write(state + "/devices-ok", "")
+ let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
+ defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
+ UserDefaults.standard.set(f.root, forKey: "shellRoot")
+ let stores = LauncherStores(xcrun: f.xcrun); let model = stores.build
+ stores.repo.path = f.repo
+ stores.dependencies.pythonPath = "/usr/bin/python3"
+ stores.deviceStore.installDevice = "DEV-1"
+ model.target = "ios"
+ model.archivePath = archive
+ model.exportedIPAPath = path("export/NX2Apple.ipa")
+ let sent = expectation(description: "Sent")
+ let token = model.$send.sink { if case .sent = $0 { sent.fulfill() } }
+ model.sendGameData()
+ wait(for: [sent], timeout: 30)
+ withExtendedLifetime(token) {}
+ XCTAssertFalse(model.running)
+ XCTAssertEqual(calls.filter { $0.hasPrefix("devicectl device copy to") }.count, 2)
+ // the app is gone: the next step is named, nothing else
+ try listApps([])
+ let missing = expectation(description: "No app")
+ let again = model.$send.sink { if $0 == .appNotFound { missing.fulfill() } }
+ model.sendGameData()
+ wait(for: [missing], timeout: 30)
+ withExtendedLifetime(again) {}
+ }
+
+ // ---- step 3: the game data to a drive or folder ----
+
+ func testTheDriveGetsTheSameFilesAsTheDeviceUnderTheTitleIDFolder() throws {
+ let archive = try makeArchive()
+ try write(archive + "/.packstamp", "stamp") // a dot file is not game data
+ let folder = path("drive")
+ let destination = DriveCopy.destination(folder: folder, titleID: titleID)
+ XCTAssertEqual(destination, folder + "/" + titleID)
+ var seen: [(Int64, Int64)] = []
+ try DriveCopy.copy(archive: archive, files: ShellInstall.localFiles(in: archive), to: destination, chunk: 3) { seen.append(($0, $1)) }
+ // what the shell scans for: <folder>/<title ID>/romfs.img of the size the image has, and the aoc images beside it
+ XCTAssertEqual(try String(contentsOfFile: destination + "/romfs.img"), "0123456789")
+ XCTAssertEqual(try String(contentsOfFile: destination + "/aoc/1.img"), "abcd")
+ XCTAssertEqual(ShellInstall.localFiles(in: destination), ShellInstall.localFiles(in: archive))
+ XCTAssertFalse(fm.fileExists(atPath: destination + "/.packstamp"))
+ XCTAssertFalse(ShellInstall.localFiles(in: destination).keys.contains { $0.hasSuffix(".partial") })
+ XCTAssertEqual(seen.first?.0, 0)
+ XCTAssertEqual(seen.last?.0, 14)
+ XCTAssertEqual(seen.last?.1, 14)
+ // a second run leaves finished files alone and finishes a cut-off one
+ try "01234".write(toFile: destination + "/romfs.img", atomically: true, encoding: .utf8)
+ var second: [(Int64, Int64)] = []
+ try DriveCopy.copy(archive: archive, files: ShellInstall.localFiles(in: archive), to: destination) { second.append(($0, $1)) }
+ XCTAssertEqual(second.last?.1, 10, "only romfs.img was short")
+ XCTAssertEqual(try String(contentsOfFile: destination + "/romfs.img"), "0123456789")
+ }
+
+ func testTheDriveCopyStopsWhenCancelledAndLeavesNoCutOffImage() throws {
+ let archive = try makeArchive()
+ let destination = path("drive", titleID)
+ var chunks = 0
+ XCTAssertThrowsError(try DriveCopy.copy(archive: archive, files: ShellInstall.localFiles(in: archive), to: destination, chunk: 2,
+ progress: { _, _ in }, cancelled: { chunks += 1; return chunks > 3 })) {
+ XCTAssertEqual($0 as? DriveCopy.CopyError, .cancelled)
+ }
+ XCTAssertFalse(fm.fileExists(atPath: destination + "/romfs.img"))
+ XCTAssertFalse(fm.fileExists(atPath: destination + "/aoc/1.img"))
+ XCTAssertFalse(ShellInstall.localFiles(in: destination).keys.contains { $0.hasSuffix(".partial") })
+ }
+
+ func testTheDriveChecksReadOnlyFAT32AndFreeSpaceWithInjectedValues() {
+ let small = ["romfs.img": Int64(2_000_000_000)]
+ let big = ["romfs.img": Int64(5_000_000_000), "aoc/1.img": 10]
+ let roomy = DriveCopy.Volume(freeBytes: 100_000_000_000, fileSystem: "exfat", readOnly: false)
+ XCTAssertNil(DriveCopy.problem(files: big, volume: roomy))
+ XCTAssertNil(DriveCopy.problem(files: big, volume: DriveCopy.Volume(freeBytes: 100_000_000_000, fileSystem: "apfs", readOnly: false)))
+ XCTAssertEqual(DriveCopy.problem(files: big, volume: DriveCopy.Volume(freeBytes: 100_000_000_000, fileSystem: "msdos", readOnly: false)),
+ .fat32(largest: 5_000_000_000))
+ XCTAssertNil(DriveCopy.problem(files: small, volume: DriveCopy.Volume(freeBytes: 100_000_000_000, fileSystem: "msdos", readOnly: false)),
+ "FAT32 holds files under 4 GB")
+ XCTAssertEqual(DriveCopy.problem(files: small, volume: DriveCopy.Volume(freeBytes: 100, fileSystem: "exfat", readOnly: true)), .readOnly)
+ XCTAssertEqual(DriveCopy.problem(files: big, volume: DriveCopy.Volume(freeBytes: 1_000_000_000, fileSystem: "exfat", readOnly: false)),
+ .noSpace(needed: 5_000_000_010, free: 1_000_000_000))
+ // what the drive holds already needs no room again
+ XCTAssertNil(DriveCopy.problem(files: big, have: big, volume: DriveCopy.Volume(freeBytes: 0, fileSystem: "exfat", readOnly: false)))
+ XCTAssertEqual(DriveCopy.fileSystemName("msdos"), "FAT32")
+ XCTAssertEqual(DriveCopy.fileSystemName("exfat"), "exFAT")
+ XCTAssertEqual(DriveCopy.fileSystemName("apfs"), "APFS")
+ }
+
+ func testTheRealVolumeOfATemporaryFolderAnswers() {
+ let volume = DriveCopy.volume(at: path("not", "made", "yet")) // the nearest folder above it answers
+ XCTAssertNotNil(volume)
+ XCTAssertEqual(volume?.readOnly, false)
+ XCTAssertGreaterThan(volume?.freeBytes ?? 0, 0)
+ }
+
+ @MainActor func testTheStoreCopiesToTheChosenFolderAndRefusesAFAT32Drive() throws {
+ let archive = try makeArchive()
+ let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) } + [(DeviceStore.driveFolderKey, UserDefaults.standard.object(forKey: DeviceStore.driveFolderKey))]
+ defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
+ let stores = LauncherStores(); let model = stores.build
+ model.archivePath = archive
+ model.exportedIPAPath = path("export/NX2Apple.ipa")
+ let folder = path("drive")
+ try fm.createDirectory(atPath: folder, withIntermediateDirectories: true)
+ model.chooseFolder = { folder }
+ model.chooseDriveFolder()
+ XCTAssertEqual(stores.deviceStore.driveFolder, folder)
+ XCTAssertEqual(model.drive?.needed, 14)
+ XCTAssertNil(model.drive?.problem)
+ XCTAssertTrue(model.canCopyToDrive)
+ let copied = expectation(description: "Copied")
+ let token = model.$send.sink { if case .copied = $0 { copied.fulfill() } }
+ model.copyToDrive()
+ wait(for: [copied], timeout: 30)
+ withExtendedLifetime(token) {}
+ XCTAssertEqual(try String(contentsOfFile: folder + "/" + titleID + "/romfs.img"), "0123456789")
+ XCTAssertFalse(model.running)
+ // a FAT32 drive keeps the button inert
+ model.drive = DriveState(volume: DriveCopy.Volume(freeBytes: 1 << 40, fileSystem: "msdos", readOnly: false), needed: 5_000_000_000,
+ problem: .fat32(largest: 5_000_000_000))
+ XCTAssertFalse(model.canCopyToDrive)
+ }
+
+ func testEveryLanguageHasTheExportTexts() {
+ let keys = ["shell.exportBuildStage", "shell.exportDone", "shell.exportFailed", "shell.exportPackStage", "shell.modeTitle", "shell.modeInstall",
+ "shell.modeExport", "shell.step1Title", "shell.step1Sub", "shell.step1Button", "shell.step1Done", "shell.showInFinder", "shell.step2Title",
+ "shell.step2Sub", "shell.step3Title", "shell.step3Sub", "shell.whereDevice", "shell.whereDrive", "shell.sendButton", "shell.sendStage",
+ "shell.sendProgress", "shell.sendDone", "shell.sendNoApp", "shell.sendSeveral", "shell.sendRefused", "shell.sendFinderSteps",
+ "shell.sendShowData", "shell.sendDetails", "shell.driveNone", "shell.driveChoose", "shell.driveCopy", "shell.driveNote", "shell.driveFat32",
+ "shell.driveReadOnly", "shell.driveNoSpace", "shell.driveProgress", "shell.driveDone", "shell.driveFailed"]
+ XCTAssertEqual(Lang.all.count, 5)
+ for key in keys {
+ for lang in Lang.all {
+ let text = L10n.string(key, lang)
+ XCTAssertNotEqual(text, key, "\(key) in \(lang.code)")
+ XCTAssertFalse(text.contains(";") || text.contains(";"), "\(key) in \(lang.code)")
+ XCTAssertFalse(text.contains("NX2Apple"), "\(key) in \(lang.code): no product name in a screen")
+ if lang != .en && !key.hasPrefix("shell.export") { XCTAssertNotEqual(text, L10n.string(key, .en), "\(key) in \(lang.code) is English") }
+ }
+ }
+ // the arguments the code passes
+ XCTAssertEqual(L10n.string("shell.step1Done", .en).components(separatedBy: "%@").count, 2)
+ for lang in Lang.all {
+ XCTAssertEqual(L10n.string("shell.driveNote", lang).components(separatedBy: "%@").count, 5, lang.code)
+ XCTAssertEqual(L10n.string("shell.driveDone", lang).components(separatedBy: "%@").count, 3, lang.code)
+ XCTAssertEqual(L10n.string("shell.sendProgress", lang).components(separatedBy: "%@").count, 4, lang.code)
+ }
+ XCTAssertTrue(L10n.string("ios.ui.gameData", .en) == "Game data", "the drive note names the shell's own row")
+ XCTAssertTrue(L10n.string("shell.driveNote", .en).contains("has to stay connected"))
+ }
+
+ // ---- the choice in the build ----
+
+ private let savedKeys = ["repoPath", "buildTarget", "buildOutputDirectory", "installDevice", "signingTeam", "shellRoot", "exportIPA"]
+
+ /// An iPhone build with the export chosen and no device and no team runs the script without `--team-id`, then ends with the IPA
+ /// instead of the "needs a device and a signing team" stop.
+ @MainActor func testBuildWithTheExportChoiceNeedsNoDeviceAndNoTeam() throws {
+ let f = try makeFixture()
+ let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
+ defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
+ UserDefaults.standard.set(f.root, forKey: "shellRoot")
+ let stores = LauncherStores(xcrun: f.xcrun); let model = stores.build
+ stores.repo.path = f.repo
+ model.target = "ios"
+ model.outDir = path("out")
+ stores.dependencies.pythonPath = "/usr/bin/python3"
+ stores.dependencies.dotnetPath = "/usr/bin/true"
+ stores.dependencies.checked = true
+ stores.dependencies.deps = [Dep(id: "test", name: "test", hint: "", present: true, installCmd: [])]
+ stores.deviceStore.installDevice = ""
+ stores.deviceStore.signingTeam = ""
+ stores.deviceStore.exportIPA = true
+ XCTAssertTrue(model.exportsShell)
+ XCTAssertFalse(model.installsDirectly)
+ try write(f.repo + "/dm/tools/nx_extract/Program.cs", "")
+ for tool in RepoLayout.requiredTools.filter({ $0 != RepoLayout.buildScript }) { try write(f.repo + "/" + tool, "") }
+ try write(f.repo + "/dm/tools/romfs_image.py", "import sys\nopen(sys.argv[3], 'wb').write(b'image')\n")
+ try write(f.repo + "/scripts/build_ipa_from_nsp.py", """
+ import sys, json, pathlib
+ open('\(state)/script.txt', 'w').write(' '.join(sys.argv[1:]))
+ work = pathlib.Path(sys.argv[sys.argv.index('--work-dir') + 1])
+ fw = pathlib.Path(sys.argv[sys.argv.index('--shell-framework') + 1]) / 'DmGame\(titleID).framework'
+ fw.mkdir(parents=True); (fw / 'game.manifest.json').write_text('{}')
+ (work / 'extract/v0/RomFS').mkdir(parents=True); (work / 'extract/v0/RomFS/data.bin').write_bytes(b'game')
+ print(json.dumps(dict(ev='stage', k=1, n=1, name='framework')), flush=True)
+ print(json.dumps(dict(ev='stage_end', k=1, name='framework', ok=True, summary='', elapsed=1)), flush=True)
+ """)
+ let base = temporary.appendingPathComponent("Test [\(titleID)].nsp"), keys = temporary.appendingPathComponent("prod.keys")
+ try Data([0]).write(to: base); try Data().write(to: keys)
+ model.slots[0].paths = [base.path]; model.slots[3].paths = [keys.path]
+
+ let finished = expectation(description: "Exported")
+ let token = model.$done.filter { $0 }.prefix(1).sink { _ in finished.fulfill() }
+ model.startBuild()
+ wait(for: [finished], timeout: 30)
+ withExtendedLifetime(token) {}
+
+ let script = try String(contentsOfFile: state + "/script.txt")
+ XCTAssertTrue(script.contains("--shell-framework \(temporary.path)/out/\(titleID)_build/shell-framework"), script)
+ XCTAssertFalse(script.contains("--team-id"), script)
+ XCTAssertEqual(model.exportedIPAPath, ShellInstall.ipaPath(root: f.root))
+ XCTAssertTrue(fm.fileExists(atPath: model.exportedIPAPath))
+ XCTAssertEqual(model.installedOn, "")
+ XCTAssertFalse(model.running)
+ XCTAssertNotEqual(model.doneNote, model.t("shell.needsDevice"))
+ XCTAssertEqual(model.doneNote, String(format: model.t("shell.exportDone"), model.exportedIPAPath))
+ XCTAssertFalse(calls.contains { $0.hasPrefix("devicectl") })
+ XCTAssertTrue(fm.fileExists(atPath: model.archivePath + "/romfs.img"), "the game data is packed beside the IPA, not in it")
+ XCTAssertFalse(try entries(ofZip: model.exportedIPAPath).contains { $0.hasSuffix("romfs.img") })
+ }
+
+ /// The choice is saved and a build without it still asks for a device and a team.
+ @MainActor func testTheChoiceIsSavedAndWithoutItTheDeviceIsStillNeeded() throws {
+ let saved = savedKeys.map { ($0, UserDefaults.standard.object(forKey: $0)) }
+ defer { for (key, value) in saved { UserDefaults.standard.set(value, forKey: key) } }
+ let stores = LauncherStores(); let model = stores.build
+ stores.repo.path = temporary.path
+ try write(temporary.path + "/dm/tools/nx_extract/Program.cs", "")
+ model.target = "ios"
+ stores.deviceStore.installDevice = ""
+ stores.deviceStore.exportIPA = true
+ XCTAssertTrue(UserDefaults.standard.bool(forKey: DeviceStore.exportKey))
+ stores.deviceStore.exportIPA = false
+ XCTAssertFalse(UserDefaults.standard.bool(forKey: DeviceStore.exportKey))
+ XCTAssertFalse(model.exportsShell)
+ model.startBuild()
+ XCTAssertEqual(model.doneNote, model.t("shell.needsDevice"))
+ // the Mac app is never an export
+ stores.deviceStore.exportIPA = true
+ model.target = BuildTarget.mac
+ XCTAssertFalse(model.exportsShell)
+ }
+}
diff --git a/frontend/Tests/NXModelTests/BuildStoreTests.swift b/frontend/Tests/NXModelTests/BuildStoreTests.swift
index f96b70da..24ba6971 100644
--- a/frontend/Tests/NXModelTests/BuildStoreTests.swift
+++ b/frontend/Tests/NXModelTests/BuildStoreTests.swift
@@ -33,6 +33,8 @@ import XCTest
private final class FakeDevices: InstallTarget {
var installDevice = ""
var signingTeam = ""
+ var exportIPA = false
+ var driveFolder = ""
var devices: [AppleDevice] = []
var xcrun = "/usr/bin/true"
var readTeams: @Sendable () -> [SigningTeam] = { [] }
@@ -91,6 +93,19 @@ import XCTest
XCTAssertFalse(store.canBuild, "a build runs")
}
+ /// #416: the export choice is not an install, so the stop for a missing device and team does not apply to it.
+ func testTheExportChoiceNeedsNoDeviceAndNoTeam() {
+ let store = makeStore()
+ store.target = "ios"
+ devices.exportIPA = true
+ XCTAssertTrue(store.exportsShell)
+ XCTAssertFalse(store.installsDirectly)
+ store.startBuild()
+ XCTAssertNotEqual(store.doneNote, store.t("shell.needsDevice"))
+ store.target = BuildTarget.mac
+ XCTAssertFalse(store.exportsShell, "a Mac app is never an IPA")
+ }
+
func testAnIPhoneBuildWithoutADeviceStopsBeforeTheLongSteps() {
let store = makeStore()
store.target = "ios"
diff --git a/frontend/Tests/NXModelTests/DeviceStoreTests.swift b/frontend/Tests/NXModelTests/DeviceStoreTests.swift
index a78b564c..7713d129 100644
--- a/frontend/Tests/NXModelTests/DeviceStoreTests.swift
+++ b/frontend/Tests/NXModelTests/DeviceStoreTests.swift
@@ -90,6 +90,14 @@ import XCTest
XCTAssertEqual(again.signingTeam, "ABCDE12345")
}
+ func testTheExportChoiceIsOffAtFirstAndSaved() {
+ let store = makeStore()
+ XCTAssertFalse(store.exportIPA)
+ store.exportIPA = true
+ XCTAssertTrue(defaults.bool(forKey: DeviceStore.exportKey))
+ XCTAssertTrue(makeStore().exportIPA)
+ }
+
func testADeviceNameFallsBackToIPhoneForOneThatIsNotListed() async {
let store = makeStore()
XCTAssertEqual(store.deviceName("UDID-1"), "iPhone")
diff --git a/frontend/l10n/de.json b/frontend/l10n/de.json
index a3383ad5..f14be72e 100644
--- a/frontend/l10n/de.json
+++ b/frontend/l10n/de.json
@@ -960,6 +960,23 @@
"shell.copyWifiOne": "Über WLAN verbunden: %@ zu kopieren dauert etwa %d Minuten. Mit Kabel geht es schneller.",
"shell.copyWired": "Lass %@ entsperrt, bis das Kopieren fertig ist.",
"shell.dataAlready": "Auf %@ installiert, die Spieldaten waren schon auf dem Gerät",
+ "shell.driveChoose": "Ordner wählen",
+ "shell.driveCopy": "Spieldaten kopieren",
+ "shell.driveDone": "Die Spieldaten liegen in %@. Verbinde das Laufwerk mit dem iPhone und wähle diesen Ordner in der App unter %@. Das Laufwerk muss beim Spielen verbunden bleiben.",
+ "shell.driveFailed": "Das Kopieren wurde angehalten: %@",
+ "shell.driveFat32": "Dieses Laufwerk ist FAT32 und kann keine Dateien über 4 GB aufnehmen. Formatiere es als exFAT oder APFS oder wähle ein anderes Laufwerk.",
+ "shell.driveNoSpace": "Nicht genug Platz auf dem Laufwerk: %@ nötig, %@ frei.",
+ "shell.driveNone": "Kein Ordner gewählt",
+ "shell.driveNote": "Braucht %@. %@ frei auf dem Laufwerk, %@. Verbinde das Laufwerk mit dem iPhone und wähle diesen Ordner in der App unter %@. Das Laufwerk muss beim Spielen verbunden bleiben.",
+ "shell.driveProgress": "Kopiere %@, %@ von %@.",
+ "shell.driveReadOnly": "Dieses Laufwerk ist schreibgeschützt. Wähle ein anderes Laufwerk oder einen anderen Ordner.",
+ "shell.exportBuildStage": "Die gemeinsame App ohne Signatur bauen",
+ "shell.exportDone": "Die IPA-Datei ist fertig: %@",
+ "shell.exportFailed": "Die IPA-Datei konnte nicht erstellt werden: %@",
+ "shell.exportPackStage": "IPA-Datei packen",
+ "shell.modeExport": "Als IPA exportieren",
+ "shell.modeInstall": "Auf Gerät installieren",
+ "shell.modeTitle": "Installieren oder exportieren",
"shell.needsDevice": "Die gemeinsame App braucht ein Gerät und ein Signier-Team. Wähle sie zuerst unter Installieren auf.",
"shell.noFramework": "Das Framework des Spiels wurde nicht gefunden: %@",
"shell.noSpace": "Nicht genug Platz auf %@: Die Spieldaten brauchen %.1f GB und auf dem Gerät sind %.1f GB frei. Gib Speicher frei und installiere dann erneut",
@@ -968,6 +985,27 @@
"shell.projectStage": "Gemeinsame App vorbereiten",
"shell.retry": "Erneut versuchen",
"shell.rootUnwritable": "Die gemeinsame App wird in %@ gespeichert, und dieser Ordner ist nicht beschreibbar (schreibgeschütztes Volume oder keine Berechtigung). Wähle zuerst unter Speichern unter einen anderen Ordner.",
+ "shell.sendButton": "Spieldaten senden",
+ "shell.sendDetails": "Einzelheiten",
+ "shell.sendDone": "Die Spieldaten sind auf dem Gerät. Öffne die App auf dem iPhone zum Spielen.",
+ "shell.sendFinderSteps": "Öffne dein iPhone im Finder, wähle Dateien und ziehe den Ordner auf die App.",
+ "shell.sendNoApp": "Die App ist noch nicht auf diesem Gerät. Installiere zuerst die IPA und sende dann die Spieldaten.",
+ "shell.sendProgress": "Sende %@, %@ von %@.",
+ "shell.sendRefused": "In diese App kann der Mac nicht schreiben. Kopiere die Spieldaten stattdessen im Finder.",
+ "shell.sendSeveral": "Dieses Gerät hat mehrere Kopien der App. Wähle eine aus.",
+ "shell.sendShowData": "Spieldaten im Finder zeigen",
+ "shell.sendStage": "App auf dem Gerät suchen",
+ "shell.showInFinder": "Im Finder zeigen",
+ "shell.step1Button": "IPA exportieren",
+ "shell.step1Done": "%@, nicht signiert. Die Spieldaten sind nicht enthalten.",
+ "shell.step1Sub": "Packt die gemeinsame App mit den Spielen, die du gebaut hast. Kein Gerät und kein Team nötig.",
+ "shell.step1Title": "IPA exportieren",
+ "shell.step2Sub": "AltStore, SideStore oder ein anderes Signier-Tool.",
+ "shell.step2Title": "Mit deinem eigenen Tool installieren",
+ "shell.step3Sub": "Kopiert das Spiel in die App auf deinem Gerät oder auf ein Laufwerk für das iPhone.",
+ "shell.step3Title": "Spieldaten senden",
+ "shell.whereDevice": "Gerät",
+ "shell.whereDrive": "Laufwerk oder Ordner",
"shellCache.note": "Der iPhone-Frameworks-Cache, aufbewahrt für die Installation mehrerer Spiele. Beim Löschen entfernt die Installation eines neuen Spiels die älteren Spiele aus der Shell.",
"shellCache.open": "Ordner öffnen",
"shellCache.row": "Cachedateien",
diff --git a/frontend/l10n/en.json b/frontend/l10n/en.json
index dadbfcbe..5eb19a39 100644
--- a/frontend/l10n/en.json
+++ b/frontend/l10n/en.json
@@ -1084,6 +1084,23 @@
"shell.copyWifiOne": "Connected over Wi-Fi: copying %@ takes about %d minutes. A cable is faster.",
"shell.copyWired": "Keep %@ unlocked until the copy finishes.",
"shell.dataAlready": "Installed on %@, the game data was already on the device",
+ "shell.driveChoose": "Choose folder",
+ "shell.driveCopy": "Copy game data",
+ "shell.driveDone": "Game data is in %@. Connect the drive to the iPhone and choose this folder in the app under %@. The drive has to stay connected while you play.",
+ "shell.driveFailed": "The copy stopped: %@",
+ "shell.driveFat32": "This drive is FAT32 and can’t hold files over 4 GB. Format it as exFAT or APFS, or choose another drive.",
+ "shell.driveNoSpace": "Not enough space on the drive: %@ needed, %@ free.",
+ "shell.driveNone": "No folder chosen",
+ "shell.driveNote": "Needs %@. %@ free on the drive, %@. Connect the drive to the iPhone and choose this folder in the app under %@. The drive has to stay connected while you play.",
+ "shell.driveProgress": "Copying %@, %@ of %@.",
+ "shell.driveReadOnly": "This drive is read-only. Choose another drive or folder.",
+ "shell.exportBuildStage": "Build the shared app without signing",
+ "shell.exportDone": "The IPA is ready: %@",
+ "shell.exportFailed": "The IPA could not be made: %@",
+ "shell.exportPackStage": "Pack the IPA",
+ "shell.modeExport": "Export as IPA",
+ "shell.modeInstall": "Install on device",
+ "shell.modeTitle": "Install or export",
"shell.needsDevice": "The shared app needs a device and a signing team. Choose them under Install on first.",
"shell.noFramework": "The game's framework was not found: %@",
"shell.noSpace": "Not enough space on %@: the game data needs %.1f GB and the device has %.1f GB free. Free up space, then install again",
@@ -1092,6 +1109,27 @@
"shell.projectStage": "Prepare the shared app",
"shell.retry": "Retry",
"shell.rootUnwritable": "The shared app is saved to %@, and that folder cannot be written (a read-only volume or no permission). Choose another folder under Save to first.",
+ "shell.sendButton": "Send game data",
+ "shell.sendDetails": "Details",
+ "shell.sendDone": "Game data is on the device. Open the app on the iPhone to play.",
+ "shell.sendFinderSteps": "Open your iPhone in Finder, choose Files, then drag the folder onto the app.",
+ "shell.sendNoApp": "The app isn’t on this device yet. Install the IPA first, then send the game data.",
+ "shell.sendProgress": "Sending %@, %@ of %@.",
+ "shell.sendRefused": "This app can’t be written to from the Mac. Copy the game data in Finder instead.",
+ "shell.sendSeveral": "This device has several copies of the app. Choose one.",
+ "shell.sendShowData": "Show game data in Finder",
+ "shell.sendStage": "Look for the app on the device",
+ "shell.showInFinder": "Show in Finder",
+ "shell.step1Button": "Export IPA",
+ "shell.step1Done": "%@, unsigned. Game data isn’t inside.",
+ "shell.step1Sub": "Packs the shared app with the games you built. No device or team needed.",
+ "shell.step1Title": "Export the IPA",
+ "shell.step2Sub": "AltStore, SideStore or another signing tool.",
+ "shell.step2Title": "Install it with your own tool",
+ "shell.step3Sub": "Copies the game into the app on your device, or onto a drive for the iPhone.",
+ "shell.step3Title": "Send the game data",
+ "shell.whereDevice": "Device",
+ "shell.whereDrive": "Drive or folder",
"shellCache.note": "The cache of the iPhone frameworks, kept so several games can be installed. Delete it and installing a new game removes the older games from the shell.",
"shellCache.open": "Open folder",
"shellCache.row": "Cache files",
diff --git a/frontend/l10n/fr.json b/frontend/l10n/fr.json
index 36b62671..f183936b 100644
--- a/frontend/l10n/fr.json
+++ b/frontend/l10n/fr.json
@@ -959,6 +959,23 @@
"shell.copyWifiOne": "Connecté en Wi-Fi : la copie de %@ prend environ %d minutes. Un câble est plus rapide.",
"shell.copyWired": "Gardez %@ déverrouillé jusqu’à la fin de la copie.",
"shell.dataAlready": "Installé sur %@, les données du jeu étaient déjà sur l’appareil",
+ "shell.driveChoose": "Choisir un dossier",
+ "shell.driveCopy": "Copier les données",
+ "shell.driveDone": "Les données du jeu sont dans %@. Branchez le disque à l’iPhone et choisissez ce dossier dans l’app sous %@. Le disque doit rester branché pendant que vous jouez.",
+ "shell.driveFailed": "La copie s’est arrêtée : %@",
+ "shell.driveFat32": "Ce disque est en FAT32 et ne peut pas contenir de fichiers de plus de 4 Go. Formatez-le en exFAT ou APFS, ou choisissez un autre disque.",
+ "shell.driveNoSpace": "Pas assez d’espace sur le disque : %@ requis, %@ libres.",
+ "shell.driveNone": "Aucun dossier choisi",
+ "shell.driveNote": "Demande %@. %@ libres sur le disque, %@. Branchez le disque à l’iPhone et choisissez ce dossier dans l’app sous %@. Le disque doit rester branché pendant que vous jouez.",
+ "shell.driveProgress": "Copie de %@, %@ sur %@.",
+ "shell.driveReadOnly": "Ce disque est en lecture seule. Choisissez un autre disque ou dossier.",
+ "shell.exportBuildStage": "Compiler l’app partagée sans signature",
+ "shell.exportDone": "L’IPA est prêt : %@",
+ "shell.exportFailed": "L’IPA n’a pas pu être créé : %@",
+ "shell.exportPackStage": "Empaqueter l’IPA",
+ "shell.modeExport": "Exporter en IPA",
+ "shell.modeInstall": "Installer sur l’appareil",
+ "shell.modeTitle": "Installer ou exporter",
"shell.needsDevice": "L’app partagée a besoin d’un appareil et d’une équipe de signature. Choisissez-les d’abord sous Installer sur.",
"shell.noFramework": "Le framework du jeu est introuvable : %@",
"shell.noSpace": "Pas assez d’espace sur %@ : les données du jeu demandent %.1f Go et l’appareil en a %.1f Go de libres. Libérez de l’espace, puis réinstallez",
@@ -967,6 +984,27 @@
"shell.projectStage": "Préparation de l’app partagée",
"shell.retry": "Réessayer",
"shell.rootUnwritable": "L’app partagée est enregistrée dans %@, et ce dossier n’est pas accessible en écriture (volume en lecture seule ou autorisation manquante). Choisissez d’abord un autre dossier sous Enregistrer dans.",
+ "shell.sendButton": "Envoyer les données",
+ "shell.sendDetails": "Détails",
+ "shell.sendDone": "Les données du jeu sont sur l’appareil. Ouvrez l’app sur l’iPhone pour jouer.",
+ "shell.sendFinderSteps": "Ouvrez votre iPhone dans le Finder, choisissez Fichiers, puis glissez le dossier sur l’app.",
+ "shell.sendNoApp": "L’app n’est pas encore sur cet appareil. Installez d’abord l’IPA, puis envoyez les données du jeu.",
+ "shell.sendProgress": "Envoi de %@, %@ sur %@.",
+ "shell.sendRefused": "Le Mac ne peut pas écrire dans cette app. Copiez plutôt les données du jeu dans le Finder.",
+ "shell.sendSeveral": "Cet appareil a plusieurs copies de l’app. Choisissez-en une.",
+ "shell.sendShowData": "Afficher les données dans le Finder",
+ "shell.sendStage": "Chercher l’app sur l’appareil",
+ "shell.showInFinder": "Afficher dans le Finder",
+ "shell.step1Button": "Exporter l’IPA",
+ "shell.step1Done": "%@, non signé. Les données du jeu n’y sont pas.",
+ "shell.step1Sub": "Regroupe l’app partagée et les jeux que vous avez compilés. Aucun appareil ni équipe requis.",
+ "shell.step1Title": "Exporter l’IPA",
+ "shell.step2Sub": "AltStore, SideStore ou un autre outil de signature.",
+ "shell.step2Title": "Installez-le avec votre propre outil",
+ "shell.step3Sub": "Copie le jeu dans l’app de votre appareil, ou sur un disque pour l’iPhone.",
+ "shell.step3Title": "Envoyer les données du jeu",
+ "shell.whereDevice": "Appareil",
+ "shell.whereDrive": "Disque ou dossier",
"shellCache.note": "Le cache des frameworks iPhone, conservé pour installer plusieurs jeux. Le supprimer fait qu’installer un nouveau jeu retire les jeux plus anciens de la coque.",
"shellCache.open": "Ouvrir le dossier",
"shellCache.row": "Fichiers de cache",
diff --git a/frontend/l10n/sv.json b/frontend/l10n/sv.json
index b4bd9f89..bbc615a2 100644
--- a/frontend/l10n/sv.json
+++ b/frontend/l10n/sv.json
@@ -796,6 +796,23 @@
"shell.copyWifiOne": "Ansluten via Wi-Fi: att kopiera %@ tar ungefär %d minuter. En kabel går fortare.",
"shell.copyWired": "Låt %@ vara olåst tills kopieringen är klar.",
"shell.dataAlready": "Installerad på %@, speldatan fanns redan på enheten",
+ "shell.driveChoose": "Välj mapp",
+ "shell.driveCopy": "Kopiera speldata",
+ "shell.driveDone": "Speldata finns i %@. Anslut disken till iPhone och välj den här mappen i appen under %@. Disken måste vara ansluten medan du spelar.",
+ "shell.driveFailed": "Kopieringen stoppades: %@",
+ "shell.driveFat32": "Disken är FAT32 och kan inte rymma filer över 4 GB. Formatera den som exFAT eller APFS, eller välj en annan disk.",
+ "shell.driveNoSpace": "Inte tillräckligt med utrymme på disken: %@ behövs, %@ ledigt.",
+ "shell.driveNone": "Ingen mapp vald",
+ "shell.driveNote": "Behöver %@. %@ ledigt på disken, %@. Anslut disken till iPhone och välj den här mappen i appen under %@. Disken måste vara ansluten medan du spelar.",
+ "shell.driveProgress": "Kopierar %@, %@ av %@.",
+ "shell.driveReadOnly": "Disken är skrivskyddad. Välj en annan disk eller mapp.",
+ "shell.exportBuildStage": "Bygg den gemensamma appen utan signering",
+ "shell.exportDone": "IPA-filen är klar: %@",
+ "shell.exportFailed": "IPA-filen kunde inte skapas: %@",
+ "shell.exportPackStage": "Paketera IPA-filen",
+ "shell.modeExport": "Exportera som IPA",
+ "shell.modeInstall": "Installera på enheten",
+ "shell.modeTitle": "Installera eller exportera",
"shell.needsDevice": "Den gemensamma appen behöver en enhet och ett signeringsteam. Välj dem först under Installera på.",
"shell.noFramework": "Spelets ramverk hittades inte: %@",
"shell.noSpace": "Inte tillräckligt med utrymme på %@: speldatan behöver %.1f GB och enheten har %.1f GB ledigt. Frigör utrymme och installera igen",
@@ -804,6 +821,27 @@
"shell.projectStage": "Förbereder den gemensamma appen",
"shell.retry": "Försök igen",
"shell.rootUnwritable": "Den gemensamma appen sparas i %@, och mappen går inte att skriva i (skrivskyddad volym eller ingen behörighet). Välj en annan mapp under Spara till först.",
+ "shell.sendButton": "Skicka speldata",
+ "shell.sendDetails": "Detaljer",
+ "shell.sendDone": "Speldata finns på enheten. Öppna appen på iPhone för att spela.",
+ "shell.sendFinderSteps": "Öppna din iPhone i Finder, välj Filer och dra mappen till appen.",
+ "shell.sendNoApp": "Appen finns inte på den här enheten än. Installera IPA-filen först och skicka sedan speldata.",
+ "shell.sendProgress": "Skickar %@, %@ av %@.",
+ "shell.sendRefused": "Det går inte att skriva till den här appen från Macen. Kopiera speldata i Finder i stället.",
+ "shell.sendSeveral": "Den här enheten har flera kopior av appen. Välj en.",
+ "shell.sendShowData": "Visa speldata i Finder",
+ "shell.sendStage": "Leta efter appen på enheten",
+ "shell.showInFinder": "Visa i Finder",
+ "shell.step1Button": "Exportera IPA",
+ "shell.step1Done": "%@, osignerad. Speldata finns inte med.",
+ "shell.step1Sub": "Paketerar den gemensamma appen med spelen du har byggt. Ingen enhet eller team behövs.",
+ "shell.step1Title": "Exportera IPA-filen",
+ "shell.step2Sub": "AltStore, SideStore eller ett annat signeringsverktyg.",
+ "shell.step2Title": "Installera den med ditt eget verktyg",
+ "shell.step3Sub": "Kopierar spelet till appen på din enhet, eller till en disk för iPhone.",
+ "shell.step3Title": "Skicka speldata",
+ "shell.whereDevice": "Enhet",
+ "shell.whereDrive": "Disk eller mapp",
"shellCache.note": "iPhone-framework-cachen, bevarad för installation av flera spel. Raderar du den tar installationen av ett nytt spel bort äldre spel från skalet.",
"shellCache.open": "Öppna mapp",
"shellCache.row": "Cachefiler",
diff --git a/frontend/l10n/zh.json b/frontend/l10n/zh.json
index da1a1c9c..e2f6c1d4 100644
--- a/frontend/l10n/zh.json
+++ b/frontend/l10n/zh.json
@@ -1085,6 +1085,23 @@
"shell.copyWifiOne": "已通过 Wi-Fi 连接:复制 %@ 大约需要 %d 分钟。用数据线会更快。",
"shell.copyWired": "复制完成前请保持 %@ 解锁。",
"shell.dataAlready": "已安装到 %@,游戏数据已经在设备上",
+ "shell.driveChoose": "选择文件夹",
+ "shell.driveCopy": "复制游戏数据",
+ "shell.driveDone": "游戏数据已放在 %@。把磁盘连接到 iPhone,并在应用的“%@”下选择这个文件夹。游玩时磁盘必须保持连接。",
+ "shell.driveFailed": "复制已停止:%@",
+ "shell.driveFat32": "这块磁盘是 FAT32,无法存放超过 4 GB 的文件。请格式化为 exFAT 或 APFS,或选择另一块磁盘。",
+ "shell.driveNoSpace": "磁盘空间不足:需要 %@,可用 %@。",
+ "shell.driveNone": "未选择文件夹",
+ "shell.driveNote": "需要 %@。磁盘上有 %@ 可用,文件系统为 %@。把磁盘连接到 iPhone,并在应用的“%@”下选择这个文件夹。游玩时磁盘必须保持连接。",
+ "shell.driveProgress": "正在复制 %@,%@ / %@。",
+ "shell.driveReadOnly": "这块磁盘是只读的。请选择另一块磁盘或文件夹。",
+ "shell.exportBuildStage": "不签名构建共用应用",
+ "shell.exportDone": "IPA 已就绪:%@",
+ "shell.exportFailed": "无法生成 IPA:%@",
+ "shell.exportPackStage": "打包 IPA",
+ "shell.modeExport": "导出为 IPA",
+ "shell.modeInstall": "安装到设备",
+ "shell.modeTitle": "安装或导出",
"shell.needsDevice": "共用应用需要一台设备和一个签名团队。请先在“安装到”里选择。",
"shell.noFramework": "没有找到游戏的框架:%@",
"shell.noSpace": "%@ 上空间不足:游戏数据需要 %.1f GB,设备只剩 %.1f GB。请先释放空间再安装",
@@ -1093,6 +1110,27 @@
"shell.projectStage": "准备共用应用",
"shell.retry": "重试",
"shell.rootUnwritable": "共用应用要保存在 %@,但那里无法写入(只读卷或没有权限)。请先在“保存到”里换一个目录。",
+ "shell.sendButton": "发送游戏数据",
+ "shell.sendDetails": "详细信息",
+ "shell.sendDone": "游戏数据已在设备上。在 iPhone 上打开应用即可游玩。",
+ "shell.sendFinderSteps": "在访达中打开你的 iPhone,选择“文件”,再把文件夹拖到应用上。",
+ "shell.sendNoApp": "应用还不在这台设备上。请先安装 IPA,再发送游戏数据。",
+ "shell.sendProgress": "正在发送 %@,%@ / %@。",
+ "shell.sendRefused": "无法从 Mac 写入这个应用。请改用访达复制游戏数据。",
+ "shell.sendSeveral": "这台设备上有多份该应用。请选择一份。",
+ "shell.sendShowData": "在访达中显示游戏数据",
+ "shell.sendStage": "在设备上查找应用",
+ "shell.showInFinder": "在访达中显示",
+ "shell.step1Button": "导出 IPA",
+ "shell.step1Done": "%@,未签名。不含游戏数据。",
+ "shell.step1Sub": "把共用应用和你构建的游戏打包在一起。不需要设备或团队。",
+ "shell.step1Title": "导出 IPA",
+ "shell.step2Sub": "AltStore、SideStore 或其他签名工具。",
+ "shell.step2Title": "用你自己的工具安装",
+ "shell.step3Sub": "把游戏复制到设备上的应用,或复制到供 iPhone 使用的磁盘。",
+ "shell.step3Title": "发送游戏数据",
+ "shell.whereDevice": "设备",
+ "shell.whereDrive": "磁盘或文件夹",
"shellCache.note": "iPhone 端 Framework 缓存,多游戏安装需保留。删除缓存后,安装新游戏,老游戏会消失。",
"shellCache.open": "打开目录",
"shellCache.row": "缓存文件",