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: card-as-button Cover Flow, full-bleed hero, controllers, Mac type scale

v0lumehicde496cfac7e
diff --git a/frontend-ios/Demo/ShellDemo.xcodeproj/project.pbxproj b/frontend-ios/Demo/ShellDemo.xcodeproj/project.pbxproj
index 22d942b3..9ab83d81 100644
--- a/frontend-ios/Demo/ShellDemo.xcodeproj/project.pbxproj
+++ b/frontend-ios/Demo/ShellDemo.xcodeproj/project.pbxproj
@@ -12,9 +12,9 @@
3E143B39E0F97A669D2F6EFF /* ShellAdditionalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF3DBBE6BC067DDD34E3560C /* ShellAdditionalTests.swift */; };
44E0EBFDB9557A0C8BB741BE /* ShellUI in Frameworks */ = {isa = PBXBuildFile; productRef = 7F6858A53523100F9E10590E /* ShellUI */; };
4749F987D74B27CAA0E02480 /* ShellDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59E0A7AE45425C5BA9689FE4 /* ShellDemoApp.swift */; };
+ 876E4B3FCD4C78C4085BCE30 /* ShellControllers in Frameworks */ = {isa = PBXBuildFile; productRef = D58DB30045BDC25980479EF9 /* ShellControllers */; };
D94D715334EE4F5E0CCBA788 /* SampleArt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39DB78D11BCF59879A3712F5 /* SampleArt.swift */; };
DF097C40B129901722DD4DF3 /* ShellDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 916109EC3198FC9C0E9D655B /* ShellDemoUITests.swift */; };
- E305EAC2B52CE23FC907C7C7 /* DemoControllerInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = 779E0E026682ED6CDDF647C6 /* DemoControllerInput.swift */; };
E71FEFEAE303CA4343BBDE2E /* SampleData.swift in Sources */ = {isa = PBXBuildFile; fileRef = CBE23919FFDC3D06EF0D3065 /* SampleData.swift */; };
F15D381F62331B5172AD6D22 /* Localizable.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = D1591481D38DDC20A1A9B215 /* Localizable.xcstrings */; };
/* End PBXBuildFile section */
@@ -32,7 +32,6 @@
/* Begin PBXFileReference section */
39DB78D11BCF59879A3712F5 /* SampleArt.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SampleArt.swift; sourceTree = "<group>"; };
59E0A7AE45425C5BA9689FE4 /* ShellDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShellDemoApp.swift; sourceTree = "<group>"; };
- 779E0E026682ED6CDDF647C6 /* DemoControllerInput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoControllerInput.swift; sourceTree = "<group>"; };
8694319745E3759D50772855 /* ShellCaptureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShellCaptureTests.swift; sourceTree = "<group>"; };
916109EC3198FC9C0E9D655B /* ShellDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShellDemoUITests.swift; sourceTree = "<group>"; };
B1D199F3FD9C677BD245559E /* ShellDemoApp.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = ShellDemoApp.app; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -50,6 +49,7 @@
buildActionMask = 2147483647;
files = (
44E0EBFDB9557A0C8BB741BE /* ShellUI in Frameworks */,
+ 876E4B3FCD4C78C4085BCE30 /* ShellControllers in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -67,7 +67,6 @@
5928E24F76B598AD8FD0D1AB /* ShellDemo */ = {
isa = PBXGroup;
children = (
- 779E0E026682ED6CDDF647C6 /* DemoControllerInput.swift */,
FF911DEE5C19B0D069418726 /* RealArt.swift */,
39DB78D11BCF59879A3712F5 /* SampleArt.swift */,
CBE23919FFDC3D06EF0D3065 /* SampleData.swift */,
@@ -134,6 +133,7 @@
name = ShellDemoApp;
packageProductDependencies = (
7F6858A53523100F9E10590E /* ShellUI */,
+ D58DB30045BDC25980479EF9 /* ShellControllers */,
);
productName = ShellDemoApp;
productReference = B1D199F3FD9C677BD245559E /* ShellDemoApp.app */;
@@ -210,7 +210,6 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
- E305EAC2B52CE23FC907C7C7 /* DemoControllerInput.swift in Sources */,
2EEF6A8F9A7D58C09181EAB5 /* RealArt.swift in Sources */,
D94D715334EE4F5E0CCBA788 /* SampleArt.swift in Sources */,
E71FEFEAE303CA4343BBDE2E /* SampleData.swift in Sources */,
@@ -484,6 +483,10 @@
isa = XCSwiftPackageProductDependency;
productName = ShellUI;
};
+ D58DB30045BDC25980479EF9 /* ShellControllers */ = {
+ isa = XCSwiftPackageProductDependency;
+ productName = ShellControllers;
+ };
/* End XCSwiftPackageProductDependency section */
};
rootObject = D41A7603C6BA5BB604CCFDE4 /* Project object */;
diff --git a/frontend-ios/Demo/project.yml b/frontend-ios/Demo/project.yml
index d3899b0e..62ceb563 100644
--- a/frontend-ios/Demo/project.yml
+++ b/frontend-ios/Demo/project.yml
@@ -28,6 +28,8 @@ targets:
dependencies:
- package: ShellUI
product: ShellUI
+ - package: ShellUI
+ product: ShellControllers
ShellDemoUITests:
type: bundle.ui-testing
platform: iOS
diff --git a/frontend-ios/Package.swift b/frontend-ios/Package.swift
index 6499bf61..fe2a1a19 100644
--- a/frontend-ios/Package.swift
+++ b/frontend-ios/Package.swift
@@ -6,11 +6,15 @@ let package = Package(
platforms: [.iOS(.v26), .macOS(.v26)],
products: [
.library(name: "ShellUI", targets: ["ShellUI"]),
+ // The controller adapter: GameController input turned into ShellInput, kept apart from the views.
+ .library(name: "ShellControllers", targets: ["ShellControllers"]),
.executable(name: "ShellDemo", targets: ["ShellDemo"])
],
targets: [
.target(name: "ShellUI", resources: [.process("Resources")]),
- .executableTarget(name: "ShellDemo", dependencies: ["ShellUI"], resources: [.process("Resources")]),
- .testTarget(name: "ShellUITests", dependencies: ["ShellUI"])
+ .target(name: "ShellControllers", dependencies: ["ShellUI"]),
+ .executableTarget(name: "ShellDemo", dependencies: ["ShellUI", "ShellControllers"], resources: [.process("Resources")]),
+ .testTarget(name: "ShellUITests", dependencies: ["ShellUI"]),
+ .testTarget(name: "ShellControllersTests", dependencies: ["ShellControllers", "ShellUI"])
]
)
diff --git a/frontend-ios/README.md b/frontend-ios/README.md
index ccdb3448..9113e9dc 100644
--- a/frontend-ios/README.md
+++ b/frontend-ios/README.md
@@ -29,7 +29,9 @@ All boundary types are in `Sources/ShellUI/ShellInputs.swift` and `ShellArtwork.
- `SettingSection`, `SettingRow`, `SettingKind`, `SettingOption`: ordered toggle, choice and range rows with string values, as in launcher.json. The caller resolves dependencies, defaults and locked rows (`enabled`).
- `ControllerInfo`: a connected controller, its player and an optional battery level.
- `ShellActions`: selection, Play, setting changes, game-data and cloud-folder requests, reset, log, app update and Back. The game ID is always passed.
-- `ShellInput`: an optional semantic controller event with an increasing sequence. Hardware belongs to the caller. The demo's `DemoControllerInput` is one such adapter.
+- `ShellInput`: an optional semantic controller event with an increasing sequence and the device that sent it (`InputDevice`: a controller family or the keyboard), so the hints draw that device's glyphs.
+
+`ShellControllers` is a separate library target, not part of the views: `GamepadAdapter` reads every GameController controller (D-pad and left stick with a deadzone and the Mac's repeat on hold, A activates, B goes back, X and Menu open game settings, Y opens Controllers, by label so each family confirms with its own button) and reports `ShellInput` actions and the connected controllers with their battery. Its pure mapping (`PadMapper`, `RepeatTiming`) is unit tested. The demo uses it, the real shell can too.
```swift
LibraryView(
@@ -55,7 +57,7 @@ Only the available size decides, never the device model, idiom or orientation (`
Settings appear only when asked for (the settings button, X on a controller) and close with Back, B or a tap outside. They are one view in one place for every layout, with the game's banner as their header, so the selected game, open settings and both scroll positions survive a fold, a rotation or a Stage Manager resize.
-Controller first: the D-pad and stick move a cream focus ring, A activates, B backs out, X opens settings, Y opens controllers. In Cover Flow, left and right move the carousel by one card and the focused card is always the middle one. Keyboard arrows, Return and Escape take the same path. Touch and pointer use ordinary controls.
+Controller first: the D-pad and stick move a cream focus ring, A activates, B backs out, X opens settings, Y opens controllers. In Cover Flow, left and right move the carousel by one card and the focused card is always the middle one. A hardware keyboard works the same way: arrows, Return, Escape, O for settings and Y for controllers. Touch hides the focus ring and the controller hints until the next press. In Cover Flow the centred card is the button: a tap does what the game needs, a tap on a side card brings it to the middle, a long press opens its settings.
Manrope and its SIL OFL licence are bundled and registered at runtime, with the system font as fallback. Reduce Motion turns the Cover Flow tilt and the slides into plain crossfades. Shell strings are in `Resources/Localizable.xcstrings`.
diff --git a/frontend-ios/Sources/ShellControllers/GamepadAdapter.swift b/frontend-ios/Sources/ShellControllers/GamepadAdapter.swift
new file mode 100644
index 00000000..c3f2f443
--- /dev/null
+++ b/frontend-ios/Sources/ShellControllers/GamepadAdapter.swift
@@ -0,0 +1,138 @@
+import Foundation
+import GameController
+import ShellUI
+
+/// A connected controller as the adapter sees it. The host turns it into a `ControllerInfo` with its own words.
+public struct ConnectedController: Equatable, Sendable {
+ public var id: String
+ public var name: String
+ /// 1 for the first controller connected.
+ public var player: Int
+ public var family: ControllerFamily
+ /// 0 to 100, nil when the controller does not report it.
+ public var batteryPercent: Int?
+ public var charging: Bool
+}
+
+/// Real controllers for the shell, on top of GameController: every controller GameController lists, wired or wireless,
+/// drives the views through `ShellInput` actions. The D-pad and the left stick move (held, they repeat), A activates,
+/// B goes back, X and Menu open the game's settings, Y opens Controllers. The device family goes with each action, so the
+/// hints draw that controller's own glyphs. Not part of the views: the host owns it and passes the actions on.
+@MainActor public final class GamepadAdapter {
+ public var onInput: (ShellInput.Action, InputDevice) -> Void = { _, _ in }
+ public var onControllersChange: ([ConnectedController]) -> Void = { _ in }
+
+ private var mapper = PadMapper()
+ private var observers: [NSObjectProtocol] = []
+ private var repeatTask: Task<Void, Never>?
+ private var repeating: (action: ShellInput.Action, controller: String)?
+ private var batteryTask: Task<Void, Never>?
+
+ public init() {}
+
+ public func start() {
+ stop()
+ let center = NotificationCenter.default
+ for name in [Notification.Name.GCControllerDidConnect, .GCControllerDidDisconnect] {
+ observers.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] note in
+ let disconnected = note.name == .GCControllerDidDisconnect
+ let gone = disconnected ? (note.object as? GCController) : nil
+ gone?.physicalInputProfile.valueDidChangeHandler = nil
+ let id = gone.map(Self.id(of:))
+ MainActor.assumeIsolated {
+ if let id {
+ self?.mapper.reset(controller: id)
+ if self?.repeating?.controller == id { self?.stopRepeat() }
+ }
+ self?.attach()
+ }
+ })
+ }
+ attach()
+ // Battery levels change slowly and GameController does not announce them: a look every 30 seconds.
+ batteryTask = Task { [weak self] in
+ while !Task.isCancelled {
+ try? await Task.sleep(for: .seconds(30))
+ self?.publish()
+ }
+ }
+ }
+
+ public func stop() {
+ observers.forEach(NotificationCenter.default.removeObserver)
+ observers.removeAll()
+ for pad in GCController.controllers() { pad.physicalInputProfile.valueDidChangeHandler = nil }
+ stopRepeat()
+ batteryTask?.cancel()
+ batteryTask = nil
+ }
+
+ private nonisolated static func id(of controller: GCController) -> String {
+ String(UInt(bitPattern: ObjectIdentifier(controller).hashValue), radix: 16)
+ }
+
+ private func attach() {
+ for pad in GCController.controllers() {
+ let id = Self.id(of: pad)
+ let family = ControllerFamily(productCategory: pad.productCategory)
+ pad.physicalInputProfile.valueDidChangeHandler = { [weak self] profile, _ in
+ let state = Self.state(of: profile)
+ MainActor.assumeIsolated { self?.read(state, controller: id, family: family) }
+ }
+ }
+ publish()
+ }
+
+ private nonisolated static func state(of pad: GCPhysicalInputProfile) -> PadState {
+ func pressed(_ name: String) -> Bool { pad.buttons[name]?.isPressed ?? false }
+ let dpad = pad.dpads[GCInputDirectionPad], stick = pad.dpads[GCInputLeftThumbstick]
+ let dx = dpad?.xAxis.value ?? 0, dy = dpad?.yAxis.value ?? 0
+ let x = dx != 0 ? dx : (stick?.xAxis.value ?? 0)
+ let y = dy != 0 ? dy : (stick?.yAxis.value ?? 0)
+ var buttons: Set<PadButton> = []
+ let names: [(String, PadButton)] = [(GCInputButtonA, .a), (GCInputButtonB, .b), (GCInputButtonX, .x), (GCInputButtonY, .y),
+ (GCInputButtonMenu, .menu), (GCInputButtonOptions, .options),
+ (GCInputLeftShoulder, .leftShoulder), (GCInputRightShoulder, .rightShoulder)]
+ for (name, button) in names where pressed(name) { buttons.insert(button) }
+ return PadState(x: x, y: y, buttons: buttons)
+ }
+
+ private func read(_ state: PadState, controller: String, family: ControllerFamily) {
+ let (pressed, released) = mapper.changes(controller: controller, state: state)
+ for action in released where repeating?.action == action && repeating?.controller == controller { stopRepeat() }
+ for action in pressed {
+ onInput(action, .controller(family))
+ if PadMapper.isDirection(action) { startRepeat(action, controller: controller, family: family) }
+ }
+ }
+
+ private func startRepeat(_ action: ShellInput.Action, controller: String, family: ControllerFamily) {
+ stopRepeat()
+ repeating = (action, controller)
+ repeatTask = Task { [weak self] in
+ try? await Task.sleep(for: .seconds(RepeatTiming.delay))
+ while !Task.isCancelled {
+ self?.onInput(action, .controller(family))
+ try? await Task.sleep(for: .seconds(RepeatTiming.interval))
+ }
+ }
+ }
+
+ private func stopRepeat() {
+ repeatTask?.cancel()
+ repeatTask = nil
+ repeating = nil
+ }
+
+ private func publish() {
+ let pads = GCController.controllers()
+ onControllersChange(pads.enumerated().map { index, pad in
+ let battery = pad.battery
+ let level = battery.map { Int(($0.batteryLevel * 100).rounded()) }
+ return ConnectedController(id: Self.id(of: pad), name: pad.vendorName ?? pad.productCategory,
+ player: index + 1, family: ControllerFamily(productCategory: pad.productCategory),
+ batteryPercent: battery?.batteryState == .unknown ? nil : level,
+ charging: battery?.batteryState == .charging)
+ })
+ }
+}
diff --git a/frontend-ios/Sources/ShellControllers/PadMapping.swift b/frontend-ios/Sources/ShellControllers/PadMapping.swift
new file mode 100644
index 00000000..3e735998
--- /dev/null
+++ b/frontend-ios/Sources/ShellControllers/PadMapping.swift
@@ -0,0 +1,102 @@
+import ShellUI
+
+/// A controller's buttons as GameController names them, by label. buttonA is the bottom of Apple's diamond: A on an
+/// Xbox controller, the cross on a PlayStation controller, and the button printed A (on the right) on a Nintendo
+/// controller, so every family confirms with its own button. The same mapping as the Mac launcher's console mode.
+public enum PadButton: Hashable, Sendable {
+ case a, b, x, y, menu, options, leftShoulder, rightShoulder
+}
+
+/// One controller's state at a moment: the D-pad or left stick as x and y from -1 to 1, and the buttons held.
+public struct PadState: Equatable, Sendable {
+ public var x: Float
+ public var y: Float
+ public var buttons: Set<PadButton>
+ public init(x: Float = 0, y: Float = 0, buttons: Set<PadButton> = []) {
+ self.x = x
+ self.y = y
+ self.buttons = buttons
+ }
+}
+
+/// Turns controller states into shell actions: one press, one action, per controller, so a button held on one
+/// controller never hides the same button on another. The pure part of the adapter, tested without hardware.
+public struct PadMapper: Sendable {
+ /// How far the stick or D-pad must move before it counts as a direction.
+ public static let deadzone: Float = 0.5
+
+ private var held: [String: Set<String>] = [:]
+ public init() {}
+
+ /// The action of each button: A activates, B goes back, X and Menu open the game's settings, Y opens Controllers.
+ public static func action(for button: PadButton) -> ShellInput.Action? {
+ switch button {
+ case .a: .activate
+ case .b: .back
+ case .x, .menu: .settings
+ case .y: .controllers
+ case .options, .leftShoulder, .rightShoulder: nil
+ }
+ }
+
+ /// The direction the state points to, the stronger axis winning, inside the deadzone none.
+ public static func direction(x: Float, y: Float) -> ShellInput.Action? {
+ if abs(x) >= abs(y) {
+ if x > deadzone { return .right }
+ if x < -deadzone { return .left }
+ } else {
+ if y > deadzone { return .up }
+ if y < -deadzone { return .down }
+ }
+ return nil
+ }
+
+ /// What changed for `controller`: the actions newly pressed and released.
+ public mutating func changes(controller: String, state: PadState) -> (pressed: [ShellInput.Action], released: [ShellInput.Action]) {
+ var now: [String: ShellInput.Action] = [:]
+ if let direction = Self.direction(x: state.x, y: state.y) { now["dir.\(direction)"] = direction }
+ for button in state.buttons {
+ if let action = Self.action(for: button) { now["btn.\(button)"] = action }
+ }
+ let before = held[controller] ?? []
+ let pressed = now.filter { !before.contains($0.key) }.sorted { $0.key < $1.key }.map(\.value)
+ let releasedKeys = before.subtracting(now.keys)
+ let released = releasedKeys.compactMap { key -> ShellInput.Action? in
+ guard key.hasPrefix("dir.") else { return nil }
+ return Self.directionAction(key)
+ }
+ held[controller] = Set(now.keys)
+ return (pressed, released)
+ }
+
+ /// Forget a controller, after it disconnects.
+ public mutating func reset(controller: String) { held[controller] = nil }
+
+ private static func directionAction(_ key: String) -> ShellInput.Action? {
+ switch key {
+ case "dir.left": .left
+ case "dir.right": .right
+ case "dir.up": .up
+ case "dir.down": .down
+ default: nil
+ }
+ }
+
+ static func isDirection(_ action: ShellInput.Action) -> Bool {
+ switch action {
+ case .left, .right, .up, .down: true
+ default: false
+ }
+ }
+}
+
+/// A held direction repeats like the Mac launcher's: after 0.4 s, then every 0.12 s.
+public enum RepeatTiming {
+ public static let delay = 0.4
+ public static let interval = 0.12
+ /// How many moves a direction held for `seconds` makes, the first press included.
+ public static func moves(heldFor seconds: Double) -> Int {
+ guard seconds >= delay else { return 1 }
+ return 2 + Int(((seconds - delay) / interval).rounded(.down))
+ }
+}
diff --git a/frontend-ios/Sources/ShellDemo/DemoControllerInput.swift b/frontend-ios/Sources/ShellDemo/DemoControllerInput.swift
deleted file mode 100644
index e6f00280..00000000
--- a/frontend-ios/Sources/ShellDemo/DemoControllerInput.swift
+++ /dev/null
@@ -1,64 +0,0 @@
-#if os(iOS)
-import GameController
-import ShellUI
-
-/// Hardware adapter belongs to the demo, never ShellUI. The real shell can use its own adapter.
-@MainActor final class DemoControllerInput {
- private var observers: [NSObjectProtocol] = []
- private var send: ((ShellInput.Action) -> Void)?
- private var heldDirection: ShellInput.Action?
- private var repeatTask: Task<Void, Never>?
-
- func start(send: @escaping (ShellInput.Action) -> Void) {
- stop()
- self.send = send
- observers.append(NotificationCenter.default.addObserver(forName: .GCControllerDidConnect, object: nil, queue: .main) { [weak self] _ in
- MainActor.assumeIsolated { self?.bind() }
- })
- observers.append(NotificationCenter.default.addObserver(forName: .GCControllerDidDisconnect, object: nil, queue: .main) { [weak self] _ in
- MainActor.assumeIsolated { self?.direction(nil) }
- })
- bind()
- }
- func stop() {
- for observer in observers { NotificationCenter.default.removeObserver(observer) }
- observers.removeAll()
- for controller in GCController.controllers() { controller.extendedGamepad?.valueChangedHandler = nil }
- repeatTask?.cancel()
- heldDirection = nil
- send = nil
- }
- private func bind() {
- for controller in GCController.controllers() {
- controller.extendedGamepad?.valueChangedHandler = { [weak self] pad, element in
- // GameController may call on its handler queue. Cross to the UI actor explicitly.
- let x = abs(pad.dpad.xAxis.value) > 0.4 ? pad.dpad.xAxis.value : pad.leftThumbstick.xAxis.value
- let y = abs(pad.dpad.yAxis.value) > 0.4 ? pad.dpad.yAxis.value : pad.leftThumbstick.yAxis.value
- let direction: ShellInput.Action? = abs(x) > abs(y) && abs(x) > 0.5 ? (x > 0 ? .right : .left) : abs(y) > 0.5 ? (y > 0 ? .up : .down) : nil
- let action: ShellInput.Action? = element == pad.buttonA && pad.buttonA.isPressed ? .activate
- : element == pad.buttonB && pad.buttonB.isPressed ? .back
- : element == pad.buttonX && pad.buttonX.isPressed ? .settings
- : element == pad.buttonY && pad.buttonY.isPressed ? .controllers : nil
- Task { @MainActor in
- self?.direction(direction)
- if let action { self?.send?(action) }
- }
- }
- }
- }
- private func direction(_ action: ShellInput.Action?) {
- guard action != heldDirection else { return }
- repeatTask?.cancel()
- heldDirection = action
- guard let action else { return }
- send?(action)
- repeatTask = Task { [weak self] in
- try? await Task.sleep(for: .milliseconds(350))
- while !Task.isCancelled {
- self?.send?(action)
- try? await Task.sleep(for: .milliseconds(140))
- }
- }
- }
-}
-#endif
diff --git a/frontend-ios/Sources/ShellDemo/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellDemo/Resources/Localizable.xcstrings
index f9b5e527..eed6f519 100644
--- a/frontend-ios/Sources/ShellDemo/Resources/Localizable.xcstrings
+++ b/frontend-ios/Sources/ShellDemo/Resources/Localizable.xcstrings
@@ -241,6 +241,16 @@
}
}
},
+ "Player %lld": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Player %lld"
+ }
+ }
+ }
+ },
"Player 1": {
"localizations": {
"en": {
diff --git a/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift b/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift
index ed705f16..d55f499b 100644
--- a/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift
+++ b/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift
@@ -1,5 +1,6 @@
import SwiftUI
import ShellUI
+import ShellControllers
@main struct ShellDemoApp: App {
var body: some Scene { WindowGroup { DemoScreen() } }
@@ -11,9 +12,9 @@ struct DemoScreen: View {
@State private var notice: String?
@State private var input: ShellInput?
@State private var unfolded = ProcessInfo.processInfo.arguments.contains("--unfolded")
- #if os(iOS)
- @State private var controller = DemoControllerInput()
- #endif
+ /// Real controllers, through the reusable adapter in ShellControllers.
+ @State private var gamepads = GamepadAdapter()
+ @State private var connected: [ConnectedController] = []
private var args: [String] { ProcessInfo.processInfo.arguments }
private func value(_ flag: String) -> String? {
guard let i = args.firstIndex(of: flag), args.indices.contains(i + 1) else { return nil }
@@ -55,15 +56,17 @@ struct DemoScreen: View {
.alert("Demo action", isPresented: Binding(get: { notice != nil }, set: { if !$0 { notice = nil } })) {
Button("OK") { notice = nil }
} message: { Text(notice ?? "") }
- #if os(iOS)
- .onAppear { controller.start { action in send(action) } }
- .onDisappear { controller.stop() }
- #endif
+ .onAppear {
+ gamepads.onInput = { action, device in send(action, from: device) }
+ gamepads.onControllersChange = { connected = $0 }
+ gamepads.start()
+ }
+ .onDisappear { gamepads.stop() }
}
private var shell: some View {
LibraryView(games: shown,
- controllers: scenario == "controllers-empty" ? [] : SampleData.controllers,
+ controllers: scenario == "controllers-empty" ? [] : controllers,
actions: actions, input: input, initialSelection: initialSelection,
initialDetailOpen: scenario == "settings",
initialControllersOpen: scenario.hasPrefix("controllers"),
@@ -105,7 +108,17 @@ struct DemoScreen: View {
default: .settings
}
}
- private func send(_ action: ShellInput.Action) { input = ShellInput(sequence: (input?.sequence ?? 0) + 1, action: action) }
+ private func send(_ action: ShellInput.Action, from device: InputDevice = .controller(.neutral)) {
+ input = ShellInput(sequence: (input?.sequence ?? 0) + 1, action: action, device: device)
+ }
+ /// The real controllers when any are connected, the sample ones otherwise.
+ private var controllers: [ControllerInfo] {
+ if !connected.isEmpty {
+ return connected.map { ControllerInfo(id: $0.id, name: $0.name, player: demoText("Player \($0.player)"),
+ batteryPercent: $0.batteryPercent, charging: $0.charging) }
+ }
+ return SampleData.controllers
+ }
private var actions: ShellActions {
ShellActions(onPlay: { _ in notice = demoText("Play requested. The demo does not launch games.") },
onChange: { game, row, value in
diff --git a/frontend-ios/Sources/ShellUI/ControllersView.swift b/frontend-ios/Sources/ShellUI/ControllersView.swift
index ed04b44f..659f4c55 100644
--- a/frontend-ios/Sources/ShellUI/ControllersView.swift
+++ b/frontend-ios/Sources/ShellUI/ControllersView.swift
@@ -14,7 +14,7 @@ public struct ControllersView: View {
ScrollView {
VStack(alignment: .leading, spacing: 30) {
HStack(alignment: .center) {
- Text(ShellStrings.text("Controllers")).shellText(30, .heavy, relativeTo: .title).tracking(-0.8)
+ Text(ShellStrings.text("Controllers")).shellType(ShellType.pageTitle)
.lineLimit(1).minimumScaleFactor(0.7).accessibilityAddTraits(.isHeader)
Spacer(minLength: 8)
Button(action: onBack) { Image(systemName: "xmark") }
@@ -46,10 +46,10 @@ public struct ControllersView: View {
VStack(alignment: .leading, spacing: 14) {
SectionHeading(title: ShellStrings.text("On a controller"))
hint(Image(systemName: "dpad"), ShellStrings.text("Move between controls"))
- hint(ButtonGlyph(letter: "A"), ShellStrings.text("Select"))
- hint(ButtonGlyph(letter: "B"), ShellStrings.text("Back"))
- hint(ButtonGlyph(letter: "X"), ShellStrings.text("Game settings"))
- hint(ButtonGlyph(letter: "Y"), ShellStrings.text("Controllers"))
+ hint(ButtonGlyph(role: .activate), ShellStrings.text("Select"))
+ hint(ButtonGlyph(role: .back), ShellStrings.text("Back"))
+ hint(ButtonGlyph(role: .settings), ShellStrings.text("Game settings"))
+ hint(ButtonGlyph(role: .controllers), ShellStrings.text("Controllers"))
}.padding(.horizontal, 4)
}.padding(24).padding(.bottom, geometry.safeAreaInsets.bottom).frame(maxWidth: 640)
.frame(maxWidth: .infinity, alignment: .leading)
diff --git a/frontend-ios/Sources/ShellUI/CoverFlowView.swift b/frontend-ios/Sources/ShellUI/CoverFlowView.swift
index c3e56a2f..e7c232a6 100644
--- a/frontend-ios/Sources/ShellUI/CoverFlowView.swift
+++ b/frontend-ios/Sources/ShellUI/CoverFlowView.swift
@@ -1,31 +1,44 @@
import SwiftUI
-/// The library when it is wider than it is tall: one cover in the middle, its neighbours turned back, the title,
-/// state and primary action underneath. The backdrop (the blurred cover) is drawn by the library behind the safe area.
-struct CoverFlowView: View {
+/// The library when it is wider than it is tall: one card in the middle, its neighbours turned back, the title and
+/// state underneath. The card is the button: a tap on the centred card does what the game needs (Play, choose its
+/// data, how to fix it). The backdrop (the blurred banner) is drawn by the library behind the safe area.
+struct CoverFlowView: View, Equatable {
let games: [GameDetail]
let selected: GameDetail
let controllers: Int
+ /// The controller hints at the bottom, while a controller or keyboard is in use.
let showsHints: Bool
let select: (String) -> Void
let primary: (GameDetail) -> Void
let openSettings: () -> Void
let openControllers: () -> Void
@State private var centredID: String?
- /// How far the carousel is scrolled: 0 with the first cover in the middle.
+ /// How far the carousel is scrolled: 0 with the first card in the middle.
@State private var scrolled: CGFloat = 0
+ /// True from the first touch of a scroll until it has settled.
@State private var userScrolling = false
+ /// The card nearest the middle when the current touch began, also mid-snap, for one card per gesture.
+ @State private var gestureStart = 0
/// False while the carousel scrolls, decelerates or snaps: a tap on the centre card then does nothing.
@State private var settled = true
+ /// A long press on the centre card opened settings: the touch that ends it must not also play.
+ @State private var longPressed = false
@Environment(\.accessibilityReduceMotion) private var reduceMotion
- @Environment(\.dynamicTypeSize) private var typeSize
+
+ /// Re-render only for what is drawn: the games' tiles, the selection and the hints. Settings changes elsewhere do
+ /// not reach the carousel.
+ nonisolated static func == (lhs: Self, rhs: Self) -> Bool {
+ lhs.games.map(\.game) == rhs.games.map(\.game) && lhs.selected.game == rhs.selected.game
+ && lhs.controllers == rhs.controllers && lhs.showsHints == rhs.showsHints
+ }
var body: some View {
GeometryReader { geometry in
let short = geometry.size.height < 520
// A wide card as large as the Mac console's focused tile: what the height allows, never so wide that the
// neighbours vanish.
- let cardHeight = max(90, min(geometry.size.height * 0.42, geometry.size.width * 0.52 * 9 / 16))
+ let cardHeight = max(90, min(geometry.size.height * (short ? 0.5 : 0.46), geometry.size.width * 0.54 * 9 / 16))
let cover = cardHeight * 16 / 9
VStack(spacing: 0) {
topBar.padding(.horizontal, 24).padding(.top, short ? 4 : 16)
@@ -34,42 +47,45 @@ struct CoverFlowView: View {
if games.count <= 3 { shelf(width: geometry.size.width, cover: cover) } else { carousel(width: geometry.size.width, cover: cover) }
}.frame(height: cover * 9 / 16 * 1.06)
info(short: short, width: geometry.size.width)
- .padding(.top, short ? 14 : 28).padding(.horizontal, 24)
+ .padding(.top, short ? 12 : 26).padding(.horizontal, 24)
Spacer(minLength: short ? 4 : 12)
- if showsHints && !short {
- hints.padding(.bottom, 20)
- }
+ // The hint row keeps its place when it is hidden, so the card does not move when it appears.
+ hints.opacity(showsHints ? 1 : 0).padding(.bottom, short ? 6 : 20)
}
}
.sensoryFeedback(.selection, trigger: selected.id)
.onAppear { centredID = selected.id }
- .onChange(of: centredID) { _, id in
- // Only a scroll the player makes chooses a game. A scroll this view animates (after the D-pad or a tap)
- // passes other covers on the way and must not choose them.
- if userScrolling, let id, id != selected.id { select(id) }
- }
.onChange(of: selected.id) { _, id in
- guard centredID != id else { return }
- withAnimation(reduceMotion ? nil : .smooth(duration: 0.32)) { centredID = id }
+ // A selection from the D-pad or a tap scrolls the carousel. Never while the player is touching it or it is
+ // still moving: the player's gesture always wins.
+ guard centredID != id, !userScrolling else { return }
+ withAnimation(reduceMotion ? nil : .smooth(duration: 0.3)) { centredID = id }
}
}
private var topBar: some View {
- HStack(alignment: .center) {
+ HStack(alignment: .center, spacing: 10) {
SectionHeading(title: ShellStrings.text("Your games"))
Text(ShellStrings.text("\(position) of \(games.count)")).shellText(12, .medium, relativeTo: .caption)
- .monospacedDigit().foregroundStyle(.white.opacity(0.45)).padding(.leading, 6)
+ .monospacedDigit().foregroundStyle(.white.opacity(0.45)).padding(.leading, 4)
Spacer(minLength: 12)
+ Button(action: openSettings) { Image(systemName: "slider.horizontal.3").frame(minWidth: 18) }
+ .buttonStyle(ChipButtonStyle())
+ .accessibilityLabel(ShellStrings.text("Game settings") + ", " + selected.game.title)
+ .accessibilityIdentifier("settings.open")
+ .shellTarget("lib.settings", radius: 22, action: openSettings)
ControllerChip(count: controllers, action: openControllers)
}
}
private var position: Int { (games.firstIndex { $0.id == selected.id } ?? 0) + 1 }
+ private var selectedIndex: Int { games.firstIndex { $0.id == selected.id } ?? 0 }
- /// More than three games: a snapping carousel. The neighbours turn back a little and tuck behind the middle card,
- /// a deck rather than a row, which suits wide banners better than the steep turn of square covers.
+ /// More than three games: a carousel that moves one card per gesture, the neighbours turned back a little and
+ /// tucked behind the middle card, a deck rather than a row.
private func carousel(width: CGFloat, cover: CGFloat) -> some View {
let spacing = cover * 0.04
let stride = cover + spacing
+ let margin = max(0, (width - cover) / 2)
return ScrollView(.horizontal) {
LazyHStack(spacing: spacing) {
ForEach(Array(games.enumerated()), id: \.element.id) { index, detail in
@@ -80,26 +96,29 @@ struct CoverFlowView: View {
}
}.scrollTargetLayout()
}
- .scrollTargetBehavior(.viewAligned)
+ .scrollTargetBehavior(CardSnap(stride: stride, count: games.count, start: gestureStart))
.scrollPosition(id: $centredID, anchor: .center)
- .contentMargins(.horizontal, max(0, (width - cover) / 2), for: .scrollContent)
+ .contentMargins(.horizontal, margin, for: .scrollContent)
.onScrollGeometryChange(for: CGFloat.self) { $0.contentOffset.x + $0.contentInsets.leading } action: { _, offset in
scrolled = offset
}
- .onScrollPhaseChange { _, phase in
- // A touch scroll goes interacting, decelerating, sometimes animating (the snap), then idle. The flag holds
- // until idle, so the snap that ends a swipe still counts as the player's. A scroll this view animates
- // starts from idle and never sets it.
+ .onScrollPhaseChange { old, phase, context in
+ // A touch scroll goes interacting, decelerating, maybe animating (the snap), then idle. Only once it has
+ // settled does the card in the middle become the selection, read from the final offset itself, so a stale
+ // value can never send the carousel back. A scroll this view animates starts from idle and never sets the
+ // flag, so it never selects.
settled = phase == .idle
+ if phase == .interacting && old != .interacting {
+ let offset = context.geometry.contentOffset.x + context.geometry.contentInsets.leading
+ gestureStart = min(games.count - 1, max(0, Int((offset / stride).rounded())))
+ }
switch phase {
case .interacting, .decelerating: userScrolling = true
case .idle:
if userScrolling {
- // The card in the middle once the scroll has settled, from the offset itself.
- let index = min(games.count - 1, max(0, Int((scrolled / stride).rounded())))
- let id = games[index].id
- if centredID != id { centredID = id }
- if id != selected.id { select(id) }
+ let offset = context.geometry.contentOffset.x + context.geometry.contentInsets.leading
+ let index = min(games.count - 1, max(0, Int((offset / stride).rounded())))
+ if games[index].id != selected.id { select(games[index].id) }
}
userScrolling = false
default: break
@@ -112,7 +131,7 @@ struct CoverFlowView: View {
/// One to three games: they sit together in the middle, the chosen one in front and larger. No empty track.
private func shelf(width: CGFloat, cover: CGFloat) -> some View {
let card = min(cover, width / (1 + CGFloat(games.count - 1) * 0.8))
- let chosenIndex = games.firstIndex { $0.id == selected.id } ?? 0
+ let chosenIndex = selectedIndex
return ZStack {
ForEach(Array(games.enumerated()), id: \.element.id) { index, detail in
let chosen = index == chosenIndex
@@ -130,13 +149,14 @@ struct CoverFlowView: View {
private func coverButton(_ detail: GameDetail, cover: CGFloat) -> some View {
let chosen = detail.id == selected.id
return Button {
- // The centred card acts like the button under it, once the carousel has settled. A side card only comes
- // to the middle and never starts anything.
+ // The centred card acts like the game's primary action, once the carousel has settled. A side card only
+ // comes to the middle and never starts anything.
+ if longPressed { longPressed = false; return }
if chosen {
if settled { primary(detail) }
return
}
- withAnimation(reduceMotion ? nil : .smooth(duration: 0.32)) { centredID = detail.id }
+ withAnimation(reduceMotion ? nil : .smooth(duration: 0.3)) { centredID = detail.id }
select(detail.id)
} label: {
CoverView(game: detail.game, radius: cover * 0.03)
@@ -144,6 +164,13 @@ struct CoverFlowView: View {
.shadow(color: .black.opacity(0.5), radius: cover * 0.05, y: cover * 0.03)
}
.buttonStyle(.plain)
+ // A long press on the centred card opens its settings, a shortcut for the button at the top.
+ .simultaneousGesture(LongPressGesture(minimumDuration: 0.5).onEnded { _ in
+ guard chosen, settled else { return }
+ longPressed = true
+ openSettings()
+ })
+ .sensoryFeedback(.impact(weight: .medium), trigger: longPressed) { _, new in new }
.shellTarget("lib.tile.\(detail.id)", radius: cover * 0.03) { primary(detail) }
.accessibilityLabel(detail.game.title + ", " + detail.game.state.title)
.accessibilityAddTraits(chosen ? .isSelected : [])
@@ -151,62 +178,98 @@ struct CoverFlowView: View {
.accessibilityIdentifier("tile.\(detail.id)")
}
- /// Under the centre card, the same on a phone and a tablet: the title centred with room for two lines, one status or
- /// reason line, then the buttons at a fixed place. The space is reserved, so nothing moves when the selection
- /// changes, only the words crossfade.
+ /// Under the centre card, the same on a phone and a tablet: the title with room for two lines, then one line of
+ /// state. For a game that cannot start, that line is the way out: a small chip that says what is wrong and what to
+ /// do. The space is reserved, so nothing moves when the selection changes, only the words crossfade.
private func info(short: Bool, width: CGFloat) -> some View {
let game = selected.game
let size: CGFloat = short ? 20 : 28
- return VStack(spacing: short ? 10 : 14) {
- ZStack(alignment: .top) {
- VStack(spacing: 6) {
- Text("M\nM").shellText(size, .heavy, relativeTo: .title)
- StatusLabel(state: .playable, prominent: true)
- }.hidden().accessibilityHidden(true)
- VStack(spacing: 6) {
- title(game, size: size).lineLimit(2).truncationMode(.tail).multilineTextAlignment(.center)
- StatusLabel(state: game.state, prominent: true)
+ return ZStack(alignment: .top) {
+ VStack(spacing: 8) {
+ Text("M\nM").shellType(ShellType.flowTitle(size))
+ StateChip(game: game) {}.allowsHitTesting(false)
+ }.hidden().accessibilityHidden(true)
+ VStack(spacing: 8) {
+ Text(game.title).shellType(ShellType.flowTitle(size))
+ .lineLimit(2).truncationMode(.tail).multilineTextAlignment(.center)
+ .shadow(color: .black.opacity(0.35), radius: 10)
+ .accessibilityAddTraits(.isHeader).accessibilityIdentifier("hero.title")
+ if game.state == .playable {
+ StatusLabel(state: game.state, prominent: true).frame(minHeight: 34)
+ } else {
+ StateChip(game: game) { primary(selected) }
}
}
- .frame(maxWidth: min(560, width - 48))
- actions(game)
+ .id(game.id).transition(.opacity)
}
+ .animation(reduceMotion ? nil : .easeOut(duration: 0.2), value: game.id)
+ .frame(maxWidth: min(560, width - 48))
.dynamicTypeSize(...(short ? DynamicTypeSize.xxLarge : DynamicTypeSize.accessibility1))
}
- private func title(_ game: GameTile, size: CGFloat) -> some View {
- Text(game.title).shellText(size, .heavy, relativeTo: .title).tracking(-size * 0.025)
- .shadow(color: .black.opacity(0.35), radius: 10)
- .accessibilityAddTraits(.isHeader).accessibilityIdentifier("hero.title")
- .id("title.\(game.id)").transition(.opacity)
- .animation(reduceMotion ? nil : .easeOut(duration: 0.2), value: game.id)
+ private var hints: some View {
+ HStack(spacing: 24) {
+ GlyphHint(role: .activate, label: selected.game.state.actionTitle)
+ GlyphHint(role: .settings, label: ShellStrings.text("Game settings"))
+ GlyphHint(role: .controllers, label: ShellStrings.text("Controllers"))
+ }
+ .frame(minHeight: 24)
+ .accessibilityHidden(true)
}
+}
- private func actions(_ game: GameTile) -> some View {
- HStack(spacing: 12) {
- // A fixed width that holds every state's label, so the row does not shift between games.
- Button { primary(selected) } label: {
- Label(game.state.actionTitle, systemImage: game.state.actionSymbol).frame(minWidth: 190)
+/// What is wrong and what to do, as one small tappable line: "Game files damaged · How to fix".
+struct StateChip: View {
+ let game: GameTile
+ let action: () -> Void
+ var body: some View {
+ Button(action: action) {
+ HStack(spacing: 8) {
+ Circle().fill(game.state.color).frame(width: 7, height: 7)
+ Text(game.state.title.uppercased()).shellType(ShellType.eyebrow)
+ .foregroundStyle(game.state.color)
+ Text("·").foregroundStyle(.white.opacity(0.4))
+ Text(game.state.chipAction).shellType(ShellType.button)
+ Image(systemName: "chevron.right").font(.system(size: 10, weight: .bold)).opacity(0.6)
}
- .buttonStyle(PrimaryPillStyle())
- .accessibilityLabel(game.state.actionTitle + ", " + game.title)
- .accessibilityIdentifier("state.action")
- .shellTarget("lib.play", radius: 25) { primary(selected) }
- Button(action: openSettings) { Image(systemName: "slider.horizontal.3") }
- .buttonStyle(RoundIconButtonStyle())
- .accessibilityLabel(ShellStrings.text("Game settings"))
- .accessibilityIdentifier("settings.open")
- .shellTarget("lib.settings", radius: 25, action: openSettings)
+ .lineLimit(1)
+ .padding(.horizontal, 14).frame(minHeight: 34)
+ .background(.black.opacity(0.35), in: Capsule())
+ .overlay(Capsule().strokeBorder(.white.opacity(0.14)))
+ .contentShape(Capsule().inset(by: -6))
}
+ .buttonStyle(.plain)
+ .foregroundStyle(.white)
+ .accessibilityLabel(game.state.title + ", " + game.state.actionTitle)
+ .accessibilityIdentifier("state.chip")
+ .shellTarget("lib.chip", radius: 17, action: action)
}
+}
- private var hints: some View {
- HStack(spacing: 24) {
- GlyphHint(letter: "A", label: selected.game.state.actionTitle)
- GlyphHint(letter: "X", label: ShellStrings.text("Game settings"))
- GlyphHint(letter: "Y", label: ShellStrings.text("Controllers"))
- }.accessibilityHidden(true)
+/// Moves the carousel one card per gesture, like paging: a flick goes to the neighbour of the card the touch began on,
+/// a slow drag settles on the card nearest the middle. The target is always a card close by, so the snap is short
+/// instead of a long glide, and a second swipe that starts mid-snap counts from where the carousel is.
+struct CardSnap: ScrollTargetBehavior {
+ let stride: CGFloat
+ let count: Int
+ /// The card nearest the middle when the touch began.
+ let start: Int
+ func updateTarget(_ target: inout ScrollTarget, context: TargetContext) {
+ let card = Self.card(target: target.rect.origin.x, velocity: context.velocity.dx, stride: stride, count: count, start: start)
+ target.rect.origin.x = CGFloat(card) * stride
+ }
+ /// The card a gesture ends on. `target` is where the scroll would rest, in content points (0 with the first card in
+ /// the middle), `velocity` the release speed in points per millisecond, positive toward the later cards.
+ static func card(target: CGFloat, velocity: CGFloat, stride: CGFloat, count: Int, start: Int) -> Int {
+ let nearest = Int((target / stride).rounded())
+ let card: Int
+ if velocity > flickVelocity { card = max(start + 1, min(nearest, start + 1)) }
+ else if velocity < -flickVelocity { card = min(start - 1, max(nearest, start - 1)) }
+ else { card = nearest }
+ return min(count - 1, max(0, card))
}
+ /// Above this release speed (points per millisecond) the gesture counts as a flick.
+ static let flickVelocity: CGFloat = 0.3
}
/// A card's turn by its place: up to 24 degrees back, smaller and darker, pulled in behind its nearer neighbour.
diff --git a/frontend-ios/Sources/ShellUI/GameDetailView.swift b/frontend-ios/Sources/ShellUI/GameDetailView.swift
index b719fb12..b4625d5f 100644
--- a/frontend-ios/Sources/ShellUI/GameDetailView.swift
+++ b/frontend-ios/Sources/ShellUI/GameDetailView.swift
@@ -21,7 +21,8 @@ public struct GameDetailView: View {
ForEach(detail.sections) { section in
group(section.title) {
ForEach(section.rows) { row in
- SettingControl(row: row) { actions.onChange(detail.id, row.id, $0) }
+ // Equatable on its row: a change re-renders the changed row only, not every row of the game.
+ SettingControl(gameID: detail.id, row: row) { actions.onChange(detail.id, row.id, $0) }.equatable()
if row.id != section.rows.last?.id { divider }
}
}
@@ -124,7 +125,7 @@ private struct SourceRow<Buttons: View>: View {
VStack(alignment: .leading, spacing: 5) {
Text(title).shellText(15, .semibold).fixedSize(horizontal: false, vertical: true)
if !note.isEmpty {
- Text(note).shellText(12.5).foregroundStyle(.white.opacity(0.5)).fixedSize(horizontal: false, vertical: true)
+ Text(note).shellType(ShellType.note).foregroundStyle(.white.opacity(0.5)).fixedSize(horizontal: false, vertical: true)
}
}
}
@@ -137,9 +138,12 @@ private struct SourceRow<Buttons: View>: View {
}
}
-private struct SettingControl: View {
+private struct SettingControl: View, Equatable {
+ /// Part of the comparison: two games can have identical rows, and the row must report to its own game.
+ let gameID: String
let row: SettingRow
let change: (String) -> Void
+ nonisolated static func == (lhs: Self, rhs: Self) -> Bool { lhs.gameID == rhs.gameID && lhs.row == rhs.row }
@Environment(\.dynamicTypeSize) private var typeSize
var body: some View {
VStack(alignment: .leading, spacing: 12) {
@@ -182,8 +186,8 @@ private struct SettingControl: View {
}
private var label: some View {
VStack(alignment: .leading, spacing: 4) {
- Text(row.label).shellText(15, .semibold).fixedSize(horizontal: false, vertical: true)
- if !row.note.isEmpty { Text(row.note).shellText(12.5).foregroundStyle(.white.opacity(0.5)).fixedSize(horizontal: false, vertical: true) }
+ Text(row.label).shellType(ShellType.settingLabel).fixedSize(horizontal: false, vertical: true)
+ if !row.note.isEmpty { Text(row.note).shellType(ShellType.note).foregroundStyle(.white.opacity(0.5)).fixedSize(horizontal: false, vertical: true) }
}
}
/// The Mac's segmented choice, across the whole card: a dim track, equal segments, the chosen value in cream.
diff --git a/frontend-ios/Sources/ShellUI/GameStateView.swift b/frontend-ios/Sources/ShellUI/GameStateView.swift
index a964be35..897a7829 100644
--- a/frontend-ios/Sources/ShellUI/GameStateView.swift
+++ b/frontend-ios/Sources/ShellUI/GameStateView.swift
@@ -61,7 +61,7 @@ public struct StateHelpView: View {
public var body: some View {
VStack(alignment: .leading, spacing: 16) {
StatusLabel(state: game.state, prominent: true)
- Text(game.state.actionTitle).shellText(26, .heavy, relativeTo: .title).tracking(-0.7)
+ 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 {
@@ -115,7 +115,7 @@ public struct EmptyLibraryView: View {
}
}.padding(.bottom, 14).accessibilityHidden(true)
SectionHeading(title: ShellStrings.text("Your games"))
- Text(ShellStrings.text("A little room for adventure")).shellText(30, .heavy, relativeTo: .title).tracking(-0.8)
+ Text(ShellStrings.text("A little room for adventure")).shellType(ShellType.heroTitle(30))
.fixedSize(horizontal: false, vertical: true)
Text(ShellStrings.text("Your games will appear here when they are included in this app."))
.shellText(15).foregroundStyle(.white.opacity(0.6)).fixedSize(horizontal: false, vertical: true)
diff --git a/frontend-ios/Sources/ShellUI/LibraryView.swift b/frontend-ios/Sources/ShellUI/LibraryView.swift
index 3567c71f..672b4d0c 100644
--- a/frontend-ios/Sources/ShellUI/LibraryView.swift
+++ b/frontend-ios/Sources/ShellUI/LibraryView.swift
@@ -47,6 +47,12 @@ public struct LibraryView: View {
@State private var libraryPosition = ScrollPosition()
@State private var layout: ShellLayout = .column
@State private var returnFocus: String?
+ /// The device that sent the last input, for the glyphs.
+ @State private var device: InputDevice = .controller(.neutral)
+ /// True after a touch: the controller hints and the focus ring step back until the next controller or key press.
+ @State private var touchMode: Bool
+ @State private var gate = InputGate()
+ @FocusState private var keyboardFocus: Bool
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@Environment(\.dynamicTypeSize) private var typeSize
@@ -62,6 +68,7 @@ public struct LibraryView: View {
_settingsOpen = State(initialValue: initialDetailOpen)
_controllersOpen = State(initialValue: initialControllersOpen)
_focus = State(initialValue: FocusAppearance(id: initialFocusVisible ? "lib.tile.\(first ?? "")" : nil, visible: initialFocusVisible))
+ _touchMode = State(initialValue: !initialFocusVisible)
}
private var selected: GameDetail? { games.first { $0.id == selectedID } ?? games.first }
@@ -170,16 +177,22 @@ public struct LibraryView: View {
.animation(reduceMotion ? nil : .smooth(duration: 0.25), value: helpGameID)
.environment(\.shellShowHelp, { game in openHelp(game.id) })
.environment(\.shellFocus, focus)
+ .environment(\.shellInputDevice, device)
.foregroundStyle(.white)
.font(ShellFonts.font(15)).tint(ShellPalette.cream).preferredColorScheme(.dark)
- .onChange(of: input) { _, event in if let event { handle(event.action) } }
- .focusable().focusEffectDisabled()
- .onKeyPress(.leftArrow) { handle(.left); return .handled }
- .onKeyPress(.rightArrow) { handle(.right); return .handled }
- .onKeyPress(.upArrow) { handle(.up); return .handled }
- .onKeyPress(.downArrow) { handle(.down); return .handled }
- .onKeyPress(.return) { handle(.activate); return .handled }
- .onKeyPress(.escape) { handle(.back); return .handled }
+ .onChange(of: input) { _, event in if let event { handle(event.action, from: event.device) } }
+ // A hardware keyboard, as on the Mac: arrows move, Return activates, Escape goes back, O opens game settings,
+ // Y opens controllers.
+ .focusable().focused($keyboardFocus).focusEffectDisabled()
+ .onAppear { keyboardFocus = true }
+ .onKeyPress(.leftArrow) { handle(.left, from: .keyboard); return .handled }
+ .onKeyPress(.rightArrow) { handle(.right, from: .keyboard); return .handled }
+ .onKeyPress(.upArrow) { handle(.up, from: .keyboard); return .handled }
+ .onKeyPress(.downArrow) { handle(.down, from: .keyboard); return .handled }
+ .onKeyPress(.return) { handle(.activate, from: .keyboard); return .handled }
+ .onKeyPress(.escape) { handle(.back, from: .keyboard); return .handled }
+ .onKeyPress("o") { handle(.settings, from: .keyboard); return .handled }
+ .onKeyPress("y") { handle(.controllers, from: .keyboard); return .handled }
.onDisappear { targets.values.removeAll() }
.onChange(of: games.map(\.id)) { _, ids in
if !ids.contains(selectedID ?? "") { selectedID = ids.first; settingsOpen = false }
@@ -188,13 +201,15 @@ public struct LibraryView: View {
@ViewBuilder private func library(_ selected: GameDetail, layout: ShellLayout, size: CGSize, insets: EdgeInsets) -> some View {
if layout.isCoverFlow {
- CoverFlowView(games: games, selected: selected, controllers: controllers.count, showsHints: !controllers.isEmpty,
+ CoverFlowView(games: games, selected: selected, controllers: controllers.count, showsHints: !touchMode,
select: select, primary: primary, openSettings: openSettings, openControllers: openControllers)
+ .equatable()
.transition(.opacity)
} else {
PortraitLibrary(games: games, selected: selected, wide: layout == .grid, size: size, topInset: insets.top, bottomInset: insets.bottom,
controllers: controllers.count, select: select, primary: primary,
openSettings: openSettings, openControllers: openControllers, position: $libraryPosition)
+ .equatable()
.transition(.opacity)
}
}
@@ -242,7 +257,14 @@ public struct LibraryView: View {
// MARK: Actions and focus
+ /// An action that did not come from a controller or key came from touch: hints and focus ring step back.
+ private func noteTouch() {
+ guard !gate.handling else { return }
+ if !touchMode { touchMode = true }
+ if focus.visible { focus.visible = false }
+ }
private func primary(_ detail: GameDetail) {
+ noteTouch()
if detail.game.state.needsHelp { openHelp(detail.id); return }
switch detail.game.state {
case .playable: actions.onPlay(detail.id)
@@ -252,12 +274,14 @@ public struct LibraryView: View {
}
}
private func select(_ id: String) {
+ noteTouch()
guard id != selectedID else { return }
selectedID = id
actions.onSelect(id)
settingsPosition.scrollTo(edge: .top)
}
private func openSettings() {
+ noteTouch()
settingsOpen = true
focus.id = "set.back"
}
@@ -265,7 +289,7 @@ public struct LibraryView: View {
settingsOpen = false
focus.id = "lib.settings"
}
- private func openControllers() { controllersOpen = true; focus.id = "ctl.close" }
+ private func openControllers() { noteTouch(); controllersOpen = true; focus.id = "ctl.close" }
private func openHelp(_ id: String) { returnFocus = focus.id; helpGameID = id; focus.id = "help.done" }
private func closeHelp() { helpGameID = nil; focus.id = returnFocus }
private func back() {
@@ -274,7 +298,11 @@ public struct LibraryView: View {
else if settingsOpen { closeSettings() }
else { actions.onBack() }
}
- private func handle(_ action: ShellInput.Action) {
+ private func handle(_ action: ShellInput.Action, from source: InputDevice) {
+ gate.handling = true
+ defer { gate.handling = false }
+ if device != source { device = source }
+ if touchMode { touchMode = false }
focus.visible = true
if focus.id == nil || !targets.values.contains(where: { $0.id == focus.id }) {
focus.id = defaultFocus
@@ -325,15 +353,15 @@ private struct PaneBanner: View {
StatusLabel(state: game.state, prominent: true)
// Two lines are always reserved, so the settings below start at the same place for every game.
ZStack(alignment: .topLeading) {
- Text("M\nM").shellText(26, .heavy, relativeTo: .title).hidden().accessibilityHidden(true)
- Text(game.title).shellText(26, .heavy, relativeTo: .title).tracking(-0.7)
+ Text("M\nM").shellType(ShellType.pageTitle).hidden().accessibilityHidden(true)
+ Text(game.title).shellType(ShellType.pageTitle)
.lineLimit(2)
.accessibilityAddTraits(.isHeader).accessibilityIdentifier("detail.title")
}
HStack(spacing: 8) {
SectionHeading(title: ShellStrings.text("Game settings"))
if !game.subtitle.isEmpty {
- Text(game.subtitle).shellText(12.5).foregroundStyle(.white.opacity(0.5))
+ Text(game.subtitle).shellType(ShellType.note).foregroundStyle(.white.opacity(0.5))
}
}.padding(.top, 2)
}
@@ -358,3 +386,8 @@ private struct PaneBanner: View {
}
}
}
+
+/// Marks the actions a controller or key press causes, so they are not taken for touch. Not observed.
+@MainActor final class InputGate {
+ var handling = false
+}
diff --git a/frontend-ios/Sources/ShellUI/PortraitLibrary.swift b/frontend-ios/Sources/ShellUI/PortraitLibrary.swift
index 1018bcf9..bc6dafea 100644
--- a/frontend-ios/Sources/ShellUI/PortraitLibrary.swift
+++ b/frontend-ios/Sources/ShellUI/PortraitLibrary.swift
@@ -4,7 +4,7 @@ import SwiftUI
/// then the collection, then recently played. In one column the primary action sits at the bottom for the thumb.
/// With regular width (an iPad or an unfolded foldable held upright) the collection becomes a grid of wide cards and
/// Play and the settings button move into the hero. Settings themselves only appear when asked for.
-struct PortraitLibrary: View {
+struct PortraitLibrary: View, Equatable {
let games: [GameDetail]
let selected: GameDetail
let wide: Bool
@@ -28,6 +28,11 @@ struct PortraitLibrary: View {
/// A short screen (the folded foldable is about 1.4:1) gets a smaller hero and smaller covers, so the hero,
/// the row and Play all fit without scrolling.
private var short: Bool { size.height + topInset < 700 }
+ /// One height for the hero per layout, a little under half the screen, so "Your games" sits high.
+ private var heroHeight: CGFloat {
+ let tall = size.height + topInset
+ return wide ? min(tall * 0.42, size.width * 0.62) : tall * 0.42
+ }
/// Whole cards only, the gap as wide as the margin: the next card starts exactly at the screen edge, so the edge
/// falls between cards and never through a name or a status. Long names end in an ellipsis inside their card.
private var coverSize: CGFloat {
@@ -37,12 +42,20 @@ struct PortraitLibrary: View {
return (available - (count - 1) * 24) / count
}
+ /// Re-render only for what is drawn: the games' tiles, the selection and the sizes. A setting changed in the panel
+ /// above does not redraw the library underneath.
+ nonisolated static func == (lhs: Self, rhs: Self) -> Bool {
+ lhs.games.map(\.game) == rhs.games.map(\.game) && lhs.selected.game == rhs.selected.game && lhs.wide == rhs.wide
+ && lhs.size == rhs.size && lhs.topInset == rhs.topInset && lhs.bottomInset == rhs.bottomInset
+ && lhs.controllers == rhs.controllers
+ }
+
var body: some View {
ScrollViewReader { proxy in
ScrollView {
VStack(alignment: .leading, spacing: 0) {
- HeroView(game: selected.game, width: size.width, topInset: topInset,
- titleSize: wide ? 34 : short ? 24 : 32, short: short, fullHeight: size.height + topInset) {
+ HeroView(game: selected.game, width: size.width, topInset: topInset, height: heroHeight,
+ titleSize: wide ? 34 : short ? 24 : 32, short: short) {
if wide {
HStack(spacing: 12) {
Button { primary(selected) } label: {
@@ -111,7 +124,7 @@ struct PortraitLibrary: View {
VStack(alignment: .leading, spacing: 0) {
CoverView(game: detail.game)
.shellTarget("lib.tile.\(detail.id)") { primary(detail) }
- Text(detail.game.title).shellText(13.5, .semibold).lineLimit(typeSize.isAccessibilitySize ? 3 : 1)
+ Text(detail.game.title).shellType(ShellType.cardTitle).lineLimit(typeSize.isAccessibilitySize ? 3 : 1)
.foregroundStyle(.white.opacity(chosen ? 1 : 0.86))
.frame(maxWidth: .infinity, alignment: .leading).padding(.top, 10)
StatusLabel(state: detail.game.state).padding(.top, 4)
@@ -182,60 +195,54 @@ struct PortraitLibrary: View {
}
}
-/// The chosen game's banner, whole and edge to edge at the top, flowing into a blurred copy of itself where the
-/// state, the title and what to do next sit. The banner's own logo and the shell's title never overlap.
+/// The chosen game's banner filling the whole hero, darkened toward the bottom where the state, the title and what to
+/// do next sit. The hero has one height for every game: the words are bottom-aligned, so a short title simply shows
+/// more of the banner and a long one covers more of it. Nothing below moves when the selection changes.
struct HeroView<Accessory: View>: View {
let game: GameTile
let width: CGFloat
let topInset: CGFloat
+ /// The hero's height including the status bar. It grows only if the reserved words need more.
+ let height: CGFloat
var titleSize: CGFloat = 34
- /// A short screen (the folded foldable): a lower banner, cropped at the sides, and one line of hint.
+ /// A short screen (the folded foldable): one line of hint.
var short = false
- var fullHeight: CGFloat = .infinity
@ViewBuilder let accessory: () -> Accessory
@Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
- let bannerHeight = short ? min(width * 9 / 16, fullHeight * 0.28) : width * 9 / 16
- VStack(alignment: .leading, spacing: 10) {
- // A stable height for every game: the hidden template reserves the status, a two-line title, the meta line
- // and a two-line hint, so the cards below never move when the selection changes. Only the text inside
- // crossfades.
- ZStack(alignment: .topLeading) {
+ VStack(alignment: .leading, spacing: 12) {
+ // The hidden template reserves the longest case (two lines of title, the meta line and the hint), so the
+ // hero keeps its height. The words are bottom-aligned inside it and crossfade.
+ ZStack(alignment: .bottomLeading) {
HeroText(status: GameState.needsGameData, title: "M\nM", meta: "M",
explanation: short ? "M" : "M\nM", titleSize: titleSize, hintLines: short ? 1 : 2)
.hidden().accessibilityHidden(true)
- HeroText(status: game.state, title: game.title, meta: meta, explanation: game.state.explanation, titleSize: titleSize,
- hintLines: short ? 1 : 2)
+ HeroText(status: game.state, title: game.title, meta: meta,
+ // The hint only where the game cannot start. For a playable game the meta line is enough.
+ explanation: game.state == .playable ? "" : game.state.explanation,
+ titleSize: titleSize, hintLines: short ? 1 : 2)
.id(game.id).transition(.opacity)
}
.animation(reduceMotion ? .linear(duration: 0.12) : .easeInOut(duration: 0.25), value: game.id)
accessory()
}
.padding(.horizontal, 24)
- // The text starts where the banner has faded out, never over the art's own lettering.
- .padding(.top, max(topInset, bannerHeight - 4))
- .padding(.bottom, 18)
- .frame(maxWidth: .infinity, alignment: .bottomLeading)
+ .padding(.top, topInset + 60)
+ .padding(.bottom, 16)
+ .frame(maxWidth: .infinity, minHeight: height, alignment: .bottomLeading)
.background {
- ZStack(alignment: .top) {
- ArtView(game: game, backdrop: true)
- .scaleEffect(1.4)
- .blur(radius: 50, opaque: true)
- .saturation(1.2)
- .overlay(Color.black.opacity(0.35))
+ ZStack {
ArtView(game: game, lettering: false)
- .frame(width: width, height: bannerHeight)
- .mask {
- LinearGradient(stops: [.init(color: .black, location: 0), .init(color: .black, location: 0.62),
- .init(color: .clear, location: 0.98)], startPoint: .top, endPoint: .bottom)
- }
- LinearGradient(stops: [.init(color: .black.opacity(0.45), location: 0),
- .init(color: .clear, location: min(0.3, (topInset + 40) / max(1, bannerHeight * 2)))],
- startPoint: .top, endPoint: .bottom)
- // The blurred colour settles into the page at the bottom edge.
- LinearGradient(stops: [.init(color: .clear, location: 0.55), .init(color: ShellPalette.background, location: 1)],
+ // Dark under the status bar, clear across the art, then deep toward the words at the bottom.
+ LinearGradient(stops: [.init(color: .black.opacity(0.5), location: 0),
+ .init(color: .clear, location: 0.22),
+ .init(color: .clear, location: 0.36),
+ .init(color: .black.opacity(0.55), location: 0.62),
+ .init(color: ShellPalette.background.opacity(0.94), location: 0.88),
+ .init(color: ShellPalette.background, location: 1)],
startPoint: .top, endPoint: .bottom)
+ LinearGradient(colors: [.black.opacity(0.3), .clear], startPoint: .leading, endPoint: .center)
}
.id(game.id).transition(.opacity)
.animation(reduceMotion ? .linear(duration: 0.15) : .easeInOut(duration: 0.35), value: game.id)
@@ -261,14 +268,14 @@ struct HeroText: View {
var body: some View {
VStack(alignment: .leading, spacing: 10) {
StatusLabel(state: status, prominent: true)
- Text(title).shellText(titleSize, .heavy, relativeTo: .largeTitle).tracking(-titleSize * 0.03)
+ Text(title).shellType(ShellType.heroTitle(titleSize))
.lineLimit(2).truncationMode(.tail)
.accessibilityAddTraits(.isHeader).accessibilityIdentifier("hero.title")
if !meta.isEmpty {
- Text(meta).shellText(13).foregroundStyle(.white.opacity(0.62)).lineLimit(1)
+ Text(meta).shellType(ShellType.meta).foregroundStyle(.white.opacity(0.62)).lineLimit(1)
}
if !explanation.isEmpty {
- Text(explanation).shellText(14.5).foregroundStyle(.white.opacity(0.78)).lineLimit(hintLines).padding(.top, 2)
+ Text(explanation).shellType(ShellType.body).foregroundStyle(.white.opacity(0.78)).lineLimit(hintLines).padding(.top, 2)
}
}
}
diff --git a/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings
index 10a68532..c6421c1f 100644
--- a/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings
+++ b/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings
@@ -71,6 +71,16 @@
}
}
},
+ "Choose": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Choose"
+ }
+ }
+ }
+ },
"Choose folder…": {
"localizations": {
"en": {
@@ -181,6 +191,16 @@
}
}
},
+ "Double-tap to select": {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Double-tap to select"
+ }
+ }
+ }
+ },
"For a bug report": {
"localizations": {
"en": {
diff --git a/frontend-ios/Sources/ShellUI/ShellInputs.swift b/frontend-ios/Sources/ShellUI/ShellInputs.swift
index c68b9d2d..cbdea436 100644
--- a/frontend-ios/Sources/ShellUI/ShellInputs.swift
+++ b/frontend-ios/Sources/ShellUI/ShellInputs.swift
@@ -110,12 +110,37 @@ public struct ControllerInfo: Identifiable, Equatable, Sendable {
}
}
+/// Which kind of controller a family of glyphs belongs to, from GameController's `productCategory`.
+/// The buttons are read by label, as on the Mac: GameController's buttonA is the cross on a PlayStation controller,
+/// A at the bottom on an Xbox controller and A on the right on a Nintendo controller, so each confirms with its own.
+public enum ControllerFamily: Equatable, Sendable {
+ case xbox, playStation, nintendo, neutral
+ public init(productCategory: String?) {
+ let c = (productCategory ?? "").lowercased().replacingOccurrences(of: "-", with: "")
+ if c.contains("dual") || c.contains("playstation") { self = .playStation }
+ else if c.contains("xbox") { self = .xbox }
+ else if c.contains("nintendo") || c.contains("switch") || c.contains("joycon") { self = .nintendo }
+ else { self = .neutral }
+ }
+}
+
+/// What sent the last input, so the hints show that device's own glyphs.
+public enum InputDevice: Equatable, Sendable {
+ case controller(ControllerFamily)
+ case keyboard
+}
+
/// An optional event supplied by the host's input adapter. Increment sequence for repeated presses.
public struct ShellInput: Equatable, Sendable {
public enum Action: Sendable { case up, down, left, right, activate, back, settings, controllers }
public var sequence: Int
public var action: Action
- public init(sequence: Int, action: Action) { self.sequence = sequence; self.action = action }
+ public var device: InputDevice
+ public init(sequence: Int, action: Action, device: InputDevice = .controller(.neutral)) {
+ self.sequence = sequence
+ self.action = action
+ self.device = device
+ }
}
/// All effects leave the package through these closures. The game ID is always explicit.
diff --git a/frontend-ios/Sources/ShellUI/ShellStyle.swift b/frontend-ios/Sources/ShellUI/ShellStyle.swift
index d57e9a8e..65867ffe 100644
--- a/frontend-ios/Sources/ShellUI/ShellStyle.swift
+++ b/frontend-ios/Sources/ShellUI/ShellStyle.swift
@@ -48,13 +48,61 @@ extension View {
}
}
+/// A text role: Manrope at a size and weight, scaled with Dynamic Type through its text style, and its tracking.
+struct TypeRole {
+ let size: CGFloat
+ let weight: Font.Weight
+ let style: Font.TextStyle
+ var tracking: CGFloat = 0
+}
+
+/// The type scale, derived from the Mac launcher's (frontend/Sources/NSPortBuilder): the same face from the same file,
+/// the same weight for the same role, the same tracking for capitals, sizes adapted to iOS. Every role scales with
+/// Dynamic Type through its text style.
+///
+/// | Role | Mac | iOS |
+/// | --- | --- | --- |
+/// | Hero title | heavy, up to 68, tracking -1.6 | heavy 32 (24 folded, 34 iPad), -0.024 per pt |
+/// | Cover Flow title | console title, bold 36, -1.6 | bold 28 (20 on a phone on its side) |
+/// | Page title (settings, controllers) | heavy 26, -0.6 | heavy 26, -0.6 |
+/// | Section capitals | console label, semibold 14, tracking 2 | semibold 11.5, tracking 1.6 |
+/// | Status eyebrow | bold 12, tracking 1.3 | bold 11.5, tracking 1.3 |
+/// | Status | medium 13 | medium 12.5 |
+/// | Card title | semibold 16 | semibold 14.5 |
+/// | Setting label | medium 14 | medium 15 |
+/// | Note | regular 12 | regular 12.5 |
+/// | Meta line | regular 13 | regular 13 |
+/// | Button | semibold 13 | semibold 14 |
+/// | Primary button | bold 18 | bold 17 |
+enum ShellType {
+ static func heroTitle(_ size: CGFloat) -> TypeRole { TypeRole(size: size, weight: .heavy, style: .largeTitle, tracking: -size * 0.024) }
+ static func flowTitle(_ size: CGFloat) -> TypeRole { TypeRole(size: size, weight: .bold, style: .title, tracking: -size * 0.04) }
+ static let pageTitle = TypeRole(size: 26, weight: .heavy, style: .title, tracking: -0.6)
+ static let sectionCaps = TypeRole(size: 11.5, weight: .semibold, style: .caption, tracking: 1.6)
+ static let eyebrow = TypeRole(size: 11.5, weight: .bold, style: .caption, tracking: 1.3)
+ static let status = TypeRole(size: 12.5, weight: .medium, style: .caption)
+ static let cardTitle = TypeRole(size: 14.5, weight: .semibold, style: .subheadline)
+ static let settingLabel = TypeRole(size: 15, weight: .medium, style: .body)
+ static let note = TypeRole(size: 12.5, weight: .regular, style: .footnote)
+ static let meta = TypeRole(size: 13, weight: .regular, style: .footnote)
+ static let body = TypeRole(size: 14.5, weight: .regular, style: .body)
+ static let button = TypeRole(size: 14, weight: .semibold, style: .body)
+ static let primaryButton = TypeRole(size: 17, weight: .bold, style: .headline)
+}
+
+extension View {
+ func shellType(_ role: TypeRole) -> some View {
+ font(ShellFonts.font(role.size, weight: role.weight, relativeTo: role.style)).tracking(role.tracking)
+ }
+}
+
/// The small cream capitals that open a section, such as YOUR GAMES.
struct SectionHeading: View {
let title: String
var trailing: String? = nil
var body: some View {
HStack(alignment: .firstTextBaseline) {
- Text(title.uppercased()).shellText(11, .bold, relativeTo: .caption).tracking(1.8)
+ Text(title.uppercased()).shellType(ShellType.sectionCaps)
.foregroundStyle(ShellPalette.cream.opacity(0.72)).accessibilityAddTraits(.isHeader)
if let trailing {
Spacer(minLength: 8)
@@ -70,7 +118,7 @@ struct ShellButtonStyle: ButtonStyle {
var fills = false
@Environment(\.isEnabled) private var enabled
func makeBody(configuration: Configuration) -> some View {
- configuration.label.shellText(14, .semibold).lineLimit(1)
+ configuration.label.shellType(ShellType.button).lineLimit(1)
.padding(.horizontal, 14).frame(maxWidth: fills ? .infinity : nil, minHeight: 44)
.foregroundStyle(.white.opacity(0.92))
.background(.white.opacity(configuration.isPressed ? 0.13 : 0.055), in: RoundedRectangle(cornerRadius: 9))
@@ -84,7 +132,7 @@ struct ShellButtonStyle: ButtonStyle {
struct PrimaryPillStyle: ButtonStyle {
var expands = false
func makeBody(configuration: Configuration) -> some View {
- configuration.label.shellText(17, .bold)
+ configuration.label.shellType(ShellType.primaryButton)
.lineLimit(1).minimumScaleFactor(0.8)
.padding(.horizontal, 26).frame(minHeight: 50)
.frame(maxWidth: expands ? .infinity : nil)
@@ -128,21 +176,38 @@ struct ChipButtonStyle: ButtonStyle {
}
struct CreamToggleStyle: ToggleStyle {
+ func makeBody(configuration: Configuration) -> some View { CreamSwitch(configuration: configuration, isOn: configuration.isOn) }
+}
+
+/// The cream switch. The knob moves the moment it is tapped, with a short spring, from its own state. The new value
+/// goes out without an animation, so the host's update does not animate the whole screen, and the knob follows the
+/// value that comes back.
+private struct CreamSwitch: View {
+ let configuration: ToggleStyleConfiguration
+ /// The value as a plain input: a change from elsewhere (a controller, the host) redraws the switch even though the
+ /// configuration's binding looks the same.
+ let isOn: Bool
+ @State private var shown: Bool?
@Environment(\.accessibilityReduceMotion) private var reduceMotion
- func makeBody(configuration: Configuration) -> some View {
+ var body: some View {
+ let on = shown ?? isOn
Button {
- withAnimation(reduceMotion ? nil : .spring(response: 0.25, dampingFraction: 0.8)) { configuration.isOn.toggle() }
+ withAnimation(reduceMotion ? nil : .snappy(duration: 0.2)) { shown = !on }
+ var transaction = Transaction(animation: nil)
+ transaction.disablesAnimations = true
+ withTransaction(transaction) { configuration.isOn = !on }
} label: {
HStack(spacing: 16) {
configuration.label.frame(maxWidth: .infinity, alignment: .leading)
- ZStack(alignment: configuration.isOn ? .trailing : .leading) {
- Capsule().fill(configuration.isOn ? ShellPalette.cream : .white.opacity(0.14))
- Circle().fill(configuration.isOn ? ShellPalette.background : .white.opacity(0.85)).padding(3)
+ ZStack(alignment: on ? .trailing : .leading) {
+ Capsule().fill(on ? ShellPalette.cream : .white.opacity(0.14))
+ Circle().fill(on ? ShellPalette.background : .white.opacity(0.85)).padding(3)
}.frame(width: 46, height: 28)
}.frame(minHeight: 44).contentShape(Rectangle())
}.buttonStyle(.plain)
- .accessibilityValue(ShellStrings.text(configuration.isOn ? "On" : "Off"))
- .accessibilityAddTraits(configuration.isOn ? .isSelected : [])
+ .onChange(of: isOn) { _, _ in shown = nil }
+ .accessibilityValue(ShellStrings.text(on ? "On" : "Off"))
+ .accessibilityAddTraits(on ? .isSelected : [])
}
}
@@ -286,37 +351,78 @@ struct StatusLabel: View {
HStack(spacing: prominent ? 8 : 6) {
Circle().fill(state.color).frame(width: prominent ? 7 : 6, height: prominent ? 7 : 6)
Text(prominent ? state.title.uppercased() : state.title)
- .shellText(prominent ? 11.5 : 12, prominent ? .bold : .medium, relativeTo: .caption)
- .tracking(prominent ? 1.4 : 0)
+ .shellType(prominent ? ShellType.eyebrow : ShellType.status)
.foregroundStyle(state.color)
.lineLimit(prominent ? 2 : 1)
}.accessibilityElement(children: .combine)
}
}
-/// A controller button as the Mac console draws it: the letter in a small rounded square.
+/// What a button does, for its glyph.
+enum GlyphRole { case activate, back, settings, controllers }
+
+/// A button as the Mac console draws it for the device used last: the letter in a rounded square for Xbox, Nintendo
+/// and unknown controllers, the shape for PlayStation (cross, circle, square, triangle), a key cap for a keyboard.
struct ButtonGlyph: View {
- let letter: String
+ let role: GlyphRole
+ @Environment(\.shellInputDevice) private var device
var body: some View {
- Text(letter).font(ShellFonts.fixed(11, weight: .bold))
- .frame(width: 20, height: 20)
- .overlay(RoundedRectangle(cornerRadius: 5).strokeBorder(.white.opacity(0.45), lineWidth: 1.2))
- .accessibilityHidden(true)
+ Group {
+ switch device {
+ case .controller(.playStation):
+ Image(systemName: playStationSymbol).font(.system(size: 9, weight: .heavy)).frame(width: 20, height: 20)
+ .overlay(RoundedRectangle(cornerRadius: 5).strokeBorder(.white.opacity(0.45), lineWidth: 1.2))
+ case .keyboard:
+ Text(keyCap).font(ShellFonts.fixed(10, weight: .bold)).padding(.horizontal, 5).frame(minWidth: 20, minHeight: 20)
+ .overlay(RoundedRectangle(cornerRadius: 5).strokeBorder(.white.opacity(0.45), lineWidth: 1.2))
+ case .controller:
+ Text(letter).font(ShellFonts.fixed(11, weight: .bold)).frame(width: 20, height: 20)
+ .overlay(RoundedRectangle(cornerRadius: 5).strokeBorder(.white.opacity(0.45), lineWidth: 1.2))
+ }
+ }.accessibilityHidden(true)
+ }
+ private var letter: String {
+ switch role { case .activate: "A"; case .back: "B"; case .settings: "X"; case .controllers: "Y" }
+ }
+ private var playStationSymbol: String {
+ switch role { case .activate: "xmark"; case .back: "circle"; case .settings: "square"; case .controllers: "triangle" }
+ }
+ private var keyCap: String {
+ switch role { case .activate: "return"; case .back: "esc"; case .settings: "O"; case .controllers: "Y" }
}
}
struct GlyphHint: View {
- let letter: String
+ let role: GlyphRole
let label: String
var body: some View {
HStack(spacing: 8) {
- ButtonGlyph(letter: letter)
+ ButtonGlyph(role: role)
Text(label).shellText(13, .medium, relativeTo: .footnote)
}.foregroundStyle(.white.opacity(0.6))
}
}
+private struct ShellInputDeviceKey: EnvironmentKey {
+ static let defaultValue = InputDevice.controller(.neutral)
+}
+extension EnvironmentValues {
+ /// The device that sent the last input. The hints and the controller help draw its glyphs.
+ var shellInputDevice: InputDevice {
+ get { self[ShellInputDeviceKey.self] }
+ set { self[ShellInputDeviceKey.self] = newValue }
+ }
+}
extension GameState {
+ /// The short verb of the state chip under a Cover Flow card.
+ var chipAction: String {
+ switch self {
+ case .playable: ShellStrings.text("Play")
+ case .needsGameData: ShellStrings.text("Choose")
+ case .needsAppUpdate: ShellStrings.text("How to update")
+ case .broken: ShellStrings.text("How to fix")
+ }
+ }
/// Broken and needs-an-update are fixed on the Mac. Their primary action explains how, instead of acting.
var needsHelp: Bool {
switch self {
diff --git a/frontend-ios/Tests/ShellControllersTests/PadMappingTests.swift b/frontend-ios/Tests/ShellControllersTests/PadMappingTests.swift
new file mode 100644
index 00000000..3122e531
--- /dev/null
+++ b/frontend-ios/Tests/ShellControllersTests/PadMappingTests.swift
@@ -0,0 +1,52 @@
+import XCTest
+import ShellUI
+@testable import ShellControllers
+
+final class PadMappingTests: XCTestCase {
+ func testButtonsMapLikeTheMacConsole() {
+ XCTAssertEqual(PadMapper.action(for: .a), .activate)
+ XCTAssertEqual(PadMapper.action(for: .b), .back)
+ XCTAssertEqual(PadMapper.action(for: .x), .settings)
+ XCTAssertEqual(PadMapper.action(for: .menu), .settings)
+ XCTAssertEqual(PadMapper.action(for: .y), .controllers)
+ XCTAssertNil(PadMapper.action(for: .leftShoulder))
+ }
+ func testDeadzoneAndStrongerAxis() {
+ XCTAssertNil(PadMapper.direction(x: 0.4, y: -0.3))
+ XCTAssertEqual(PadMapper.direction(x: 0.8, y: 0.6), .right)
+ XCTAssertEqual(PadMapper.direction(x: -0.2, y: 0.9), .up)
+ XCTAssertEqual(PadMapper.direction(x: 0.1, y: -0.7), .down)
+ XCTAssertEqual(PadMapper.direction(x: -0.51, y: 0), .left)
+ }
+ func testOnePressOneActionPerController() {
+ var mapper = PadMapper()
+ XCTAssertEqual(mapper.changes(controller: "one", state: PadState(buttons: [.a])).pressed, [.activate])
+ XCTAssertEqual(mapper.changes(controller: "one", state: PadState(buttons: [.a])).pressed, [], "held is not pressed again")
+ XCTAssertEqual(mapper.changes(controller: "two", state: PadState(buttons: [.a])).pressed, [.activate], "another controller counts on its own")
+ XCTAssertEqual(mapper.changes(controller: "one", state: PadState()).pressed, [])
+ XCTAssertEqual(mapper.changes(controller: "one", state: PadState(buttons: [.a])).pressed, [.activate])
+ }
+ func testDirectionPressAndRelease() {
+ var mapper = PadMapper()
+ XCTAssertEqual(mapper.changes(controller: "one", state: PadState(x: 1)).pressed, [.right])
+ let released = mapper.changes(controller: "one", state: PadState(x: 0))
+ XCTAssertEqual(released.released, [.right])
+ mapper.reset(controller: "one")
+ XCTAssertEqual(mapper.changes(controller: "one", state: PadState(x: 1)).pressed, [.right])
+ }
+ func testRepeatTiming() {
+ XCTAssertEqual(RepeatTiming.moves(heldFor: 0.2), 1)
+ XCTAssertEqual(RepeatTiming.moves(heldFor: 0.4), 2)
+ XCTAssertEqual(RepeatTiming.moves(heldFor: 0.52), 3)
+ XCTAssertEqual(RepeatTiming.moves(heldFor: 1.0), 7)
+ }
+ func testFamiliesFromProductCategory() {
+ XCTAssertEqual(ControllerFamily(productCategory: "DualSense"), .playStation)
+ XCTAssertEqual(ControllerFamily(productCategory: "DualShock 4"), .playStation)
+ XCTAssertEqual(ControllerFamily(productCategory: "Xbox One"), .xbox)
+ XCTAssertEqual(ControllerFamily(productCategory: "Switch Pro Controller"), .nintendo)
+ XCTAssertEqual(ControllerFamily(productCategory: "Nintendo Switch JoyCon (L/R)"), .nintendo)
+ XCTAssertEqual(ControllerFamily(productCategory: "MFi"), .neutral)
+ XCTAssertEqual(ControllerFamily(productCategory: nil), .neutral)
+ }
+}
diff --git a/frontend-ios/Tests/ShellUITests/LayoutTests.swift b/frontend-ios/Tests/ShellUITests/LayoutTests.swift
index 42a27823..5a657d81 100644
--- a/frontend-ios/Tests/ShellUITests/LayoutTests.swift
+++ b/frontend-ios/Tests/ShellUITests/LayoutTests.swift
@@ -41,4 +41,17 @@ final class LayoutTests: XCTestCase {
XCTAssertTrue(ShellLayout.grid.settingsFloat)
XCTAssertFalse(ShellLayout.column.settingsFloat)
}
+
+ /// Cover Flow moves one card per gesture: a flick to the neighbour of where the touch began, a slow drag to the
+ /// nearest card.
+ func testCardSnap() {
+ let stride: CGFloat = 100
+ XCTAssertEqual(CardSnap.card(target: 160, velocity: 0, stride: stride, count: 7, start: 0), 2, "slow drag: nearest")
+ XCTAssertEqual(CardSnap.card(target: 40, velocity: 0, stride: stride, count: 7, start: 0), 0)
+ XCTAssertEqual(CardSnap.card(target: 30, velocity: 0.6, stride: stride, count: 7, start: 0), 1, "a short flick still moves one")
+ XCTAssertEqual(CardSnap.card(target: 450, velocity: 2, stride: stride, count: 7, start: 1), 2, "a hard flick moves one, not four")
+ XCTAssertEqual(CardSnap.card(target: 90, velocity: -0.8, stride: stride, count: 7, start: 1), 0)
+ XCTAssertEqual(CardSnap.card(target: 700, velocity: 0.8, stride: stride, count: 7, start: 6), 6, "never past the last card")
+ XCTAssertEqual(CardSnap.card(target: -50, velocity: -0.8, stride: stride, count: 7, start: 0), 0)
+ }
}
diff --git a/frontend-ios/UITests/ShellAdditionalTests.swift b/frontend-ios/UITests/ShellAdditionalTests.swift
index d99d6f55..175680c6 100644
--- a/frontend-ios/UITests/ShellAdditionalTests.swift
+++ b/frontend-ios/UITests/ShellAdditionalTests.swift
@@ -188,4 +188,23 @@ import XCTest
XCTAssertFalse(app.alerts["Demo action"].waitForExistence(timeout: 1), "the action ran once")
XCUIDevice.shared.orientation = .portrait
}
+
+ /// A slow drag to the next card, then at once a quick swipe the same way: two cards on, never back.
+ func testSlowDragThenQuickSwipeAdvancesTwo() {
+ XCUIDevice.shared.orientation = .landscapeLeft
+ app.launchArguments = ["--screen", "library"]
+ app.launch()
+ XCTAssertTrue(app.buttons["tile.orbit"].waitForExistence(timeout: 10))
+ let start = centreCard()
+ let window = app.windows.firstMatch.frame
+ let step = window.width * 0.32
+ start.press(forDuration: 0.1, thenDragTo: start.withOffset(CGVector(dx: -step, dy: 0)), withVelocity: XCUIGestureVelocity(250), thenHoldForDuration: 0)
+ start.press(forDuration: 0.02, thenDragTo: start.withOffset(CGVector(dx: -step * 0.6, dy: 0)), withVelocity: .fast, thenHoldForDuration: 0)
+ sleep(2)
+ let counter = app.staticTexts.matching(NSPredicate(format: "label ENDSWITH ' of 7'")).firstMatch
+ XCTAssertEqual(counter.label, "3 of 7")
+ XCTAssertEqual(app.staticTexts["hero.title"].label, "Paper Trails")
+ XCTAssertFalse(app.alerts["Demo action"].exists)
+ XCUIDevice.shared.orientation = .portrait
+ }
}
diff --git a/frontend-ios/UITests/ShellDemoUITests.swift b/frontend-ios/UITests/ShellDemoUITests.swift
index 2ff7bf71..ba0a6e1a 100644
--- a/frontend-ios/UITests/ShellDemoUITests.swift
+++ b/frontend-ios/UITests/ShellDemoUITests.swift
@@ -31,9 +31,13 @@ import XCTest
XCTAssertTrue(app.alerts.staticTexts["Play requested. The demo does not launch games."].exists)
app.alerts.buttons["OK"].tap()
if app.buttons["library.back"].exists { app.buttons["library.back"].tap() }
- XCTAssertTrue(app.buttons["tile.orbit"].isHittable)
+ // The panel slides away first.
+ let orbit = app.buttons["tile.orbit"]
+ expectation(for: NSPredicate(format: "isHittable == true"), evaluatedWith: orbit)
+ waitForExpectations(timeout: 5)
app.buttons["controllers.open"].tap()
- XCTAssertTrue(app.staticTexts["Pro Controller"].waitForExistence(timeout: 5))
+ // The sheet lists the real controllers when the device has any, the sample ones otherwise.
+ XCTAssertTrue(app.buttons["controllers.close"].waitForExistence(timeout: 5))
app.buttons["controllers.close"].tap()
XCTAssertFalse(app.staticTexts["Pro Controller"].exists)
}
@@ -43,7 +47,8 @@ import XCTest
launch("library")
app.buttons["tile.paper"].tap()
XCTAssertEqual(app.staticTexts["hero.title"].label, "Paper Trails")
- XCTAssertEqual(app.buttons["state.action"].firstMatch.label, "Choose game data…, Paper Trails")
+ // Under the card the state line is the way out: what is wrong and what to do.
+ XCTAssertEqual(app.buttons["state.chip"].label, "Needs game data, Choose game data…")
XCUIDevice.shared.orientation = .portrait
}
func testLargeText() {