From a316395428dbe2268bc1eccd68f74795b444bce2 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 01/13] Add event support in Package.swift --- Package.swift | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/Package.swift b/Package.swift index a58069a..2c72e24 100644 --- a/Package.swift +++ b/Package.swift @@ -94,16 +94,20 @@ let package = Package( .library( name: "GraphiteDialogs", targets: ["GraphiteDialogs"] - ) + ), + .library(name: "GraphiteEvents", targets: ["GraphiteEvents"]), + .library(name: "GraphiteSDLEvents", targets: ["GraphiteSDLEvents"]) ], // FreeType reads outline fonts; builds without it keep the bitmap font. traits: [ .trait(name: "FreeType", description: "Outline fonts through FreeType"), + .trait(name: "SDL3", description: "SDL3 event host"), .default(enabledTraits: ["FreeType"]), ], dependencies: [ .package(url: "https://github.com/apple/swift-system.git", from: "1.9.0"), .package(url: "https://github.com/PureSwift/swift-freetype.git", from: "0.1.1"), + .package(url: "https://github.com/PureSwift/SDL.git", exact: "3.3.0"), ], targets: [ .target( @@ -165,9 +169,13 @@ let package = Package( name: "GraphiteDialogs", dependencies: ["GraphiteBase", "GraphiteWindows", "GraphiteControls", "GraphiteResources"] ), + .target(name: "GraphiteEvents", dependencies: ["GraphiteBase"]), + .target(name: "GraphiteSDLEvents", dependencies: ["GraphiteEvents", "GraphiteBase", + .product(name: "SDL3Swift", package: "SDL", condition: .when(traits: ["SDL3"]))], + swiftSettings: [.define("GRAPHITE_SDL3", .when(traits: ["SDL3"]))]), .target( name: "Graphite", - dependencies: ["GraphiteBase", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAppleEvents", "GraphiteQuickDraw", "GraphiteText", "GraphiteSound", "GraphiteWindows", "GraphiteMenus", "GraphiteControls", "GraphiteDialogs"] + dependencies: ["GraphiteBase", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAppleEvents", "GraphiteQuickDraw", "GraphiteText", "GraphiteSound", "GraphiteWindows", "GraphiteMenus", "GraphiteControls", "GraphiteDialogs", "GraphiteEvents"] ), .testTarget( name: "GraphiteBaseTests", @@ -216,6 +224,10 @@ let package = Package( .testTarget( name: "GraphiteDialogsTests", dependencies: ["GraphiteDialogs"] - ) + ), + .testTarget(name: "GraphiteEventsTests", dependencies: ["GraphiteEvents"]), + .testTarget(name: "GraphiteSDLEventsTests", dependencies: ["GraphiteSDLEvents", "GraphiteEvents", "GraphiteBase", + .product(name: "SDL3Swift", package: "SDL", condition: .when(traits: ["SDL3"]))], + swiftSettings: [.define("GRAPHITE_SDL3", .when(traits: ["SDL3"]))]) ] ) From 98993f1796317756654daa852b13361bb5e4f5d9 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 02/13] Add event support in README.md --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index 940a78b..bc360a0 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,15 @@ swift build swift test ``` +The optional `GraphiteSDLEvents` product supplies an SDL3 event-loop host. +Install SDL3 (`brew install sdl3` or the SDL3 development package) and enable +its trait with `swift build --traits SDL3`. Initialize SDL's event subsystem +before constructing `SDLEventHost`, and supply a callback for SDL events the +host does not translate. The SDL event pump must run on the main thread. The +host's `globalPosition` callback maps window-local SDL mouse coordinates to +global coordinates; provide it when windows are not at the origin. Translated +events carry their SDL window ID in the `swin` parameter. + ## License MIT. Code ported from [Pomme](https://github.com/jorio/Pomme) keeps its MIT From 1a5d059a3662adca0cf45fe69bd9fc0938b7e847 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 03/13] Add event support in Graphite.swift --- Sources/Graphite/Graphite.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/Graphite/Graphite.swift b/Sources/Graphite/Graphite.swift index 68013c5..684e7ef 100644 --- a/Sources/Graphite/Graphite.swift +++ b/Sources/Graphite/Graphite.swift @@ -13,3 +13,4 @@ @_exported import GraphiteMenus @_exported import GraphiteControls @_exported import GraphiteDialogs +@_exported import GraphiteEvents From 45c11176e9802c51591e52be70fa3977c916217e Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 04/13] Add event support in CarbonEvent.swift --- Sources/GraphiteEvents/CarbonEvent.swift | 48 ++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Sources/GraphiteEvents/CarbonEvent.swift diff --git a/Sources/GraphiteEvents/CarbonEvent.swift b/Sources/GraphiteEvents/CarbonEvent.swift new file mode 100644 index 0000000..a8e1308 --- /dev/null +++ b/Sources/GraphiteEvents/CarbonEvent.swift @@ -0,0 +1,48 @@ +import GraphiteBase + +/// A Carbon event class and kind. +public struct EventType: Hashable, Sendable { + public var eventClass: FourCharCode + public var kind: UInt32 + public init(eventClass: FourCharCode, kind: UInt32) { + self.eventClass = eventClass + self.kind = kind + } +} + +/// A typed parameter; its byte representation is agreed by its producer and consumer. +public struct EventParameter: Hashable, Sendable { + public var type: FourCharCode + public var bytes: [UInt8] + public init(type: FourCharCode, bytes: [UInt8]) { + self.type = type + self.bytes = bytes + } +} + +/// A Carbon event. Copies have independent parameter tables. +public struct CarbonEvent: Sendable { + public var type: EventType + public var time: Double + public var attributes: UInt32 + public private(set) var parameters: [FourCharCode: EventParameter] = [:] + + public init(type: EventType, time: Double, attributes: UInt32 = 0) { + self.type = type + self.time = time + self.attributes = attributes + } + + public mutating func setParameter(_ name: FourCharCode, type: FourCharCode, bytes: [UInt8]) { + parameters[name] = EventParameter(type: type, bytes: bytes) + } + + public func parameter(_ name: FourCharCode, type: FourCharCode? = nil) -> EventParameter? { + guard let parameter = parameters[name], type == nil || parameter.type == type else { return nil } + return parameter + } + + public mutating func removeParameter(_ name: FourCharCode) { + parameters.removeValue(forKey: name) + } +} From 8a10f22faafdb96d01253b32839e57b63ca0edd8 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 05/13] Add event support in ClassicEvent.swift --- Sources/GraphiteEvents/ClassicEvent.swift | 87 +++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Sources/GraphiteEvents/ClassicEvent.swift diff --git a/Sources/GraphiteEvents/ClassicEvent.swift b/Sources/GraphiteEvents/ClassicEvent.swift new file mode 100644 index 0000000..60fdb92 --- /dev/null +++ b/Sources/GraphiteEvents/ClassicEvent.swift @@ -0,0 +1,87 @@ +import GraphiteBase +import Synchronization + +/// The classic EventRecord; the host supplies ticks and global mouse state. +public struct ClassicEvent: Hashable, Sendable { + public var what: UInt16 + public var message: UInt32 + public var when: UInt32 + public var where_: Point + public var modifiers: UInt16 + + public init(what: UInt16, message: UInt32 = 0, when: UInt32 = 0, + location: Point = .zero, modifiers: UInt16 = 0) { + self.what = what + self.message = message + self.when = when + self.where_ = location + self.modifiers = modifiers + } +} + +/// The classic queue supports EventAvail's peek, GetNextEvent's removal, +/// and FlushEvents' stop mask. Event masks have one bit per event code. +public final class ClassicEventQueue: Sendable { + private let events = Mutex<[ClassicEvent]>([]) + public init() {} + public func post(_ event: ClassicEvent) { events.withLock { $0.append(event) } } + public func next(mask: UInt16, remove: Bool = true) -> ClassicEvent? { + events.withLock { queue in + guard let index = queue.firstIndex(where: { Self.matches($0, mask) }) else { return nil } + return remove ? queue.remove(at: index) : queue[index] + } + } + public func flush(mask: UInt16, stopMask: UInt16 = 0) { + events.withLock { queue in + let stop = queue.firstIndex { Self.matches($0, stopMask) } ?? queue.endIndex + queue.replaceSubrange(0.. Bool { + event.what < 16 && (mask & (UInt16(1) << event.what)) != 0 + } +} + +/// The host blocks until input, a mouse-region transition, or the deadline. +/// The deadline is in seconds on the host's monotonic event clock. +public protocol ClassicEventHost: AnyObject { + var eventTime: Double { get } + var ticks: UInt32 { get } + var mouseLocation: Point { get } + var modifiers: UInt16 { get } + func waitForClassicEvents(until deadline: Double, queue: ClassicEventQueue) +} + +/// Classic Event Manager retrieval over a host's event source. +public final class ClassicEventManager { + public let queue: ClassicEventQueue + public let host: any ClassicEventHost + + public init(host: any ClassicEventHost, queue: ClassicEventQueue = ClassicEventQueue()) { + self.host = host + self.queue = queue + } + + /// A missing event is represented by a null event with current input state. + public func next(mask: UInt16, remove: Bool = true) -> (found: Bool, event: ClassicEvent) { + if let event = queue.next(mask: mask, remove: remove) { return (true, event) } + return (false, nullEvent()) + } + + /// WaitNextEvent's sleep is in 60 Hz ticks. `mouseInside`, when supplied, + /// returns false after the mouse leaves the caller's region. + public func waitNext(mask: UInt16, sleepTicks: UInt32, + mouseInside: ((Point) -> Bool)? = nil) -> (found: Bool, event: ClassicEvent) { + let deadline = host.eventTime + Double(sleepTicks) / 60 + while true { + if let event = queue.next(mask: mask) { return (true, event) } + if let mouseInside, !mouseInside(host.mouseLocation) { return (false, nullEvent()) } + guard host.eventTime < deadline else { return (false, nullEvent()) } + host.waitForClassicEvents(until: deadline, queue: queue) + } + } + + private func nullEvent() -> ClassicEvent { + ClassicEvent(what: 0, when: host.ticks, location: host.mouseLocation, modifiers: host.modifiers) + } +} From 7e28d27af3ff0d060c05404ea5597ba712f36c6f Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 06/13] Add event support in EventLoop.swift --- Sources/GraphiteEvents/EventLoop.swift | 106 +++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 Sources/GraphiteEvents/EventLoop.swift diff --git a/Sources/GraphiteEvents/EventLoop.swift b/Sources/GraphiteEvents/EventLoop.swift new file mode 100644 index 0000000..d4c3f82 --- /dev/null +++ b/Sources/GraphiteEvents/EventLoop.swift @@ -0,0 +1,106 @@ +/// The host waits for input until the supplied monotonic deadline. A nil +/// deadline means no timeout. It posts received events to the loop's queue. +public protocol EventLoopHost: AnyObject { + var eventTime: Double { get } + func waitForEvents(until deadline: Double?, queue: EventQueue) + func wakeEventLoop() +} + +/// The result of waiting for a Carbon event. +public enum EventReceiveResult: Sendable { + case event(CarbonEvent) + case timedOut + case quit +} + +/// A host-driven Carbon event loop. Call its methods on the loop's thread; +/// other threads can post to the queue and wake the host. +public final class EventLoop { + private struct Timer { + let id: UInt64 + var fireTime: Double + var interval: Double + let callback: (UInt64) -> Void + } + public let queue: EventQueue + public let target: EventTarget + public let host: any EventLoopHost + private var timers: [Timer] = [] + private var nextTimer: UInt64 = 1 + private var shouldQuit = false + + public init(host: any EventLoopHost, queue: EventQueue = EventQueue(), target: EventTarget = EventTarget()) { + self.host = host + self.queue = queue + self.target = target + } + + public func post(_ event: CarbonEvent, priority: EventPriority = .standard) { + queue.post(event, priority: priority) + host.wakeEventLoop() + } + + @discardableResult + public func installTimer(delay: Double, interval: Double = 0, callback: @escaping (UInt64) -> Void) -> UInt64 { + let id = nextTimer + nextTimer &+= 1 + timers.append(Timer(id: id, fireTime: host.eventTime + max(0, delay), interval: max(0, interval), callback: callback)) + host.wakeEventLoop() + return id + } + + public func removeTimer(_ id: UInt64) { timers.removeAll { $0.id == id } } + public func setTimer(_ id: UInt64, delay: Double) { + guard let index = timers.firstIndex(where: { $0.id == id }) else { return } + timers[index].fireTime = host.eventTime + max(0, delay) + host.wakeEventLoop() + } + public func quit() { shouldQuit = true; host.wakeEventLoop() } + + /// Wait for a matching event, running timers while the host waits. A nil + /// timeout waits indefinitely; zero checks the queue without waiting. + public func receive(matching types: Set = [], timeout: Double? = nil, + remove: Bool = true) -> EventReceiveResult { + let deadline = timeout.map { host.eventTime + max(0, $0) } + while true { + if shouldQuit { return .quit } + if let event = queue.receive(matching: types, remove: remove) { return .event(event) } + let now = host.eventTime + if let deadline, now >= deadline { return .timedOut } + if fireDueTimer(at: now) { continue } + let timerDeadline = timers.map(\.fireTime).min() + let wake = [deadline, timerDeadline].compactMap { $0 }.min() + host.waitForEvents(until: wake, queue: queue) + } + } + + private func fireDueTimer(at now: Double) -> Bool { + guard let index = timers.indices.filter({ timers[$0].fireTime <= now }).min(by: { timers[$0].fireTime < timers[$1].fireTime }) else { return false } + let timer = timers[index] + if timer.interval > 0 { timers[index].fireTime = now + timer.interval } + else { timers.remove(at: index) } + timer.callback(timer.id) + return true + } + + /// Dispatch one event or a due timer; if neither is ready, wait once. + @discardableResult + public func runOne(until deadline: Double? = nil) -> Bool { + let now = host.eventTime + if fireDueTimer(at: now) { return true } + if var event = queue.receive() { + _ = target.send(&event) + return true + } + guard !shouldQuit, deadline == nil || now < deadline! else { return false } + let timerDeadline = timers.map(\.fireTime).min() + let wake = [deadline, timerDeadline].compactMap { $0 }.min() + host.waitForEvents(until: wake, queue: queue) + return false + } + + public func run() { + shouldQuit = false + while !shouldQuit { _ = runOne() } + } +} From 8ad7f7a3ba26cd48f9670425eeb70c89ea3ce3c0 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 07/13] Add event support in EventQueue.swift --- Sources/GraphiteEvents/EventQueue.swift | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Sources/GraphiteEvents/EventQueue.swift diff --git a/Sources/GraphiteEvents/EventQueue.swift b/Sources/GraphiteEvents/EventQueue.swift new file mode 100644 index 0000000..3374556 --- /dev/null +++ b/Sources/GraphiteEvents/EventQueue.swift @@ -0,0 +1,37 @@ +import Synchronization + +/// Carbon queue priorities; events of equal priority retain posting order. +public enum EventPriority: Int, Comparable, Sendable { + case low = 0, standard = 1, high = 2 + public static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue } +} + +/// A thread-safe queue. Waiting and waking the host's event loop are the +/// responsibility of the host; retrieving an event never removes other types. +public final class EventQueue: Sendable { + private struct Entry: Sendable { + var event: CarbonEvent + var priority: EventPriority + } + private let entries = Mutex<[Entry]>([]) + + public init() {} + + public func post(_ event: CarbonEvent, priority: EventPriority = .standard) { + entries.withLock { queue in + let index = queue.firstIndex { $0.priority < priority } ?? queue.endIndex + queue.insert(Entry(event: event, priority: priority), at: index) + } + } + + /// An empty type set matches every event. `remove: false` peeks. + public func receive(matching types: Set = [], remove: Bool = true) -> CarbonEvent? { + entries.withLock { queue in + guard let index = queue.firstIndex(where: { types.isEmpty || types.contains($0.event.type) }) else { return nil } + return remove ? queue.remove(at: index).event : queue[index].event + } + } + + public var count: Int { entries.withLock { $0.count } } + public func flush() { entries.withLock { $0.removeAll() } } +} From aab1dedb0819b9266bbb423b9817c9e713875fb7 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 08/13] Add event support in EventTarget.swift --- Sources/GraphiteEvents/EventTarget.swift | 56 ++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Sources/GraphiteEvents/EventTarget.swift diff --git a/Sources/GraphiteEvents/EventTarget.swift b/Sources/GraphiteEvents/EventTarget.swift new file mode 100644 index 0000000..2fdada3 --- /dev/null +++ b/Sources/GraphiteEvents/EventTarget.swift @@ -0,0 +1,56 @@ +/// A handler either handles an event, declines it, or reports a status. +public enum EventHandlingResult: Equatable, Sendable { + case handled + case notHandled + case error(Int32) +} + +/// The continuation supplied to a handler invokes the next matching handler. +public typealias EventHandler = (inout CarbonEvent, (inout CarbonEvent) -> EventHandlingResult) -> EventHandlingResult + +/// Installed handlers are called newest first. A handler may explicitly call +/// the continuation to wrap the rest of the chain; returning notHandled +/// without doing so automatically passes the event along. +public final class EventTarget { + private struct Registration { + let id: UInt64 + var types: Set + let handler: EventHandler + } + private var registrations: [Registration] = [] + private var nextID: UInt64 = 1 + + public init() {} + + @discardableResult + public func install(types: Set, handler: @escaping EventHandler) -> UInt64 { + let id = nextID + nextID &+= 1 + registrations.insert(Registration(id: id, types: types, handler: handler), at: 0) + return id + } + + public func remove(_ id: UInt64) { registrations.removeAll { $0.id == id } } + public func addTypes(_ types: Set, to id: UInt64) { + guard let index = registrations.firstIndex(where: { $0.id == id }) else { return } + registrations[index].types.formUnion(types) + } + public func removeTypes(_ types: Set, from id: UInt64) { + guard let index = registrations.firstIndex(where: { $0.id == id }) else { return } + registrations[index].types.subtract(types) + } + + public func send(_ event: inout CarbonEvent) -> EventHandlingResult { + let handlers = registrations.filter { $0.types.contains(event.type) }.map(\.handler) + func dispatch(_ index: Int, _ event: inout CarbonEvent) -> EventHandlingResult { + guard index < handlers.count else { return .notHandled } + var calledNext = false + let result = handlers[index](&event) { nextEvent in + calledNext = true + return dispatch(index + 1, &nextEvent) + } + return result == .notHandled && !calledNext ? dispatch(index + 1, &event) : result + } + return dispatch(0, &event) + } +} From 19205b9ed2d4d14c0a39c1f46e448a897188b259 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 09/13] Add event support in HotKey.swift --- Sources/GraphiteEvents/HotKey.swift | 52 +++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Sources/GraphiteEvents/HotKey.swift diff --git a/Sources/GraphiteEvents/HotKey.swift b/Sources/GraphiteEvents/HotKey.swift new file mode 100644 index 0000000..77f6986 --- /dev/null +++ b/Sources/GraphiteEvents/HotKey.swift @@ -0,0 +1,52 @@ +import GraphiteBase + +/// The signature and identifier returned to an application for a hot key. +public struct HotKeyID: Hashable, Sendable { + public var signature: FourCharCode + public var id: UInt32 + public init(signature: FourCharCode, id: UInt32) { + self.signature = signature + self.id = id + } +} + +/// An in-process registry. The host is responsible for requesting global +/// registration from the desktop and reporting key presses and releases. +public final class HotKeyRegistry { + private struct Combination: Hashable { + var keyCode: UInt32 + var modifiers: UInt32 + } + private struct Registration { + var id: HotKeyID + var target: EventTarget + } + private var registrations: [Combination: Registration] = [:] + public init() {} + + /// Returns false if this combination is already registered. + @discardableResult + public func register(keyCode: UInt32, modifiers: UInt32, id: HotKeyID, target: EventTarget) -> Bool { + let combination = Combination(keyCode: keyCode, modifiers: modifiers) + guard registrations[combination] == nil else { return false } + registrations[combination] = Registration(id: id, target: target) + return true + } + + public func unregister(keyCode: UInt32, modifiers: UInt32) { + registrations.removeValue(forKey: Combination(keyCode: keyCode, modifiers: modifiers)) + } + + /// Delivers to the registered target. The four-character signature and + /// numeric ID are encoded big-endian in the hot-key direct object. + @discardableResult + public func send(keyCode: UInt32, modifiers: UInt32, pressed: Bool, time: Double) -> EventHandlingResult { + guard let registration = registrations[Combination(keyCode: keyCode, modifiers: modifiers)] else { return .notHandled } + var writer = BigEndianWriter() + writer.write(registration.id.signature.rawValue) + writer.write(registration.id.id) + var event = CarbonEvent(type: EventType(eventClass: "keyb", kind: pressed ? 5 : 6), time: time) + event.setParameter("----", type: "hkid", bytes: writer.bytes) + return registration.target.send(&event) + } +} From 8c6e09bb4aee52efcc0a225970458c2e4ff5660c Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 10/13] Add event support in InputState.swift --- Sources/GraphiteEvents/InputState.swift | 43 +++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Sources/GraphiteEvents/InputState.swift diff --git a/Sources/GraphiteEvents/InputState.swift b/Sources/GraphiteEvents/InputState.swift new file mode 100644 index 0000000..82b2e15 --- /dev/null +++ b/Sources/GraphiteEvents/InputState.swift @@ -0,0 +1,43 @@ +import GraphiteBase +import Synchronization + +/// Input state maintained by a host as it receives native input. The key map +/// uses classic virtual key codes: bit n of byte n/8 is key n. +public final class InputState: Sendable { + private struct State: Sendable { + var keys = [UInt8](repeating: 0, count: 16) + var modifiers: UInt32 = 0 + var buttons: UInt32 = 0 + var mouse: Point = .zero + } + private let state = Mutex(State()) + public init() {} + + public var keyMap: [UInt8] { state.withLock { $0.keys } } + public var modifiers: UInt32 { + get { state.withLock { $0.modifiers } } + set { state.withLock { $0.modifiers = newValue } } + } + public var buttons: UInt32 { + get { state.withLock { $0.buttons } } + set { state.withLock { $0.buttons = newValue } } + } + public var mouse: Point { + get { state.withLock { $0.mouse } } + set { state.withLock { $0.mouse = newValue } } + } + public var buttonDown: Bool { buttons & 1 != 0 } + + public func setKey(_ code: UInt8, down: Bool) { + guard code < 128 else { return } + state.withLock { state in + let index = Int(code) / 8 + let mask = UInt8(1) << (code % 8) + if down { state.keys[index] |= mask } else { state.keys[index] &= ~mask } + } + } + public func isKeyDown(_ code: UInt8) -> Bool { + guard code < 128 else { return false } + return state.withLock { $0.keys[Int(code) / 8] & (UInt8(1) << (code % 8)) != 0 } + } +} From d8d88a6a10d78c45726072ba86b295a92228a56d Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 11/13] Add event support in SDLEventHost.swift --- Sources/GraphiteSDLEvents/SDLEventHost.swift | 126 +++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 Sources/GraphiteSDLEvents/SDLEventHost.swift diff --git a/Sources/GraphiteSDLEvents/SDLEventHost.swift b/Sources/GraphiteSDLEvents/SDLEventHost.swift new file mode 100644 index 0000000..dc2140e --- /dev/null +++ b/Sources/GraphiteSDLEvents/SDLEventHost.swift @@ -0,0 +1,126 @@ +#if GRAPHITE_SDL3 +import GraphiteBase +import GraphiteEvents +import SDL3Swift + +/// SDL owns the event pump: create this after SDL initialization and call +/// `waitForEvents` on SDL's main thread. Events outside the supported input +/// subset are forwarded to `unhandled`, so window and quit events are not lost. +public final class SDLEventHost: EventLoopHost { + public enum HostError: Error { case cannotReserveWakeEvent } + private let wakeType: UInt32 + public let input = InputState() + public var unhandled: (SDLEvent) -> Void + /// Convert SDL window-local coordinates to global coordinates. Hosts with + /// multiple windows must provide their window positions. + public var globalPosition: (UInt32, Float, Float) -> (Float, Float) + + public init(globalPosition: @escaping (UInt32, Float, Float) -> (Float, Float) = { _, x, y in (x, y) }, + unhandled: @escaping (SDLEvent) -> Void) throws { + guard let wake = SDL.registerEvents() else { throw HostError.cannotReserveWakeEvent } + wakeType = wake + self.globalPosition = globalPosition + self.unhandled = unhandled + } + + public var eventTime: Double { Double(SDL.ticks) / 1_000_000_000 } + + public func wakeEventLoop() { SDL.pushUserEvent(type: wakeType) } + + public func waitForEvents(until deadline: Double?, queue: EventQueue) { + let timeout: Int32 + if let deadline { + let milliseconds = max(0, (deadline - eventTime) * 1000) + timeout = milliseconds >= Double(Int32.max) ? Int32.max : Int32(milliseconds.rounded(.up)) + } else { timeout = -1 } + guard let event = SDL.waitEvent(timeout: timeout) else { return } + process(event, queue: queue) + } + + /// Translate one SDL event. Useful when an application owns the SDL pump. + public func process(_ event: SDLEvent, queue: EventQueue) { + switch event { + case .user(let type, _, _) where type == wakeType: + return + case .mouseMotion(let window, _, _, let x, let y, _, _): + postMouse(kind: 5, window: window, x: x, y: y, button: nil, queue: queue) + case .mouseButtonDown(let window, _, let button, _, let x, let y): + updateButton(button.rawValue, down: true) + postMouse(kind: 1, window: window, x: x, y: y, button: button.rawValue, queue: queue) + case .mouseButtonUp(let window, _, let button, _, let x, let y): + updateButton(button.rawValue, down: false) + postMouse(kind: 2, window: window, x: x, y: y, button: button.rawValue, queue: queue) + case .keyDown(let window, let scan, _, let modifiers, let repeated): + if !postKey(window: window, scan: scan.rawValue, modifiers: modifiers, kind: repeated ? 2 : 1, queue: queue) { unhandled(event) } + case .keyUp(let window, let scan, _, let modifiers, _): + if !postKey(window: window, scan: scan.rawValue, modifiers: modifiers, kind: 3, queue: queue) { unhandled(event) } + default: + unhandled(event) + } + } + + private func updateButton(_ button: UInt8, down: Bool) { + guard button > 0, button <= 32 else { return } + let carbonButton: UInt8 = button == 2 ? 3 : (button == 3 ? 2 : button) + let mask = UInt32(1) << (carbonButton - 1) + if down { input.buttons |= mask } else { input.buttons &= ~mask } + } + + private func postMouse(kind: UInt32, window: UInt32, x: Float, y: Float, button: UInt8?, queue: EventQueue) { + let (globalX, globalY) = globalPosition(window, x, y) + guard globalX.isFinite, globalY.isFinite else { return } + func coordinate(_ value: Float) -> Int16 { + Int16(max(Float(Int16.min), min(Float(Int16.max), value.rounded()))) + } + input.mouse = Point(v: coordinate(globalY), h: coordinate(globalX)) + var event = CarbonEvent(type: EventType(eventClass: "mous", kind: kind), time: eventTime) + var point = BigEndianWriter() + point.write(globalX.bitPattern); point.write(globalY.bitPattern) + event.setParameter("mloc", type: "hipt", bytes: point.bytes) + var windowID = BigEndianWriter(); windowID.write(window) + event.setParameter("swin", type: "magn", bytes: windowID.bytes) + var mods = BigEndianWriter(); mods.write(Self.macModifiers(SDL.modifierState)) + event.setParameter("kmod", type: "magn", bytes: mods.bytes) + if let button { + let carbonButton: UInt8 = button == 2 ? 3 : (button == 3 ? 2 : button) + var value = BigEndianWriter(); value.write(UInt16(carbonButton)) + event.setParameter("mbtn", type: "mbtn", bytes: value.bytes) + } + queue.post(event) + } + + private func postKey(window: UInt32, scan: UInt32, modifiers: KeyModifiers, kind: UInt32, queue: EventQueue) -> Bool { + guard let code = Self.macKeyCode(scan) else { return false } + let flags = Self.macModifiers(modifiers) + input.modifiers = flags + input.setKey(code, down: kind != 3) + var event = CarbonEvent(type: EventType(eventClass: "keyb", kind: kind), time: eventTime) + var key = BigEndianWriter(); key.write(UInt32(code)) + var mods = BigEndianWriter(); mods.write(flags) + event.setParameter("kcod", type: "magn", bytes: key.bytes) + event.setParameter("kmod", type: "magn", bytes: mods.bytes) + var windowID = BigEndianWriter(); windowID.write(window) + event.setParameter("swin", type: "magn", bytes: windowID.bytes) + queue.post(event) + return true + } + + private static func macModifiers(_ flags: KeyModifiers) -> UInt32 { + var value: UInt32 = 0 + if !flags.intersection(.gui).isEmpty { value |= 0x0100 } + if !flags.intersection(.shift).isEmpty { value |= 0x0200 } + if flags.contains(.capsLock) { value |= 0x0400 } + if !flags.intersection(.alt).isEmpty { value |= 0x0800 } + if !flags.intersection(.control).isEmpty { value |= 0x1000 } + return value + } + + /// USB HID scancodes for the standard US keyboard, mapped to Mac virtual keys. + private static func macKeyCode(_ scan: UInt32) -> UInt8? { + let letters: [UInt8] = [0, 11, 8, 2, 14, 3, 5, 4, 34, 38, 40, 37, 46, 45, 31, 35, 12, 15, 1, 17, 32, 9, 13, 7, 16, 6] + if (4...29).contains(scan) { return letters[Int(scan - 4)] } + let others: [UInt32: UInt8] = [30: 18, 31: 19, 32: 20, 33: 21, 34: 23, 35: 22, 36: 26, 37: 28, 38: 25, 39: 29, 40: 36, 41: 53, 42: 51, 43: 48, 44: 49, 45: 27, 46: 24, 47: 33, 48: 30, 49: 42, 51: 41, 52: 39, 53: 50, 54: 43, 55: 47, 56: 44, 79: 124, 80: 123, 81: 125, 82: 126] + return others[scan] + } +} +#endif From c54a022c965e37fb0052ad05b45048dcaf7517f1 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 12/13] Add event support in EventTests.swift --- Tests/GraphiteEventsTests/EventTests.swift | 149 +++++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 Tests/GraphiteEventsTests/EventTests.swift diff --git a/Tests/GraphiteEventsTests/EventTests.swift b/Tests/GraphiteEventsTests/EventTests.swift new file mode 100644 index 0000000..3fe0610 --- /dev/null +++ b/Tests/GraphiteEventsTests/EventTests.swift @@ -0,0 +1,149 @@ +import Testing +import GraphiteBase +import GraphiteEvents + +private final class TestHost: EventLoopHost { + var eventTime: Double = 0 + var deadline: Double? + var wakeCount = 0 + func waitForEvents(until deadline: Double?, queue: EventQueue) { self.deadline = deadline } + func wakeEventLoop() { wakeCount += 1 } +} + +private final class WaitingHost: EventLoopHost, ClassicEventHost { + var eventTime: Double = 0 + var ticks: UInt32 = 60 + var mouseLocation = Point(v: 5, h: 7) + var modifiers: UInt16 = 0x100 + var onWait: (() -> Void)? + func waitForEvents(until deadline: Double?, queue: EventQueue) { + if let deadline { eventTime = deadline } + onWait?() + } + func waitForClassicEvents(until deadline: Double, queue: ClassicEventQueue) { + eventTime = deadline + onWait?() + } + func wakeEventLoop() {} +} + +@Suite struct EventTests { + let key = EventType(eventClass: "keyb", kind: 1) + let mouse = EventType(eventClass: "mous", kind: 1) + + @Test func parametersAreCopiedAndTyped() { + var original = CarbonEvent(type: key, time: 3) + original.setParameter("----", type: "long", bytes: [1, 2]) + var copy = original + copy.setParameter("----", type: "TEXT", bytes: [3]) + #expect(original.parameter("----", type: "long")?.bytes == [1, 2]) + #expect(copy.parameter("----", type: "long") == nil) + #expect(copy.parameter("----")?.bytes == [3]) + } + + @Test func prioritiesFilteringAndPeek() { + let queue = EventQueue() + queue.post(CarbonEvent(type: key, time: 1)) + queue.post(CarbonEvent(type: mouse, time: 2), priority: .high) + queue.post(CarbonEvent(type: key, time: 3), priority: .high) + #expect(queue.receive(matching: [key], remove: false)?.time == 3) + #expect(queue.count == 3) + #expect(queue.receive()?.time == 2) + #expect(queue.receive()?.time == 3) + #expect(queue.receive()?.time == 1) + } + + @Test func classicPeekAndFlushStop() { + let queue = ClassicEventQueue() + for kind: UInt16 in [1, 3, 1, 3] { queue.post(ClassicEvent(what: kind)) } + #expect(queue.next(mask: 1 << 3, remove: false)?.what == 3) + queue.flush(mask: 1 << 1, stopMask: 1 << 3) + #expect(queue.next(mask: 0xffff)?.what == 3) + #expect(queue.next(mask: 0xffff)?.what == 1) + } + + @Test func handlerChainsAndChanges() { + let target = EventTarget() + var order: [Int] = [] + target.install(types: [key]) { _, _ in order.append(1); return .handled } + let top = target.install(types: [key]) { event, next in + order.append(2) + let result = next(&event) + order.append(3) + return result + } + var event = CarbonEvent(type: key, time: 0) + #expect(target.send(&event) == .handled) + #expect(order == [2, 1, 3]) + target.removeTypes([key], from: top) + order.removeAll() + #expect(target.send(&event) == .handled) + #expect(order == [1]) + } + + @Test func hostLoopAndTimers() { + let host = TestHost() + let loop = EventLoop(host: host) + var fired: [UInt64] = [] + let timer = loop.installTimer(delay: 2) { fired.append($0) } + #expect(!loop.runOne(until: 10)) + #expect(host.deadline == 2) + host.eventTime = 2 + #expect(loop.runOne()) + #expect(fired == [timer]) + #expect(!loop.runOne(until: 2)) + } + + @Test func inputState() { + let input = InputState() + input.setKey(42, down: true) + #expect(input.isKeyDown(42)) + #expect(input.keyMap[5] == 4) + input.setKey(42, down: false) + #expect(!input.isKeyDown(42)) + input.buttons = 1 + #expect(input.buttonDown) + } + + @Test func receiveWaitsForMatchingEventsAndTimers() { + let host = WaitingHost() + let loop = EventLoop(host: host) + loop.post(CarbonEvent(type: mouse, time: 1)) + loop.installTimer(delay: 2) { _ in loop.post(CarbonEvent(type: key, time: 2)) } + if case .event(let event) = loop.receive(matching: [key], timeout: 5, remove: false) { + #expect(event.time == 2) + } else { Issue.record("Expected matching event") } + #expect(loop.queue.count == 2) + if case .timedOut = loop.receive(matching: [EventType(eventClass: "none", kind: 1)], timeout: 0) {} else { + Issue.record("Expected timeout") + } + } + + @Test func classicWaitReturnsNullStateOrPostedEvent() { + let host = WaitingHost() + let manager = ClassicEventManager(host: host) + let empty = manager.waitNext(mask: 2, sleepTicks: 30) + #expect(!empty.found && empty.event.what == 0) + #expect(empty.event.where_ == Point(v: 5, h: 7)) + #expect(empty.event.modifiers == 0x100) + host.onWait = { manager.queue.post(ClassicEvent(what: 1, message: 42)) } + let received = manager.waitNext(mask: 2, sleepTicks: 60) + #expect(received.found && received.event.message == 42) + } + + @Test func registeredHotKeyDeliversItsIdentifier() { + let target = EventTarget() + let registry = HotKeyRegistry() + var identifier: [UInt8] = [] + target.install(types: [EventType(eventClass: "keyb", kind: 5)]) { event, _ in + identifier = event.parameter("----", type: "hkid")?.bytes ?? [] + return .handled + } + #expect(registry.register(keyCode: 12, modifiers: 256, id: HotKeyID(signature: "TEST", id: 7), target: target)) + #expect(!registry.register(keyCode: 12, modifiers: 256, id: HotKeyID(signature: "TEST", id: 8), target: target)) + #expect(registry.send(keyCode: 12, modifiers: 256, pressed: true, time: 1) == .handled) + #expect(identifier == [84, 69, 83, 84, 0, 0, 0, 7]) + registry.unregister(keyCode: 12, modifiers: 256) + #expect(registry.send(keyCode: 12, modifiers: 256, pressed: true, time: 1) == .notHandled) + } +} From 2f1529040e6cae137d610b0cd185892fc0073a60 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 18:22:30 -0500 Subject: [PATCH 13/13] Add event support in SDLEventHostTests.swift --- .../SDLEventHostTests.swift | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Tests/GraphiteSDLEventsTests/SDLEventHostTests.swift diff --git a/Tests/GraphiteSDLEventsTests/SDLEventHostTests.swift b/Tests/GraphiteSDLEventsTests/SDLEventHostTests.swift new file mode 100644 index 0000000..ed87e73 --- /dev/null +++ b/Tests/GraphiteSDLEventsTests/SDLEventHostTests.swift @@ -0,0 +1,35 @@ +#if GRAPHITE_SDL3 +import Testing +import GraphiteBase +import GraphiteEvents +import GraphiteSDLEvents +import SDL3Swift + +@Suite(.serialized) struct SDLEventHostTests { + @Test func translatesInputAndForwardsOtherEvents() throws { + try SDL.initialize(subSystems: [.events]) + defer { SDL.quit() } + var quitReceived = false + let host = try SDLEventHost(globalPosition: { _, x, y in (x + 100, y + 200) }) { event in + if case .quit = event { quitReceived = true } + } + let queue = EventQueue() + host.wakeEventLoop() + host.waitForEvents(until: host.eventTime + 1, queue: queue) + #expect(queue.count == 0) + host.process(.keyDown(windowID: 1, scancode: Scancode(rawValue: 4), keycode: Keycode(rawValue: 97), modifiers: .shift, isRepeat: false), queue: queue) + let key = try #require(queue.receive()) + #expect(key.type == EventType(eventClass: "keyb", kind: 1)) + #expect(key.parameter("kcod", type: "magn")?.bytes == [0, 0, 0, 0]) + #expect(key.parameter("kmod", type: "magn")?.bytes == [0, 0, 2, 0]) + #expect(host.input.isKeyDown(0)) + host.process(.mouseButtonDown(windowID: 1, which: MouseID(rawValue: 0), button: .left, clicks: 1, x: 3, y: 4), queue: queue) + let mouse = try #require(queue.receive()) + #expect(mouse.type == EventType(eventClass: "mous", kind: 1)) + #expect(host.input.mouse == Point(v: 204, h: 103)) + #expect(host.input.buttonDown) + host.process(.quit, queue: queue) + #expect(quitReceived) + } +} +#endif