Files
VCCPlusOSS/platforms/macos/App/InputHub.swift
T

187 lines
10 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import AppKit
import Combine
/// Cached host observations, kept separate from core acknowledgement. This DTO
/// permits authored diagnostics tests without opening HID devices or polling.
struct InputDiagnosticObservation {
var preview: [JoystickSample]?
var submitted: [JoystickSample]?
var submittedInterfaces: [JoystickInterface]?
var applicationActive: Bool?
var displayAcceptsInput: Bool?
var pollAgeMilliseconds: Int?
var submissionAgeMilliseconds: Int?
var settingsError = false
}
@MainActor
final class InputHub: ObservableObject {
@Published var settings: InputSettings { didSet {
guard settings != oldValue else { return }
release(); epoch &+= 1
do { try store.save(settings); error = nil } catch { self.error = "Could not save input settings: \(error.localizedDescription)" }
} }
@Published private(set) var devices: [ControllerReading] = []
@Published private(set) var preview = [JoystickSample(), JoystickSample()]
@Published private(set) var error: String?
private(set) var epoch: UInt64 = 0
var acceptsInput: () -> Bool = { false }
private let store: InputSettingsStore
private let controller: VCCMachineController
private let hardware: ControllerDevices
private var timer: Timer?
private var routing = InputRouting()
private var last: [JoystickSample] = []
private var lastActive = false
private var lastPollUptime: TimeInterval?
private var lastSubmissionUptime: TimeInterval?
private var lastApplicationActive: Bool?
private var lastDisplayAcceptsInput: Bool?
private var submitted: [JoystickSample]?
private var submittedInterfaces: [JoystickInterface]?
init(controller: VCCMachineController, store: InputSettingsStore = .standard) {
self.controller = controller; self.store = store; hardware = ControllerDevices()
do { settings = try store.load() } catch {
settings = InputSettings(); self.error = "Could not read input settings: \(error.localizedDescription)"
}
timer = Timer.scheduledTimer(withTimeInterval: 1 / 60, repeats: true) { [weak self] _ in
MainActor.assumeIsolated { self?.poll() }
}
#if VCC_UI_TESTING
// Keep the authored preview moving even during native menu tracking.
if let timer { RunLoop.main.add(timer, forMode: .common) }
#endif
}
deinit { timer?.invalidate() }
func swap() { var next = settings; next.right = settings.left; next.left = settings.right; settings = next }
func key(_ code: UInt16, down: Bool) -> Bool {
routing.key(code, down: down, settings: settings)
}
func mouseMove(x: Double, y: Double) {
guard x.isFinite, y.isFinite else { return }
routing.mouse.x = Int(min(1, max(0, x)) * 16383)
routing.mouse.y = Int(min(1, max(0, y)) * 16383)
}
func mouseLeave() { routing.mouse = JoystickSample() }
func mouseButton(_ button: Int, down: Bool) {
guard (0...1).contains(button) else { return }
if down { routing.mouse.buttons |= 1 << button } else { routing.mouse.buttons &= ~(1 << button) }
}
func release() {
routing.release(); last = []
lastPollUptime = nil; lastApplicationActive = nil; lastDisplayAcceptsInput = nil
submit([JoystickSample(), JoystickSample()])
}
private func poll() {
#if VCC_UI_TESTING
// Exercise the real preview/selection views with changing input even
// when no physical controller is attached to the test Mac.
let phase = ProcessInfo.processInfo.systemUptime
let readings = [ControllerReading(id: "ui-fixture", name: "Authored test controller",
x: sin(phase), y: cos(phase), rx: sin(phase * 2), ry: cos(phase * 2))]
#else
let readings = hardware.read()
#endif
if devices != readings { devices = readings }
let displayAcceptsInput = acceptsInput(), applicationActive = NSApp.isActive
let active = displayAcceptsInput && applicationActive
lastPollUptime = ProcessInfo.processInfo.systemUptime
lastApplicationActive = applicationActive; lastDisplayAcceptsInput = displayAcceptsInput
if active != lastActive { last = []; lastActive = active }
let delivered = routing.delivery(settings: settings, devices: readings, active: active)
let samples = routing.samples(settings: settings, devices: readings)
if preview != samples { preview = samples }
if delivered != last {
last = delivered
submit(delivered)
}
}
private func submit(_ samples: [JoystickSample]) {
submitted = samples; submittedInterfaces = (0..<2).map { settings[$0].interface }
lastSubmissionUptime = ProcessInfo.processInfo.systemUptime
for port in 0..<2 {
controller.setJoystick(UInt(port), x: UInt(samples[port].x), y: UInt(samples[port].y),
buttons: UInt(samples[port].buttons), mode: UInt(settings[port].interface.rawValue))
}
}
/// Reads cached native observations and a caller-supplied immutable machine
/// snapshot. It never polls HID, changes focus/settings, or queues input.
func diagnostics(machine: VCCMachineSnapshot) -> [String: Any] {
let now = ProcessInfo.processInfo.systemUptime
func age(_ time: TimeInterval?) -> Int? { time.map { Int(max(0, now - $0) * 1000) } }
return Self.diagnostics(settings: settings, devices: devices,
observation: InputDiagnosticObservation(preview: lastPollUptime == nil ? nil : preview,
submitted: submitted, submittedInterfaces: submittedInterfaces,
applicationActive: lastApplicationActive, displayAcceptsInput: lastDisplayAcceptsInput,
pollAgeMilliseconds: age(lastPollUptime), submissionAgeMilliseconds: age(lastSubmissionUptime),
settingsError: error != nil), machine: machine)
}
static func unavailableDiagnostics(machine: VCCMachineSnapshot) -> [String: Any] {
var result = diagnostics(settings: InputSettings(), devices: [], observation: InputDiagnosticObservation(), machine: machine)
result["configuration_available"] = false; result["settings_error"] = NSNull()
if let ports = result["ports"] as? [[String: Any]] {
result["ports"] = ports.map { value -> [String: Any] in
var port = value
port["source"] = "unknown"
for key in ["interface", "dead_zone", "controller_connected", "controller_mapping", "keyboard_binding"] { port[key] = NSNull() }
return port
}
}
return result
}
static func diagnostics(settings: InputSettings, devices: [ControllerReading],
observation: InputDiagnosticObservation, machine: VCCMachineSnapshot) -> [String: Any] {
func interface(_ mode: Int) -> String {
switch mode { case 0: return "standard"; case 1: return "software"; case 2: return "tandy"; case 3: return "coco_max"; default: return "unknown" }
}
func source(_ value: JoystickSource) -> String {
switch value { case .none: return "none"; case .keyboard: return "keyboard"; case .mouse: return "mouse"; case .controller: return "controller" }
}
func buttons(_ value: Int) -> [String] { [(value & 1) != 0 ? "fire1" : nil, (value & 2) != 0 ? "fire2" : nil].compactMap { $0 } }
func sample(_ value: JoystickSample, mode: Int) -> [String: Any] {
["x": value.x, "y": value.y, "buttons": buttons(value.buttons), "interface": interface(mode)]
}
let available = machine.state == .running || machine.state == .paused
let focusActive: Bool? = observation.applicationActive.flatMap { app in observation.displayAcceptsInput.map { app && $0 } }
let ports: [[String: Any]] = (0..<2).map { port in
let config = settings[port]
let preview: Any = observation.preview.flatMap { values in
values.indices.contains(port) ? sample(values[port], mode: config.interface.rawValue) : nil
} ?? NSNull()
let submitted: Any = observation.submitted.flatMap { values in
guard values.indices.contains(port), let modes = observation.submittedInterfaces, modes.indices.contains(port) else { return nil }
return sample(values[port], mode: modes[port].rawValue)
} ?? NSNull()
let actual: Any
if available, machine.joystickInputs.indices.contains(port) {
let value = machine.joystickInputs[port]
actual = sample(JoystickSample(x: Int(value.x), y: Int(value.y), buttons: Int(value.buttons)), mode: Int(value.mode))
} else { actual = NSNull() }
return ["port": port == 0 ? "right" : "left", "source": source(config.source),
"interface": interface(config.interface.rawValue), "dead_zone": config.deadZone,
"controller_connected": config.source == .controller ? devices.contains { $0.id == config.device } as Any : NSNull(),
"controller_mapping": config.source == .controller
? ["stick": config.rightStick ? "right" : "left", "fire1_button": config.fire1, "fire2_button": config.fire2] as Any : NSNull(),
"keyboard_binding": config.source == .keyboard ? config.keys.rawValue as Any : NSNull(),
"preview": preview, "submitted": submitted, "actual": actual]
}
return ["source": "shared_machine", "axis_min": 0, "axis_max": 16383, "axis_center": 8191,
"x_direction": "right", "y_direction": "down", "configuration_available": true, "settings_error": observation.settingsError,
"host_observation": ["age_ms": observation.pollAgeMilliseconds as Any? ?? NSNull(),
"application_active": observation.applicationActive as Any? ?? NSNull(),
"display_accepts_input": observation.displayAcceptsInput as Any? ?? NSNull(),
"active": focusActive as Any? ?? NSNull()],
"submission_age_ms": observation.submissionAgeMilliseconds as Any? ?? NSNull(),
"submission_is_delivery_confirmation": false,
"machine_observation": ["available": available, "generation": machine.generation,
"frame": machine.frames, "cycles": machine.cycles,
"keyboard_held": available ? machine.keyboardInputHeld as Any : NSNull()],
"ports": ports]
}
}