// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later import Foundation import GameController #if canImport(UIKit) import UIKit #endif /// Hardware keyboards and gamepads through the GameController framework (Android's /// KeyboardInput and GamepadInput). Both feed InputRouter; their maps are /// InputBindings'. Keys are ignored while a text field is being typed into. /// /// Keyboard: bound hotkeys first ("octaveUp"/"octaveDown" move the piano's octave, /// Shift+the next-column key goes back a column), then the fixed two-octave piano. /// Gamepad: buttons, the D-pad and both sticks (edge-detected with hysteresis) go /// through one press/release path, so any of them can be bound or chorded. @MainActor final class HardwareInput { static let shared = HardwareInput() /// The keyboard piano's octave (Android's KeyboardInput.baseOctave). private(set) var baseOctave = 4 private var pianoHeld: [Int: Int] = [:] // key code -> pitch it started private var heldPad: [Int] = [] // gamepad controls held, in press order private var learnSeq: [Int] = [] private var axes: [Int: Int] = [:] // axis id -> sign (-1, 0, 1) private var started = false private var router: InputRouter { InputRouter.shared } private var bindings: InputBindings { InputBindings.shared } func start() { guard !started else { return } started = true let nc = NotificationCenter.default nc.addObserver(forName: .GCKeyboardDidConnect, object: nil, queue: .main) { n in Task { @MainActor in (n.object as? GCKeyboard).map(HardwareInput.shared.attach) } } nc.addObserver(forName: .GCControllerDidConnect, object: nil, queue: .main) { n in Task { @MainActor in (n.object as? GCController).map(HardwareInput.shared.attach) } } if let kb = GCKeyboard.coalesced { attach(kb) } GCController.controllers().forEach(attach) } // MARK: Keyboard private func attach(_ kb: GCKeyboard) { kb.keyboardInput?.keyChangedHandler = { _, _, code, pressed in Task { @MainActor in HardwareInput.shared.key(code.rawValue, pressed) } } } private func shiftHeld() -> Bool { guard let k = GCKeyboard.coalesced?.keyboardInput else { return false } return (k.button(forKeyCode: .leftShift)?.isPressed ?? false) || (k.button(forKeyCode: .rightShift)?.isPressed ?? false) } private func key(_ code: Int, _ pressed: Bool) { if !pressed { router.releaseRepeat(AnyHashable("k\(code)")) if let pitch = pianoHeld.removeValue(forKey: code) { router.dispatch(.noteOff(pitch: pitch, channel: -1, sounded: false)) } return } if Self.typingInTextField() { return } if router.learnSource == .keyboard { router.dispatch(.raw(source: .keyboard, code: code, value: 1, modifier: 0)) return } if let id = bindings.keyboard[code] { switch id { case "octaveDown": baseOctave = max(0, baseOctave - 1) case "octaveUp": baseOctave = min(8, baseOctave + 1) case "nextColumn": router.pressRepeat(AnyHashable("k\(code)"), shiftHeld() ? .prevColumn : .nextColumn) default: if let a = InputActions.action(id) { router.pressRepeat(AnyHashable("k\(code)"), a) } } return } if let offset = InputBindings.piano[code] { let pitch = min(max(60 + (baseOctave - 4) * 12 + offset, 0), 127) pianoHeld[code] = pitch router.dispatch(.noteOn(pitch: pitch, velocity: 100, channel: -1, sounded: false)) } } #if canImport(UIKit) fileprivate static var found: UIResponder? private static func typingInTextField() -> Bool { found = nil UIApplication.shared.sendAction(#selector(UIResponder.sizzleFindFirstResponder(_:)), to: nil, from: nil, for: nil) defer { found = nil } return found is UITextField || found is UITextView } #else private static func typingInTextField() -> Bool { false } #endif // MARK: Gamepad private func attach(_ c: GCController) { guard let g = c.extendedGamepad else { return } typealias P = InputBindings.Pad let buttons: [(GCControllerButtonInput?, Int)] = [ (g.buttonA, P.a), (g.buttonB, P.b), (g.buttonX, P.x), (g.buttonY, P.y), (g.leftShoulder, P.l1), (g.rightShoulder, P.r1), (g.leftTrigger, P.l2), (g.rightTrigger, P.r2), (g.buttonMenu, P.menu), (g.buttonOptions, P.options), (g.leftThumbstickButton, P.l3), (g.rightThumbstickButton, P.r3), (g.dpad.up, P.up), (g.dpad.down, P.down), (g.dpad.left, P.left), (g.dpad.right, P.right), ] for (button, code) in buttons { button?.pressedChangedHandler = { _, _, pressed in Task { @MainActor in pressed ? HardwareInput.shared.padDown(code) : HardwareInput.shared.padUp(code) } } } // Up is negative, as on Android (GameController's y points up). g.leftThumbstick.valueChangedHandler = { _, x, y in Task { @MainActor in HardwareInput.shared.axis(0, x, P.lsLeft, P.lsRight) HardwareInput.shared.axis(1, -y, P.lsUp, P.lsDown) } } g.rightThumbstick.valueChangedHandler = { _, x, y in Task { @MainActor in HardwareInput.shared.axis(2, x, P.rsLeft, P.rsRight) HardwareInput.shared.axis(3, -y, P.rsUp, P.rsDown) } } } /// Push past 0.6 = press, back inside 0.4 = release; in between, hold. private func axis(_ id: Int, _ value: Float, _ neg: Int, _ pos: Int) { let last = axes[id] ?? 0 let sign = value <= -0.6 ? -1 : value >= 0.6 ? 1 : (value > -0.4 && value < 0.4) ? 0 : last guard sign != last else { return } axes[id] = sign if last == -1 { padUp(neg) } else if last == 1 { padUp(pos) } if sign == -1 { padDown(neg) } else if sign == 1 { padDown(pos) } } private func padDown(_ code: Int) { if router.learnSource == .gamepad { if !learnSeq.contains(code) { learnSeq.append(code) } if !heldPad.contains(code) { heldPad.append(code) } return } // A chord first: any control already held may be the modifier. for mod in heldPad { if let id = bindings.gamepad[GamepadChord(modifier: mod, code: code)] { heldPad.append(code) if let a = InputActions.action(id) { router.pressRepeat(AnyHashable("g\(code)"), a) } return } } if !heldPad.contains(code) { heldPad.append(code) } if let id = bindings.gamepad[GamepadChord(modifier: 0, code: code)], let a = InputActions.action(id) { router.pressRepeat(AnyHashable("g\(code)"), a) } } private func padUp(_ code: Int) { heldPad.removeAll { $0 == code } router.releaseRepeat(AnyHashable("g\(code)")) // A learn capture ends once every control of the combo is released. if router.learnSource == .gamepad, !learnSeq.isEmpty, !heldPad.contains(where: learnSeq.contains) { let main = learnSeq.last!, mod = learnSeq.count >= 2 ? learnSeq.first! : 0 learnSeq.removeAll() router.dispatch(.raw(source: .gamepad, code: main, value: 1, modifier: mod)) } } } #if canImport(UIKit) extension UIResponder { @objc fileprivate func sizzleFindFirstResponder(_ sender: Any?) { HardwareInput.found = self } } #endif