Skip to content

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

iOS shell host: player-facing messages for broken games, library order, version line

v0lumehi7af05040778e
diff --git a/frontend-ios/Sources/ShellDemo/RealArt.swift b/frontend-ios/Sources/ShellDemo/RealArt.swift
index 8a5414da..bdb6a6cb 100644
--- a/frontend-ios/Sources/ShellDemo/RealArt.swift
+++ b/frontend-ios/Sources/ShellDemo/RealArt.swift
@@ -53,7 +53,7 @@ extension SampleArt {
/// A sample game: the real title with its banner when the art is found, else the fictional one with its drawn icon.
static func tile(_ id: String, title: String, version: String, real: RealTitle?, state: GameState = .playable,
recentlyPlayed: String? = nil) -> GameTile {
- let subtitle = demoText("Version \(version)")
+ let subtitle = ShellFormat.version(version)
if let real, let banner = RealArt.banner(for: real) {
return GameTile(id: id, title: real.title, subtitle: subtitle, banner: banner, state: state, recentlyPlayed: recentlyPlayed)
}
diff --git a/frontend-ios/Sources/ShellDemo/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellDemo/Resources/Localizable.xcstrings
index eed6f519..6bfaa873 100644
--- a/frontend-ios/Sources/ShellDemo/Resources/Localizable.xcstrings
+++ b/frontend-ios/Sources/ShellDemo/Resources/Localizable.xcstrings
@@ -221,26 +221,6 @@
}
}
},
- "Played today": {
- "localizations": {
- "en": {
- "stringUnit": {
- "state": "translated",
- "value": "Played today"
- }
- }
- }
- },
- "Played yesterday": {
- "localizations": {
- "en": {
- "stringUnit": {
- "state": "translated",
- "value": "Played yesterday"
- }
- }
- }
- },
"Player %lld": {
"localizations": {
"en": {
@@ -401,16 +381,6 @@
}
}
},
- "Version %@": {
- "localizations": {
- "en": {
- "stringUnit": {
- "state": "translated",
- "value": "Version %@"
- }
- }
- }
- },
"Wireless Controller": {
"localizations": {
"en": {
diff --git a/frontend-ios/Sources/ShellDemo/SampleData.swift b/frontend-ios/Sources/ShellDemo/SampleData.swift
index eb46c868..8ecfb15d 100644
--- a/frontend-ios/Sources/ShellDemo/SampleData.swift
+++ b/frontend-ios/Sources/ShellDemo/SampleData.swift
@@ -14,9 +14,9 @@ func demoText(_ key: String.LocalizationValue) -> String {
static var games: [GameDetail] {
let tiles: [GameTile] = [
SampleArt.tile("orbit", title: "Orbit Valley", version: "1.4.0", real: RealTitle("The Legend of Zelda: Breath of the Wild", "01007EF00011E000", "zelda-breath-of-the-wild.jpg"),
- recentlyPlayed: demoText("Played today")),
+ recentlyPlayed: ShellFormat.played(Date())),
SampleArt.tile("tide", title: "The Quiet Tide", version: "2.0.1", real: RealTitle("Hades", "0100535012974000", "hades.jpg"),
- recentlyPlayed: demoText("Played yesterday")),
+ recentlyPlayed: ShellFormat.played(Date().addingTimeInterval(-86_400))),
SampleArt.tile("paper", title: "Paper Trails", version: "1.0.0", real: RealTitle("The Legend of Zelda: Tears of the Kingdom", "0100F2C0115B6000", "zelda-tears-of-the-kingdom.jpg"),
state: .needsGameData),
SampleArt.tile("moon", title: "Moonlit Express", version: "3.1.0", real: RealTitle("Super Smash Bros. Ultimate", "01006A800016E000", "super-smash-bros-ultimate.jpg"),
diff --git a/frontend-ios/Sources/ShellHost/GameCatalogue.swift b/frontend-ios/Sources/ShellHost/GameCatalogue.swift
index 3c0cdc5e..500cb559 100644
--- a/frontend-ios/Sources/ShellHost/GameCatalogue.swift
+++ b/frontend-ios/Sources/ShellHost/GameCatalogue.swift
@@ -1,6 +1,9 @@
import Foundation
+import os
import ShellUI
+private let logger = Logger(subsystem: "dev.nx2apple.shell", category: "catalogue")
+
/// What the shell and the app it runs in are, for the checks that need an app version: the shader chain it was built
/// with and the OS it runs on. A nil chain skips the chain check (the demo has no engine).
public struct HostEnvironment: Equatable, Sendable {
@@ -53,31 +56,35 @@ public enum GameCatalogue {
var entry = CatalogueEntry(id: id, directory: dir, bannerURL: image(named: "banner", in: dir, fm), iconURL: image(named: "icon", in: dir, fm))
do {
guard let data = fm.contents(atPath: dir.appendingPathComponent("game.manifest.json").path) else {
- throw GameProblem(reason: hostText("Game manifest missing"), detail: hostText("This game's folder has no game.manifest.json."))
+ throw GameProblem(cause: .manifestMissing, reason: hostText("Game manifest missing"), detail: hostText("This game's folder has no game.manifest.json."))
}
let manifest = try GameManifest.parse(data)
entry.manifest = manifest
guard manifest.titleID == id else {
- throw GameProblem(reason: hostText("Game files damaged"), detail: hostText("The folder is named \(id) but the manifest says \(manifest.titleID)."))
+ throw GameProblem(cause: .filesDamaged, reason: hostText("Game files damaged"), detail: hostText("The folder is named \(id) but the manifest says \(manifest.titleID)."))
}
var isDir: ObjCBool = false
guard fm.fileExists(atPath: dir.appendingPathComponent(manifest.framework).path, isDirectory: &isDir), isDir.boolValue else {
- throw GameProblem(reason: hostText("Game code missing"), detail: hostText("\(manifest.framework) is not in this game's folder. Install the game again."))
+ throw GameProblem(cause: .codeMissing, reason: hostText("Game code missing"), detail: hostText("\(manifest.framework) is not in this game's folder. Install the game again."))
}
let direct = dir.appendingPathComponent("launcher.json")
let inFramework = dir.appendingPathComponent(manifest.framework).appendingPathComponent(manifest.launcher)
guard let launcherData = fm.contents(atPath: direct.path) ?? fm.contents(atPath: inFramework.path) else {
- throw GameProblem(reason: hostText("Settings list missing"), detail: hostText("This game has no launcher.json."))
+ throw GameProblem(cause: .settingsMissing, reason: hostText("Settings list missing"), detail: hostText("This game has no launcher.json."))
}
let profile = try LauncherProfile.parse(launcherData)
guard profile.game == manifest.titleID else {
- throw GameProblem(reason: hostText("Game files damaged"), detail: hostText("launcher.json is for \(profile.game), the manifest for \(manifest.titleID)."))
+ throw GameProblem(cause: .filesDamaged, reason: hostText("Game files damaged"), detail: hostText("launcher.json is for \(profile.game), the manifest for \(manifest.titleID)."))
}
entry.profile = profile
} catch let problem as GameProblem {
entry.problem = problem
} catch {
- entry.problem = GameProblem(reason: hostText("Game files damaged"), detail: error.localizedDescription)
+ entry.problem = GameProblem(cause: .filesDamaged, reason: hostText("Game files damaged"), detail: error.localizedDescription)
+ }
+ if let problem = entry.problem {
+ // The technical message is for the log and the Details of the How to fix sheet, not for the hero.
+ logger.error("\(id, privacy: .public): \(problem.reason, privacy: .public): \(problem.detail, privacy: .public)")
}
return entry
}
@@ -140,8 +147,8 @@ public enum DataLocator {
/// built for another chain or a newer OS needs an app update, a game without reachable data needs game data.
public enum GameStateResolver {
public static func state(for entry: CatalogueEntry, data: DataResolution, environment: HostEnvironment) -> GameState {
- if let problem = entry.problem { return .broken(reason: problem.reason, detail: problem.detail) }
- guard let manifest = entry.manifest else { return .broken(reason: hostText("Game manifest missing")) }
+ if let problem = entry.problem { return problem.state }
+ guard let manifest = entry.manifest else { return GameProblem(cause: .manifestMissing, reason: hostText("Game manifest missing")).state }
if let chain = environment.chain, chain != manifest.chain { return .needsAppUpdate }
if let min = manifest.minOSVersion, !isVersion(environment.osVersion, atLeast: min) { return .needsAppUpdate }
return data.found ? .playable : .needsGameData
diff --git a/frontend-ios/Sources/ShellHost/GameManifest.swift b/frontend-ios/Sources/ShellHost/GameManifest.swift
index c96f234d..7a1e21a1 100644
--- a/frontend-ios/Sources/ShellHost/GameManifest.swift
+++ b/frontend-ios/Sources/ShellHost/GameManifest.swift
@@ -43,25 +43,25 @@ public struct GameManifest: Decodable, Equatable, Sendable {
public static func parse(_ data: Data) throws(GameProblem) -> GameManifest {
let manifest: GameManifest
do { manifest = try JSONDecoder().decode(GameManifest.self, from: data) }
- catch { throw describe(error, file: "game.manifest.json", what: hostText("The game's manifest")) }
+ catch { throw describe(error, file: "game.manifest.json", cause: .manifestDamaged) }
guard manifest.schema == supportedSchema else {
- throw GameProblem(reason: hostText("Manifest not supported"),
+ throw GameProblem(cause: .manifestUnsupported, reason: hostText("Manifest not supported"),
detail: hostText("game.manifest.json has schema \(manifest.schema), this app reads schema \(supportedSchema)."))
}
guard isTitleID(manifest.titleID) else {
- throw GameProblem(reason: hostText("Manifest damaged"), detail: hostText("title_id \"\(manifest.titleID)\" is not 16 hex digits."))
+ throw GameProblem(cause: .manifestDamaged, reason: hostText("Manifest damaged"), detail: hostText("title_id \"\(manifest.titleID)\" is not 16 hex digits."))
}
guard !manifest.modules.isEmpty else {
- throw GameProblem(reason: hostText("Manifest damaged"), detail: hostText("The manifest lists no modules."))
+ throw GameProblem(cause: .manifestDamaged, reason: hostText("Manifest damaged"), detail: hostText("The manifest lists no modules."))
}
guard manifest.chain.hasPrefix("b-"), manifest.chain.count > 2, manifest.chain.dropFirst(2).allSatisfy(\.isHexDigit) else {
- throw GameProblem(reason: hostText("Manifest damaged"), detail: hostText("chain \"\(manifest.chain)\" is not of the form b-<hex>."))
+ throw GameProblem(cause: .manifestDamaged, reason: hostText("Manifest damaged"), detail: hostText("chain \"\(manifest.chain)\" is not of the form b-<hex>."))
}
guard ["FR", "FH"].contains(manifest.loader) else {
- throw GameProblem(reason: hostText("Manifest damaged"), detail: hostText("loader \"\(manifest.loader)\" is neither FR nor FH."))
+ throw GameProblem(cause: .manifestDamaged, reason: hostText("Manifest damaged"), detail: hostText("loader \"\(manifest.loader)\" is neither FR nor FH."))
}
guard manifest.framework.hasSuffix(".framework"), !manifest.framework.contains("/") else {
- throw GameProblem(reason: hostText("Manifest damaged"), detail: hostText("framework \"\(manifest.framework)\" is not a .framework name."))
+ throw GameProblem(cause: .manifestDamaged, reason: hostText("Manifest damaged"), detail: hostText("framework \"\(manifest.framework)\" is not a .framework name."))
}
return manifest
}
@@ -86,19 +86,19 @@ func isVersion(_ a: OperatingSystemVersion, atLeast b: OperatingSystemVersion) -
}
/// A decoding error as one readable sentence.
-func describe(_ error: Error, file: String, what: String) -> GameProblem {
+func describe(_ error: Error, file: String, cause: ProblemCause) -> GameProblem {
let short = hostText("Game files damaged")
- guard let e = error as? DecodingError else { return GameProblem(reason: short, detail: "\(file): \(error.localizedDescription)") }
+ guard let e = error as? DecodingError else { return GameProblem(cause: cause, reason: short, detail: "\(file): \(error.localizedDescription)") }
func path(_ c: [CodingKey]) -> String { c.map { $0.stringValue }.joined(separator: ".") }
switch e {
case .keyNotFound(let key, let c):
let at = c.codingPath.isEmpty ? "" : " (in \(path(c.codingPath)))"
- return GameProblem(reason: short, detail: hostText("\(file) has no \"\(key.stringValue)\"\(at)."))
+ return GameProblem(cause: cause, reason: short, detail: hostText("\(file) has no \"\(key.stringValue)\"\(at)."))
case .typeMismatch(_, let c), .valueNotFound(_, let c):
- return GameProblem(reason: short, detail: hostText("\(file) has a wrong or missing value at \"\(path(c.codingPath))\"."))
+ return GameProblem(cause: cause, reason: short, detail: hostText("\(file) has a wrong or missing value at \"\(path(c.codingPath))\"."))
case .dataCorrupted:
- return GameProblem(reason: short, detail: hostText("\(file) is not valid JSON."))
+ return GameProblem(cause: cause, reason: short, detail: hostText("\(file) is not valid JSON."))
@unknown default:
- return GameProblem(reason: short, detail: file)
+ return GameProblem(cause: cause, reason: short, detail: file)
}
}
diff --git a/frontend-ios/Sources/ShellHost/HostText.swift b/frontend-ios/Sources/ShellHost/HostText.swift
index d66c2943..fd93c191 100644
--- a/frontend-ios/Sources/ShellHost/HostText.swift
+++ b/frontend-ios/Sources/ShellHost/HostText.swift
@@ -1,15 +1,45 @@
import Foundation
+import ShellUI
/// The host layer's own words, from `Resources/Localizable.xcstrings` (English source, like ShellUI).
func hostText(_ key: String.LocalizationValue) -> String {
String(localized: key, bundle: .module)
}
-/// Why a game cannot be shown as playable: `reason` is the short line under the title, `detail` the sentence for the
-/// How to fix sheet. Both are already localized.
+/// What is wrong with a bundle that cannot run at all. Each cause has one plain sentence for the player.
+public enum ProblemCause: Equatable, Sendable {
+ case manifestMissing, manifestDamaged, manifestUnsupported
+ case settingsMissing, settingsDamaged, settingsUnsupported
+ case codeMissing
+ case filesDamaged
+
+ /// What happened and what to do, for the player. The technical message stays in `GameProblem.detail`.
+ public var message: String {
+ switch self {
+ case .manifestMissing: hostText("This game's manifest is missing. Rebuild the game in the launcher on your Mac.")
+ case .manifestDamaged: hostText("This game's manifest is damaged. Rebuild the game in the launcher on your Mac.")
+ case .manifestUnsupported, .settingsUnsupported:
+ hostText("This game was built for a different version of this app. Update the app or rebuild the game in the launcher on your Mac.")
+ case .settingsMissing: hostText("This game's settings list is missing. Rebuild the game in the launcher on your Mac.")
+ case .settingsDamaged: hostText("This game's settings list is damaged. Rebuild the game in the launcher on your Mac.")
+ case .codeMissing: hostText("The game's code is missing from this app. Rebuild and reinstall it.")
+ case .filesDamaged: hostText("This game's files are damaged. Rebuild the game in the launcher on your Mac.")
+ }
+ }
+}
+
+/// Why a game cannot be shown as playable: `reason` is the short line under the title, `cause` says which of the
+/// known problems it is, `detail` is the technical message (logged and shown as Details, never as the hero text).
+/// `reason` and `detail` are already localized.
public struct GameProblem: Error, Equatable, Sendable, LocalizedError {
+ public var cause: ProblemCause
public var reason: String
public var detail: String
- public init(reason: String, detail: String = "") { self.reason = reason; self.detail = detail }
+ public init(cause: ProblemCause = .filesDamaged, reason: String, detail: String = "") {
+ self.cause = cause; self.reason = reason; self.detail = detail
+ }
public var errorDescription: String? { detail.isEmpty ? reason : "\(reason): \(detail)" }
+
+ /// The broken state a tile shows: the short reason, the player's sentence and the technical message.
+ public var state: GameState { .broken(reason: reason, detail: cause.message, technical: detail) }
}
diff --git a/frontend-ios/Sources/ShellHost/LauncherProfile.swift b/frontend-ios/Sources/ShellHost/LauncherProfile.swift
index 0db494f4..3af6322d 100644
--- a/frontend-ios/Sources/ShellHost/LauncherProfile.swift
+++ b/frontend-ios/Sources/ShellHost/LauncherProfile.swift
@@ -54,34 +54,34 @@ public struct LauncherProfile: Decodable, Equatable, Sendable {
public static func parse(_ data: Data) throws(GameProblem) -> LauncherProfile {
let profile: LauncherProfile
do { profile = try JSONDecoder().decode(LauncherProfile.self, from: data) }
- catch { throw describe(error, file: "launcher.json", what: hostText("The settings list")) }
+ catch { throw describe(error, file: "launcher.json", cause: .settingsDamaged) }
let reason = hostText("Settings list damaged")
if let schema = profile.schema, schema != 1 {
- throw GameProblem(reason: hostText("Settings list not supported"), detail: hostText("launcher.json has schema \(schema), this app reads schema 1."))
+ throw GameProblem(cause: .settingsUnsupported, reason: hostText("Settings list not supported"), detail: hostText("launcher.json has schema \(schema), this app reads schema 1."))
}
guard isTitleID(profile.game) else {
- throw GameProblem(reason: reason, detail: hostText("game \"\(profile.game)\" in launcher.json is not 16 hex digits."))
+ throw GameProblem(cause: .settingsDamaged, reason: reason, detail: hostText("game \"\(profile.game)\" in launcher.json is not 16 hex digits."))
}
var seen = Set<String>()
for s in profile.settings {
guard s.env.hasPrefix("DM_"), s.env.dropFirst(3).allSatisfy({ $0.isUppercase || $0.isNumber || $0 == "_" }), s.env.count > 3 else {
- throw GameProblem(reason: reason, detail: hostText("\"\(s.env)\" is not a DM_ switch."))
+ throw GameProblem(cause: .settingsDamaged, reason: reason, detail: hostText("\"\(s.env)\" is not a DM_ switch."))
}
guard seen.insert(s.env).inserted else {
- throw GameProblem(reason: reason, detail: hostText("\(s.env) appears twice in launcher.json."))
+ throw GameProblem(cause: .settingsDamaged, reason: reason, detail: hostText("\(s.env) appears twice in launcher.json."))
}
switch s.kind {
case "choice":
guard let o = s.options, !o.isEmpty, o.allSatisfy({ $0.count == 2 }) else {
- throw GameProblem(reason: reason, detail: hostText("\(s.env) is a choice without [value, label] options."))
+ throw GameProblem(cause: .settingsDamaged, reason: reason, detail: hostText("\(s.env) is a choice without [value, label] options."))
}
case "range":
guard s.min != nil, s.max != nil, let step = s.step, step > 0 else {
- throw GameProblem(reason: reason, detail: hostText("\(s.env) is a range without min, max and step."))
+ throw GameProblem(cause: .settingsDamaged, reason: reason, detail: hostText("\(s.env) is a range without min, max and step."))
}
case "toggle": break
default:
- throw GameProblem(reason: reason, detail: hostText("\(s.env) has the unknown kind \"\(s.kind)\"."))
+ throw GameProblem(cause: .settingsDamaged, reason: reason, detail: hostText("\(s.env) has the unknown kind \"\(s.kind)\"."))
}
}
return profile
diff --git a/frontend-ios/Sources/ShellHost/LibraryOrder.swift b/frontend-ios/Sources/ShellHost/LibraryOrder.swift
new file mode 100644
index 00000000..b182de34
--- /dev/null
+++ b/frontend-ios/Sources/ShellHost/LibraryOrder.swift
@@ -0,0 +1,39 @@
+import Foundation
+import ShellUI
+
+/// When a game was last played, in the game's own defaults suite. A separate key from the `launcher.<VAR>` choices,
+/// so Reset to tested defaults keeps it.
+public struct LastPlayedStore {
+ public static let key = "shell.lastPlayed"
+ private let defaults: UserDefaults
+ public init(defaults: UserDefaults) { self.defaults = defaults }
+ public var date: Date? { defaults.object(forKey: Self.key) as? Date }
+ public func record(_ date: Date) { defaults.set(date, forKey: Self.key) }
+}
+
+/// The library's order: recently played first (the latest first), then playable, then needs game data, then needs an
+/// app update, then broken. Alphabetical by title within each group. Applied when the library loads or reloads, never
+/// on a single game's change of state, so nothing moves under the player's finger.
+public enum LibraryOrder {
+ static func group(_ game: GameTile, lastPlayed: Date?) -> Int {
+ if lastPlayed != nil { return 0 }
+ switch game.state {
+ case .playable: return 1
+ case .needsGameData: return 2
+ case .needsAppUpdate: return 3
+ case .broken: return 4
+ }
+ }
+
+ /// The ids in library order.
+ public static func ids(of games: [GameTile], lastPlayed: [String: Date]) -> [String] {
+ games.sorted { a, b in
+ let (da, db) = (lastPlayed[a.id], lastPlayed[b.id])
+ let (ga, gb) = (group(a, lastPlayed: da), group(b, lastPlayed: db))
+ if ga != gb { return ga < gb }
+ if let da, let db, da != db { return da > db }
+ let byTitle = a.title.localizedCaseInsensitiveCompare(b.title)
+ return byTitle == .orderedSame ? a.id < b.id : byTitle == .orderedAscending
+ }.map(\.id)
+ }
+}
diff --git a/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings
index b6231b79..9d02129d 100644
--- a/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings
+++ b/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings
@@ -331,6 +331,16 @@
}
}
},
+ "The game's code is missing from this app. Rebuild and reinstall it.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "The game's code is missing from this app. Rebuild and reinstall it."
+ }
+ }
+ }
+ },
"The game's manifest": {
"localizations": {
"en": {
@@ -411,6 +421,26 @@
}
}
},
+ "This game was built for a different version of this app. Update the app or rebuild the game in the launcher on your Mac.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This game was built for a different version of this app. Update the app or rebuild the game in the launcher on your Mac."
+ }
+ }
+ }
+ },
+ "This game's files are damaged. Rebuild the game in the launcher on your Mac.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This game's files are damaged. Rebuild the game in the launcher on your Mac."
+ }
+ }
+ }
+ },
"This game's folder has no game.manifest.json.": {
"localizations": {
"en": {
@@ -421,6 +451,46 @@
}
}
},
+ "This game's manifest is damaged. Rebuild the game in the launcher on your Mac.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This game's manifest is damaged. Rebuild the game in the launcher on your Mac."
+ }
+ }
+ }
+ },
+ "This game's manifest is missing. Rebuild the game in the launcher on your Mac.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This game's manifest is missing. Rebuild the game in the launcher on your Mac."
+ }
+ }
+ }
+ },
+ "This game's settings list is damaged. Rebuild the game in the launcher on your Mac.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This game's settings list is damaged. Rebuild the game in the launcher on your Mac."
+ }
+ }
+ }
+ },
+ "This game's settings list is missing. Rebuild the game in the launcher on your Mac.": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "This game's settings list is missing. Rebuild the game in the launcher on your Mac."
+ }
+ }
+ }
+ },
"chain \"%@\" is not of the form b-<hex>.": {
"localizations": {
"en": {
diff --git a/frontend-ios/Sources/ShellHost/ShellHostModel.swift b/frontend-ios/Sources/ShellHost/ShellHostModel.swift
index 609bcd8d..61d17c98 100644
--- a/frontend-ios/Sources/ShellHost/ShellHostModel.swift
+++ b/frontend-ios/Sources/ShellHost/ShellHostModel.swift
@@ -17,16 +17,20 @@ public struct ShellHostConfig: Sendable {
public var updateURL: URL?
public var defaults: @Sendable (String) -> UserDefaults
public var openURL: @MainActor @Sendable (URL) -> Void
+ /// The clock, for the last-played date and its wording.
+ public var now: @Sendable () -> Date
public init(gamesRoot: URL, appDataRoot: URL, environment: HostEnvironment = HostEnvironment(), updateURL: URL? = nil,
defaults: @escaping @Sendable (String) -> UserDefaults = GameDefaults.suite(for:),
- openURL: @escaping @MainActor @Sendable (URL) -> Void = ShellHostConfig.systemOpen) {
+ openURL: @escaping @MainActor @Sendable (URL) -> Void = ShellHostConfig.systemOpen,
+ now: @escaping @Sendable () -> Date = { Date() }) {
self.gamesRoot = gamesRoot
self.appDataRoot = appDataRoot
self.environment = environment
self.updateURL = updateURL
self.defaults = defaults
self.openURL = openURL
+ self.now = now
}
@MainActor public static func systemOpen(_ url: URL) {
@@ -71,12 +75,20 @@ public struct ShellHostConfig: Sendable {
// MARK: Catalogue
- /// Reads the games folder again.
+ /// Reads the games folder again and sorts the library (see `LibraryOrder`). Only this and the first load re-sort:
+ /// a change to one game updates it in place.
public func reload() {
- entries = GameCatalogue.scan(root: config.gamesRoot)
- details = entries.map(detail(for:))
+ let scanned = GameCatalogue.scan(root: config.gamesRoot)
+ let built = scanned.map(detail(for:))
+ let order = LibraryOrder.ids(of: built.map(\.game), lastPlayed: Dictionary(uniqueKeysWithValues: scanned.compactMap { e in
+ lastPlayed(e.id).map { (e.id, $0) } }))
+ let position = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($1, $0) })
+ entries = scanned.sorted { position[$0.id] ?? 0 < position[$1.id] ?? 0 }
+ details = built.sorted { position[$0.id] ?? 0 < position[$1.id] ?? 0 }
}
+ private func lastPlayed(_ id: String) -> Date? { LastPlayedStore(defaults: config.defaults(id)).date }
+
private func refresh(_ id: String) {
guard let e = entries.firstIndex(where: { $0.id == id }), let d = details.firstIndex(where: { $0.id == id }) else { return }
details[d] = detail(for: entries[e])
@@ -116,8 +128,10 @@ public struct ShellHostConfig: Sendable {
private func detail(for entry: CatalogueEntry) -> GameDetail {
let data = data(for: entry)
let state = GameStateResolver.state(for: entry, data: data, environment: config.environment)
- let tile = GameTile(id: entry.id, title: entry.title, subtitle: entry.manifest?.displayVersion ?? "",
- banner: image(entry.bannerURL), icon: image(entry.iconURL), state: state)
+ let played = lastPlayed(entry.id)
+ let tile = GameTile(id: entry.id, title: entry.title, subtitle: ShellFormat.version(entry.manifest?.displayVersion ?? ""),
+ banner: image(entry.bannerURL), icon: image(entry.iconURL), state: state,
+ recentlyPlayed: played.map { ShellFormat.played($0, now: config.now()) })
guard let profile = entry.profile, entry.problem == nil else {
return GameDetail(game: tile, dataNote: dataNote(data, found: false))
}
@@ -247,6 +261,9 @@ public struct ShellHostConfig: Sendable {
details.first(where: { $0.id == id })?.game.state == .playable, let dataURL = data(for: entry).url else { return }
var cloud: URL?
if case .url(let url) = cloudStore(id).resolve() { cloud = url }
+ // Remembered when Play is triggered, even if the launcher then fails (the stub). The order changes at the next load.
+ LastPlayedStore(defaults: config.defaults(id)).record(config.now())
+ refresh(id)
let game = LaunchableGame(
titleID: id, name: entry.title, manifest: manifest, directory: entry.directory, frameworkURL: framework, dataURL: dataURL,
appFolder: appFolder(for: id), environment: GameSettingsStore(profile: profile, defaults: config.defaults(id)).values(), cloudSavesURL: cloud)
diff --git a/frontend-ios/Sources/ShellUI/GameStateView.swift b/frontend-ios/Sources/ShellUI/GameStateView.swift
index 897a7829..52d6818b 100644
--- a/frontend-ios/Sources/ShellUI/GameStateView.swift
+++ b/frontend-ios/Sources/ShellUI/GameStateView.swift
@@ -64,8 +64,13 @@ public struct StateHelpView: View {
Text(game.state.actionTitle).shellType(ShellType.pageTitle)
.accessibilityAddTraits(.isHeader).accessibilityIdentifier("help.title")
Text(message).shellText(15).foregroundStyle(.white.opacity(0.78)).fixedSize(horizontal: false, vertical: true)
- if case .broken(_, let detail) = game.state, !detail.isEmpty {
- Text(detail).shellText(13).foregroundStyle(.white.opacity(0.5)).fixedSize(horizontal: false, vertical: true)
+ if case .broken(_, _, let technical) = game.state, !technical.isEmpty {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(ShellStrings.text("Details")).shellText(11.5, .semibold).foregroundStyle(.white.opacity(0.5))
+ Text(verbatim: technical).font(.system(size: 12, design: .monospaced)).foregroundStyle(.white.opacity(0.5))
+ .textSelection(.enabled).fixedSize(horizontal: false, vertical: true)
+ .accessibilityIdentifier("help.details")
+ }
}
VStack(spacing: 10) {
Button(action: onClose) { Text(ShellStrings.text("Done")).frame(maxWidth: .infinity) }
@@ -95,6 +100,7 @@ public struct StateHelpView: View {
}
private var message: String {
switch game.state {
+ case .broken(_, let detail, _) where !detail.isEmpty: detail
case .broken: ShellStrings.text("Build this game again on your Mac and install it on this device. The Mac app checks every file while it builds, so the new copy is complete.")
case .needsAppUpdate: ShellStrings.text("This game needs a newer version of this app. Update it with the Mac app on your Mac, then install it on this device again.")
default: ""
diff --git a/frontend-ios/Sources/ShellUI/PortraitLibrary.swift b/frontend-ios/Sources/ShellUI/PortraitLibrary.swift
index 45bfae8c..8a90d7e7 100644
--- a/frontend-ios/Sources/ShellUI/PortraitLibrary.swift
+++ b/frontend-ios/Sources/ShellUI/PortraitLibrary.swift
@@ -257,7 +257,7 @@ struct HeroView<Accessory: View>: View {
}
private var meta: String {
- [game.subtitle, game.recentlyPlayed ?? ""].filter { !$0.isEmpty }.joined(separator: " · ")
+ ShellFormat.metaLine(game.subtitle, game.recentlyPlayed)
}
}
diff --git a/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings
index c6421c1f..e132daaa 100644
--- a/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings
+++ b/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings
@@ -181,6 +181,16 @@
}
}
},
+ "Details": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Details"
+ }
+ }
+ }
+ },
"Done": {
"localizations": {
"en": {
@@ -381,6 +391,36 @@
}
}
},
+ "Played %@": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Played %@"
+ }
+ }
+ }
+ },
+ "Played today": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Played today"
+ }
+ }
+ }
+ },
+ "Played yesterday": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Played yesterday"
+ }
+ }
+ }
+ },
"Ready to play": {
"localizations": {
"en": {
@@ -491,6 +531,16 @@
}
}
},
+ "Version %@": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Version %@"
+ }
+ }
+ }
+ },
"Your games": {
"localizations": {
"en": {
diff --git a/frontend-ios/Sources/ShellUI/ShellFormat.swift b/frontend-ios/Sources/ShellUI/ShellFormat.swift
new file mode 100644
index 00000000..6c2c8d04
--- /dev/null
+++ b/frontend-ios/Sources/ShellUI/ShellFormat.swift
@@ -0,0 +1,38 @@
+import Foundation
+
+/// The wording of the version and last-played line, shared by every view and by the host and the demo that fill it:
+/// "Version 1.0.0", "Played today", "Played yesterday", "Played 3 days ago", joined as "Version 1.0.0 · Played today".
+public enum ShellFormat {
+ /// "Version 1.0.0", empty for an empty version.
+ public static func version(_ version: String) -> String {
+ version.isEmpty ? "" : ShellStrings.text("Version \(version)")
+ }
+
+ /// "Played today", "Played yesterday" or "Played <relative date>", by calendar days, not by 24 hour spans.
+ public static func played(_ date: Date, now: Date = Date(), calendar: Calendar = .current, locale: Locale = .current) -> String {
+ let days = calendar.dateComponents([.day], from: calendar.startOfDay(for: date), to: calendar.startOfDay(for: now)).day ?? 0
+ switch days {
+ case ...0: return ShellStrings.text("Played today")
+ case 1: return ShellStrings.text("Played yesterday")
+ default:
+ let formatter = RelativeDateTimeFormatter()
+ formatter.locale = locale
+ formatter.calendar = calendar
+ formatter.unitsStyle = .full
+ formatter.dateTimeStyle = .numeric
+ let relative = formatter.localizedString(for: calendar.startOfDay(for: date), relativeTo: calendar.startOfDay(for: now))
+ return ShellStrings.text("Played \(relative)")
+ }
+ }
+
+ /// The parts that are not empty, joined by a middle dot.
+ public static func metaLine(_ parts: String?...) -> String {
+ parts.compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")
+ }
+
+ /// "Version 1.0.0 · Played today": the version line with the last-played date when there is one.
+ public static func versionLine(version v: String, lastPlayed: Date?, now: Date = Date(), calendar: Calendar = .current,
+ locale: Locale = .current) -> String {
+ metaLine(version(v), lastPlayed.map { played($0, now: now, calendar: calendar, locale: locale) })
+ }
+}
diff --git a/frontend-ios/Sources/ShellUI/ShellInputs.swift b/frontend-ios/Sources/ShellUI/ShellInputs.swift
index cbdea436..555d878d 100644
--- a/frontend-ios/Sources/ShellUI/ShellInputs.swift
+++ b/frontend-ios/Sources/ShellUI/ShellInputs.swift
@@ -5,9 +5,10 @@ public enum GameState: Equatable, Sendable {
case playable
case needsGameData
case needsAppUpdate
- /// `reason` is one short line for under the title, such as "Game files damaged". `detail` may add a sentence
- /// for the How to fix sheet.
- case broken(reason: String, detail: String = "")
+ /// `reason` is one short line for under the title, such as "Game files damaged". `detail` is a plain sentence
+ /// for the player (what happened, what to do), shown under the title and in the How to fix sheet. `technical`
+ /// is the underlying message, shown only as small secondary Details in the sheet.
+ case broken(reason: String, detail: String = "", technical: String = "")
}
public struct GameTile: Identifiable, Equatable, Sendable {
diff --git a/frontend-ios/Sources/ShellUI/ShellStyle.swift b/frontend-ios/Sources/ShellUI/ShellStyle.swift
index ab1276f0..a2d1fea9 100644
--- a/frontend-ios/Sources/ShellUI/ShellStyle.swift
+++ b/frontend-ios/Sources/ShellUI/ShellStyle.swift
@@ -331,7 +331,7 @@ extension GameState {
case .playable: ShellStrings.text("Ready to play")
case .needsGameData: ShellStrings.text("Needs game data")
case .needsAppUpdate: ShellStrings.text("App update needed")
- case .broken(let reason, _): reason.isEmpty ? ShellStrings.text("Unavailable") : reason
+ case .broken(let reason, _, _): reason.isEmpty ? ShellStrings.text("Unavailable") : reason
}
}
var color: Color {
@@ -346,7 +346,7 @@ extension GameState {
case .playable: ""
case .needsGameData: ShellStrings.text("Choose this game's data to get ready to play.")
case .needsAppUpdate: ShellStrings.text("Install a newer version of this app to play this game.")
- case .broken(_, let detail): detail
+ case .broken(_, let detail, _): detail
}
}
var actionTitle: String {
diff --git a/frontend-ios/Tests/ShellHostTests/CatalogueStateTests.swift b/frontend-ios/Tests/ShellHostTests/CatalogueStateTests.swift
index c145c9dc..a01e3636 100644
--- a/frontend-ios/Tests/ShellHostTests/CatalogueStateTests.swift
+++ b/frontend-ios/Tests/ShellHostTests/CatalogueStateTests.swift
@@ -75,10 +75,10 @@ import ShellUI
@Test func brokenBundlesAreBrokenWhateverElseIsPresent() {
for id in [Fixtures.noFramework, Fixtures.badManifest, Fixtures.missingKey, Fixtures.badSettings] {
- guard case .broken(let reason, let detail) = GameStateResolver.state(for: entry(id), data: found, environment: env) else {
+ guard case .broken(let reason, let detail, let technical) = GameStateResolver.state(for: entry(id), data: found, environment: env) else {
Issue.record("\(id) is not broken"); continue
}
- #expect(!reason.isEmpty && !detail.isEmpty)
+ #expect(!reason.isEmpty && !detail.isEmpty && !technical.isEmpty && detail != technical)
}
}
diff --git a/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift b/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift
index 7224312c..b8bdc589 100644
--- a/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift
+++ b/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift
@@ -19,6 +19,9 @@ final class RecordingLauncher: GameLauncher, @unchecked Sendable {
}
}
+struct Failure: Error {}
+final class Clock: @unchecked Sendable { var date: Date; init(_ d: Date) { date = d } }
+
@MainActor @Suite struct ShellHostModelTests {
private func detail(_ model: ShellHostModel, _ id: String = Fixtures.orbit) throws -> GameDetail {
try #require(model.details.first { $0.id == id })
@@ -32,13 +35,14 @@ final class RecordingLauncher: GameLauncher, @unchecked Sendable {
let model = ShellHostModel(config: box.config())
#expect(model.details.count == 8)
let orbit = try detail(model)
- #expect(orbit.game.title == "Orbit Fixture" && orbit.game.subtitle == "1.0.0")
+ #expect(orbit.game.title == "Orbit Fixture" && orbit.game.subtitle == "Version 1.0.0" && orbit.game.recentlyPlayed == nil)
#expect(orbit.game.state == .needsGameData)
#expect(orbit.sections.map(\.title) == ["Game", "Performance"])
#expect(orbit.dataSource == "" && !orbit.dataNote.isEmpty)
#expect(orbit.cloudSaves == nil && orbit.dlc == "No additional content")
#expect(try detail(model, Fixtures.chain).game.state == .needsAppUpdate)
- #expect(try detail(model, Fixtures.noFramework).game.state == .broken(reason: "Game code missing", detail: "DmGame.framework is not in this game's folder. Install the game again."))
+ #expect(try detail(model, Fixtures.noFramework).game.state == .broken(reason: "Game code missing", detail: "The game's code is missing from this app. Rebuild and reinstall it.",
+ technical: "DmGame.framework is not in this game's folder. Install the game again."))
#expect(try detail(model, Fixtures.badManifest).sections.isEmpty)
}
@@ -239,4 +243,93 @@ final class RecordingLauncher: GameLauncher, @unchecked Sendable {
let c = ConnectedController(id: "a", name: "Pro Controller", player: 2, family: .nintendo, batteryPercent: 40, charging: true)
#expect(ShellHostModel.info(for: c) == ControllerInfo(id: "a", name: "Pro Controller", player: "Player 2", batteryPercent: 40, charging: true))
}
+
+ // MARK: Messages, order, last played
+
+ @Test func brokenGamesShowPlayerSentencesAndKeepTheTechnicalMessage() throws {
+ let box = try Sandbox()
+ let model = ShellHostModel(config: box.config())
+ func broken(_ id: String) throws -> (reason: String, detail: String, technical: String) {
+ guard case .broken(let r, let d, let t) = try detail(model, id).game.state else { throw Failure() }
+ return (r, d, t)
+ }
+ let settings = try broken(Fixtures.badSettings)
+ #expect(settings.detail == "This game's settings list is damaged. Rebuild the game in the launcher on your Mac.")
+ #expect(settings.technical == "DM_X is a choice without [value, label] options.")
+ let code = try broken(Fixtures.noFramework)
+ #expect(code.detail == "The game's code is missing from this app. Rebuild and reinstall it.")
+ #expect(code.technical.contains("DmGame.framework"))
+ #expect(try broken(Fixtures.badManifest).detail == "This game's manifest is damaged. Rebuild the game in the launcher on your Mac.")
+ #expect(try broken(Fixtures.missingKey).detail == "This game's manifest is damaged. Rebuild the game in the launcher on your Mac.")
+ #expect(try broken(Fixtures.badManifest).technical.contains("not valid JSON"))
+ for id in [Fixtures.badSettings, Fixtures.noFramework, Fixtures.badManifest, Fixtures.missingKey] {
+ let b = try broken(id)
+ #expect(!b.detail.contains("DM_") && !b.detail.contains("json") && !b.detail.contains(";") && !b.detail.contains(";"))
+ }
+ }
+
+ @Test func everyCauseHasItsOwnSentence() {
+ let causes: [ProblemCause] = [.manifestMissing, .manifestDamaged, .manifestUnsupported, .settingsMissing, .settingsDamaged,
+ .settingsUnsupported, .codeMissing, .filesDamaged]
+ #expect(ProblemCause.manifestMissing.message == "This game's manifest is missing. Rebuild the game in the launcher on your Mac.")
+ #expect(ProblemCause.settingsMissing.message == "This game's settings list is missing. Rebuild the game in the launcher on your Mac.")
+ #expect(ProblemCause.manifestUnsupported.message == "This game was built for a different version of this app. Update the app or rebuild the game in the launcher on your Mac.")
+ #expect(ProblemCause.settingsUnsupported.message == ProblemCause.manifestUnsupported.message)
+ #expect(ProblemCause.filesDamaged.message == "This game's files are damaged. Rebuild the game in the launcher on your Mac.")
+ #expect(causes.allSatisfy { !$0.message.isEmpty && !$0.message.contains(";") })
+ let problem = GameProblem(cause: .settingsDamaged, reason: "Settings list damaged", detail: "raw")
+ #expect(problem.state == .broken(reason: "Settings list damaged", detail: ProblemCause.settingsDamaged.message, technical: "raw"))
+ }
+
+ @Test func libraryStartsWithPlayableThenDataThenUpdateThenBroken() throws {
+ let box = try Sandbox()
+ try box.giveAppData()
+ let model = ShellHostModel(config: box.config())
+ // Orbit playable, Quiet and the missing-framework game and others by state, alphabetical within a group.
+ let ids = model.details.map(\.id)
+ #expect(ids.first == Fixtures.orbit)
+ let rank = model.details.map { d -> Int in
+ switch d.game.state { case .playable: 1; case .needsGameData: 2; case .needsAppUpdate: 3; case .broken: 4 }
+ }
+ #expect(rank == rank.sorted())
+ let broken = model.details.filter { if case .broken = $0.game.state { true } else { false } }.map(\.game.title)
+ #expect(broken == broken.sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending })
+ #expect(model.details.map(\.id) == model.entries.map(\.id))
+ #expect(model.details.first?.game.title != "Bad Settings Fixture")
+ }
+
+ @Test func recentlyPlayedComesFirstAndPlayRecordsTheDate() async throws {
+ let box = try Sandbox()
+ try box.giveAppData()
+ let clock = Clock(Date(timeIntervalSince1970: 1_000_000))
+ let config = box.config(now: { clock.date })
+ let model = ShellHostModel(config: config)
+ await model.playNow(Fixtures.orbit) // the stub launcher fails, the date is stored anyway
+ #expect(LastPlayedStore(defaults: box.defaults(Fixtures.orbit)).date == clock.date)
+ #expect(try detail(model).game.recentlyPlayed == "Played today")
+ #expect(model.details.first?.id == Fixtures.orbit, "no reorder under the player's finger")
+ // A second playable game, played later, goes first after the next reload.
+ try box.giveAppData(Fixtures.chain)
+ let quiet = "0100000000080000"
+ try box.giveAppData(quiet)
+ clock.date = clock.date.addingTimeInterval(3600)
+ let other = ShellHostModel(config: config)
+ await other.playNow(quiet)
+ #expect(other.details.first?.id == Fixtures.orbit || other.details.first?.id == quiet)
+ other.reload()
+ #expect(other.details.prefix(2).map(\.id) == [quiet, Fixtures.orbit])
+ // A broken game is last even after its neighbours were played.
+ #expect(other.details.last.map { if case .broken = $0.game.state { true } else { false } } == true)
+ }
+
+ @Test func selectionOrderStaysWhenOneGameChangesState() throws {
+ let box = try Sandbox()
+ let model = ShellHostModel(config: box.config())
+ let before = model.details.map(\.id)
+ try box.giveAppData()
+ model.useAppData(Fixtures.orbit) // refresh: orbit becomes playable without a re-sort
+ #expect(model.details.map(\.id) == before)
+ model.reload()
+ #expect(model.details.first?.id == Fixtures.orbit)
+ }
}
diff --git a/frontend-ios/Tests/ShellHostTests/TestSupport.swift b/frontend-ios/Tests/ShellHostTests/TestSupport.swift
index af2e921d..b86750af 100644
--- a/frontend-ios/Tests/ShellHostTests/TestSupport.swift
+++ b/frontend-ios/Tests/ShellHostTests/TestSupport.swift
@@ -23,16 +23,17 @@ final class Sandbox: @unchecked Sendable {
}
deinit {
try? FileManager.default.removeItem(at: root)
- for id in ["0100000000010000", "0100000000020000", "0100000000030000"] { UserDefaults().removePersistentDomain(forName: suite + id) }
+ for id in ["0100000000010000", "0100000000020000", "0100000000030000", "0100000000040000", "0100000000080000"] { UserDefaults().removePersistentDomain(forName: suite + id) }
}
func defaults(_ id: String) -> UserDefaults { UserDefaults(suiteName: suite + id)! }
func config(chain: String? = "b-3f9a2c", os: OperatingSystemVersion = OperatingSystemVersion(majorVersion: 26, minorVersion: 0, patchVersion: 0),
- updateURL: URL? = nil, open: @escaping @MainActor @Sendable (URL) -> Void = { _ in }) -> ShellHostConfig {
+ updateURL: URL? = nil, open: @escaping @MainActor @Sendable (URL) -> Void = { _ in },
+ now: @escaping @Sendable () -> Date = { Date() }) -> ShellHostConfig {
let suite = suite
return ShellHostConfig(gamesRoot: games, appDataRoot: appData, environment: HostEnvironment(chain: chain, osVersion: os),
- updateURL: updateURL, defaults: { UserDefaults(suiteName: suite + $0)! }, openURL: open)
+ updateURL: updateURL, defaults: { UserDefaults(suiteName: suite + $0)! }, openURL: open, now: now)
}
/// The game's app data folder with the marker file the orbit fixture's manifest names (not game data: an empty file).
diff --git a/frontend-ios/Tests/ShellUITests/FormatTests.swift b/frontend-ios/Tests/ShellUITests/FormatTests.swift
new file mode 100644
index 00000000..1c298412
--- /dev/null
+++ b/frontend-ios/Tests/ShellUITests/FormatTests.swift
@@ -0,0 +1,38 @@
+import Foundation
+import Testing
+@testable import ShellUI
+
+@Suite struct FormatTests {
+ private var calendar: Calendar {
+ var c = Calendar(identifier: .gregorian)
+ c.timeZone = TimeZone(identifier: "UTC")!
+ return c
+ }
+ private let en = Locale(identifier: "en_US")
+ private var now: Date { calendar.date(from: DateComponents(year: 2026, month: 10, day: 30, hour: 9))! }
+ private func ago(_ days: Int, hour: Int = 23) -> Date {
+ calendar.date(byAdding: .day, value: -days, to: calendar.date(bySettingHour: hour, minute: 0, second: 0, of: now)!)!
+ }
+
+ @Test func versionHasItsWord() {
+ #expect(ShellFormat.version("1.0.0") == "Version 1.0.0")
+ #expect(ShellFormat.version("") == "")
+ }
+
+ @Test func playedIsCountedInCalendarDays() {
+ #expect(ShellFormat.played(now, now: now, calendar: calendar, locale: en) == "Played today")
+ #expect(ShellFormat.played(ago(0, hour: 0), now: now, calendar: calendar, locale: en) == "Played today")
+ #expect(ShellFormat.played(ago(1), now: now, calendar: calendar, locale: en) == "Played yesterday")
+ #expect(ShellFormat.played(ago(3), now: now, calendar: calendar, locale: en) == "Played 3 days ago")
+ #expect(ShellFormat.played(ago(14), now: now, calendar: calendar, locale: en) == "Played 2 weeks ago")
+ #expect(ShellFormat.played(now.addingTimeInterval(86_400 * 2), now: now, calendar: calendar, locale: en) == "Played today", "a clock set back never says tomorrow")
+ }
+
+ @Test func versionLineJoinsWithAMiddleDot() {
+ #expect(ShellFormat.versionLine(version: "1.0.0", lastPlayed: nil, now: now, calendar: calendar, locale: en) == "Version 1.0.0")
+ #expect(ShellFormat.versionLine(version: "1.0.0", lastPlayed: now, now: now, calendar: calendar, locale: en) == "Version 1.0.0 · Played today")
+ #expect(ShellFormat.versionLine(version: "2.0.1", lastPlayed: ago(1), now: now, calendar: calendar, locale: en) == "Version 2.0.1 · Played yesterday")
+ #expect(ShellFormat.metaLine("Version 1.0.0", nil) == "Version 1.0.0")
+ #expect(ShellFormat.metaLine("", "Played today") == "Played today")
+ }
+}
diff --git a/frontend-ios/UITests/ShellHostUITests.swift b/frontend-ios/UITests/ShellHostUITests.swift
index 96b1c380..042613b1 100644
--- a/frontend-ios/UITests/ShellHostUITests.swift
+++ b/frontend-ios/UITests/ShellHostUITests.swift
@@ -27,6 +27,30 @@ import XCTest
launch(select: "0100000000040000")
XCTAssertEqual(app.staticTexts["hero.title"].label, "No Framework Fixture")
XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS[c] 'Game code missing'")).firstMatch.waitForExistence(timeout: 5))
+ // The hero says what to do, not the parser's message.
+ XCTAssertTrue(app.staticTexts["The game's code is missing from this app. Rebuild and reinstall it."].exists)
+ XCTAssertFalse(app.staticTexts.matching(NSPredicate(format: "label CONTAINS 'DmGame.framework'")).firstMatch.exists)
+ }
+
+ func testBadSettingsShowsASentenceAndKeepsTheRawMessageInDetails() {
+ launch(select: "0100000000070000")
+ XCTAssertTrue(app.staticTexts["This game's settings list is damaged. Rebuild the game in the launcher on your Mac."].exists)
+ XCTAssertFalse(app.staticTexts.matching(NSPredicate(format: "label CONTAINS 'DM_X'")).firstMatch.exists)
+ let fix = app.buttons.matching(identifier: "state.action").allElementsBoundByIndex.first { $0.isHittable }
+ fix?.tap()
+ XCTAssertTrue(app.staticTexts["help.title"].waitForExistence(timeout: 5))
+ XCTAssertTrue(app.staticTexts["DM_X is a choice without [value, label] options."].waitForExistence(timeout: 5))
+ XCTAssertTrue(app.staticTexts["Details"].exists)
+ }
+
+ func testLibraryStartsOnAPlayableGameWithTheVersionLine() {
+ XCUIDevice.shared.orientation = .portrait
+ app.launchArguments = ["--host"]
+ app.launch()
+ XCTAssertTrue(app.staticTexts["hero.title"].waitForExistence(timeout: 10))
+ XCTAssertNotEqual(app.staticTexts["hero.title"].label, "Bad Settings Fixture")
+ XCTAssertEqual(app.staticTexts["hero.title"].label, "Orbit Fixture")
+ XCTAssertTrue(app.staticTexts["Version 1.0.0"].exists)
}
func testSettingChangeSurvivesReopeningSettings() {