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
4 changes: 2 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ let package = Package(
),
.target(
name: "GraphiteAutomation",
dependencies: ["GraphiteCore", "GraphiteFiles"]
dependencies: ["GraphiteCore", "GraphiteFiles", "GraphiteEvents"]
),
.target(
name: "Graphite2D",
Expand Down Expand Up @@ -196,7 +196,7 @@ let package = Package(
),
.testTarget(
name: "GraphiteAutomationTests",
dependencies: ["GraphiteAutomation"]
dependencies: ["GraphiteAutomation", "GraphiteEvents"]
),
.testTarget(
name: "Graphite2DTests",
Expand Down
1 change: 1 addition & 0 deletions ReferenceTests/Retro68/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
184 changes: 184 additions & 0 deletions ReferenceTests/Retro68/HighLevelEventCapture.c
Original file line number Diff line number Diff line change
@@ -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 <Quickdraw.h>
#include <Fonts.h>
#include <Windows.h>
#include <Menus.h>
#include <TextEdit.h>
#include <Dialogs.h>
#include <Events.h>
#include <Files.h>
#include <Processes.h>
#include <AppleEvents.h>
#include <stdio.h>
#include <string.h>

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;
}
24 changes: 24 additions & 0 deletions ReferenceTests/Retro68/HighLevelEventCapture.r
Original file line number Diff line number Diff line change
@@ -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
};
1 change: 1 addition & 0 deletions ReferenceTests/Retro68/HighLevelEvents-macos-9.2.2-ppc.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Launchlaunch event: found=1 what=23 message=61657674 'aevt' where.v=6F61 where.h=7070 handler: 'aevt' 'oapp' num=0launch: AEProcessAppleEvent 0# FlushEventssend num=1: 0queued high-level: found=1 what=23 message=47727068 'Grph' where.v=7465 where.h=7374high-level after FlushEvents(everyEvent, 0): found=1 what=23 message=47727068 'Grph' where.v=7465 where.h=7374app1 after FlushEvents(everyEvent, 0): found=0 what=0 message=00000000 '....' where.v=0058 where.h=0048# Ordersend num=2: 0GetNextEvent 1: found=1 what=12 message=0000000C '....' where.v=0058 where.h=0048GetNextEvent 2: found=1 what=23 message=47727068 'Grph' where.v=7465 where.h=7374GetNextEvent 3: found=1 what=23 message=47727068 'Grph' where.v=7465 where.h=7374# Processing handler: 'Grph' 'test' num=2last retrieved: AEProcessAppleEvent 0first retrieved, after: AEProcessAppleEvent -608high-level left: found=0 what=0 message=00000000 '....' where.v=0058 where.h=0048an app1 record: AEProcessAppleEvent -608the last again: AEProcessAppleEvent -608# FlushEvents stop masksend num=3: 0after FlushEvents(app1Mask, highLevelEventMask) 1: found=1 what=23 message=47727068 'Grph' where.v=7465 where.h=7374 handler: 'Grph' 'test' num=3 it: AEProcessAppleEvent 0after FlushEvents(app1Mask, highLevelEventMask) 2: found=0 what=0 message=00000000 '....' where.v=0058 where.h=0048after FlushEvents(app1Mask, highLevelEventMask) 3: found=0 what=0 message=00000000 '....' where.v=0058 where.h=0048
Expand Down
25 changes: 25 additions & 0 deletions ReferenceTests/Retro68/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
125 changes: 125 additions & 0 deletions Sources/GraphiteAutomation/AppleEventInbox.swift
Original file line number Diff line number Diff line change
@@ -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) }
}
}
Loading
Loading