diff --git a/Package.swift b/Package.swift index 05351f7..b94a858 100644 --- a/Package.swift +++ b/Package.swift @@ -138,7 +138,7 @@ let package = Package( ), .target( name: "GraphiteAutomation", - dependencies: ["GraphiteCore", "GraphiteFiles"] + dependencies: ["GraphiteCore", "GraphiteFiles", "GraphiteEvents"] ), .target( name: "Graphite2D", @@ -196,7 +196,7 @@ let package = Package( ), .testTarget( name: "GraphiteAutomationTests", - dependencies: ["GraphiteAutomation"] + dependencies: ["GraphiteAutomation", "GraphiteEvents"] ), .testTarget( name: "Graphite2DTests", diff --git a/ReferenceTests/Retro68/CMakeLists.txt b/ReferenceTests/Retro68/CMakeLists.txt index 34cc36f..b09a680 100644 --- a/ReferenceTests/Retro68/CMakeLists.txt +++ b/ReferenceTests/Retro68/CMakeLists.txt @@ -5,3 +5,4 @@ add_application(EqualStringCapture EqualStringCapture.c) add_application(FileManagerCapture FileManagerCapture.c) add_application(RelStringCapture RelStringCapture.c) add_application(CatalogOrderCapture CatalogOrderCapture.c) +add_application(HighLevelEventCapture HighLevelEventCapture.c HighLevelEventCapture.r) diff --git a/ReferenceTests/Retro68/HighLevelEventCapture.c b/ReferenceTests/Retro68/HighLevelEventCapture.c new file mode 100644 index 0000000..2cfa305 --- /dev/null +++ b/ReferenceTests/Retro68/HighLevelEventCapture.c @@ -0,0 +1,184 @@ +/* + * Captures how the Event Manager hands Apple events to a program as + * high-level events, writing "HighLevelEvents.txt" next to itself. It + * refuses to run if that file is already there. Its SIZE resource + * (HighLevelEventCapture.r) makes it aware of high-level events. + * + * It records: + * - the events it gets as it starts, with how AEProcessAppleEvent takes + * the launch event, and the EventRecord's message and `where`; + * - whether FlushEvents removes a queued high-level event, or stops at one; + * - the order GetNextEvent gives queued low- and high-level events in; + * - which event AEProcessAppleEvent delivers after two were retrieved, and + * what it returns for records it can't deliver. + * + * Events to itself are sent to its own process serial number, not + * kCurrentProcess, so that they go through its event queue; every line + * says whether they did. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static short out; +static ProcessSerialNumber self; + +static void line(const char *text) +{ + long count = strlen(text); + FSWrite(out, &count, text); + count = 1; + FSWrite(out, &count, "\r"); +} + +static void code(char *to, unsigned long value) +{ + int i; + for (i = 0; i < 4; ++i) { + unsigned char c = (unsigned char)(value >> (24 - 8 * i)); + to[i] = (c >= 32 && c < 127) ? (char)c : '.'; + } + to[4] = 0; +} + +static void describe(const char *label, Boolean found, const EventRecord *e) +{ + char text[200], message[5]; + code(message, (unsigned long)e->message); + snprintf(text, sizeof text, "%s: found=%d what=%d message=%08lX '%s' where.v=%04X where.h=%04X", + label, found, e->what, (unsigned long)e->message, message, + (unsigned short)e->where.v, (unsigned short)e->where.h); + line(text); +} + +static pascal OSErr handler(const AppleEvent *event, AppleEvent *reply, long refcon) +{ + char text[120], classText[5], idText[5]; + DescType type; + Size size; + long number = 0; + OSType eventClass = 0, eventID = 0; + AEGetAttributePtr((AppleEvent *)event, keyEventClassAttr, typeType, &type, (Ptr)&eventClass, 4, &size); + AEGetAttributePtr((AppleEvent *)event, keyEventIDAttr, typeType, &type, (Ptr)&eventID, 4, &size); + AEGetParamPtr((AppleEvent *)event, 'num ', 'long', &type, (Ptr)&number, 4, &size); + code(classText, eventClass); + code(idText, eventID); + snprintf(text, sizeof text, " handler: '%s' '%s' num=%ld", classText, idText, number); + line(text); + return noErr; +} + +/* Sends 'Grph' 'test' with a number to its own PSN, without waiting. */ +static void sendNumbered(long number) +{ + AEAddressDesc target; + AppleEvent event, reply; + char text[80]; + OSErr error; + AECreateDesc(typeProcessSerialNumber, &self, sizeof self, &target); + AECreateAppleEvent('Grph', 'test', &target, kAutoGenerateReturnID, kAnyTransactionID, &event); + AEPutParamPtr(&event, 'num ', 'long', &number, 4); + reply.descriptorType = typeNull; + reply.dataHandle = 0; + error = AESend(&event, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, 0, 0); + snprintf(text, sizeof text, "send num=%ld: %d", number, error); + line(text); + AEDisposeDesc(&event); + AEDisposeDesc(&target); +} + +static void process(const char *label, EventRecord *e) +{ + char text[80]; + OSErr error = AEProcessAppleEvent(e); + snprintf(text, sizeof text, "%s: AEProcessAppleEvent %d", label, error); + line(text); +} + +int main(void) +{ + static const unsigned char name[] = { 19, 'H','i','g','h','L','e','v','e','l','E','v','e','n','t','s','.','t','x','t' }; + EventRecord e, first = { 0 }, second = { 0 }; + Boolean found; + int i, nulls = 0; + char text[80]; + + InitGraf(&qd.thePort); + InitFonts(); + InitWindows(); + InitMenus(); + TEInit(); + InitDialogs(0); + InitCursor(); + + if (Create(name, 0, 'Grph', 'TEXT') != noErr) return 1; + if (FSOpen(name, 0, &out) != noErr) return 2; + GetCurrentProcess(&self); + AEInstallEventHandler(kCoreEventClass, typeWildCard, NewAEEventHandlerUPP(handler), 0, false); + AEInstallEventHandler('Grph', typeWildCard, NewAEEventHandlerUPP(handler), 0, false); + + line("# Launch"); + for (i = 0; i < 200 && nulls < 20; ++i) { + found = WaitNextEvent(everyEvent, &e, 1, 0); + if (!found || e.what == nullEvent) { ++nulls; continue; } + describe("launch event", found, &e); + if (e.what == kHighLevelEvent) process("launch", &e); + } + + line("# FlushEvents"); + sendNumbered(1); + PostEvent(app1Evt, 11); + found = EventAvail(highLevelEventMask, &e); + describe("queued high-level", found, &e); + FlushEvents(everyEvent, 0); + found = EventAvail(highLevelEventMask, &e); + describe("high-level after FlushEvents(everyEvent, 0)", found, &e); + found = EventAvail(app1Mask, &e); + describe("app1 after FlushEvents(everyEvent, 0)", found, &e); + + line("# Order"); + sendNumbered(2); + PostEvent(app1Evt, 12); + for (i = 1; i <= 3; ++i) { + found = GetNextEvent(everyEvent, &e); + snprintf(text, sizeof text, "GetNextEvent %d", i); + describe(text, found, &e); + if (e.what == kHighLevelEvent) { + if (first.what != kHighLevelEvent) first = e; else second = e; + } + } + + line("# Processing"); + process("last retrieved", &second); + process("first retrieved, after", &first); + found = EventAvail(highLevelEventMask, &e); + describe("high-level left", found, &e); + e.what = app1Evt; + process("an app1 record", &e); + e = second; + process("the last again", &e); + + line("# FlushEvents stop mask"); + PostEvent(app1Evt, 21); + sendNumbered(3); + PostEvent(app1Evt, 22); + FlushEvents(app1Mask, highLevelEventMask); + for (i = 1; i <= 3; ++i) { + found = GetNextEvent(everyEvent, &e); + snprintf(text, sizeof text, "after FlushEvents(app1Mask, highLevelEventMask) %d", i); + describe(text, found, &e); + if (found && e.what == kHighLevelEvent) process(" it", &e); + } + + FSClose(out); + return 0; +} diff --git a/ReferenceTests/Retro68/HighLevelEventCapture.r b/ReferenceTests/Retro68/HighLevelEventCapture.r new file mode 100644 index 0000000..fde2964 --- /dev/null +++ b/ReferenceTests/Retro68/HighLevelEventCapture.r @@ -0,0 +1,24 @@ +/* HighLevelEventCapture's SIZE: aware of high-level events, replacing the + Retro68 template's. */ +#include "Processes.r" + +resource 'SIZE' (-1) { + reserved, + ignoreSuspendResumeEvents, + reserved, + cannotBackground, + needsActivateOnFGSwitch, + backgroundAndForeground, + dontGetFrontClicks, + ignoreChildDiedEvents, + is32BitCompatible, + isHighLevelEventAware, + localAndRemoteHLEvents, + notStationeryAware, + dontUseTextEditServices, + reserved, + reserved, + reserved, + 1024 * 1024, + 1024 * 1024 +}; diff --git a/ReferenceTests/Retro68/HighLevelEvents-macos-9.2.2-ppc.txt b/ReferenceTests/Retro68/HighLevelEvents-macos-9.2.2-ppc.txt new file mode 100644 index 0000000..18a8b11 --- /dev/null +++ b/ReferenceTests/Retro68/HighLevelEvents-macos-9.2.2-ppc.txt @@ -0,0 +1 @@ +# Launch launch event: found=1 what=23 message=61657674 'aevt' where.v=6F61 where.h=7070 handler: 'aevt' 'oapp' num=0 launch: AEProcessAppleEvent 0 # FlushEvents send num=1: 0 queued high-level: found=1 what=23 message=47727068 'Grph' where.v=7465 where.h=7374 high-level after FlushEvents(everyEvent, 0): found=1 what=23 message=47727068 'Grph' where.v=7465 where.h=7374 app1 after FlushEvents(everyEvent, 0): found=0 what=0 message=00000000 '....' where.v=0058 where.h=0048 # Order send num=2: 0 GetNextEvent 1: found=1 what=12 message=0000000C '....' where.v=0058 where.h=0048 GetNextEvent 2: found=1 what=23 message=47727068 'Grph' where.v=7465 where.h=7374 GetNextEvent 3: found=1 what=23 message=47727068 'Grph' where.v=7465 where.h=7374 # Processing handler: 'Grph' 'test' num=2 last retrieved: AEProcessAppleEvent 0 first retrieved, after: AEProcessAppleEvent -608 high-level left: found=0 what=0 message=00000000 '....' where.v=0058 where.h=0048 an app1 record: AEProcessAppleEvent -608 the last again: AEProcessAppleEvent -608 # FlushEvents stop mask send num=3: 0 after FlushEvents(app1Mask, highLevelEventMask) 1: found=1 what=23 message=47727068 'Grph' where.v=7465 where.h=7374 handler: 'Grph' 'test' num=3 it: AEProcessAppleEvent 0 after FlushEvents(app1Mask, highLevelEventMask) 2: found=0 what=0 message=00000000 '....' where.v=0058 where.h=0048 after FlushEvents(app1Mask, highLevelEventMask) 3: found=0 what=0 message=00000000 '....' where.v=0058 where.h=0048 \ No newline at end of file diff --git a/ReferenceTests/Retro68/README.md b/ReferenceTests/Retro68/README.md index 45ad9d5..7af8e20 100644 --- a/ReferenceTests/Retro68/README.md +++ b/ReferenceTests/Retro68/README.md @@ -143,3 +143,28 @@ described in the source). Its output on Mac OS 9.2.2, on an HFS volume made by `CatalogOrderTests` checks that `SnapshotCatalog` and indexed `PBGetCatInfo` list the same names in the same order. + +## High-level events + +`HighLevelEventCapture.c`, with a SIZE resource (`HighLevelEventCapture.r`) +that makes it aware of high-level events, records how the Event Manager hands +Apple events to a program. It sends events to its own process serial number, +not `kCurrentProcess`, so they go through its event queue. Its output on Mac +OS 9.2.2 is `HighLevelEvents-macos-9.2.2-ppc.txt` (CR line endings). + +- The first event a program started from the Finder gets is `oapp`, as an + `EventRecord` of kind 23 whose message is the class (`'aevt'`) and whose + `where` is the ID, its high half in `v` (`0x6F61`) and its low half in `h` + (`0x7070`). +- `FlushEvents(everyEvent, 0)` left a queued high-level event, and + `FlushEvents(app1Mask, highLevelEventMask)` did not stop at one: high-level + events are not in the Operating System's queue. +- `GetNextEvent(everyEvent)` returned an app1 event posted after two + high-level events before either of them. +- With two high-level events retrieved and neither processed, + `AEProcessAppleEvent` on the second record delivered the second event; the + first was then gone, and processing its record gave `noOutstandingHLE` + (-608). So did a record of kind 12 and the second record again. + +`EventTests.classicHighLevelEventsStayApart` and `AppleEventInboxTests` check +`ClassicEventQueue` and `AppleEventInbox` against these. diff --git a/Sources/GraphiteAutomation/AppleEventInbox.swift b/Sources/GraphiteAutomation/AppleEventInbox.swift new file mode 100644 index 0000000..a8327de --- /dev/null +++ b/Sources/GraphiteAutomation/AppleEventInbox.swift @@ -0,0 +1,125 @@ +// The Apple events waiting for a Classic program: each arrives as a +// high-level event in its Classic event queue, an EventRecord of kind 23 +// whose message is the event's class and whose `where` is its ID, which the +// program finds with EventAvail, GetNextEvent or WaitNextEvent and hands to +// AEProcessAppleEvent. The event itself waits here until then. +// +// Retrieving the record does not deliver the event; AEProcessAppleEvent +// does, with the record of the event retrieved last. Events retrieved before +// it and never processed are dropped then, as a program that isn't aware of +// high-level events never processes them. Peeking with EventAvail retrieves +// nothing. Mac OS 9.2.2 behaved so (ReferenceTests/Retro68, +// HighLevelEventCapture.c): of two events retrieved, AEProcessAppleEvent +// delivered the second, and the first was gone. +// +// The launch events are the first a program gets: 'oapp' when it opens +// with no documents, 'odoc' or 'pdoc' with them, and after 'pdoc' a 'quit', +// as the Finder sends a program it started only to print. + +import Synchronization +import GraphiteCore +import GraphiteEvents + +public final class AppleEventInbox: Sendable { + + private struct Pending: Sendable { + var tag: UInt64 + var event: AppleEvent + var waitsForReply: Bool + } + + private struct State: Sendable { + var pending: [Pending] = [] + var nextTag: UInt64 = 1 + } + + public let queue: ClassicEventQueue + + private let state = Mutex(State()) + + public init(queue: ClassicEventQueue) { + self.queue = queue + } + + /// The EventRecord an Apple event arrives as: kind 23, the class as the + /// message, the ID as `where`, its high half the vertical coordinate. + public static func record(for event: AppleEvent, when: UInt32 = 0, modifiers: UInt16 = 0) -> ClassicEvent { + let id = event.eventID.rawValue + return ClassicEvent(what: ClassicEventQueue.highLevelEvent, message: event.eventClass.rawValue, when: when, + location: Point(v: Int16(truncatingIfNeeded: id >> 16), h: Int16(truncatingIfNeeded: id)), + modifiers: modifiers) + } + + /// The class and ID a high-level EventRecord names. + public static func eventClassAndID(of record: ClassicEvent) -> (eventClass: FourCharCode, eventID: FourCharCode) { + let id = UInt32(UInt16(bitPattern: record.where_.v)) << 16 | UInt32(UInt16(bitPattern: record.where_.h)) + return (FourCharCode(rawValue: record.message), FourCharCode(rawValue: id)) + } + + /// Events waiting: those queued and those retrieved but not processed. + public var count: Int { state.withLock { $0.pending.count } } + + /// Queues an event for the program. A sender that waits for a reply + /// gets one to fill in; else the reply is typeNull. + public func post(_ event: AppleEvent, waitsForReply: Bool = false, when: UInt32 = 0) { + state.withLock { state in + let tag = state.nextTag + state.nextTag &+= 1 + state.pending.append(Pending(tag: tag, event: event, waitsForReply: waitsForReply)) + queue.post(Self.record(for: event, when: when), tag: tag) + } + } + + /// Queues the events a program gets as it starts: 'oapp' with no + /// documents; else 'odoc', or 'pdoc' and then 'quit', with the + /// documents as a list in the direct object. + public func postLaunch(documents: [Descriptor] = [], print: Bool = false, when: UInt32 = 0) { + let core = AppleEvent.Core.self + guard !documents.isEmpty || print else { + post(AppleEvent(eventClass: core.eventClass, eventID: core.openApplication, target: AppleEvent.currentProcess), when: when) + return + } + var event = AppleEvent(eventClass: core.eventClass, eventID: print ? core.printDocuments : core.openDocuments, + target: AppleEvent.currentProcess) + event[parameter: AppleEvent.Parameter.directObject] = .list(documents) + post(event, when: when) + if print { + post(AppleEvent(eventClass: core.eventClass, eventID: core.quitApplication, target: AppleEvent.currentProcess), when: when) + } + } + + /// AEProcessAppleEvent's first step: the event of the record retrieved + /// last, and the reply for its handler, no longer waiting. Events + /// retrieved before it are dropped. noOutstandingHLE for a record + /// that isn't a high-level event, that names another event than the one + /// retrieved last, or when none is waiting, as Mac OS 9.2.2 gave for + /// each of these (ReferenceTests/Retro68, HighLevelEventCapture.c). + public func take(_ record: ClassicEvent) throws(MacError) -> (event: AppleEvent, reply: Descriptor) { + let taken: Pending? = state.withLock { state in + guard record.what == ClassicEventQueue.highLevelEvent else { return nil } + let retrieved = state.pending.indices.filter { !queue.contains(tag: state.pending[$0].tag) } + guard let last = retrieved.last else { return nil } + let pending = state.pending[last] + let (eventClass, eventID) = Self.eventClassAndID(of: record) + guard pending.event.eventClass == eventClass && pending.event.eventID == eventID else { return nil } + state.pending.remove(atOffsets: retrieved) + return pending + } + guard let taken else { throw .noOutstandingHighLevelEvent } + return (taken.event, taken.waitsForReply ? AppleEvent.reply(to: taken.event).descriptor : .null) + } + + /// AEProcessAppleEvent: delivers the event of a retrieved record to + /// the program's handlers. + public func process(_ record: ClassicEvent, with dispatcher: AppleEventDispatcher, + in table: DescriptorTable) throws(MacError) -> AppleEventDispatcher.Delivery { + let (event, reply) = try take(record) + return dispatcher.beginDelivery(event, reply: reply, in: table) + } +} + +private extension Array { + mutating func remove(atOffsets offsets: [Int]) { + for offset in offsets.sorted(by: >) { remove(at: offset) } + } +} diff --git a/Sources/GraphiteCore/MacError.swift b/Sources/GraphiteCore/MacError.swift index 11036ae..7cc438c 100644 --- a/Sources/GraphiteCore/MacError.swift +++ b/Sources/GraphiteCore/MacError.swift @@ -143,6 +143,9 @@ public extension MacError { /// procNotFound: no process of the address is running. static var processNotFound: MacError { MacError(-600) } + /// noOutstandingHLE: no high-level event retrieved and waiting to be + /// processed. + static var noOutstandingHighLevelEvent: MacError { MacError(-608) } /// errAECoercionFail: the data can't be coerced to the type. static var coercionFailed: MacError { MacError(-1700) } /// errAEDescNotFound: no descriptor of the keyword. @@ -186,7 +189,7 @@ extension MacError: CustomStringConvertible { -47: "fBsyErr", -48: "dupFNErr", -49: "opWrErr", -51: "rfNumErr", -54: "permErr", -61: "wrPermErr", -120: "dirNFErr", -1302: "afpItemNotFound", -1417: "errFSNoMoreItems", -1421: "errFSForkExists", -1424: "errFSForkNotFound", -192: "resNotFound", -193: "resFNotFound", -194: "addResFailed", - -196: "rmvResFailed", -198: "resAttrErr", -199: "mapReadErr", -600: "procNotFound", + -196: "rmvResFailed", -198: "resAttrErr", -199: "mapReadErr", -600: "procNotFound", -608: "noOutstandingHLE", -1700: "errAECoercionFail", -1701: "errAEDescNotFound", -1702: "errAECorruptData", -1703: "errAEWrongDataType", -1704: "errAENotAEDesc", -1705: "errAEBadListItem", -1707: "errAENotAppleEvent", -1708: "errAEEventNotHandled", -1709: "errAEReplyNotValid", diff --git a/Sources/GraphiteEvents/ClassicEvent.swift b/Sources/GraphiteEvents/ClassicEvent.swift index 1702ecf..b632a38 100644 --- a/Sources/GraphiteEvents/ClassicEvent.swift +++ b/Sources/GraphiteEvents/ClassicEvent.swift @@ -20,27 +20,67 @@ public struct ClassicEvent: Hashable, Sendable { } /// The classic queue supports EventAvail's peek, GetNextEvent's removal, -/// and FlushEvents' stop mask. High-level events use a special mask bit. +/// and FlushEvents' stop mask. +/// +/// High-level events (kind 23, highLevelEventMask 0x0400) are kept apart +/// from the Operating System's queue, as the Event Manager kept them: they +/// are retrieved, in the order posted, only when no low-level event matches, +/// and FlushEvents neither removes them nor stops at them, as Mac OS 9.2.2 +/// did (ReferenceTests/Retro68, HighLevelEventCapture.c). Masks: each kind +/// below 16 is its own bit, 1 << kind; kinds 16 to 22 match no mask. public final class ClassicEventQueue: Sendable { - private let events = Mutex<[ClassicEvent]>([]) + + private struct Entry: Sendable { + var event: ClassicEvent + var tag: UInt64? + } + + private let events = Mutex<[Entry]>([]) + public init() {} - public func post(_ event: ClassicEvent) { events.withLock { $0.append(event) } } + + public func post(_ event: ClassicEvent) { events.withLock { $0.append(Entry(event: event)) } } + + /// Posts an event with a tag of the poster's, which `contains(tag:)` + /// finds while the event is queued. + public func post(_ event: ClassicEvent, tag: UInt64) { + events.withLock { $0.append(Entry(event: event, tag: tag)) } + } + + /// Whether the event posted with a tag is still queued. + public func contains(tag: UInt64) -> Bool { + events.withLock { $0.contains { $0.tag == tag } } + } + 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] + guard let index = queue.firstIndex(where: { !Self.isHighLevel($0.event) && Self.matches($0.event, mask) }) + ?? queue.firstIndex(where: { Self.isHighLevel($0.event) && Self.matches($0.event, mask) }) else { return nil } + return remove ? queue.remove(at: index).event : queue[index].event } } + + /// FlushEvents: removes the low-level events of a mask, up to the first + /// of the stop mask. 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 == highLevelEvent } + private static func matches(_ event: ClassicEvent, _ mask: UInt16) -> Bool { let eventMask: UInt16 - if event.what == 23 { - eventMask = 0x0400 + if event.what == highLevelEvent { + eventMask = highLevelEventMask } else if event.what < 16 { eventMask = UInt16(1) << event.what } else { diff --git a/Tests/GraphiteAutomationTests/AppleEventInboxTests.swift b/Tests/GraphiteAutomationTests/AppleEventInboxTests.swift new file mode 100644 index 0000000..d25f9d6 --- /dev/null +++ b/Tests/GraphiteAutomationTests/AppleEventInboxTests.swift @@ -0,0 +1,86 @@ +import Testing +import GraphiteCore +import GraphiteEvents +import GraphiteAutomation + +@Suite struct AppleEventInboxTests { + + private func outcome(_ delivery: AppleEventDispatcher.Delivery) throws -> AppleEventDispatcher.Outcome { + guard case .finished(let outcome) = delivery else { throw MacError.parameter } + return outcome + } + + @Test func recordsCarryTheClassAndID() { + let record = AppleEventInbox.record(for: AppleEvent(eventClass: "aevt", eventID: "oapp"), when: 9) + #expect(record.what == 23 && record.when == 9) + #expect(record.message == FourCharCode("aevt").rawValue) + // The ID's high half is `where`'s vertical coordinate. + #expect(UInt16(bitPattern: record.where_.v) == 0x6F61 && UInt16(bitPattern: record.where_.h) == 0x7070) + let (eventClass, eventID) = AppleEventInbox.eventClassAndID(of: record) + #expect(eventClass == "aevt" && eventID == "oapp") + } + + @Test func launchingWithoutDocumentsOpensTheApplication() throws { + let queue = ClassicEventQueue() + let inbox = AppleEventInbox(queue: queue) + inbox.postLaunch() + // EventAvail sees it without retrieving it: AEProcessAppleEvent + // can't take it yet. + let peeked = try #require(queue.next(mask: ClassicEventQueue.highLevelEventMask, remove: false)) + #expect(throws: MacError.noOutstandingHighLevelEvent) { try inbox.take(peeked) } + let record = try #require(queue.next(mask: 0xFFFF)) + #expect(AppleEventInbox.eventClassAndID(of: record).eventID == "oapp") + let (event, reply) = try inbox.take(record) + #expect(event.eventID == "oapp" && event.isForCurrentProcess && reply.isNull) + #expect(inbox.count == 0) + #expect(throws: MacError.noOutstandingHighLevelEvent) { try inbox.take(record) } + } + + @Test func launchingToPrintQuitsAfter() throws { + let queue = ClassicEventQueue() + let inbox = AppleEventInbox(queue: queue) + inbox.postLaunch(documents: [Descriptor(text: "a"), Descriptor(text: "b")], print: true) + var ids: [FourCharCode] = [] + while let record = queue.next(mask: ClassicEventQueue.highLevelEventMask) { + let (event, _) = try inbox.take(record) + ids.append(event.eventID) + if event.eventID == "pdoc" { #expect(event[parameter: AppleEvent.Parameter.directObject]?.count == 2) } + } + #expect(ids == ["pdoc", "quit"]) + inbox.postLaunch(documents: [Descriptor(text: "a")]) + #expect(try inbox.take(#require(queue.next(mask: 0xFFFF))).event.eventID == "odoc") + } + + @Test func processingDeliversTheEventRetrievedLast() throws { + let queue = ClassicEventQueue() + let inbox = AppleEventInbox(queue: queue) + let dispatcher = AppleEventDispatcher() + let table = DescriptorTable() + dispatcher.install(.init(eventClass: "Grph", eventID: "test") { event, reply in + reply[AppleEvent.Parameter.directObject] = event[parameter: "num "] + }) + for number in 1 ... 2 as ClosedRange { + var event = AppleEvent(eventClass: "Grph", eventID: "test") + event[parameter: "num "] = Descriptor(number) + inbox.post(event, waitsForReply: true) + } + let first = try #require(queue.next(mask: 0xFFFF)) + let second = try #require(queue.next(mask: 0xFFFF)) + let done = try outcome(inbox.process(second, with: dispatcher, in: table)) + #expect(done.reply[AppleEvent.Parameter.directObject] == Descriptor(Int32(2))) + // The first was retrieved and never processed: it is gone. + #expect(inbox.count == 0) + #expect(throws: MacError.noOutstandingHighLevelEvent) { try inbox.process(first, with: dispatcher, in: table) } + #expect(throws: MacError.noOutstandingHighLevelEvent) { try inbox.process(ClassicEvent(what: 12), with: dispatcher, in: table) } + } + + @Test func aRecordMustNameTheEventRetrieved() throws { + let queue = ClassicEventQueue() + let inbox = AppleEventInbox(queue: queue) + inbox.post(AppleEvent(eventClass: "Grph", eventID: "test")) + _ = queue.next(mask: 0xFFFF) + let other = AppleEventInbox.record(for: AppleEvent(eventClass: "Grph", eventID: "othr")) + #expect(throws: MacError.noOutstandingHighLevelEvent) { try inbox.take(other) } + #expect(inbox.count == 1) + } +} diff --git a/Tests/GraphiteEventsTests/EventTests.swift b/Tests/GraphiteEventsTests/EventTests.swift index bc95da6..93e5cd6 100644 --- a/Tests/GraphiteEventsTests/EventTests.swift +++ b/Tests/GraphiteEventsTests/EventTests.swift @@ -69,15 +69,36 @@ private final class WaitingHost: EventLoopHost, ClassicEventHost { #expect(queue.next(mask: 0x0400, remove: false)?.message == 42) #expect(queue.next(mask: 0xffff)?.message == 42) - queue.post(ClassicEvent(what: 1)) - queue.post(ClassicEvent(what: 23)) - queue.post(ClassicEvent(what: 1)) - queue.flush(mask: 0x0002, stopMask: 0x0400) - #expect(queue.next(mask: 0x0400)?.what == 23) - #expect(queue.next(mask: 0x0002)?.what == 1) - queue.post(ClassicEvent(what: 15)) #expect(queue.next(mask: 0x8000)?.what == 15) + // Kinds 16 to 22 match no mask. + queue.post(ClassicEvent(what: 16)) + #expect(queue.next(mask: 0xffff) == nil) + } + + /// As Mac OS 9.2.2 did (ReferenceTests/Retro68, + /// HighLevelEvents-macos-9.2.2-ppc.txt). + @Test func classicHighLevelEventsStayApart() { + let queue = ClassicEventQueue() + // FlushEvents neither removes a high-level event nor stops at one. + queue.post(ClassicEvent(what: 12, message: 21)) + queue.post(ClassicEvent(what: 23, message: 3)) + queue.post(ClassicEvent(what: 12, message: 22)) + queue.flush(mask: 1 << 12, stopMask: 0x0400) + #expect(queue.next(mask: 0xffff)?.message == 3) + #expect(queue.next(mask: 0xffff) == nil) + queue.post(ClassicEvent(what: 23, message: 1)) + queue.flush(mask: 0xffff) + #expect(queue.next(mask: 0x0400, remove: false)?.message == 1) + // A low-level event comes first, though posted after. + queue.post(ClassicEvent(what: 23, message: 2)) + queue.post(ClassicEvent(what: 12, message: 12)) + #expect([queue.next(mask: 0xffff), queue.next(mask: 0xffff), queue.next(mask: 0xffff)].map { $0?.message } == [12, 1, 2]) + // Tagged events are found while queued. + queue.post(ClassicEvent(what: 23), tag: 7) + #expect(queue.contains(tag: 7)) + _ = queue.next(mask: 0x0400) + #expect(!queue.contains(tag: 7)) } @Test func handlerChainsAndChanges() {