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: the echo window on a monotonic clock, held buttons, the covered library, and tests

Haseenesssd5051fe84793
diff --git a/frontend-ios/Sources/ShellControllers/GamepadAdapter.swift b/frontend-ios/Sources/ShellControllers/GamepadAdapter.swift
index 993c3980..efc5183a 100644
--- a/frontend-ios/Sources/ShellControllers/GamepadAdapter.swift
+++ b/frontend-ios/Sources/ShellControllers/GamepadAdapter.swift
@@ -20,6 +20,9 @@ public struct ConnectedController: Equatable, Sendable {
/// 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 }
+ /// A button or direction let go. The shell restarts its window for the system's echo of a controller button here,
+ /// since iPadOS sends that echo as the button comes up.
+ public var onRelease: (ShellInput.Action, InputDevice) -> Void = { _, _ in }
public var onControllersChange: ([ConnectedController]) -> Void = { _ in }
/// Every state of any controller, for the button test. Nil (the default) reports none. Set, it reports the state of
/// the first controller at once, then each change of whichever controller moved, and again the first controller's
@@ -141,7 +144,10 @@ public struct ConnectedController: Equatable, Sendable {
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 released {
+ if repeating?.action == action && repeating?.controller == controller { stopRepeat() }
+ onRelease(action, .controller(family))
+ }
for action in pressed {
onInput(action, .controller(family))
if PadMapper.isDirection(action) { startRepeat(action, controller: controller, family: family) }
diff --git a/frontend-ios/Sources/ShellControllers/PadMapping.swift b/frontend-ios/Sources/ShellControllers/PadMapping.swift
index 3e735998..84bfb702 100644
--- a/frontend-ios/Sources/ShellControllers/PadMapping.swift
+++ b/frontend-ios/Sources/ShellControllers/PadMapping.swift
@@ -25,7 +25,7 @@ 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>] = [:]
+ private var held: [String: [String: ShellInput.Action]] = [:]
public init() {}
/// The action of each button: A activates, B goes back, X and Menu open the game's settings, Y opens Controllers.
@@ -51,37 +51,23 @@ public struct PadMapper: Sendable {
return nil
}
- /// What changed for `controller`: the actions newly pressed and released.
+ /// What changed for `controller`: the actions of the buttons and directions newly pressed, and of those let go.
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)
+ let before = held[controller] ?? [:]
+ let pressed = now.filter { before[$0.key] == nil }.sorted { $0.key < $1.key }.map(\.value)
+ let released = before.filter { now[$0.key] == nil }.sorted { $0.key < $1.key }.map(\.value)
+ held[controller] = now
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
diff --git a/frontend-ios/Sources/ShellHost/ShellHostModel.swift b/frontend-ios/Sources/ShellHost/ShellHostModel.swift
index eca0b530..defc89d8 100644
--- a/frontend-ios/Sources/ShellHost/ShellHostModel.swift
+++ b/frontend-ios/Sources/ShellHost/ShellHostModel.swift
@@ -507,6 +507,10 @@ public struct ShellHostConfig: Sendable {
guard let self else { return }
self.input = ShellInput(sequence: (self.input?.sequence ?? 0) + 1, action: action, device: device)
}
+ adapter.onRelease = { [weak self] action, device in
+ guard let self else { return }
+ self.input = ShellInput(sequence: (self.input?.sequence ?? 0) + 1, action: action, device: device, released: true)
+ }
adapter.onControllersChange = { [weak self] connected in
self?.controllers = connected.map(Self.info(for:))
}
diff --git a/frontend-ios/Sources/ShellUI/InputGate.swift b/frontend-ios/Sources/ShellUI/InputGate.swift
new file mode 100644
index 00000000..3ee74d87
--- /dev/null
+++ b/frontend-ios/Sources/ShellUI/InputGate.swift
@@ -0,0 +1,100 @@
+import Foundation
+
+/// Whether a button press with no shell input behind it is iPadOS's echo of a controller button. iPadOS also takes a
+/// controller's A as a press on a button of its own choosing (Play in portrait, the middle cover in landscape, a close
+/// button, a switch), about 25 ms after A comes up, past the shell's own input. Such a press counts as the echo when no
+/// finger came down since the last controller button, and that button is still held (up to `heldLimit`) or went down or
+/// came up less than `span` ago. A button still held counts because the shell hears of a button coming up through a
+/// SwiftUI update, and the system's press can come before it: with A held longer than `span`, the window of A going down
+/// was over and the press got through.
+///
+/// Times are seconds of a monotonic clock (`ProcessInfo.systemUptime`), which a time change or a network time sync does
+/// not move. A time before the last controller button (a clock that went back) is never the echo.
+struct SystemEchoWindow: Equatable {
+ static let span: TimeInterval = 1
+ /// A button held longer than this is taken for one whose coming up was lost (a controller that went away).
+ static let heldLimit: TimeInterval = 30
+ /// When a controller button last went down or came up.
+ private(set) var controllerAt: TimeInterval?
+ /// How many controller buttons are down. Directions are not counted: held, they repeat.
+ private(set) var held = 0
+ /// When a finger last came down anywhere on the screen.
+ private(set) var touchAt: TimeInterval?
+
+ /// A controller direction moved, or a direction repeated.
+ mutating func controller(at time: TimeInterval) { controllerAt = time }
+ /// A controller button went down.
+ mutating func buttonDown(at time: TimeInterval) { controllerAt = time; held += 1 }
+ /// A controller button came up. The echo comes after this, so the window starts again here.
+ mutating func buttonUp(at time: TimeInterval) { controllerAt = time; held = max(0, held - 1) }
+ mutating func touch(at time: TimeInterval) { touchAt = time }
+
+ func isEcho(at now: TimeInterval) -> Bool {
+ guard let controllerAt else { return false }
+ let elapsed = now - controllerAt
+ guard elapsed >= 0 else { return false }
+ if let touchAt, touchAt >= controllerAt { return false }
+ return elapsed < (held > 0 ? Self.heldLimit : Self.span)
+ }
+}
+
+/// Marks the actions a controller or key press causes, so they are not taken for touch, and keeps the window for the
+/// system's echo of a controller button. Not observed.
+@MainActor final class InputGate {
+ /// True while `handle` acts on a controller or key press.
+ var handling = false
+ private var window = SystemEchoWindow()
+ private let clock: () -> TimeInterval
+
+ init(clock: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }) { self.clock = clock }
+
+ /// A controller action came in: a button going down, or a direction (which repeats while held).
+ func controller(_ action: ShellInput.Action) {
+ if Self.isDirection(action) { window.controller(at: clock()) } else { window.buttonDown(at: clock()) }
+ }
+ /// A controller button or direction came up.
+ func controllerUp(_ action: ShellInput.Action) {
+ if Self.isDirection(action) { window.controller(at: clock()) } else { window.buttonUp(at: clock()) }
+ }
+ private static func isDirection(_ action: ShellInput.Action) -> Bool {
+ switch action {
+ case .up, .down, .left, .right: true
+ default: false
+ }
+ }
+ func touch() { window.touch(at: clock()) }
+ /// A press acted on now, outside `handle`, is the system's echo of a controller button.
+ var isSystemEcho: Bool { !handling && window.isEcho(at: clock()) }
+}
+
+/// What sits on top of the library and owns the D-pad, the topmost first. Each one's focus targets start with its
+/// prefix; the library's own targets start with `FocusLayer.libraryPrefix`.
+enum FocusLayer: CaseIterable {
+ case buttonTest, padMapping, choice, touchLayout, controllers, shellSettings, help, delete, settings
+
+ static let libraryPrefix = "lib."
+
+ var prefix: String {
+ switch self {
+ case .buttonTest: "test."
+ case .padMapping: "map."
+ case .choice: "pick."
+ case .touchLayout: "lay."
+ case .controllers: "ctl."
+ case .shellSettings: "shs."
+ case .help: "help."
+ case .delete: "del."
+ case .settings: "set."
+ }
+ }
+
+ /// Whether the library acts on a press of one of its own buttons: one from the shell's input always, any other only
+ /// with nothing over the library. Under a dialog or a panel the library takes no hits, so no finger made that press.
+ static func libraryTakesPress(fromShell: Bool, under top: FocusLayer?) -> Bool { fromShell || top == nil }
+
+ /// Whether the D-pad reaches target `id` with `top` open (nil: nothing over the library).
+ static func isLive(_ id: String, under top: FocusLayer?) -> Bool {
+ if let top { return id.hasPrefix(top.prefix) }
+ return !allCases.contains { id.hasPrefix($0.prefix) }
+ }
+}
diff --git a/frontend-ios/Sources/ShellUI/LibraryView.swift b/frontend-ios/Sources/ShellUI/LibraryView.swift
index 82afd12e..591783a0 100644
--- a/frontend-ios/Sources/ShellUI/LibraryView.swift
+++ b/frontend-ios/Sources/ShellUI/LibraryView.swift
@@ -289,10 +289,10 @@ public struct LibraryView: View {
ended: { finishEdgeSwipe(travel: $0, velocity: $1, span: controllersOpen || shellSettingsOpen ? min(width, 520) : pane) },
cancelled: cancelEdgeSwipe)
}
- // Every target on screen. Which of them the D-pad reaches is decided when it is used (`isLive`), from the state
- // at that moment: a filter here would run only when some target changes, and closing a panel changes none, so
- // the closed panel's targets stayed and the focus on the button that opened it was taken for lost.
- .onPreferenceChange(FocusTargets.self) { all in targets.values = all.filter { $0.frame.width > 1 } }
+ // Every target on screen. Which of them the D-pad reaches is decided when it is used (`isLive`), from the
+ // state at that moment: a filter here would run only when some target changes, and closing a panel changes
+ // none, so the closed panel's targets stayed and the focus on the button that opened it was taken for lost.
+ .onPreferenceChange(FocusTargets.self) { all in targets.values = all.filter { $0.frame.width > 1 } }
.onAppear { self.layout = layout }
.onChange(of: layout) { _, new in self.layout = new }
}
@@ -309,19 +309,24 @@ public struct LibraryView: View {
.environment(\.shellPickChoice, { request in openChoice(request) })
.environment(\.shellOpenPadMapping, { id in openPadMapping(id) })
.environment(\.shellOpenButtonTest, { openButtonTest() })
- .environment(\.shellIgnoresPress, { [gate] in !gate.handling && gate.isSystemEcho })
+ .environment(\.shellIgnoresPress, { [gate] in gate.isSystemEcho })
.environment(\.shellShowHelp, { game in openHelp(game.id) })
.environment(\.shellAskDelete, { game in openDelete(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, from: event.device) } }
+ .onChange(of: input) { _, event in
+ guard let event else { return }
+ // A button let go only restarts the window for the system's echo, which comes as the button comes up.
+ if event.released { if case .controller = event.device { gate.controllerUp(event.action) }; return }
+ 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 }
- .onAnyTouch { gate.touchAt = .now }
+ .onAnyTouch { gate.touch() }
.onKeyPress(.leftArrow) { handle(.left, from: .keyboard); return .handled }
.onKeyPress(.rightArrow) { handle(.right, from: .keyboard); return .handled }
.onKeyPress(.upArrow) { handle(.up, from: .keyboard); return .handled }
@@ -419,18 +424,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. False when
- /// it came from neither: iPadOS also takes a controller's A as a press on a button of its own choosing (Play in
- /// portrait, the middle cover in landscape), as the button comes up, past `handle`. Such a press, right after a
- /// controller button and with no finger down since, is not acted on: the shell's own focus already took that button.
- /// The system's echo of a controller button (see `noteTouch`), for the actions that close or go back: they do not
- /// change the touch mode, but the echo must not close the panel the button just opened.
- private var fromSystemEcho: Bool { !gate.handling && gate.isSystemEcho }
+ /// The system's echo of a controller button (see `SystemEchoWindow`), for the actions that close or go back: they
+ /// do not change the touch mode, but the echo must not close the panel the button just opened.
+ private var fromSystemEcho: Bool { gate.isSystemEcho }
/// `actions` for the views that change settings or data themselves (a switch, a row, a button in the settings): the
/// system's echo of a controller button changes nothing through them.
private var guardedActions: ShellActions {
let gate = gate
- func echo() -> Bool { !gate.handling && gate.isSystemEcho }
+ func echo() -> Bool { gate.isSystemEcho }
var a = actions
let o = actions
a.onSelect = { if !echo() { o.onSelect($0) } }
@@ -453,6 +454,9 @@ public struct LibraryView: View {
a.onDeleteGame = { if !echo() { o.onDeleteGame($0, $1) } }
return a
}
+ /// An action that did not come from a controller or key came from touch: hints and focus ring step back. False when
+ /// it came from neither but is the system's echo of a controller button (see `SystemEchoWindow`): the shell's own
+ /// focus already took that button, so the press is not acted on.
private func noteTouch() -> Bool {
guard !gate.handling else { return true }
if gate.isSystemEcho { return false }
@@ -460,8 +464,13 @@ public struct LibraryView: View {
if focus.visible { focus.visible = false }
return true
}
+ /// A press on the library's own buttons that the shell may act on: from `handle`, or with nothing over the library.
+ /// Under a dialog or a panel no finger reaches the library (it takes no hits there), so a press on its buttons is the
+ /// system's echo of a controller button, whatever the window says: a finger that came down elsewhere just before the
+ /// echo (a tap in the settings pane right after A) ends the window, and Play behind the pane started the game.
+ private var libraryPressAllowed: Bool { FocusLayer.libraryTakesPress(fromShell: gate.handling, under: topLayer) }
private func primary(_ detail: GameDetail) {
- guard noteTouch() else { return }
+ guard libraryPressAllowed, noteTouch() else { return }
if detail.game.state.needsHelp { openHelp(detail.id); return }
switch detail.game.state {
case .playable: actions.onPlay(detail.id)
@@ -471,7 +480,7 @@ public struct LibraryView: View {
}
}
private func select(_ id: String) {
- guard noteTouch() else { return }
+ guard libraryPressAllowed, noteTouch() else { return }
guard id != selectedID else { return }
selectedID = id
actions.onSelect(id)
@@ -617,8 +626,8 @@ public struct LibraryView: View {
private func handle(_ action: ShellInput.Action, from source: InputDevice) {
gate.handling = true
defer { gate.handling = false }
+ if case .controller = source { gate.controller(action) }
// Every controller button belongs to the button test while it is open: it closes on B held, touch or Escape.
- if case .controller = source { gate.controllerAt = .now }
if buttonTestOpen, case .controller = source { return }
if device != source { device = source }
if touchMode { touchMode = false }
@@ -655,17 +664,19 @@ public struct LibraryView: View {
}
/// The targets the D-pad reaches now: the open dialog's or panel's own, else the library's.
private var liveTargets: [FocusTarget] { targets.values.filter { isLive($0.id) } }
- private func isLive(_ id: String) -> Bool {
- if buttonTestOpen { return id.hasPrefix("test.") }
- if padMapping != nil { return id.hasPrefix("map.") }
- if choice != nil { return id.hasPrefix("pick.") }
- if touchLayout != nil { return id.hasPrefix("lay.") }
- if controllersOpen { return id.hasPrefix("ctl.") }
- if shellSettingsOpen { return id.hasPrefix("shs.") }
- if helpGameID != nil { return id.hasPrefix("help.") }
- if deleteGameID != nil { return id.hasPrefix("del.") }
- if settingsOpen { return id.hasPrefix("set.") }
- return !["ctl.", "help.", "pick.", "shs.", "del.", "map.", "test.", "lay.", "set."].contains { id.hasPrefix($0) }
+ private func isLive(_ id: String) -> Bool { FocusLayer.isLive(id, under: topLayer) }
+ /// The dialog or panel on top, in the order of `FocusLayer`.
+ private var topLayer: FocusLayer? {
+ if buttonTestOpen { return .buttonTest }
+ if padMapping != nil { return .padMapping }
+ if choice != nil { return .choice }
+ if touchLayout != nil { return .touchLayout }
+ if controllersOpen { return .controllers }
+ if shellSettingsOpen { return .shellSettings }
+ if helpGameID != nil { return .help }
+ if deleteGameID != nil { return .delete }
+ if settingsOpen { return .settings }
+ return nil
}
private func move(_ action: ShellInput.Action) {
let live = liveTargets
@@ -796,19 +807,3 @@ private struct CoverThumbnail: View {
.accessibilityHidden(true)
}
}
-
-/// 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
- /// When the last controller button went down.
- var controllerAt: Date?
- /// When a finger last came down anywhere on the screen.
- var touchAt: Date?
- /// How long after a controller button a button press is the system's echo of it: the press comes as A comes up.
- static let systemEcho: TimeInterval = 1
- /// A button pressed now came from no finger: a controller button went down within `systemEcho` and no finger since.
- var isSystemEcho: Bool {
- guard let controllerAt, Date.now.timeIntervalSince(controllerAt) < Self.systemEcho else { return false }
- return touchAt.map { $0 < controllerAt } ?? true
- }
-}
diff --git a/frontend-ios/Sources/ShellUI/ShellInputs.swift b/frontend-ios/Sources/ShellUI/ShellInputs.swift
index 4533d0ef..719a5333 100644
--- a/frontend-ios/Sources/ShellUI/ShellInputs.swift
+++ b/frontend-ios/Sources/ShellUI/ShellInputs.swift
@@ -162,10 +162,14 @@ public struct ShellInput: Equatable, Sendable {
public var sequence: Int
public var action: Action
public var device: InputDevice
- public init(sequence: Int, action: Action, device: InputDevice = .controller(.neutral)) {
+ /// The button or direction of `action` came up. Nothing acts on it; it only restarts the window for the system's
+ /// echo of a controller button (`SystemEchoWindow`).
+ public var released: Bool
+ public init(sequence: Int, action: Action, device: InputDevice = .controller(.neutral), released: Bool = false) {
self.sequence = sequence
self.action = action
self.device = device
+ self.released = released
}
}
diff --git a/frontend-ios/Tests/ShellControllersTests/PadMappingTests.swift b/frontend-ios/Tests/ShellControllersTests/PadMappingTests.swift
index 3122e531..7bbbf19c 100644
--- a/frontend-ios/Tests/ShellControllersTests/PadMappingTests.swift
+++ b/frontend-ios/Tests/ShellControllersTests/PadMappingTests.swift
@@ -34,6 +34,13 @@ final class PadMappingTests: XCTestCase {
mapper.reset(controller: "one")
XCTAssertEqual(mapper.changes(controller: "one", state: PadState(x: 1)).pressed, [.right])
}
+ func testButtonRelease() {
+ var mapper = PadMapper()
+ XCTAssertEqual(mapper.changes(controller: "one", state: PadState(buttons: [.a])).released, [])
+ XCTAssertEqual(mapper.changes(controller: "one", state: PadState(buttons: [.a])).released, [], "held is not let go")
+ XCTAssertEqual(mapper.changes(controller: "one", state: PadState()).released, [.activate], "A coming up is reported")
+ XCTAssertEqual(mapper.changes(controller: "one", state: PadState()).released, [])
+ }
func testRepeatTiming() {
XCTAssertEqual(RepeatTiming.moves(heldFor: 0.2), 1)
XCTAssertEqual(RepeatTiming.moves(heldFor: 0.4), 2)
diff --git a/frontend-ios/Tests/ShellUITests/SystemEchoTests.swift b/frontend-ios/Tests/ShellUITests/SystemEchoTests.swift
new file mode 100644
index 00000000..46496713
--- /dev/null
+++ b/frontend-ios/Tests/ShellUITests/SystemEchoTests.swift
@@ -0,0 +1,155 @@
+import XCTest
+@testable import ShellUI
+
+/// The decision behind #638: a button press that no shell input caused, right after a controller button and with no
+/// finger since, is iPadOS's echo of that button and is not acted on. The press itself needs a device; this does not.
+final class SystemEchoWindowTests: XCTestCase {
+ func testNoControllerButtonNoEcho() {
+ XCTAssertFalse(SystemEchoWindow().isEcho(at: 100))
+ var w = SystemEchoWindow()
+ w.touch(at: 99)
+ XCTAssertFalse(w.isEcho(at: 100))
+ }
+ func testInsideTheWindowIsTheEcho() {
+ var w = SystemEchoWindow()
+ w.controller(at: 100)
+ XCTAssertTrue(w.isEcho(at: 100))
+ XCTAssertTrue(w.isEcho(at: 100.025), "the echo comes about 25 ms after A comes up")
+ XCTAssertTrue(w.isEcho(at: 100.999))
+ }
+ func testAfterTheWindowIsNot() {
+ var w = SystemEchoWindow()
+ w.controller(at: 100)
+ XCTAssertFalse(w.isEcho(at: 101))
+ XCTAssertFalse(w.isEcho(at: 160))
+ }
+ func testATouchAfterTheButtonEndsTheWindow() {
+ var w = SystemEchoWindow()
+ w.controller(at: 100)
+ w.touch(at: 100.2)
+ XCTAssertFalse(w.isEcho(at: 100.3), "a tap right after a controller button acts at once")
+ w.touch(at: 100)
+ XCTAssertFalse(w.isEcho(at: 100.3), "a finger at the same moment counts as after")
+ }
+ func testATouchBeforeTheButtonDoesNot() {
+ var w = SystemEchoWindow()
+ w.touch(at: 99.5)
+ w.controller(at: 100)
+ XCTAssertTrue(w.isEcho(at: 100.1))
+ }
+ func testAClockThatWentBackIsNeverTheEcho() {
+ var w = SystemEchoWindow()
+ w.controller(at: 100)
+ XCTAssertFalse(w.isEcho(at: 99.9))
+ XCTAssertFalse(w.isEcho(at: 0))
+ }
+ func testAButtonHeldLongerThanTheWindow() {
+ var w = SystemEchoWindow()
+ w.buttonDown(at: 100)
+ XCTAssertTrue(w.isEcho(at: 101.5), "held 1.5 s, the shell not yet told of A coming up: still the echo")
+ w.buttonUp(at: 101.5)
+ XCTAssertTrue(w.isEcho(at: 101.525), "the echo after A comes up is caught")
+ XCTAssertFalse(w.isEcho(at: 102.5))
+ }
+ func testATouchWhileAButtonIsHeldActs() {
+ var w = SystemEchoWindow()
+ w.buttonDown(at: 100)
+ w.touch(at: 101)
+ XCTAssertFalse(w.isEcho(at: 101.1))
+ }
+ func testAButtonWhoseComingUpWasLostStopsCounting() {
+ var w = SystemEchoWindow()
+ w.buttonDown(at: 100)
+ XCTAssertTrue(w.isEcho(at: 129))
+ XCTAssertFalse(w.isEcho(at: 130))
+ }
+ func testTwoButtonsHeldCountUntilBothComeUp() {
+ var w = SystemEchoWindow()
+ w.buttonDown(at: 100)
+ w.buttonDown(at: 100.1)
+ w.buttonUp(at: 100.2)
+ XCTAssertTrue(w.isEcho(at: 105), "one is still held")
+ w.buttonUp(at: 105)
+ w.buttonUp(at: 105) // an extra coming up does not go below none
+ XCTAssertEqual(w.held, 0)
+ XCTAssertFalse(w.isEcho(at: 106.1))
+ }
+ func testANewButtonAfterATouchOpensTheWindowAgain() {
+ var w = SystemEchoWindow()
+ w.buttonDown(at: 100)
+ w.buttonUp(at: 100.1)
+ w.touch(at: 100.2)
+ w.buttonDown(at: 100.5)
+ XCTAssertTrue(w.isEcho(at: 100.6))
+ }
+
+ @MainActor func testTheGateUsesItsClockAndNeverMarksItsOwnInput() {
+ var now: TimeInterval = 10
+ let gate = InputGate(clock: { now })
+ XCTAssertFalse(gate.isSystemEcho)
+ gate.controller(.activate)
+ now = 12
+ XCTAssertTrue(gate.isSystemEcho, "A still held")
+ gate.controllerUp(.activate)
+ now = 12.5
+ XCTAssertTrue(gate.isSystemEcho)
+ gate.handling = true
+ XCTAssertFalse(gate.isSystemEcho, "the shell's own handling of a press is not the echo")
+ gate.handling = false
+ gate.touch()
+ XCTAssertFalse(gate.isSystemEcho)
+ gate.controller(.right)
+ now = 13.6
+ XCTAssertFalse(gate.isSystemEcho, "a held direction repeats and is not counted as held")
+ }
+}
+
+/// Which focus targets the D-pad reaches: those of the dialog or panel on top, else only the library's.
+final class FocusLayerTests: XCTestCase {
+ func testTheTopLayerOwnsTheDPad() {
+ XCTAssertTrue(FocusLayer.isLive("set.back", under: .settings))
+ XCTAssertFalse(FocusLayer.isLive("lib.play", under: .settings))
+ XCTAssertFalse(FocusLayer.isLive("set.back", under: .padMapping))
+ XCTAssertTrue(FocusLayer.isLive("map.close", under: .padMapping))
+ XCTAssertTrue(FocusLayer.isLive("lib.play", under: nil))
+ XCTAssertTrue(FocusLayer.isLive("lib.tile.x", under: nil))
+ for layer in FocusLayer.allCases {
+ XCTAssertFalse(FocusLayer.isLive(layer.prefix + "close", under: nil), "\(layer) closed is not reached")
+ }
+ }
+ func testTheLibraryUnderALayerTakesOnlyTheShellsPresses() {
+ XCTAssertTrue(FocusLayer.libraryTakesPress(fromShell: false, under: nil), "a tap on the library")
+ XCTAssertTrue(FocusLayer.libraryTakesPress(fromShell: true, under: .settings), "A on a focused cover with the pane sliding in")
+ for layer in FocusLayer.allCases {
+ XCTAssertFalse(FocusLayer.libraryTakesPress(fromShell: false, under: layer), "Play behind \(layer) pressed by the system")
+ }
+ }
+ func testPrefixesDoNotOverlap() {
+ let all = FocusLayer.allCases.map(\.prefix) + [FocusLayer.libraryPrefix]
+ XCTAssertEqual(Set(all).count, all.count)
+ for a in all { for b in all where a != b { XCTAssertFalse(a.hasPrefix(b), "\(a) starts with \(b)") } }
+ }
+
+ /// Every focus target id written in ShellUI starts with exactly one prefix: a target with none would be reached from
+ /// the library under every panel, and one with a prefix of the wrong layer could never be reached.
+ func testEveryTargetIDInTheSourcesHasExactlyOnePrefix() throws {
+ let sources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
+ .deletingLastPathComponent().appendingPathComponent("Sources/ShellUI")
+ let files = try FileManager.default.contentsOfDirectory(at: sources, includingPropertiesForKeys: nil)
+ .filter { $0.pathExtension == "swift" }
+ // The literal at the start of a target id or a target prefix, as the views pass them.
+ let pattern = try Regex(#"(?:shellTarget\(|target: |targetID: |targetPrefix: |targetPrefix = )"([^"\\]*)"#)
+ let prefixes = FocusLayer.allCases.map(\.prefix) + [FocusLayer.libraryPrefix]
+ var seen = 0
+ for file in files {
+ let text = try String(contentsOf: file, encoding: .utf8)
+ for match in text.matches(of: pattern) {
+ guard let literal = match.output[1].substring.map(String.init), !literal.isEmpty else { continue }
+ seen += 1
+ let count = prefixes.filter { literal.hasPrefix($0) }.count
+ XCTAssertEqual(count, 1, "\(file.lastPathComponent): \"\(literal)\" has \(count) known prefixes")
+ }
+ }
+ XCTAssertGreaterThan(seen, 40, "the pattern still finds the target ids")
+ }
+}