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
202 changes: 202 additions & 0 deletions Sources/GraphiteAutomation/AppleEventDelivery.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
// Delivering an Apple event to handlers that may be the guest's. The
// dispatcher lends the event and its reply from a DescriptorTable and tries
// its candidates in order: a host's handler it calls itself; for a guest's
// it gives the host an invocation to make (the procedure, the reference
// constant and the two borrowed descriptors), and the host completes it
// with the signed OSErr the procedure returned. errAEEventNotHandled from
// one of the application's handlers passes the event on to the system's
// table; any other result ends the delivery, and the loans with it, giving
// back the event and the reply as the handlers left them.
//
// A handler may send an event of its own, which begins a delivery inside
// its own; deliveries finish innermost first, so completing an outer one
// while an inner one is still open is paramErr. Abandoning a delivery, as
// when the guest faults or runs out of instructions, ends it and every
// delivery begun inside it.

import Synchronization
import GraphiteCore

public extension AppleEventDispatcher {

/// A guest's handler to call: `procedure(event, reply, referenceConstant)`.
struct Invocation: Hashable, Sendable {

/// The delivery's own number.
public let delivery: UInt64

/// The handler's table entry: its class and ID, which may be
/// typeWildCard, and its table.
public let eventClass: FourCharCode

public let eventID: FourCharCode

public let isSystem: Bool

/// The guest's UPP and reference constant, as installed.
public let procedure: UInt

public let referenceConstant: UInt

/// The event and reply, lent for the call.
public let event: DescriptorID

public let reply: DescriptorID

/// 1 for a delivery begun outside any handler, one more for each
/// delivery it is inside.
public let depth: Int
}

/// How a finished delivery went.
struct Outcome: Hashable, Sendable {

/// The event, with whatever parameters the handlers changed.
public var event: Descriptor

/// The reply: a failed handler's result is its keyErrorNumber,
/// unless the handler gave one, or it is typeNull.
public var reply: Descriptor

/// The last handler's result: errAEEventNotHandled if none took the
/// event.
public var result: Int16

public var error: MacError? { result == 0 ? nil : MacError(Int32(result)) }
}

/// A step of a delivery.
enum Delivery: Hashable, Sendable {
/// The host calls a guest's handler, then completes the invocation.
case invoke(Invocation)
/// The delivery is over.
case finished(Outcome)
}

/// The deliveries open, innermost last.
var openDeliveries: Int { deliveries.withLock { $0.open.count } }

/// AEProcessAppleEvent's, AESend's and AEResumeTheCurrentEvent's work:
/// begins delivering an event, lending it and the reply from a table.
func beginDelivery(_ event: AppleEvent, reply: Descriptor = .null, in table: DescriptorTable) -> Delivery {
let token = deliveries.withLock { stack in
let token = stack.next
stack.next &+= 1
stack.open.append(OpenDelivery(token: token, table: table, event: table.lend(event.descriptor),
reply: table.lend(reply),
remaining: candidates(eventClass: event.eventClass, eventID: event.eventID)))
return token
}
return advance(token, after: nil)
}

/// Completes the invocation a delivery asked for with the result the
/// guest's handler returned. paramErr for an invocation that isn't the
/// innermost delivery's outstanding one.
func complete(_ invocation: Invocation, result: Int16) throws(MacError) -> Delivery {
let valid = deliveries.withLock { stack in
guard let last = stack.open.last, last.token == invocation.delivery, last.current?.procedure == invocation.procedure,
last.current?.isSystem == invocation.isSystem else { return false }
stack.open[stack.open.count - 1].current = nil
return true
}
guard valid else { throw .parameter }
return advance(invocation.delivery, after: (isSystem: invocation.isSystem, result: result))
}

/// Ends a delivery the host can't complete, and every delivery begun
/// inside it, ending their loans. paramErr for one not open.
func abandon(_ invocation: Invocation) throws(MacError) {
let ended = deliveries.withLock { stack -> [OpenDelivery]? in
guard let index = stack.open.firstIndex(where: { $0.token == invocation.delivery }) else { return nil }
defer { stack.open.removeSubrange(index...) }
return Array(stack.open[index...])
}
guard let ended else { throw .parameter }
for delivery in ended.reversed() {
_ = try? delivery.table.endLoan(delivery.event)
_ = try? delivery.table.endLoan(delivery.reply)
}
}

// MARK: Steps

/// Moves a delivery on: to its next handler after one that returned a
/// result, or to its first.
private func advance(_ token: UInt64, after last: (isSystem: Bool, result: Int16)?) -> Delivery {
var last = last
while true {
if let (isSystem, result) = last {
guard result == MacError.eventNotHandled.code16 && !isSystem else { return finish(token, result: result) }
}
let step = deliveries.withLock { stack -> (entry: Entry, delivery: OpenDelivery, depth: Int)? in
guard let index = stack.open.firstIndex(where: { $0.token == token }) else { return nil }
if last != nil { stack.open[index].remaining.removeAll { !$0.isSystem } }
guard !stack.open[index].remaining.isEmpty else { return nil }
let entry = stack.open[index].remaining.removeFirst()
if entry.isGuest { stack.open[index].current = entry }
return (entry, stack.open[index], index + 1)
}
guard let (entry, delivery, depth) = step else { return finish(token, result: MacError.eventNotHandled.code16) }
guard let handler = entry.handler else {
return .invoke(Invocation(delivery: token, eventClass: entry.eventClass, eventID: entry.eventID,
isSystem: entry.isSystem, procedure: entry.procedure,
referenceConstant: entry.referenceConstant,
event: delivery.event, reply: delivery.reply, depth: depth))
}
last = (entry.isSystem, Self.call(handler, delivery))
}
}

/// Calls a host's handler on the lent event and reply, outside the
/// dispatcher's lock, giving its result.
private static func call(_ handler: Handler, _ delivery: OpenDelivery) -> Int16 {
do throws(MacError) {
let descriptor = try delivery.table.descriptor(delivery.event)
var reply = try delivery.table.descriptor(delivery.reply)
let event = try AppleEvent(descriptor)
defer { try? delivery.table.replace(delivery.reply, with: reply) }
try handler(event, &reply)
return 0
} catch {
return error.code16
}
}

/// Ends a delivery and its loans.
private func finish(_ token: UInt64, result: Int16) -> Delivery {
let delivery = deliveries.withLock { stack -> OpenDelivery? in
guard let index = stack.open.firstIndex(where: { $0.token == token }) else { return nil }
return stack.open.remove(at: index)
}
guard let delivery else { return .finished(Outcome(event: .null, reply: .null, result: result)) }
let event = (try? delivery.table.endLoan(delivery.event)) ?? .null
var reply = (try? delivery.table.endLoan(delivery.reply)) ?? .null
if result != 0, !reply.isNull, reply[AppleEvent.Parameter.errorNumber] == nil {
reply[AppleEvent.Parameter.errorNumber] = Descriptor(Int32(result))
}
return .finished(Outcome(event: event, reply: reply, result: result))
}
}

/// A delivery begun and not finished.
struct OpenDelivery: Sendable {
var token: UInt64
var table: DescriptorTable
var event: DescriptorID
var reply: DescriptorID
/// The handlers left to try.
var remaining: [AppleEventDispatcher.Entry]
/// The guest's handler the host is calling.
var current: AppleEventDispatcher.Entry?
}

struct DeliveryStack: Sendable {
var open: [OpenDelivery] = []
var next: UInt64 = 1
}

extension MacError {
/// The result as an OSErr.
var code16: Int16 { Int16(truncatingIfNeeded: code) }
}
88 changes: 69 additions & 19 deletions Sources/GraphiteAutomation/AppleEventDispatcher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@
// sends: those for this process go straight to its handlers; no other
// process receives them, so one for another fails as one that isn't
// running would.
//
// A handler is the host's, a closure the dispatcher calls, or the guest's, a
// procedure the dispatcher can only name: delivering an event to one is a
// request the host carries out and then completes (AppleEventDelivery.swift).

import Synchronization
import GraphiteCore

public final class AppleEventDispatcher: Sendable {

/// A handler: it reads the event and fills in the reply, and throws
/// the result it returns otherwise.
/// A host's handler: it reads the event and fills in the reply, and
/// throws the result it returns otherwise.
public typealias Handler = @Sendable (AppleEvent, inout Descriptor) throws(MacError) -> Void

/// An installed handler.
Expand All @@ -29,7 +33,9 @@ public final class AppleEventDispatcher: Sendable {
/// The host's own: the reference constant installed with it.
public var referenceConstant: UInt

public var handler: Handler
/// The host's handler; nil for a guest's, whose procedure and
/// reference constant a delivery hands back to the host to call.
public var handler: Handler?

public init(eventClass: FourCharCode, eventID: FourCharCode, isSystem: Bool = false, procedure: UInt = 0,
referenceConstant: UInt = 0, handler: @escaping Handler) {
Expand All @@ -40,6 +46,26 @@ public final class AppleEventDispatcher: Sendable {
self.referenceConstant = referenceConstant
self.handler = handler
}

/// A guest's handler: its UPP and reference constant, opaque to
/// the dispatcher.
public init(eventClass: FourCharCode, eventID: FourCharCode, isSystem: Bool = false, guestProcedure: UInt,
referenceConstant: UInt = 0) {
self.eventClass = eventClass
self.eventID = eventID
self.isSystem = isSystem
self.procedure = guestProcedure
self.referenceConstant = referenceConstant
self.handler = nil
}

/// Whether the guest's procedure handles the event.
public var isGuest: Bool { handler == nil }

func matches(eventClass: FourCharCode, eventID: FourCharCode) -> Bool {
(self.eventClass == eventClass || self.eventClass == DescriptorType.wildCard)
&& (self.eventID == eventID || self.eventID == DescriptorType.wildCard)
}
}

/// AESend's modes.
Expand All @@ -60,6 +86,9 @@ public final class AppleEventDispatcher: Sendable {

private let entries = Mutex<[Entry]>([])

/// Deliveries begun and not yet finished, innermost last.
let deliveries = Mutex(DeliveryStack())

public let coercions: CoercionTable

public init(coercions: CoercionTable = CoercionTable()) {
Expand Down Expand Up @@ -97,27 +126,48 @@ public final class AppleEventDispatcher: Sendable {
entries.withLock { $0.first { $0.eventClass == eventClass && $0.eventID == eventID && $0.isSystem == isSystem } }
}

/// The handler an event goes to: the application's for its class and
/// ID, else the system's, else one with typeWildCard for either.
public func handler(eventClass: FourCharCode, eventID: FourCharCode) -> Entry? {
/// The handlers an event may go to, in the order the Apple Event
/// Manager tries them: the application's table, its handler for the
/// class and ID and then those with typeWildCard for either, then the
/// system's table the same way. A handler that returns
/// errAEEventNotHandled passes the event on to the system's table.
public func candidates(eventClass: FourCharCode, eventID: FourCharCode) -> [Entry] {
entries.withLock { entries in
let ordered = entries.filter { !$0.isSystem } + entries.filter(\.isSystem)
return ordered.first { $0.eventClass == eventClass && $0.eventID == eventID }
?? ordered.first {
($0.eventClass == eventClass || $0.eventClass == DescriptorType.wildCard)
&& ($0.eventID == eventID || $0.eventID == DescriptorType.wildCard)
[false, true].flatMap { system in
let table = entries.filter { $0.isSystem == system }
let exact = table.filter { $0.eventClass == eventClass && $0.eventID == eventID }
let wild = table.filter {
!($0.eventClass == eventClass && $0.eventID == eventID) && $0.matches(eventClass: eventClass, eventID: eventID)
}
return exact + wild
}
}
}

/// The handler an event goes to first.
public func handler(eventClass: FourCharCode, eventID: FourCharCode) -> Entry? {
candidates(eventClass: eventClass, eventID: eventID).first
}

// MARK: Dispatching

/// AEProcessAppleEvent's and AEResumeTheCurrentEvent's work: hands an
/// event to its handler, with a reply it fills in. errAEEventNotHandled
/// if there is none.
/// AEProcessAppleEvent's and AEResumeTheCurrentEvent's work for the
/// host's handlers: hands an event to its handler, with a reply it fills
/// in, passing it to the system's table if the handler returns
/// errAEEventNotHandled. errAEEventNotHandled if no host handler takes
/// it; a guest's handler is called only through `beginDelivery`.
public func dispatch(_ event: AppleEvent, reply: inout Descriptor) throws(MacError) {
guard let entry = handler(eventClass: event.eventClass, eventID: event.eventID) else { throw .eventNotHandled }
try entry.handler(event, &reply)
var remaining = candidates(eventClass: event.eventClass, eventID: event.eventID).filter { !$0.isGuest }
while !remaining.isEmpty {
let entry = remaining.removeFirst()
do {
try entry.handler?(event, &reply)
return
} catch where error == .eventNotHandled && !entry.isSystem {
remaining.removeAll { !$0.isSystem }
}
}
throw .eventNotHandled
}

/// AESend: an event for this process goes to its handler at once. The
Expand All @@ -140,12 +190,12 @@ public final class AppleEventDispatcher: Sendable {
return reply
}

/// Sends one of the required events to the application, from the
/// system: false if no handler takes it, so the caller can do what the
/// Sends one of the required events to the host's handlers, from the
/// system: false if no host handler takes it, so the caller can do what the
/// system does without one (a quit with no handler quits).
@discardableResult
public func sendCoreEvent(_ eventID: FourCharCode, directObject: Descriptor? = nil) -> Bool {
guard handler(eventClass: AppleEvent.Core.eventClass, eventID: eventID) != nil else { return false }
guard candidates(eventClass: AppleEvent.Core.eventClass, eventID: eventID).contains(where: { !$0.isGuest }) else { return false }
var event = AppleEvent(eventClass: AppleEvent.Core.eventClass, eventID: eventID, target: AppleEvent.currentProcess)
if let directObject { event[parameter: AppleEvent.Parameter.directObject] = directObject }
var reply = Descriptor.null
Expand Down
Loading
Loading