Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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"]))])
]
)
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions Sources/Graphite/Graphite.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@
@_exported import GraphiteMenus
@_exported import GraphiteControls
@_exported import GraphiteDialogs
@_exported import GraphiteEvents
48 changes: 48 additions & 0 deletions Sources/GraphiteEvents/CarbonEvent.swift
Original file line number Diff line number Diff line change
@@ -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)
}
}
87 changes: 87 additions & 0 deletions Sources/GraphiteEvents/ClassicEvent.swift
Original file line number Diff line number Diff line change
@@ -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..<stop, with: queue[..<stop].filter { !Self.matches($0, mask) })
}
}
private static func matches(_ event: ClassicEvent, _ mask: UInt16) -> 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)
}
}
106 changes: 106 additions & 0 deletions Sources/GraphiteEvents/EventLoop.swift
Original file line number Diff line number Diff line change
@@ -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<EventType> = [], 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() }
}
}
37 changes: 37 additions & 0 deletions Sources/GraphiteEvents/EventQueue.swift
Original file line number Diff line number Diff line change
@@ -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<EventType> = [], 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() } }
}
Loading
Loading