122 lines
6.8 KiB
Swift
122 lines
6.8 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import Foundation
|
|
import GameController
|
|
import IOKit.hid
|
|
|
|
struct ControllerReading: Identifiable, Equatable {
|
|
let id: String, name: String
|
|
var x = 0.0, y = 0.0, rx = 0.0, ry = 0.0
|
|
var buttons: UInt32 = 0
|
|
func sample(_ settings: PortSettings) -> JoystickSample {
|
|
JoystickSample(x: JoystickSample.axis(settings.rightStick ? rx : x, deadZone: settings.deadZone),
|
|
y: JoystickSample.axis(settings.rightStick ? ry : y, deadZone: settings.deadZone),
|
|
buttons: (buttons & (1 << (settings.fire1 - 1)) != 0 ? 1 : 0)
|
|
| (buttons & (1 << (settings.fire2 - 1)) != 0 ? 2 : 0))
|
|
}
|
|
}
|
|
|
|
// GameController handles macOS-supported pads (including PlayStation/Xbox).
|
|
// Native HID covers standard USB joysticks/gamepads such as the F310 in D mode.
|
|
// Never seize devices, match keyboards/mice, or install a system driver.
|
|
@MainActor
|
|
final class ControllerDevices {
|
|
private let manager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone))
|
|
private var devices: [IOHIDDevice] = []
|
|
private var elements: [String: [IOHIDElement]] = [:]
|
|
private var controllerIDs: [ObjectIdentifier: (base: String, ordinal: Int)] = [:]
|
|
private var nextRefresh = Date.distantPast
|
|
init() {
|
|
let matches = [4, 5].map { [kIOHIDDeviceUsagePageKey: 1, kIOHIDDeviceUsageKey: $0] }
|
|
IOHIDManagerSetDeviceMatchingMultiple(manager, matches as CFArray)
|
|
IOHIDManagerScheduleWithRunLoop(manager, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
|
|
IOHIDManagerOpen(manager, IOOptionBits(kIOHIDOptionsTypeNone))
|
|
GCController.shouldMonitorBackgroundEvents = false
|
|
}
|
|
deinit {
|
|
IOHIDManagerUnscheduleFromRunLoop(manager, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
|
|
IOHIDManagerClose(manager, IOOptionBits(kIOHIDOptionsTypeNone))
|
|
}
|
|
private func property(_ device: IOHIDDevice, _ key: String) -> String {
|
|
IOHIDDeviceGetProperty(device, key as CFString).map { String(describing: $0) } ?? ""
|
|
}
|
|
private func identity(_ device: IOHIDDevice) -> String {
|
|
let serial = property(device, kIOHIDSerialNumberKey)
|
|
return "hid:\(property(device, kIOHIDVendorIDKey)):\(property(device, kIOHIDProductIDKey)):\(serial.isEmpty ? property(device, kIOHIDLocationIDKey) : serial)"
|
|
}
|
|
func read() -> [ControllerReading] {
|
|
if Date() >= nextRefresh {
|
|
devices = (IOHIDManagerCopyDevices(manager) as? Set<IOHIDDevice> ?? []).filter { !GCController.supportsHIDDevice($0) }
|
|
elements.removeAll()
|
|
for device in devices {
|
|
elements[identity(device)] = IOHIDDeviceCopyMatchingElements(device, nil, 0) as? [IOHIDElement] ?? []
|
|
}
|
|
nextRefresh = Date().addingTimeInterval(0.5)
|
|
}
|
|
var readings: [ControllerReading] = []
|
|
let controllers = GCController.controllers()
|
|
let connected = Set(controllers.map(ObjectIdentifier.init))
|
|
controllerIDs = controllerIDs.filter { connected.contains($0.key) }
|
|
for controller in controllers {
|
|
guard let pad = controller.extendedGamepad else { continue }
|
|
let name = controller.vendorName ?? "Game controller"
|
|
let base = "gc:\(name):\(controller.productCategory)"
|
|
let identity = ObjectIdentifier(controller)
|
|
if controllerIDs[identity] == nil {
|
|
let used = Set(controllerIDs.values.filter { $0.base == base }.map(\.ordinal))
|
|
var ordinal = 0
|
|
while used.contains(ordinal) { ordinal += 1 }
|
|
controllerIDs[identity] = (base, ordinal)
|
|
}
|
|
let ordinal = controllerIDs[identity]!.ordinal
|
|
var value = ControllerReading(id: "\(base):\(ordinal)", name: name + (ordinal == 0 ? "" : " \(ordinal + 1)"))
|
|
let direction = pad.dpad.xAxis.value != 0 || pad.dpad.yAxis.value != 0 ? pad.dpad : pad.leftThumbstick
|
|
value.x = Double(direction.xAxis.value); value.y = -Double(direction.yAxis.value)
|
|
value.rx = Double(pad.rightThumbstick.xAxis.value); value.ry = -Double(pad.rightThumbstick.yAxis.value)
|
|
let buttons: [GCControllerButtonInput?] = [pad.buttonA,pad.buttonB,pad.buttonX,pad.buttonY,
|
|
pad.leftShoulder,pad.rightShoulder,pad.leftTrigger,pad.rightTrigger,
|
|
pad.buttonOptions,pad.buttonMenu,pad.leftThumbstickButton,pad.rightThumbstickButton]
|
|
for (index, button) in buttons.enumerated() where button?.isPressed == true { value.buttons |= 1 << index }
|
|
readings.append(value)
|
|
}
|
|
for device in devices {
|
|
var value = ControllerReading(id: identity(device), name: property(device, kIOHIDProductKey))
|
|
var hasValue = false
|
|
var hat: Int?
|
|
var axes: [UInt32: Double] = [:]
|
|
for element in elements[value.id] ?? [] {
|
|
let type = IOHIDElementGetType(element)
|
|
guard (1...3).contains(type.rawValue) else { continue }
|
|
let page = IOHIDElementGetUsagePage(element), usage = IOHIDElementGetUsage(element)
|
|
guard page == 1 || page == 9 else { continue }
|
|
let raw: IOHIDValue? = withUnsafeTemporaryAllocation(of: Unmanaged<IOHIDValue>.self, capacity: 1) { buffer in
|
|
guard IOHIDDeviceGetValue(device, element, buffer.baseAddress!) == kIOReturnSuccess else { return nil }
|
|
return buffer[0].takeUnretainedValue()
|
|
}
|
|
guard let raw else { continue }
|
|
hasValue = true
|
|
let integer = IOHIDValueGetIntegerValue(raw)
|
|
if page == 9, (1...16).contains(usage), integer != 0 { value.buttons |= 1 << (usage - 1) }
|
|
if page == 1 {
|
|
let low = IOHIDElementGetLogicalMin(element), high = IOHIDElementGetLogicalMax(element)
|
|
guard high > low else { continue }
|
|
let normalized = min(1, max(-1, 2 * Double(integer - low) / Double(high - low) - 1))
|
|
switch usage {
|
|
case 0x30...0x35: axes[usage] = normalized
|
|
case 0x39: if (low...high).contains(integer), high - low == 7 { hat = integer - low }
|
|
default: break
|
|
}
|
|
}
|
|
}
|
|
value.x = axes[0x30] ?? 0; value.y = axes[0x31] ?? 0
|
|
value.rx = axes[0x33] ?? axes[0x32] ?? 0; value.ry = axes[0x34] ?? axes[0x35] ?? 0
|
|
if let hat {
|
|
value.x = [1,2,3].contains(hat) ? 1 : ([5,6,7].contains(hat) ? -1 : 0)
|
|
value.y = [7,0,1].contains(hat) ? -1 : ([3,4,5].contains(hat) ? 1 : 0)
|
|
}
|
|
// A removed device may remain in our half-second inventory cache.
|
|
if hasValue { readings.append(value) }
|
|
}
|
|
return readings.sorted { $0.id < $1.id }
|
|
}
|
|
}
|