Files

154 lines
7.0 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
enum JoystickSource: String, Codable, CaseIterable {
case none = "None", keyboard = "Keyboard", mouse = "Mouse", controller = "Controller"
}
enum JoystickInterface: Int, Codable, CaseIterable {
case standard = 0, software = 1, tandy = 2, cocoMax = 3
var label: String { ["Standard", "Software high resolution", "Tandy high resolution", "CoCoMax"][rawValue] }
}
enum JoystickKeys: String, Codable, CaseIterable {
case arrows = "Arrows + Z / X", wasd = "W A S D + F / G", keypad = "Keypad 8 2 4 6 + 0 / ."
// up, down, left, right, fire 1, fire 2
var codes: [UInt16] {
switch self {
case .arrows: return [126,125,123,124,6,7]
case .wasd: return [13,1,0,2,3,5]
case .keypad: return [91,84,86,88,82,65]
}
}
}
struct PortSettings: Codable, Equatable {
var source: JoystickSource = .none
var interface: JoystickInterface = .standard
var keys: JoystickKeys = .arrows
var device = ""
var rightStick = false
var fire1 = 1, fire2 = 2
var deadZone = 0.15
}
struct InputSettings: Codable, Equatable {
var keyboard: KeyboardMode = .natural
var right = PortSettings(), left = PortSettings(keys: .wasd)
subscript(port: Int) -> PortSettings {
get { port == 0 ? right : left }
set { if port == 0 { right = newValue } else { left = newValue } }
}
/// An unassigned Controller source can adopt an unambiguous connection.
/// A remembered device remains authoritative even while disconnected.
static var freshDefaults: Self {
var value = Self(); value.right.source = .mouse
return value
}
func assigningSoleController(_ deviceIDs: [String], automaticRight: Bool = false) -> Self {
guard deviceIDs.count == 1, let device = deviceIDs.first,
!device.isEmpty, device.count < 1024 else { return self }
var result = self
if automaticRight, result.right.source == .mouse, result.right.device.isEmpty {
result.right.source = .controller
}
for port in 0..<2 where result[port].source == .controller && result[port].device.isEmpty {
result[port].device = device
}
return result
}
func validated() throws -> Self {
for p in [right, left] {
guard p.deadZone.isFinite, (0...0.5).contains(p.deadZone),
(1...16).contains(p.fire1), (1...16).contains(p.fire2), p.device.count < 1024 else {
throw CocoaError(.coderReadCorrupt)
}
}
return self
}
}
struct InputSettingsStore {
struct State {
let settings: InputSettings
let automaticRightController: Bool
}
/// Keep the existing flat settings document/profile contract. This optional
/// store-only marker distinguishes a fresh fallback from a person's choice.
private struct Record: Codable {
let settings: InputSettings
let automaticRightController: Bool
private enum Keys: String, CodingKey { case automaticRightController }
init(settings: InputSettings, automaticRightController: Bool) {
self.settings = settings; self.automaticRightController = automaticRightController
}
init(from decoder: Decoder) throws {
settings = try InputSettings(from: decoder)
automaticRightController = try decoder.container(keyedBy: Keys.self)
.decodeIfPresent(Bool.self, forKey: .automaticRightController) ?? false
}
func encode(to encoder: Encoder) throws {
try settings.encode(to: encoder)
if automaticRightController {
var fields = encoder.container(keyedBy: Keys.self)
try fields.encode(true, forKey: .automaticRightController)
}
}
}
let url: URL
static let standard = InputSettingsStore(url: AppIdentity.supportDirectory.appendingPathComponent("InputSettings.json"))
func load() throws -> InputSettings {
try loadState().settings
}
func loadState() throws -> State {
guard FileManager.default.fileExists(atPath: url.path) else {
return State(settings: .freshDefaults, automaticRightController: true)
}
let record = try JSONDecoder().decode(Record.self, from: Data(contentsOf: url))
return State(settings: try record.settings.validated(), automaticRightController: record.automaticRightController)
}
func save(_ value: InputSettings, automaticRightController: Bool = false) throws {
_ = try value.validated()
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try JSONEncoder().encode(Record(settings: value, automaticRightController: automaticRightController)).write(to: url, options: .atomic)
}
}
struct JoystickSample: Equatable {
var x = 8191, y = 8191, buttons = 0
static func axis(_ value: Double, deadZone: Double) -> Int {
guard value.isFinite else { return 8191 }
let v = min(1, max(-1, value)), dead = min(0.5, max(0, deadZone))
if abs(v) <= dead { return 8191 }
let adjusted = (abs(v) - dead) / (1 - dead) * (v < 0 ? -1 : 1)
return Int(((adjusted + 1) * 8191.5).rounded())
}
static func keyboard(_ held: Set<UInt16>, keys: JoystickKeys) -> Self {
let down = keys.codes.map { held.contains($0) }
func axis(_ low: Bool, _ high: Bool) -> Int { low == high ? 8191 : (low ? 0 : 16383) }
return Self(x: axis(down[2], down[3]), y: axis(down[0], down[1]), buttons: (down[4] ? 1 : 0) | (down[5] ? 2 : 0))
}
}
// Device-independent host state. Focus loss drops held keys/buttons; a missing
// remembered controller always yields neutral input, never another device.
struct InputRouting {
private(set) var held: Set<UInt16> = []
var mouse = JoystickSample()
mutating func key(_ code: UInt16, down: Bool, settings: InputSettings) -> Bool {
let reserved = [settings.right, settings.left].contains { $0.source == .keyboard && $0.keys.codes.contains(code) }
if down && reserved { held.insert(code) } else { held.remove(code) }
return reserved
}
mutating func release() { held.removeAll(); mouse = JoystickSample() }
func samples(settings: InputSettings, devices: [ControllerReading]) -> [JoystickSample] {
(0..<2).map { port in
let config = settings[port]
switch config.source {
case .none: return JoystickSample()
case .keyboard: return .keyboard(held, keys: config.keys)
case .mouse: return mouse
case .controller: return devices.first { $0.id == config.device }?.sample(config) ?? JoystickSample()
}
}
}
mutating func delivery(settings: InputSettings, devices: [ControllerReading], active: Bool) -> [JoystickSample] {
guard active else { release(); return [JoystickSample(), JoystickSample()] }
return samples(settings: settings, devices: devices)
}
}