diff --git a/Sources/GraphiteAutomation/AppleEventDelivery.swift b/Sources/GraphiteAutomation/AppleEventDelivery.swift new file mode 100644 index 0000000..ff89600 --- /dev/null +++ b/Sources/GraphiteAutomation/AppleEventDelivery.swift @@ -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) } +} diff --git a/Sources/GraphiteAutomation/AppleEventDispatcher.swift b/Sources/GraphiteAutomation/AppleEventDispatcher.swift index 9f3c35b..a62d33f 100644 --- a/Sources/GraphiteAutomation/AppleEventDispatcher.swift +++ b/Sources/GraphiteAutomation/AppleEventDispatcher.swift @@ -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. @@ -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) { @@ -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. @@ -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()) { @@ -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 @@ -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 diff --git a/Sources/GraphiteAutomation/DescriptorByteOrder.swift b/Sources/GraphiteAutomation/DescriptorByteOrder.swift new file mode 100644 index 0000000..b3c23d0 --- /dev/null +++ b/Sources/GraphiteAutomation/DescriptorByteOrder.swift @@ -0,0 +1,135 @@ +// A descriptor's numbers are in the byte order of the program that made +// it: this machine's for a native program, big-endian for a Classic one. +// Converting between the two reverses each scalar field of the types whose +// layout is known, through lists, records, parameters and attributes, so a +// host passing a guest's descriptor in or out needs no rule of its own for +// any one event, attribute or parameter. Text, file URLs, bundle IDs and +// types without a layout here are bytes, kept as they are. + +import GraphiteCore + +/// The order of a value's bytes. +public enum ByteOrder: Hashable, Sendable { + + case bigEndian + + case littleEndian + + /// This machine's. + public static var host: ByteOrder { + UInt16(1).bigEndian == 1 ? .bigEndian : .littleEndian + } +} + +/// Where the scalar fields of a descriptor type's data are. +public struct ScalarLayout: Hashable, Sendable { + + /// The fields' widths in bytes, from the start of the data. Bytes past + /// them are kept as they are. + public var fields: [Int] + + /// The fields repeat to the end of the data, as UTF-16 text's code + /// units do. A trailing part of a field is kept as it is. + public var repeats: Bool + + /// The data has exactly the fields' bytes, as a number does; data of + /// another length is left as it is. Otherwise, the data has at least + /// those bytes, followed by others, as an FSSpec's name follows its + /// volume and folder; shorter data is left as it is. + public var isExact: Bool + + public init(fields: [Int], repeats: Bool = false, isExact: Bool = true) { + self.fields = fields + self.repeats = repeats + self.isExact = isExact + } + + /// One field of a width, as a number is. + public static func scalar(_ width: Int) -> ScalarLayout { ScalarLayout(fields: [width]) } + + /// The standard types' layouts. + public static let standard: [FourCharCode: ScalarLayout] = [ + DescriptorType.sInt16: .scalar(2), + DescriptorType.sInt32: .scalar(4), + DescriptorType.sInt64: .scalar(8), + DescriptorType.uInt32: .scalar(4), + DescriptorType.float: .scalar(4), + DescriptorType.double: .scalar(8), + DescriptorType.type: .scalar(4), + DescriptorType.enumerated: .scalar(4), + DescriptorType.keyword: .scalar(4), + DescriptorType.property: .scalar(4), + DescriptorType.kernelProcessID: .scalar(4), + // typeFixed, typeLongDateTime. + "fixd": .scalar(4), + "ldt ": .scalar(8), + // A ProcessSerialNumber's two halves. + DescriptorType.processSerialNumber: ScalarLayout(fields: [4, 4]), + // typeQDPoint, typeQDRectangle, typeRGBColor. + "QDpt": ScalarLayout(fields: [2, 2]), + "qdrt": ScalarLayout(fields: [2, 2, 2, 2]), + "cRGB": ScalarLayout(fields: [2, 2, 2]), + // UTF-16 code units. + DescriptorType.unicodeText: ScalarLayout(fields: [2], repeats: true, isExact: false), + // An FSSpec's volume and folder ID; its Str63 name is bytes. + DescriptorType.fsSpec: ScalarLayout(fields: [2, 4], isExact: false), + // An alias handle's user type and size; the record after them is + // big-endian on every machine. + DescriptorType.alias: ScalarLayout(fields: [4, 2], isExact: false), + ] + + /// The data with each field's bytes reversed. + func swapped(_ bytes: [UInt8]) -> [UInt8] { + let width = fields.reduce(0, +) + guard width > 0 else { return bytes } + if isExact && !repeats { + guard bytes.count == width else { return bytes } + } else if bytes.count < width { + return bytes + } + var result = bytes + var start = 0 + repeat { + for field in fields { + guard start + field <= result.count else { return result } + result[start ..< start + field].reverse() + start += field + } + } while repeats && start < result.count + return result + } +} + +public extension Descriptor { + + /// The descriptor with its numbers changed from one byte order to + /// another: those of its own type's layout, and those of every item and + /// attribute in it. + func converted(from source: ByteOrder, to destination: ByteOrder, + layouts: [FourCharCode: ScalarLayout] = ScalarLayout.standard) -> Descriptor { + guard source != destination else { return self } + return swappingScalars(layouts) + } + + /// A guest's descriptor, numbers big-endian, in this machine's order. + func fromBigEndian(layouts: [FourCharCode: ScalarLayout] = ScalarLayout.standard) -> Descriptor { + converted(from: .bigEndian, to: .host, layouts: layouts) + } + + /// The descriptor in a guest's big-endian order. + func toBigEndian(layouts: [FourCharCode: ScalarLayout] = ScalarLayout.standard) -> Descriptor { + converted(from: .host, to: .bigEndian, layouts: layouts) + } + + private func swappingScalars(_ layouts: [FourCharCode: ScalarLayout]) -> Descriptor { + var result = self + if let layout = layouts[type] { result.bytes = layout.swapped(bytes) } + for index in result.items.indices { + result.items[index].descriptor = result.items[index].descriptor.swappingScalars(layouts) + } + for index in result.attributes.indices { + result.attributes[index].descriptor = result.attributes[index].descriptor.swappingScalars(layouts) + } + return result + } +} diff --git a/Sources/GraphiteAutomation/DescriptorTable.swift b/Sources/GraphiteAutomation/DescriptorTable.swift new file mode 100644 index 0000000..18442bb --- /dev/null +++ b/Sources/GraphiteAutomation/DescriptorTable.swift @@ -0,0 +1,186 @@ +// The descriptors a program holds, each behind an opaque identity: a slot +// and the slot's generation. Disposing of a descriptor frees its slot and +// moves the slot to its next generation, so an identity kept past its +// descriptor's disposal, as a guest's AEDesc can keep a handle the Memory +// Manager has since reused, names nothing rather than whatever took the slot +// after it. +// +// A descriptor is the program's own, which it disposes of, or borrowed: an +// event and reply the Apple Event Manager lends a handler for the length of +// a call. A handler may read and change what it borrows, but it is the +// lender that ends the loan and takes the descriptor back; AEDisposeDesc of +// a borrowed descriptor, as of any, reports noErr and leaves it be. + +import Synchronization +import GraphiteCore + +/// A descriptor's identity in a DescriptorTable. +public struct DescriptorID: Hashable, Sendable, CustomStringConvertible { + + public var slot: UInt32 + + public var generation: UInt32 + + public init(slot: UInt32, generation: UInt32) { + self.slot = slot + self.generation = generation + } + + public var description: String { "#\(slot).\(generation)" } +} + +public final class DescriptorTable: Sendable { + + /// Who disposes of a descriptor. + public enum Ownership: Hashable, Sendable { + /// The program, with AEDisposeDesc. + case owned + /// The lender, by ending the loan. + case borrowed + } + + private struct Slot { + var generation: UInt32 = 0 + var descriptor: Descriptor? + var ownership: Ownership = .owned + } + + private struct State { + var slots: [Slot] = [] + var free: [UInt32] = [] + var live = 0 + } + + private let state = Mutex(State()) + + public init() {} + + /// The descriptors held, owned and borrowed. + public var count: Int { state.withLock { $0.live } } + + /// Holds a descriptor, giving its new identity. + public func insert(_ descriptor: Descriptor, ownership: Ownership = .owned) -> DescriptorID { + state.withLock { state in + let slot: UInt32 + if let reused = state.free.popLast() { + slot = reused + } else { + slot = UInt32(state.slots.count) + state.slots.append(Slot()) + } + state.slots[Int(slot)].descriptor = descriptor + state.slots[Int(slot)].ownership = ownership + state.live += 1 + return DescriptorID(slot: slot, generation: state.slots[Int(slot)].generation) + } + } + + /// Lends a descriptor, as to an event handler: the program may use it + /// until `endLoan` takes it back. + public func lend(_ descriptor: Descriptor) -> DescriptorID { + insert(descriptor, ownership: .borrowed) + } + + /// The descriptor an identity names: errAENotAEDesc for one disposed + /// of, or never given. + public func descriptor(_ id: DescriptorID) throws(MacError) -> Descriptor { + let found = state.withLock { state in Self.index(id, in: state).flatMap { state.slots[$0].descriptor } } + guard let found else { throw .notDescriptor } + return found + } + + /// Whether an identity names a descriptor held. + public func contains(_ id: DescriptorID) -> Bool { + state.withLock { Self.index(id, in: $0) != nil } + } + + /// Who disposes of a held descriptor: nil for an identity that names + /// none. + public func ownership(_ id: DescriptorID) -> Ownership? { + state.withLock { state in Self.index(id, in: state).map { state.slots[$0].ownership } } + } + + /// Changes a held descriptor, as AEPutParamDesc or AEPutDesc do: + /// errAENotAEDesc for an identity that names none. What the change + /// throws leaves the descriptor as the change left it. + public func update(_ id: DescriptorID, + _ body: (inout Descriptor) throws(MacError) -> Result) throws(MacError) -> Result { + let outcome: Swift.Result = state.withLock { state in + guard let index = Self.index(id, in: state), var descriptor = state.slots[index].descriptor else { + return .failure(.notDescriptor) + } + state.slots[index].descriptor = nil + defer { state.slots[index].descriptor = descriptor } + do throws(MacError) { + return .success(try body(&descriptor)) + } catch { + return .failure(error) + } + } + return try outcome.get() + } + + /// Replaces a held descriptor. + public func replace(_ id: DescriptorID, with descriptor: Descriptor) throws(MacError) { + try update(id) { $0 = descriptor } + } + + /// AEDuplicateDesc: a copy the program owns. + public func duplicate(_ id: DescriptorID) throws(MacError) -> DescriptorID { + insert(try descriptor(id)) + } + + /// AEDisposeDesc: frees an owned descriptor's slot, giving the + /// descriptor. A borrowed descriptor stays until its loan ends, and + /// gives nil. errAENotAEDesc for an identity that names none. + @discardableResult + public func dispose(_ id: DescriptorID) throws(MacError) -> Descriptor? { + let outcome: Swift.Result = state.withLock { state in + guard let index = Self.index(id, in: state) else { return .failure(.notDescriptor) } + guard state.slots[index].ownership == .owned else { return .success(nil) } + return .success(Self.free(index, in: &state)) + } + return try outcome.get() + } + + /// Ends a loan, giving the descriptor back as the program left it: + /// errAENotAEDesc for an identity that names none, paramErr for one the + /// program owns. + public func endLoan(_ id: DescriptorID) throws(MacError) -> Descriptor { + let outcome: Swift.Result = state.withLock { state in + guard let index = Self.index(id, in: state) else { return .failure(.notDescriptor) } + guard state.slots[index].ownership == .borrowed else { return .failure(.parameter) } + return .success(Self.free(index, in: &state)) + } + return try outcome.get() + } + + /// Frees every slot, as when the program quits: no identity given + /// before names anything after. + public func removeAll() { + state.withLock { state in + for index in state.slots.indices where state.slots[index].descriptor != nil { + _ = Self.free(index, in: &state) + } + } + } + + // MARK: Slots + + private static func index(_ id: DescriptorID, in state: State) -> Int? { + let index = Int(id.slot) + guard index < state.slots.count, state.slots[index].generation == id.generation, + state.slots[index].descriptor != nil else { return nil } + return index + } + + private static func free(_ index: Int, in state: inout State) -> Descriptor { + let descriptor = state.slots[index].descriptor ?? .null + state.slots[index].descriptor = nil + state.slots[index].ownership = .owned + state.slots[index].generation &+= 1 + state.free.append(UInt32(index)) + state.live -= 1 + return descriptor + } +} diff --git a/Tests/GraphiteAutomationTests/AppleEventDeliveryTests.swift b/Tests/GraphiteAutomationTests/AppleEventDeliveryTests.swift new file mode 100644 index 0000000..3588af4 --- /dev/null +++ b/Tests/GraphiteAutomationTests/AppleEventDeliveryTests.swift @@ -0,0 +1,149 @@ +import Synchronization +import Testing +import GraphiteCore +import GraphiteAutomation + +@Suite struct AppleEventDeliveryTests { + + private typealias Entry = AppleEventDispatcher.Entry + + private func invocation(_ delivery: AppleEventDispatcher.Delivery) throws -> AppleEventDispatcher.Invocation { + guard case .invoke(let invocation) = delivery else { throw MacError.parameter } + return invocation + } + + private func outcome(_ delivery: AppleEventDispatcher.Delivery) throws -> AppleEventDispatcher.Outcome { + guard case .finished(let outcome) = delivery else { throw MacError.parameter } + return outcome + } + + @Test func guestHandlersAreInvocations() throws { + let dispatcher = AppleEventDispatcher() + let table = DescriptorTable() + dispatcher.install(Entry(eventClass: "aevt", eventID: "oapp", guestProcedure: 0x1000, referenceConstant: 42)) + let event = AppleEvent(eventClass: "aevt", eventID: "oapp") + let call = try invocation(dispatcher.beginDelivery(event, reply: AppleEvent.reply(to: event).descriptor, in: table)) + #expect(call.procedure == 0x1000 && call.referenceConstant == 42 && call.depth == 1 && !call.isSystem) + // The guest reads the event and writes the reply through the table. + #expect(try AppleEvent(table.descriptor(call.event)).eventID == "oapp") + try table.update(call.reply) { $0[AppleEvent.Parameter.directObject] = Descriptor(text: "done") } + #expect(dispatcher.openDeliveries == 1 && table.count == 2) + let done = try outcome(dispatcher.complete(call, result: 0)) + #expect(done.result == 0 && done.error == nil) + #expect(done.reply[AppleEvent.Parameter.directObject] == Descriptor(text: "done")) + #expect(try AppleEvent(done.event) == event) + // The loans are over. + #expect(dispatcher.openDeliveries == 0 && table.count == 0) + #expect(throws: MacError.notDescriptor) { try table.descriptor(call.reply) } + #expect(throws: MacError.parameter) { try dispatcher.complete(call, result: 0) } + } + + @Test func eventNotHandledFallsToTheSystemTable() throws { + let dispatcher = AppleEventDispatcher() + let table = DescriptorTable() + let ran = Mutex<[String]>([]) + dispatcher.install(Entry(eventClass: "core", eventID: "getd", guestProcedure: 1)) + // Another of the application's, skipped once its first passes. + dispatcher.install(Entry(eventClass: "core", eventID: DescriptorType.wildCard) { _, _ in ran.withLock { $0.append("app wildcard") } }) + dispatcher.install(Entry(eventClass: "core", eventID: "getd", isSystem: true, guestProcedure: 2)) + dispatcher.install(Entry(eventClass: DescriptorType.wildCard, eventID: DescriptorType.wildCard, isSystem: true) { _, reply in + ran.withLock { $0.append("system wildcard") } + reply[AppleEvent.Parameter.directObject] = Descriptor(true) + }) + let event = AppleEvent(eventClass: "core", eventID: "getd") + let first = try invocation(dispatcher.beginDelivery(event, reply: AppleEvent.reply(to: event).descriptor, in: table)) + #expect(first.procedure == 1) + let second = try invocation(dispatcher.complete(first, result: -1708)) + #expect(second.procedure == 2 && second.isSystem && second.event == first.event) + // The system's own errAEEventNotHandled goes no further. + let done = try outcome(dispatcher.complete(second, result: -1708)) + #expect(done.error == .eventNotHandled) + #expect(done.reply[AppleEvent.Parameter.errorNumber]?.load(as: Int32.self) == -1708) + #expect(ran.withLock { $0 }.isEmpty) + // A system handler of the host's after the guest's passes. + dispatcher.install(Entry(eventClass: "core", eventID: "getd", isSystem: true, guestProcedure: 3)) + try dispatcher.remove(eventClass: "core", eventID: "getd", isSystem: true) + let again = try invocation(dispatcher.beginDelivery(event, reply: AppleEvent.reply(to: event).descriptor, in: table)) + let handled = try outcome(dispatcher.complete(again, result: -1708)) + #expect(handled.result == 0 && handled.reply[AppleEvent.Parameter.directObject] == Descriptor(true)) + #expect(ran.withLock { $0 } == ["system wildcard"]) + } + + @Test func otherResultsEndTheDelivery() throws { + let dispatcher = AppleEventDispatcher() + let table = DescriptorTable() + dispatcher.install(Entry(eventClass: "test", eventID: "fail", guestProcedure: 1)) + dispatcher.install(Entry(eventClass: "test", eventID: "fail", isSystem: true, guestProcedure: 2)) + let event = AppleEvent(eventClass: "test", eventID: "fail") + // A negative OSErr goes in a reply that has no error number of its own. + var call = try invocation(dispatcher.beginDelivery(event, reply: AppleEvent.reply(to: event).descriptor, in: table)) + var done = try outcome(dispatcher.complete(call, result: -1702)) + #expect(done.error == .corruptData && done.reply[AppleEvent.Parameter.errorNumber]?.load(as: Int32.self) == -1702) + // One the handler gave stays; a sender with no reply gets typeNull. + call = try invocation(dispatcher.beginDelivery(event, reply: AppleEvent.reply(to: event).descriptor, in: table)) + try table.update(call.reply) { $0[AppleEvent.Parameter.errorNumber] = Descriptor(Int32(-1)) } + done = try outcome(dispatcher.complete(call, result: -1702)) + #expect(done.reply[AppleEvent.Parameter.errorNumber]?.load(as: Int32.self) == -1) + call = try invocation(dispatcher.beginDelivery(event, in: table)) + done = try outcome(dispatcher.complete(call, result: -1702)) + #expect(done.reply.isNull && done.result == -1702) + // No handler at all. + done = try outcome(dispatcher.beginDelivery(AppleEvent(eventClass: "none", eventID: "none"), in: table)) + #expect(done.error == .eventNotHandled) + #expect(table.count == 0) + } + + @Test func deliveriesNestAndFinishInnermostFirst() throws { + let dispatcher = AppleEventDispatcher() + let table = DescriptorTable() + dispatcher.install(Entry(eventClass: "test", eventID: "outr", guestProcedure: 1)) + dispatcher.install(Entry(eventClass: "test", eventID: "innr", guestProcedure: 2)) + let outer = try invocation(dispatcher.beginDelivery(AppleEvent(eventClass: "test", eventID: "outr"), in: table)) + // The outer handler sends an event of its own. + let inner = try invocation(dispatcher.beginDelivery(AppleEvent(eventClass: "test", eventID: "innr"), in: table)) + #expect(inner.depth == 2 && dispatcher.openDeliveries == 2) + #expect(throws: MacError.parameter) { try dispatcher.complete(outer, result: 0) } + #expect(try outcome(dispatcher.complete(inner, result: 0)).result == 0) + #expect(try outcome(dispatcher.complete(outer, result: 0)).result == 0) + #expect(table.count == 0) + } + + @Test func abandoningEndsTheDeliveriesInside() throws { + let dispatcher = AppleEventDispatcher() + let table = DescriptorTable() + dispatcher.install(Entry(eventClass: "test", eventID: "loop", guestProcedure: 1)) + let event = AppleEvent(eventClass: "test", eventID: "loop") + let outer = try invocation(dispatcher.beginDelivery(event, in: table)) + let inner = try invocation(dispatcher.beginDelivery(event, in: table)) + // The guest faults inside the outer handler's send. + try dispatcher.abandon(outer) + #expect(dispatcher.openDeliveries == 0 && table.count == 0) + #expect(throws: MacError.parameter) { try dispatcher.complete(inner, result: 0) } + #expect(throws: MacError.parameter) { try dispatcher.abandon(inner) } + } + + @Test func hostHandlersRunWithinADelivery() throws { + let dispatcher = AppleEventDispatcher() + let table = DescriptorTable() + dispatcher.install(Entry(eventClass: "test", eventID: "echo") { event, reply in + reply[AppleEvent.Parameter.directObject] = event[parameter: AppleEvent.Parameter.directObject] + }) + var event = AppleEvent(eventClass: "test", eventID: "echo") + event[parameter: AppleEvent.Parameter.directObject] = Descriptor(Int32(5)) + let done = try outcome(dispatcher.beginDelivery(event, reply: AppleEvent.reply(to: event).descriptor, in: table)) + #expect(done.reply[AppleEvent.Parameter.directObject] == Descriptor(Int32(5))) + // Synchronous dispatch takes only the host's handlers. + dispatcher.install(Entry(eventClass: "test", eventID: "gues", guestProcedure: 1)) + var reply = Descriptor.null + #expect(throws: MacError.eventNotHandled) { try dispatcher.dispatch(AppleEvent(eventClass: "test", eventID: "gues"), reply: &reply) } + #expect(!dispatcher.sendCoreEvent(AppleEvent.Core.openApplication)) + } + + @Test func applicationWildcardsComeBeforeTheSystemTable() { + let dispatcher = AppleEventDispatcher() + dispatcher.install(Entry(eventClass: "aevt", eventID: "oapp", isSystem: true, guestProcedure: 1)) + dispatcher.install(Entry(eventClass: "aevt", eventID: DescriptorType.wildCard, guestProcedure: 2)) + dispatcher.install(Entry(eventClass: "aevt", eventID: "oapp", guestProcedure: 3)) + #expect(dispatcher.candidates(eventClass: "aevt", eventID: "oapp").map(\.procedure) == [3, 2, 1]) + } +} diff --git a/Tests/GraphiteAutomationTests/DescriptorByteOrderTests.swift b/Tests/GraphiteAutomationTests/DescriptorByteOrderTests.swift new file mode 100644 index 0000000..a34aa1b --- /dev/null +++ b/Tests/GraphiteAutomationTests/DescriptorByteOrderTests.swift @@ -0,0 +1,73 @@ +import Testing +import GraphiteCore +import GraphiteAutomation + +@Suite struct DescriptorByteOrderTests { + + /// A descriptor as a big-endian guest makes it. + private func guest(_ type: FourCharCode, _ bytes: [UInt8]) -> Descriptor { Descriptor(type: type, bytes: bytes) } + + @Test func numbersReverseByTheirWidth() { + let short = guest(DescriptorType.sInt16, [0x12, 0x34]).fromBigEndian() + #expect(short.load(as: Int16.self) == 0x1234) + #expect(guest(DescriptorType.sInt32, [0, 0, 1, 2]).fromBigEndian().load(as: Int32.self) == 0x0102) + #expect(guest(DescriptorType.double, [0x3F, 0xF0, 0, 0, 0, 0, 0, 0]).fromBigEndian().load(as: Double.self) == 1) + #expect(guest(DescriptorType.type, Array("TEXT".utf8)).fromBigEndian().code == "TEXT") + // A PSN's halves and a rectangle's sides each reverse alone. + let psn = guest(DescriptorType.processSerialNumber, [0, 0, 0, 0, 0, 0, 0, 2]).fromBigEndian() + #expect(psn == AppleEvent.currentProcess) + let rect = guest("qdrt", [0, 1, 0, 2, 0, 3, 0, 4]).fromBigEndian() + #expect(rect.load(as: (Int16, Int16, Int16, Int16).self).map { [$0.0, $0.1, $0.2, $0.3] } == [1, 2, 3, 4]) + // Booleans, text and unknown types are bytes. + for descriptor in [guest(DescriptorType.boolean, [1]), Descriptor(text: "ab"), guest("what", [1, 2, 3, 4])] { + #expect(descriptor.fromBigEndian() == descriptor) + } + } + + @Test func malformedDataIsKept() { + // A number of the wrong length, and an FSSpec too short to have a folder. + #expect(guest(DescriptorType.sInt32, [1, 2]).fromBigEndian().bytes == [1, 2]) + #expect(guest(DescriptorType.fsSpec, [0, 1, 0]).fromBigEndian().bytes == [0, 1, 0]) + // UTF-16 text: each whole unit, and an odd byte left over. + #expect(guest(DescriptorType.unicodeText, [0, 0x41, 0, 0x42, 9]).fromBigEndian().bytes == + (ByteOrder.host == .littleEndian ? [0x41, 0, 0x42, 0, 9] : [0, 0x41, 0, 0x42, 9])) + } + + @Test func structuresReverseOnlyTheirNumbers() { + // An FSSpec: volume -1, folder 2, then its name as it is. + let name: [UInt8] = [3] + Array("Doc".utf8) + [UInt8](repeating: 0, count: 60) + let spec = guest(DescriptorType.fsSpec, [0xFF, 0xFF, 0, 0, 0, 2] + name).fromBigEndian() + #expect(spec.bytes.withUnsafeBytes { ($0.loadUnaligned(as: Int16.self), $0.loadUnaligned(fromByteOffset: 2, as: UInt32.self)) } == (-1, 2)) + #expect(Array(spec.bytes.dropFirst(6)) == name) + // An alias handle's header, and not its record. + let alias = guest(DescriptorType.alias, [0, 0, 0, 0, 0, 8, 0xAA, 0xBB]).fromBigEndian() + #expect(Array(alias.bytes.suffix(2)) == [0xAA, 0xBB]) + #expect(alias.bytes.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: 4, as: UInt16.self) } == 8) + } + + @Test func eventsConvertThroughout() throws { + // The guest's oapp, attributes and all, built big-endian. + var guestEvent = Descriptor(type: DescriptorType.appleEvent, isKeyed: true) + guestEvent.setAttribute(AppleEvent.Attribute.eventClass, guest(DescriptorType.type, Array("aevt".utf8))) + guestEvent.setAttribute(AppleEvent.Attribute.eventID, guest(DescriptorType.type, Array("odoc".utf8))) + guestEvent.setAttribute(AppleEvent.Attribute.returnID, guest(DescriptorType.sInt16, [0, 7])) + guestEvent.setAttribute(AppleEvent.Attribute.transactionID, guest(DescriptorType.sInt32, [0, 0, 0, 9])) + guestEvent[AppleEvent.Parameter.directObject] = .list([.record([("size" as FourCharCode, guest(DescriptorType.sInt32, [0, 0, 1, 0]))])]) + let event = try AppleEvent(guestEvent.fromBigEndian()) + #expect(event.eventClass == "aevt" && event.eventID == "odoc" && event.returnID == 7) + #expect(event.descriptor.attribute(AppleEvent.Attribute.transactionID)?.load(as: Int32.self) == 9) + let size = try event[parameter: AppleEvent.Parameter.directObject]?.item(at: 1).descriptor["size"] + #expect(size?.load(as: Int32.self) == 256) + // And back again, byte for byte. + #expect(event.descriptor.toBigEndian() == guestEvent) + // The same order both ways changes nothing. + #expect(guestEvent.converted(from: .bigEndian, to: .bigEndian) == guestEvent) + } + + @Test func hostsAddTheirOwnLayouts() { + var layouts = ScalarLayout.standard + layouts["pair"] = ScalarLayout(fields: [2, 4]) + let pair = guest("pair", [0, 1, 0, 0, 0, 2]).fromBigEndian(layouts: layouts) + #expect(pair.bytes.withUnsafeBytes { ($0.loadUnaligned(as: UInt16.self), $0.loadUnaligned(fromByteOffset: 2, as: UInt32.self)) } == (1, 2)) + } +} diff --git a/Tests/GraphiteAutomationTests/DescriptorTableTests.swift b/Tests/GraphiteAutomationTests/DescriptorTableTests.swift new file mode 100644 index 0000000..3d1fa02 --- /dev/null +++ b/Tests/GraphiteAutomationTests/DescriptorTableTests.swift @@ -0,0 +1,67 @@ +import Testing +import GraphiteCore +import GraphiteAutomation + +@Suite struct DescriptorTableTests { + + @Test func identitiesNameOnlyTheirOwnDescriptor() throws { + let table = DescriptorTable() + let first = table.insert(Descriptor(Int32(1))) + #expect(try table.descriptor(first) == Descriptor(Int32(1))) + #expect(table.count == 1 && table.ownership(first) == .owned) + #expect(try table.dispose(first) == Descriptor(Int32(1))) + // The slot is reused, in its next generation: the old identity + // names nothing, not the new descriptor. + let second = table.insert(Descriptor(Int32(2))) + #expect(second.slot == first.slot && second.generation == first.generation + 1) + #expect(throws: MacError.notDescriptor) { try table.descriptor(first) } + #expect(throws: MacError.notDescriptor) { try table.dispose(first) } + #expect(throws: MacError.notDescriptor) { try table.replace(first, with: .null) } + #expect(!table.contains(first) && table.contains(second)) + #expect(try table.descriptor(second) == Descriptor(Int32(2))) + // One never given. + #expect(throws: MacError.notDescriptor) { try table.descriptor(DescriptorID(slot: 40, generation: 0)) } + } + + @Test func updatesAndCopies() throws { + let table = DescriptorTable() + let list = table.insert(.list()) + try table.update(list) { (list: inout Descriptor) throws(MacError) in try list.put(Descriptor(true), at: 0) } + let copy = try table.duplicate(list) + try table.update(list) { (list: inout Descriptor) throws(MacError) in try list.removeItem(at: 1) } + #expect(try table.descriptor(list).count == 0) + #expect(try table.descriptor(copy).count == 1) + // A failed change keeps what it did before failing. + #expect(throws: MacError.illegalIndex) { + try table.update(copy) { (list: inout Descriptor) throws(MacError) in + try list.put(Descriptor(false), at: 0) + try list.removeItem(at: 9) + } + } + #expect(try table.descriptor(copy).count == 2) + } + + @Test func loansEndOnlyWithTheLender() throws { + let table = DescriptorTable() + let event = table.lend(AppleEvent(eventClass: "aevt", eventID: "oapp").descriptor) + #expect(table.ownership(event) == .borrowed) + // AEDisposeDesc of a borrowed descriptor reports noErr and keeps it. + #expect(try table.dispose(event) == nil) + try table.update(event) { $0[AppleEvent.Parameter.directObject] = Descriptor(Int16(3)) } + let owned = table.insert(.null) + #expect(throws: MacError.parameter) { try table.endLoan(owned) } + let returned = try table.endLoan(event) + #expect(returned[AppleEvent.Parameter.directObject] == Descriptor(Int16(3))) + #expect(throws: MacError.notDescriptor) { try table.endLoan(event) } + #expect(table.count == 1) + } + + @Test func removingAllEndsEveryIdentity() throws { + let table = DescriptorTable() + let ids = (0 ..< 3).map { table.insert(Descriptor(Int32($0))) } + [table.lend(.null)] + table.removeAll() + #expect(table.count == 0) + for id in ids { #expect(!table.contains(id)) } + #expect(table.insert(.null).generation == 1) + } +}