diff --git a/ReferenceTests/Retro68/AEDescLayout-macos-9.2.2-ppc.txt b/ReferenceTests/Retro68/AEDescLayout-macos-9.2.2-ppc.txt new file mode 100644 index 0000000..78c3654 --- /dev/null +++ b/ReferenceTests/Retro68/AEDescLayout-macos-9.2.2-ppc.txt @@ -0,0 +1 @@ +CreateList list -> 0 list empty: type list size 24 00000000 64825d33 00000018 6c697374 00000000 00000000 PutPtr long -> 0 list long: type list size 36 00000000 64825d33 00000018 6c697374 00000001 00000000 6c6f6e67 00000004 11223344 PutPtr TEXT 5 -> 0 list long TEXT: type list size 50 00000000 64825d33 00000018 6c697374 00000002 00000000 6c6f6e67 00000004 11223344 54455854 00000005 68656c6c 6f00 PutPtr TEXT 0 -> 0 list long TEXT empty: type list size 58 00000000 64825d33 00000018 6c697374 00000003 00000000 6c6f6e67 00000004 11223344 54455854 00000005 68656c6c 6f005445 58540000 0000 PutPtr null -> 0 list long TEXT empty null: type list size 66 00000000 64825d33 00000018 6c697374 00000004 00000000 6c6f6e67 00000004 11223344 54455854 00000005 68656c6c 6f005445 58540000 00006e75 6c6c0000 0000 DeleteItem 2 -> 0 list after deleting item 2: type list size 52 00000000 00000032 00000018 6c697374 00000003 00000000 6c6f6e67 00000004 11223344 54455854 00000000 6e756c6c 00000000 CreateList record -> 0 record empty: type reco size 24 00000000 fcfcf700 00000018 7265636f 00000000 00000000 PutParamPtr k001 -> 0 record k001: type reco size 40 00000000 fcfcf700 00000018 7265636f 00000001 00000000 6b303031 6c6f6e67 00000004 00000001 PutParamPtr k002 -> 0 record k001 k002: type reco size 56 00000000 fcfcf700 00000018 7265636f 00000002 00000000 6b303031 6c6f6e67 00000004 00000001 6b303032 54455854 00000003 68656c6c PutParamPtr k001 again -> 0 record k001 replaced: type reco size 56 00000000 fcfcf700 00000018 7265636f 00000002 00000000 6b303031 6c6f6e67 00000004 00000002 6b303032 54455854 00000003 68656c6c PutParamDesc list in record -> 0 record with a list: type reco size 104 00000000 fcfcf700 00000018 7265636f 00000003 00000000 6b303031 6c6f6e67 00000004 00000002 6b303032 54455854 00000003 68656c6c 6c697374 6c697374 00000024 00000003 00000000 6c6f6e67 00000004 11223344 54455854 00000000 6e756c6c 00000000 CreateList inner record -> 0 PutParamDesc record in record -> 0 record with a list and a record: type reco size 140 00000000 fcfcf700 00000018 7265636f 00000004 00000000 6b303031 6c6f6e67 00000004 00000002 6b303032 54455854 00000003 68656c6c 6c697374 6c697374 00000024 00000003 00000000 6c6f6e67 00000004 11223344 54455854 00000000 6e756c6c 00000000 7265636f 7265636f 00000018 00000001 00000000 6b303037 6c6f6e67 00000004 00000007 PutDesc record in list -> 0 list with a record: type list size 84 00000000 00000032 00000018 6c697374 00000004 00000000 6c6f6e67 00000004 11223344 54455854 00000000 6e756c6c 00000000 7265636f 00000018 00000001 00000000 6b303037 6c6f6e67 00000004 00000007 GetParamDesc list -> 0 the list got back: type list size 52 00000000 6c697374 00000018 6c697374 00000003 00000000 6c6f6e67 00000004 11223344 54455854 00000000 6e756c6c 00000000 DuplicateDesc record -> 0 the duplicate: type reco size 140 00000000 fcfcf700 00000018 7265636f 00000004 00000000 6b303031 6c6f6e67 00000004 00000002 6b303032 54455854 00000003 68656c6c 6c697374 6c697374 00000024 00000003 00000000 6c6f6e67 00000004 11223344 54455854 00000000 6e756c6c 00000000 7265636f 7265636f 00000018 00000001 00000000 6b303037 6c6f6e67 00000004 00000007 CreateDesc target -> 0 target: type psn size 8 00000000 00000002 CreateAppleEvent -> 0 event empty: type aevt size 106 00000000 00000002 0000006a 00000001 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 0000636f 72656372 656c0000 12347073 6e200000 00080000 00000000 00026165 76740001 00017472 616e6c6f 6e670000 00045566 77883b3b 3b3b GetAttributeDesc optk on a new event -> -1701 left type null handle 00000000 PutParamPtr key1 -> 0 event key1: type aevt size 122 00000000 00000002 0000006a 00000001 00000001 00000000 00000000 00000000 00000000 00000000 00000000 00000000 0000636f 72656372 656c0000 12347073 6e200000 00080000 00000000 00026165 76740001 00017472 616e6c6f 6e670000 00045566 77883b3b 3b3b6b65 79316c6f 6e670000 00040000 000b PutParamPtr key2 -> 0 event key1 key2: type aevt size 140 00000000 00000002 0000006a 00000001 00000002 00000000 00000000 00000000 00000000 00000000 00000000 00000000 0000636f 72656372 656c0000 12347073 6e200000 00080000 00000000 00026165 76740001 00017472 616e6c6f 6e670000 00045566 77883b3b 3b3b6b65 79316c6f 6e670000 00040000 000b6b65 79325445 58540000 00056865 6c6c6f00 CreateList keywords -> 0 keyword list: type list size 48 00000000 ab00001c 00000018 6c697374 00000002 00000000 6b657977 00000004 6b657931 6b657977 00000004 6b657932 PutAttributeDesc optk -> 0 event with optk: type aevt size 184 00000000 00000002 00000096 00000002 00000002 00000000 00000000 00000000 00000000 00000000 00000000 00000000 0000636f 72656372 656c0000 12347073 6e200000 00080000 00000000 00026165 76740001 00017472 616e6c6f 6e670000 00045566 77886f70 746b6c69 73740000 00200000 00020000 00006b65 79770000 00046b65 79316b65 79770000 00046b65 79323b3b 3b3b6b65 79316c6f 6e670000 00040000 000b6b65 79325445 58540000 00056865 6c6c6f00 GetAttributeDesc optk -> 0 optk got back: type list size 48 00000000 6f70746b 00000018 6c697374 00000002 00000000 6b657977 00000004 6b657931 6b657977 00000004 6b657932 PutAttributePtr zzzz -> 0 event with another attribute: type aevt size 200 00000000 00000002 000000a6 00000003 00000002 00000000 00000000 00000000 00000000 00000000 00000000 00000000 0000636f 72656372 656c0000 12347073 6e200000 00080000 00000000 00026165 76740001 00017472 616e6c6f 6e670000 00045566 77886f70 746b6c69 73740000 00200000 00020000 00006b65 79770000 00046b65 79316b65 79770000 00046b65 79327a7a 7a7a6c6f 6e670000 00040000 00633b3b 3b3b6b65 79316c6f 6e670000 00040000 000b6b65 79325445 58540000 00056865 6c6c6f00 DeleteParam key1 -> 0 event without key1: type aevt size 184 00000000 000000b6 000000a6 00000003 00000001 00000000 00000000 00000000 00000000 00000000 00000000 00000000 0000636f 72656372 656c0000 12347073 6e200000 00080000 00000000 00026165 76740001 00017472 616e6c6f 6e670000 00045566 77886f70 746b6c69 73740000 00200000 00020000 00006b65 79770000 00046b65 79316b65 79770000 00046b65 79327a7a 7a7a6c6f 6e670000 00040000 00633b3b 3b3b6b65 79325445 58540000 00056865 6c6c6f00 DuplicateDesc event -> 0 event duplicate: type aevt size 184 00000000 000000b6 000000a6 00000003 00000001 00000000 00000000 00000000 00000000 00000000 00000000 00000000 0000636f 72656372 656c0000 12347073 6e200000 00080000 00000000 00026165 76740001 00017472 616e6c6f 6e670000 00045566 77886f70 746b6c69 73740000 00200000 00020000 00006b65 79770000 00046b65 79316b65 79770000 00046b65 79327a7a 7a7a6c6f 6e670000 00040000 00633b3b 3b3b6b65 79325445 58540000 00056865 6c6c6f00 CreateAppleEvent nil target -> 0 event without a target: type aevt size 82 00000000 000000b6 00000052 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00004772 70687465 73740000 41a7ffc1 00000000 00006165 76740001 00013b3b 3b3b done \ No newline at end of file diff --git a/ReferenceTests/Retro68/AEDescLayoutCapture.c b/ReferenceTests/Retro68/AEDescLayoutCapture.c new file mode 100644 index 0000000..6e96bae --- /dev/null +++ b/ReferenceTests/Retro68/AEDescLayoutCapture.c @@ -0,0 +1,187 @@ +/* + * Captures what the Apple Event Manager keeps in a descriptor's data handle: + * lists, records and events, empty and with items, parameters and attributes, + * nested, and after replacing and deleting. Programs that write that data + * themselves (BBEdit Lite 6.1 does) depend on its layout. + * + * It sends nothing. It writes its results as text lines to "AEDescLayout.txt" + * in its own folder, and refuses to run if that is already there. Each dump is + * the descriptor's type, its handle's size and the handle's bytes. + */ +#include +#include +#include +#include +#include +#include + +static short out; + +static void line(const char *text) +{ + long count = strlen(text); + FSWrite(out, &count, text); + count = 1; + FSWrite(out, &count, "\r"); + FlushVol(0, 0); +} + +static void pstr(Str255 to, const char *from) +{ + int n = 0; + while (from[n] && n < 255) { to[n + 1] = (unsigned char)from[n]; ++n; } + to[0] = (unsigned char)n; +} + +static void result(const char *label, OSErr error) +{ + char text[200]; + sprintf(text, "%s -> %d", label, error); + line(text); +} + +static void dump(const char *label, const AEDesc *d) +{ + char text[200]; + DescType type = d->descriptorType; + Size size, i; + int used; + + if (d->dataHandle == NULL) { + sprintf(text, "%s: type %.4s handle nil", label, (const char *)&type); + line(text); + return; + } + size = GetHandleSize((Handle)d->dataHandle); + sprintf(text, "%s: type %.4s size %ld", label, (const char *)&type, (long)size); + line(text); + used = 0; + for (i = 0; i < size && i < 1024; ++i) { + used += sprintf(text + used, "%02x", (unsigned char)(*(Handle)d->dataHandle)[i]); + if (i % 4 == 3) text[used++] = ' '; + if (i % 32 == 31 || i == size - 1) { + text[used] = 0; + line(text); + used = 0; + } + } +} + +int main(void) +{ + Str255 name; + short vRef; + ProcessSerialNumber psn; + AEDesc target, event, record, list, inner, got, copy; + long v; + char hello[] = "hello"; + DescType keys[2]; + + pstr(name, "AEDescLayout.txt"); + if (FSOpen(name, 0, &vRef) == noErr) { FSClose(vRef); return 1; } + if (Create(name, 0, 'Grph', 'TEXT') != noErr) return 2; + if (FSOpen(name, 0, &out) != noErr) return 3; + + /* A list: empty, then one item at a time. */ + result("CreateList list", AECreateList(NULL, 0, false, &list)); + dump("list empty", &list); + v = 0x11223344; + result("PutPtr long", AEPutPtr(&list, 0, 'long', &v, 4)); + dump("list long", &list); + result("PutPtr TEXT 5", AEPutPtr(&list, 0, typeChar, hello, 5)); + dump("list long TEXT", &list); + result("PutPtr TEXT 0", AEPutPtr(&list, 0, typeChar, hello, 0)); + dump("list long TEXT empty", &list); + result("PutPtr null", AEPutPtr(&list, 0, typeNull, NULL, 0)); + dump("list long TEXT empty null", &list); + result("DeleteItem 2", AEDeleteItem(&list, 2)); + dump("list after deleting item 2", &list); + + /* A record. */ + result("CreateList record", AECreateList(NULL, 0, true, &record)); + dump("record empty", &record); + v = 1; + result("PutParamPtr k001", AEPutParamPtr(&record, 'k001', 'long', &v, 4)); + dump("record k001", &record); + result("PutParamPtr k002", AEPutParamPtr(&record, 'k002', typeChar, hello, 3)); + dump("record k001 k002", &record); + v = 2; + result("PutParamPtr k001 again", AEPutParamPtr(&record, 'k001', 'long', &v, 4)); + dump("record k001 replaced", &record); + + /* Nested: a list and a record in a record, a record in a list. */ + result("PutParamDesc list in record", AEPutParamDesc(&record, 'list', &list)); + dump("record with a list", &record); + result("CreateList inner record", AECreateList(NULL, 0, true, &inner)); + v = 7; + AEPutParamPtr(&inner, 'k007', 'long', &v, 4); + result("PutParamDesc record in record", AEPutParamDesc(&record, 'reco', &inner)); + dump("record with a list and a record", &record); + result("PutDesc record in list", AEPutDesc(&list, 0, &inner)); + dump("list with a record", &list); + result("GetParamDesc list", AEGetParamDesc(&record, 'list', typeWildCard, &got)); + dump("the list got back", &got); + AEDisposeDesc(&got); + result("DuplicateDesc record", AEDuplicateDesc(&record, ©)); + dump("the duplicate", ©); + AEDisposeDesc(©); + AEDisposeDesc(&inner); + AEDisposeDesc(&record); + AEDisposeDesc(&list); + + /* An event for this process, with fixed IDs so two runs compare. */ + psn.highLongOfPSN = 0; + psn.lowLongOfPSN = kCurrentProcess; + result("CreateDesc target", AECreateDesc(typeProcessSerialNumber, &psn, sizeof psn, &target)); + dump("target", &target); + result("CreateAppleEvent", AECreateAppleEvent('core', 'crel', &target, 0x1234, 0x55667788, &event)); + dump("event empty", &event); + got.descriptorType = '????'; + got.dataHandle = (Handle)0x12345678; + result("GetAttributeDesc optk on a new event", AEGetAttributeDesc(&event, keyOptionalKeywordAttr, typeAEList, &got)); + { + char text[100]; + DescType type = got.descriptorType; + sprintf(text, " left type %.4s handle %08lx", (const char *)&type, (unsigned long)got.dataHandle); + line(text); + } + v = 11; + result("PutParamPtr key1", AEPutParamPtr(&event, 'key1', 'long', &v, 4)); + dump("event key1", &event); + result("PutParamPtr key2", AEPutParamPtr(&event, 'key2', typeChar, hello, 5)); + dump("event key1 key2", &event); + + /* The optional keywords, as an attribute. */ + result("CreateList keywords", AECreateList(NULL, 0, false, &list)); + keys[0] = 'key1'; + keys[1] = 'key2'; + AEPutPtr(&list, 0, 'keyw', &keys[0], 4); + AEPutPtr(&list, 0, 'keyw', &keys[1], 4); + dump("keyword list", &list); + result("PutAttributeDesc optk", AEPutAttributeDesc(&event, keyOptionalKeywordAttr, &list)); + dump("event with optk", &event); + AEDisposeDesc(&list); + result("GetAttributeDesc optk", AEGetAttributeDesc(&event, keyOptionalKeywordAttr, typeAEList, &got)); + dump("optk got back", &got); + AEDisposeDesc(&got); + v = 99; + result("PutAttributePtr zzzz", AEPutAttributePtr(&event, 'zzzz', 'long', &v, 4)); + dump("event with another attribute", &event); + result("DeleteParam key1", AEDeleteParam(&event, 'key1')); + dump("event without key1", &event); + result("DuplicateDesc event", AEDuplicateDesc(&event, ©)); + dump("event duplicate", ©); + AEDisposeDesc(©); + AEDisposeDesc(&event); + + /* An event with no target, and the automatic return ID. */ + result("CreateAppleEvent nil target", AECreateAppleEvent('Grph', 'test', NULL, kAutoGenerateReturnID, kAnyTransactionID, &event)); + dump("event without a target", &event); + AEDisposeDesc(&event); + + AEDisposeDesc(&target); + line("done"); + FSClose(out); + FlushVol(0, 0); + return 0; +} diff --git a/ReferenceTests/Retro68/CMakeLists.txt b/ReferenceTests/Retro68/CMakeLists.txt index 0e9cb64..1ebb14a 100644 --- a/ReferenceTests/Retro68/CMakeLists.txt +++ b/ReferenceTests/Retro68/CMakeLists.txt @@ -26,3 +26,4 @@ add_application(TextCapture TextCapture.c TextCapture.r) add_application(GWorldCapture GWorldCapture.c) add_application(UtilitiesCapture UtilitiesCapture.c) add_application(TrackingCapture TrackingCapture.c) +add_application(AEDescLayoutCapture AEDescLayoutCapture.c) diff --git a/ReferenceTests/Retro68/README.md b/ReferenceTests/Retro68/README.md index df49efc..ab23a0d 100644 --- a/ReferenceTests/Retro68/README.md +++ b/ReferenceTests/Retro68/README.md @@ -790,3 +790,62 @@ quick for Mac OS to follow give a useless capture. Not captured: a drag at the limit's edges, a rear window released outside the limit (Graphite selects it), a drag with the Command key, and submenus. + +## Apple event data + +`AEDescLayoutCapture.c` dumps what the Apple Event Manager keeps in a +descriptor's data handle: lists, records and events, empty and filled, nested, +and after replacing and deleting. Programs that write that data themselves +depend on it; BBEdit Lite 6.1 builds the event that opens its untitled window +this way. It sends nothing, and writes `AEDescLayout.txt`. The output on Mac OS +9.2.2 is `AEDescLayout-macos-9.2.2-ppc.txt` (CR line endings). All values are +big-endian, and an item's data is padded to an even length that its size +doesn't count; the padding byte is whatever followed the data copied. + +A list or record (type `list` or `reco`): + +| Offset | Size | Contents | +|---|---|---| +| 0 | 4 | 0 | +| 4 | 4 | varies between runs of the same calls; leftover | +| 8 | 4 | offset of the first item, 24 | +| 12 | 4 | the descriptor's type (`optk` for an attribute got back) | +| 16 | 4 | item count | +| 20 | 4 | 0 | +| 24 | | items | + +A list's item is its type, size and data; a record's is its keyword, type, size +and data. A list or record inside another is its count, a zero long and its +items: the outer 16 bytes are left out. + +An event (type `aevt`): + +| Offset | Size | Contents | +|---|---|---| +| 0 | 4 | 0 | +| 4 | 4 | leftover | +| 8 | 4 | offset of the first parameter | +| 12 | 4 | count of the attributes in the attribute list below | +| 16 | 4 | parameter count | +| 20 | 30 | zero, through offset 49 | +| 50 | 4 | event class | +| 54 | 4 | event ID | +| 58 | 4 | return ID | +| 62 | | target address: type, size, data | +| | 4 | `aevt` | +| | 4 | the words 1 and 1 | +| | | attributes: keyword, type, size, data | +| | 4 | `;;;;` | +| | | parameters: keyword, type, size, data | + +- The transaction ID is a listed attribute, and is left out when it is + `kAnyTransactionID`. With no target, the address has size 0 and a type that + is not meaningful. +- `AEGetAttributeDesc` for a keyword that isn't there gave -1701 and left the + result typeNull with a nil handle. +- A duplicate has the same bytes. + +`DescriptorClassicDataTests` builds the same lists, records and events with +`Descriptor.classicData()` and compares them byte for byte, apart from the +leftover long and padding byte. The null-target event is not compared: its +target type is not meaningful. diff --git a/Sources/GraphiteAutomation/DescriptorClassicData.swift b/Sources/GraphiteAutomation/DescriptorClassicData.swift new file mode 100644 index 0000000..88d6c53 --- /dev/null +++ b/Sources/GraphiteAutomation/DescriptorClassicData.swift @@ -0,0 +1,216 @@ +// What Mac OS 9.2.2 keeps in the data handle of a list, a record or an Apple +// event (ReferenceTests/Retro68/AEDescLayout-macos-9.2.2-ppc.txt). Programs +// that write that data themselves depend on it. The layout's own numbers are +// big-endian, and a descriptor's bytes are copied as they are, so one made +// with host numbers goes through toBigEndian() first. + +import GraphiteCore + +public extension Descriptor { + + /// The data handle's bytes for a list, record or Apple event; + /// errAENotAEDesc for another descriptor, and errAEWrongDataType for an + /// event inside one, whose layout isn't known. + func classicData() throws(MacError) -> [UInt8] { + if isAppleEvent { return try classicEventData() } + guard isList || isKeyed else { throw .notDescriptor } + var data = ClassicData() + data.long(0) + data.long(0) // Left over from earlier use on Mac OS. + data.long(UInt32(ClassicData.listHeader)) + data.long(type.rawValue) + data.long(UInt32(items.count)) + data.long(0) + try data.append(items, keyed: !isList, depth: 0) + return data.bytes + } + + /// A list, record or Apple event from its data handle's bytes; + /// errAECorruptData for bytes that don't hold what they say they do. + init(type: FourCharCode, classicData bytes: [UInt8]) throws(MacError) { + var data = ClassicData(bytes: bytes) + if type == DescriptorType.appleEvent { + self = try data.event() + return + } + let isList = type == DescriptorType.list + data.position = 8 + let start = try data.long() + data.position = 16 + let count = try data.long() + data.position = Int(start) + self.init(type: type, items: try data.items(count, keyed: !isList, depth: 0), isKeyed: !isList) + } + + private func classicEventData() throws(MacError) -> [UInt8] { + // The class, ID, return ID and target have places of their own. + let fields = [AppleEvent.Attribute.eventClass, AppleEvent.Attribute.eventID, + AppleEvent.Attribute.returnID, AppleEvent.Attribute.address] + // A transaction ID of kAnyTransactionID is not listed. + let listed = attributes.filter { item in + !fields.contains(item.keyword) + && !(item.keyword == AppleEvent.Attribute.transactionID && item.descriptor.bytes.allSatisfy { $0 == 0 }) + } + var data = ClassicData() + data.long(0) + data.long(0) + data.long(0) // Where the parameters start, once known. + data.long(UInt32(listed.count)) + data.long(UInt32(items.count)) + data.bytes += [UInt8](repeating: 0, count: ClassicData.eventClassOffset - data.bytes.count) + for keyword in [AppleEvent.Attribute.eventClass, AppleEvent.Attribute.eventID] { + let code = attribute(keyword)?.bytes ?? [] + data.bytes += code.count == 4 ? code : [0, 0, 0, 0] + } + // An AEReturnID is a short, kept here as a long. + let returnID = attribute(AppleEvent.Attribute.returnID)?.bytes ?? [] + data.long(returnID.count == 2 ? UInt32(bitPattern: Int32(Int16(bitPattern: UInt16(returnID[0]) << 8 | UInt16(returnID[1])))) : 0) + let address = attribute(AppleEvent.Attribute.address) + data.long((address?.type ?? DescriptorType.null).rawValue) + data.value(address?.bytes ?? []) + data.long(DescriptorType.appleEvent.rawValue) + data.long(0x0001_0001) + for item in listed { + data.long(item.keyword.rawValue) + try data.append(item.descriptor, depth: 0) + } + data.long(ClassicData.endOfAttributes) + data.replaceLong(UInt32(data.bytes.count), at: 8) + try data.append(items, keyed: true, depth: 0) + return data.bytes + } +} + +/// A data handle's bytes, written or read in order. +private struct ClassicData { + + static let listHeader = 24 + static let eventClassOffset = 50 + /// ';;;;' + static let endOfAttributes: UInt32 = 0x3B3B_3B3B + private static let maximumDepth = 32 + + var bytes: [UInt8] = [] + var position = 0 + + // MARK: Writing + + mutating func long(_ value: UInt32) { + withUnsafeBytes(of: value.bigEndian) { bytes += $0 } + } + + mutating func replaceLong(_ value: UInt32, at offset: Int) { + withUnsafeBytes(of: value.bigEndian) { bytes.replaceSubrange(offset ..< offset + 4, with: $0) } + } + + /// A size and that much data, padded to an even length. + mutating func value(_ data: [UInt8]) { + long(UInt32(data.count)) + bytes += data + if data.count & 1 != 0 { bytes.append(0) } + } + + /// A descriptor's type, size and data. A list or record inside another is + /// its count, a zero and its items. + mutating func append(_ descriptor: Descriptor, depth: Int) throws(MacError) { + if descriptor.isAppleEvent { throw .wrongDataType } + long(descriptor.type.rawValue) + guard descriptor.isList || descriptor.isKeyed else { + value(descriptor.bytes) + return + } + guard depth < Self.maximumDepth else { throw MacError(-108) } + var inner = ClassicData() + inner.long(UInt32(descriptor.items.count)) + inner.long(0) + try inner.append(descriptor.items, keyed: !descriptor.isList, depth: depth + 1) + value(inner.bytes) + } + + mutating func append(_ items: [Descriptor.Item], keyed: Bool, depth: Int) throws(MacError) { + for item in items { + if keyed { long(item.keyword.rawValue) } + try append(item.descriptor, depth: depth) + } + } + + // MARK: Reading + + mutating func long() throws(MacError) -> UInt32 { + guard position >= 0, position <= bytes.count - 4 else { throw .corruptData } + defer { position += 4 } + return bytes[position ..< position + 4].reduce(0) { $0 << 8 | UInt32($1) } + } + + mutating func code() throws(MacError) -> FourCharCode { FourCharCode(rawValue: try long()) } + + mutating func value() throws(MacError) -> [UInt8] { + let size = Int(try long()) + guard size <= bytes.count - position else { throw .corruptData } + defer { position += size + (size & 1) } + return Array(bytes[position ..< position + size]) + } + + mutating func descriptor(depth: Int) throws(MacError) -> Descriptor { + let type = try code() + let data = try value() + guard type == DescriptorType.list || type == DescriptorType.record else { + return Descriptor(type: type, bytes: data) + } + guard depth < Self.maximumDepth else { throw MacError(-108) } + var inner = ClassicData(bytes: data) + let count = try inner.long() + _ = try inner.long() + let keyed = type == DescriptorType.record + return Descriptor(type: type, items: try inner.items(count, keyed: keyed, depth: depth + 1), isKeyed: keyed) + } + + mutating func items(_ count: UInt32, keyed: Bool, depth: Int) throws(MacError) -> [Descriptor.Item] { + // Each item takes at least its type and size. + guard count <= bytes.count / 8 else { throw .corruptData } + var items: [Descriptor.Item] = [] + for _ in 0 ..< count { + let keyword = keyed ? try code() : FourCharCode(0) + items.append(Descriptor.Item(keyword: keyword, descriptor: try descriptor(depth: depth))) + } + return items + } + + /// An event, its numbers big-endian. + mutating func event() throws(MacError) -> Descriptor { + position = 8 + let parameters = try long() + let attributeCount = try long() + let parameterCount = try long() + position = Self.eventClassOffset + func big(_ value: UInt32) -> [UInt8] { withUnsafeBytes(of: value.bigEndian) { Array($0) } } + var attributes = [ + Descriptor.Item(keyword: AppleEvent.Attribute.eventClass, + descriptor: Descriptor(type: DescriptorType.type, bytes: big(try long()))), + Descriptor.Item(keyword: AppleEvent.Attribute.eventID, + descriptor: Descriptor(type: DescriptorType.type, bytes: big(try long()))), + ] + let returnID = try long() + let target = try code() + let address = try value() + if !address.isEmpty { + attributes.append(Descriptor.Item(keyword: AppleEvent.Attribute.address, + descriptor: Descriptor(type: target, bytes: address))) + } + attributes.append(Descriptor.Item(keyword: AppleEvent.Attribute.returnID, + descriptor: Descriptor(type: DescriptorType.sInt16, + bytes: Array(big(returnID).suffix(2))))) + guard try code() == DescriptorType.appleEvent else { throw .corruptData } + _ = try long() + let listed = try items(attributeCount, keyed: true, depth: 0) + guard try long() == Self.endOfAttributes else { throw .corruptData } + if !listed.contains(where: { $0.keyword == AppleEvent.Attribute.transactionID }) { + attributes.append(Descriptor.Item(keyword: AppleEvent.Attribute.transactionID, + descriptor: Descriptor(type: DescriptorType.sInt32, bytes: big(0)))) + } + attributes += listed + position = Int(parameters) + return Descriptor(type: DescriptorType.appleEvent, items: try items(parameterCount, keyed: true, depth: 0), + attributes: attributes, isKeyed: true) + } +} diff --git a/Tests/GraphiteAutomationTests/DescriptorClassicDataTests.swift b/Tests/GraphiteAutomationTests/DescriptorClassicDataTests.swift new file mode 100644 index 0000000..72f0517 --- /dev/null +++ b/Tests/GraphiteAutomationTests/DescriptorClassicDataTests.swift @@ -0,0 +1,128 @@ +import Testing +import Foundation +import GraphiteCore +import GraphiteAutomation + +/// The data handles of lists, records and events, compared byte for byte with +/// what Mac OS 9.2.2 held (ReferenceTests/Retro68, AEDescLayoutCapture.c). +@Suite struct DescriptorClassicDataTests { + + private static let capture: [String] = { + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + let data = try! Data(contentsOf: root.appendingPathComponent("ReferenceTests/Retro68/AEDescLayout-macos-9.2.2-ppc.txt")) + return String(decoding: data, as: UTF8.self).split(separator: "\r").map(String.init) + }() + + /// The bytes dumped under a label, with what Mac OS left over cleared: the + /// long at offset 4, and the byte that pads the 3 bytes of "hel", which is + /// the one that followed them in the probe's memory. + private func captured(_ label: String, sourceLocation: SourceLocation = #_sourceLocation) -> [UInt8] { + guard let start = Self.capture.firstIndex(where: { $0.hasPrefix(label + ": type ") }) else { + Issue.record("no capture for \(label)", sourceLocation: sourceLocation) + return [] + } + var hex = "" + for line in Self.capture[(start + 1)...] { + guard line.allSatisfy({ $0 == " " || $0.isHexDigit }) else { break } + hex += line.filter { $0 != " " } + } + var bytes = stride(from: 0, to: hex.count, by: 2).map { offset in + UInt8(hex.dropFirst(offset).prefix(2), radix: 16)! + } + bytes.replaceSubrange(4 ..< 8, with: [0, 0, 0, 0]) + let odd: [UInt8] = [0, 0, 0, 3] + Array("hell".utf8) + for start in bytes.indices.dropLast(odd.count - 1) where Array(bytes[start ..< start + odd.count]) == odd { + bytes[start + odd.count - 1] = 0 + } + return bytes + } + + private func check(_ label: String, _ descriptor: Descriptor, sourceLocation: SourceLocation = #_sourceLocation) throws { + let expected = captured(label, sourceLocation: sourceLocation) + #expect(try descriptor.classicData() == expected, "\(label)", sourceLocation: sourceLocation) + // And the same bytes read back make a descriptor that writes them again. + let read = try Descriptor(type: descriptor.type, classicData: expected) + #expect(try read.classicData() == expected, "\(label) read back", sourceLocation: sourceLocation) + } + + private func long(_ value: Int32) -> Descriptor { + Descriptor(type: "long", integer: value.bigEndian) + } + + private func text(_ value: String) -> Descriptor { Descriptor(type: "TEXT", bytes: Array(value.utf8)) } + + @Test func listsAsMacOSKeepsThem() throws { + var list = Descriptor.list() + try check("list empty", list) + try list.put(long(0x11223344), at: 0) + try check("list long", list) + try list.put(text("hello"), at: 0) + try check("list long TEXT", list) + try list.put(text(""), at: 0) + try check("list long TEXT empty", list) + try list.put(.null, at: 0) + try check("list long TEXT empty null", list) + try list.removeItem(at: 2) + try check("list after deleting item 2", list) + } + + @Test func recordsAndNestingAsMacOSKeepsThem() throws { + var list = Descriptor.list([long(0x11223344), text(""), .null]) + var record = Descriptor.record() + try check("record empty", record) + try record.putParameter("k001", long(1)) + try check("record k001", record) + try record.putParameter("k002", text("hel")) + try check("record k001 k002", record) + try record.putParameter("k001", long(2)) + try check("record k001 replaced", record) + try record.putParameter("list", list) + try check("record with a list", record) + let inner = Descriptor.record([("k007", long(7))]) + try record.putParameter("reco", inner) + try check("record with a list and a record", record) + try list.put(inner, at: 0) + try check("list with a record", list) + } + + @Test func eventsAsMacOSKeepsThem() throws { + let target = Descriptor(type: "psn ", bytes: [0, 0, 0, 0, 0, 0, 0, 2]) + var event = AppleEvent(eventClass: "core", eventID: "crel", target: target, returnID: 0x1234, + transactionID: 0x55667788).descriptor.toBigEndian() + // The target's bytes are the program's own already, so they are not swapped. + event.setAttribute("addr", target) + try check("event empty", event) + try event.putParameter("key1", long(11)) + try check("event key1", event) + try event.putParameter("key2", text("hello")) + try check("event key1 key2", event) + let keyword = { (code: String) in Descriptor(type: "keyw", bytes: Array(code.utf8)) } + event.setAttribute("optk", Descriptor.list([keyword("key1"), keyword("key2")])) + try check("event with optk", event) + event.setAttribute("zzzz", long(99)) + try check("event with another attribute", event) + try event.deleteParameter("key1") + try check("event without key1", event) + + let read = try Descriptor(type: "aevt", classicData: captured("event without key1")) + #expect(read.attribute("evcl")?.bytes == Array("core".utf8)) + #expect(read.attribute("rtid")?.bytes == [0x12, 0x34]) + #expect(read.attribute("tran")?.bytes == [0x55, 0x66, 0x77, 0x88]) + #expect(read.attribute("optk")?.items.count == 2) + #expect(read["key2"]?.bytes == Array("hello".utf8)) + } + + /// A program may put anything in a handle. + @Test func dataThatDoesNotHoldWhatItSaysIsCorrupt() throws { + let list = try Descriptor.list([long(1)]).classicData() + for count in [0, 16, list.count - 2] { + #expect(throws: MacError(-1702)) { try Descriptor(type: "list", classicData: Array(list.prefix(count))) } + } + var tooMany = list + tooMany[19] = 200 + #expect(throws: MacError(-1702)) { try Descriptor(type: "list", classicData: tooMany) } + #expect(throws: MacError(-1702)) { try Descriptor(type: "aevt", classicData: list) } + #expect(throws: MacError(-1704)) { try long(1).classicData() } + } +}