From ee6a72e96add36bdc3ac5bff7eeebdc7ce97bd27 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 02:19:12 -0500 Subject: [PATCH 01/10] Add a probe of window and menu tracking --- ReferenceTests/Retro68/TrackingCapture.c | 227 +++++++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 ReferenceTests/Retro68/TrackingCapture.c diff --git a/ReferenceTests/Retro68/TrackingCapture.c b/ReferenceTests/Retro68/TrackingCapture.c new file mode 100644 index 0000000..e37b90a --- /dev/null +++ b/ReferenceTests/Retro68/TrackingCapture.c @@ -0,0 +1,227 @@ +/* + * Captures what TrackGoAway, DragWindow and MenuSelect do with a press and + * release of the mouse, writing "Tracking.txt" next to itself. It refuses to + * run if that file is already there. The file is flushed after every line. + * + * It needs a person (or a driver) at the mouse. The front window's title says + * what to do next; every press is recorded with where it was released, so the + * pointer need not be placed exactly. A key press ends the probe early. + * + * 1 press the close box, release inside it + * 2 press the close box, release well outside it + * 3 drag the title bar a short way, staying inside the limit + * 4 drag the title bar far below and right of the limit + * 5 drag the title bar to just past the limit's right edge + * 6 click the title bar without moving + * 7 drag the other (rear) window's title bar a short way + * 8 press File, release on New + * 9 press File, release on the dimmed Close + * 10 press File, release outside every menu + * 11 press Edit, release on Copy + * 12 click File without dragging, then click elsewhere + * + * The drag limit is (60,60,400,500), as top, left, bottom, right. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +enum { kSteps = 12 }; + +static short out; +static WindowPtr window, rear; +static MenuHandle fileMenu, editMenu; + +static void line(const char *text) +{ + long count = strlen(text); + FSWrite(out, &count, text); + count = 1; + FSWrite(out, &count, "\r"); + FlushVol(0, 0); +} + +static const char *which(const void *p) +{ + if (!p) return "nil"; + if (p == (const void *)window) return "window"; + if (p == (const void *)rear) return "rear"; + return "another"; +} + +static Point mouse(void) +{ + Point p; + GrafPtr saved, screen; + GetPort(&saved); + GetWMgrPort(&screen); + SetPort(screen); + GetMouse(&p); + LocalToGlobal(&p); + SetPort(saved); + return p; +} + +static void place(char *text, const char *name, WindowPtr w) +{ + Rect r = (**((WindowPeek)w)->contRgn).rgnBBox; + sprintf(text + strlen(text), " %s content (%d,%d,%d,%d) visible %d hilited %d", name, + r.top, r.left, r.bottom, r.right, (int)(unsigned char)((WindowPeek)w)->visible, + (int)(unsigned char)((WindowPeek)w)->hilited); +} + +static void state(const char *label) +{ + char text[400]; + sprintf(text, "%s ->", label); + place(text, "window", window); + place(text, "rear", rear); + sprintf(text + strlen(text), " front %s", which(FrontWindow())); + line(text); +} + +static void reset(int step) +{ + static const char *names[] = { + "1 close box, release inside", "2 close box, release outside", "3 drag a little", + "4 drag far down right", "5 drag just past right limit", "6 click title", "7 drag rear window", + "8 File > New", "9 File > Close (dimmed)", "10 File, release outside", "11 Edit > Copy", + "12 click File, click away" + }; + Str255 title; + size_t n; + EventRecord ignored; + + ShowWindow(window); + MoveWindow(window, 200, 150, false); + MoveWindow(rear, 120, 300, false); + SelectWindow(window); + n = strlen(names[step]); + title[0] = (unsigned char)n; + memcpy(title + 1, names[step], n); + SetWTitle(window, title); + while (GetNextEvent(updateMask | activMask, &ignored)) + if (ignored.what == updateEvt) { + BeginUpdate((WindowPtr)ignored.message); + EndUpdate((WindowPtr)ignored.message); + } + FlushEvents(everyEvent, 0); +} + +static void layout(void) +{ + /* The menu list: the last entry's offset, the bar's right edge and the + definition, then each menu's handle and left edge. */ + Handle list = *(Handle *)0x0A1C; + char text[300]; + short last = *(short *)*list, offset; + EventRecord ignored; + + sprintf(text, "screen (%d,%d,%d,%d) menuBarHeight %d lastRight %d", qd.screenBits.bounds.top, + qd.screenBits.bounds.left, qd.screenBits.bounds.bottom, qd.screenBits.bounds.right, + (int)GetMBarHeight(), (int)*(short *)(*list + 2)); + line(text); + for (offset = 6; offset <= last; offset += 6) { + MenuHandle m = *(MenuHandle *)(*list + offset); + short left = *(short *)(*list + offset + 4); + CalcMenuSize(m); + sprintf(text, "menu %d left %d width %d height %d items %d", (**m).menuID, left, (**m).menuWidth, + (**m).menuHeight, (int)CountMItems(m)); + line(text); + } + (void)ignored; +} + +int main(void) +{ + static const unsigned char name[] = { 12, 'T','r','a','c','k','i','n','g','.','t','x','t' }; + Rect front = { 150, 200, 270, 440 }, back = { 300, 120, 400, 360 }, limit = { 60, 60, 400, 500 }; + EventRecord event; + char text[400]; + int step = 0; + + if (Create(name, 0, 'Grph', 'TEXT') != noErr) return 1; + if (FSOpen(name, 0, &out) != noErr) return 2; + + InitGraf(&qd.thePort); + InitFonts(); + InitWindows(); + InitMenus(); + TEInit(); + InitDialogs(0); + InitCursor(); + + fileMenu = NewMenu(129, "\pFile"); + AppendMenu(fileMenu, "\pNew/N;Open\311;(-;(Close;Quit/Q"); + InsertMenu(fileMenu, 0); + editMenu = NewMenu(130, "\pEdit"); + AppendMenu(editMenu, "\pCut;Copy"); + InsertMenu(editMenu, 0); + DrawMenuBar(); + + rear = NewWindow(0, &back, "\prear", true, noGrowDocProc, (WindowPtr)-1L, true, 0); + window = NewWindow(0, &front, "\pwindow", true, noGrowDocProc, (WindowPtr)-1L, true, 0); + + line("# Layout"); + layout(); + reset(0); + + while (step < kSteps) { + WindowPtr hit = 0; + short part; + Point end; + + if (!WaitNextEvent(everyEvent, &event, 10, 0)) continue; + if (event.what == keyDown) break; + if (event.what == updateEvt) { + BeginUpdate((WindowPtr)event.message); + EndUpdate((WindowPtr)event.message); + } + if (event.what != mouseDown) continue; + + part = FindWindow(event.where, &hit); + sprintf(text, "# step %d: press (%d,%d) FindWindow %d %s", step + 1, event.where.v, event.where.h, + part, which(hit)); + line(text); + /* A press somewhere the step doesn't ask for is not counted. */ + if (step < 2 ? part != inGoAway : step < 7 ? part != inDrag : part != inMenuBar) continue; + + state("before"); + if (part == inGoAway) { + Boolean result = TrackGoAway(hit, event.where); + end = mouse(); + sprintf(text, "TrackGoAway -> %d released (%d,%d)", (int)(result != 0), end.v, end.h); + } else if (part == inDrag) { + DragWindow(hit, event.where, &limit); + end = mouse(); + sprintf(text, "DragWindow %s released (%d,%d)", which(hit), end.v, end.h); + } else { + long choice = MenuSelect(event.where); + end = mouse(); + sprintf(text, "MenuSelect -> menu %d item %d released (%d,%d) TheMenu %d", + (int)(short)(choice >> 16), (int)(short)choice, end.v, end.h, (int)*(short *)0x0A26); + line(text); + sprintf(text, "MenuChoice -> %ld,%ld", MenuChoice() >> 16, MenuChoice() & 0xFFFF); + HiliteMenu(0); + } + line(text); + sprintf(text, "mouseUp left in queue %d", (int)(EventAvail(mUpMask, &event) != 0)); + line(text); + state("after"); + + if (++step < kSteps) reset(step); + } + + line("done"); + FSClose(out); + FlushVol(0, 0); + return 0; +} From 9331bfcb940519c5e7efa2b355ec82950f400111 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 02:19:12 -0500 Subject: [PATCH 02/10] Build the tracking probe --- ReferenceTests/Retro68/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/ReferenceTests/Retro68/CMakeLists.txt b/ReferenceTests/Retro68/CMakeLists.txt index f0a4966..adc24da 100644 --- a/ReferenceTests/Retro68/CMakeLists.txt +++ b/ReferenceTests/Retro68/CMakeLists.txt @@ -24,3 +24,4 @@ add_application(PolygonCapture PolygonCapture.c) add_application(CopyBitsCapture CopyBitsCapture.c) add_application(TextCapture TextCapture.c TextCapture.r) add_application(GWorldCapture GWorldCapture.c) +add_application(TrackingCapture TrackingCapture.c) From d27f8dbc8f493a16ea0c5029eac47843b6cacba4 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 02:19:12 -0500 Subject: [PATCH 03/10] Capture window and menu tracking on Mac OS 9.2.2 --- ReferenceTests/Retro68/Tracking-macos-9.2.2-ppc.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 ReferenceTests/Retro68/Tracking-macos-9.2.2-ppc.txt diff --git a/ReferenceTests/Retro68/Tracking-macos-9.2.2-ppc.txt b/ReferenceTests/Retro68/Tracking-macos-9.2.2-ppc.txt new file mode 100644 index 0000000..78a7189 --- /dev/null +++ b/ReferenceTests/Retro68/Tracking-macos-9.2.2-ppc.txt @@ -0,0 +1 @@ +# Layout screen (0,0,480,640) menuBarHeight 20 lastRight 82 menu 129 left 10 width 95 height 70 items 5 menu 130 left 45 width 61 height 32 items 2 # step 1: press (138,203) FindWindow 6 window before -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window TrackGoAway -> 1 released (138,203) mouseUp left in queue 0 after -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window # step 2: press (138,203) FindWindow 6 window before -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window TrackGoAway -> 0 released (329,468) mouseUp left in queue 0 after -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window # step 3: press (136,240) FindWindow 4 window before -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window DragWindow window released (166,279) mouseUp left in queue 0 after -> window content (180,239,300,479) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window # step 4: press (136,240) FindWindow 4 window before -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window DragWindow window released (458,621) mouseUp left in queue 0 after -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window # step 5: press (136,240) FindWindow 4 window before -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window DragWindow window released (136,514) mouseUp left in queue 0 after -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window # step 6: press (136,240) FindWindow 4 window before -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window DragWindow window released (136,240) mouseUp left in queue 0 after -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window # step 7: press (287,170) FindWindow 4 rear before -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window DragWindow rear released (309,200) mouseUp left in queue 0 after -> window content (150,200,270,440) visible 1 hilited 0 rear content (322,150,422,390) visible 1 hilited 1 front rear # step 8: press (9,24) FindWindow 1 nil before -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window MenuSelect -> menu 129 item 1 released (27,50) TheMenu 129 MenuChoice -> 129,1 mouseUp left in queue 0 after -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window # step 9: press (9,24) FindWindow 1 nil before -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window MenuSelect -> menu 0 item 0 released (65,50) TheMenu 0 MenuChoice -> 129,4 mouseUp left in queue 0 after -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window # step 10: press (9,24) FindWindow 1 nil before -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window MenuSelect -> menu 0 item 0 released (351,389) TheMenu 0 MenuChoice -> 129,0 mouseUp left in queue 0 after -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window # step 11: press (9,61) FindWindow 1 nil before -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window MenuSelect -> menu 130 item 2 released (44,77) TheMenu 130 MenuChoice -> 130,2 mouseUp left in queue 0 after -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window # step 12: press (9,24) FindWindow 1 nil before -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window MenuSelect -> menu 0 item 0 released (229,334) TheMenu 0 MenuChoice -> 129,0 mouseUp left in queue 0 after -> window content (150,200,270,440) visible 1 hilited 1 rear content (300,120,400,360) visible 1 hilited 0 front window done \ No newline at end of file From 714c887e2c48207a1681af27c4ec166204b9b6d4 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 02:19:12 -0500 Subject: [PATCH 04/10] Make menu separators 6 pixels tall --- Sources/GraphiteMenus/MenuDefinition.swift | 32 +++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/Sources/GraphiteMenus/MenuDefinition.swift b/Sources/GraphiteMenus/MenuDefinition.swift index ab08ad9..cd037e7 100644 --- a/Sources/GraphiteMenus/MenuDefinition.swift +++ b/Sources/GraphiteMenus/MenuDefinition.swift @@ -33,10 +33,37 @@ public protocol MenuDefinition: Sendable { /// mChooseMsg: the item a point of the menu is on, nil for none. func hitTest(_ point: Point, in bounds: Rect, itemCount: Int) -> Int? + + /// How tall an item is; a definition's items are all `itemHeight` unless + /// it says otherwise. + func height(of item: MenuItem) -> Int16 +} + +extension MenuDefinition { + + public func height(of item: MenuItem) -> Int16 { itemHeight } + + /// mSizeMsg's height for a menu's own items. + public func menuHeight(of items: [MenuItem]) -> Int16 { + Int16(clamping: items.reduce(0) { $0 + Int(height(of: $1)) }) + } + + /// The rectangle one of a menu's items occupies in its bounds. + public func itemRect(at index: Int, in bounds: Rect, items: [MenuItem]) -> Rect { + let top = bounds.top &+ menuHeight(of: Array(items.prefix(index))) + let height = items.indices.contains(index) ? height(of: items[index]) : itemHeight + return Rect(top: top, left: bounds.left, bottom: top &+ height, right: bounds.right) + } + + /// mChooseMsg: which of a menu's items a point is on, nil for none. + public func hitTest(_ point: Point, in bounds: Rect, items: [MenuItem]) -> Int? { + guard bounds.contains(point) else { return nil } + return items.indices.first { itemRect(at: $0, in: bounds, items: items).contains(point) } + } } /// The standard menu definition, the classic's look: a bar 20 pixels tall, -/// items 16, and a column each for the icon, the mark and the key +/// items 16, separators 6, and a column each for the icon, the mark and the key /// equivalent that the menu's items use, two pixels of margin around. public struct StandardMenuDefinition: MenuDefinition { @@ -52,6 +79,9 @@ public struct StandardMenuDefinition: MenuDefinition { public var itemHeight: Int16 { 16 } + /// A separator is shorter, as Mac OS 9.2.2 measured a menu with one. + public func height(of item: MenuItem) -> Int16 { item.isSeparator ? 6 : itemHeight } + public func menuHeight(itemCount: Int) -> Int16 { Int16(clamping: itemCount) * itemHeight } From b5ae2c8ab162f885f6a81c46e2d8ca8ae9656249 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 02:19:12 -0500 Subject: [PATCH 05/10] Track a window's boxes and drags --- Sources/GraphiteWindows/WindowTracking.swift | 53 ++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Sources/GraphiteWindows/WindowTracking.swift diff --git a/Sources/GraphiteWindows/WindowTracking.swift b/Sources/GraphiteWindows/WindowTracking.swift new file mode 100644 index 0000000..543c2aa --- /dev/null +++ b/Sources/GraphiteWindows/WindowTracking.swift @@ -0,0 +1,53 @@ +// Mouse tracking in a window's frame: TrackGoAway, TrackBox and DragWindow. +// The classic calls looped while the button was down; here the host has the +// loop. It gives the tracker each mouse position, and the one the button was +// released at, in global coordinates. Compared with Mac OS 9.2.2 in +// ReferenceTests/Retro68 (TrackingCapture.c). + +import GraphiteCore + +extension Window { + + /// TrackGoAway and TrackBox: whether the pointer is on a box of the + /// frame, so that the box draws pressed, and, where the button is + /// released, whether that chooses it. + public func isTracking(_ box: WindowRegion, at point: Point) -> Bool { + region(box).contains(point) + } +} + +/// DragWindow: a window following the pointer from where its title bar was +/// pressed, within a limit. +public struct WindowDrag { + + public let window: Window + + /// Where the button was pressed. + public let start: Point + + /// DragWindow's boundsRect: where the pointer has to be released for the + /// window to move. + public let limit: Rect + + public init(window: Window, start: Point, limit: Rect) { + self.window = window + self.start = start + self.limit = limit + } + + /// How far the outline is from the window with the pointer at a point; + /// nil outside the limit, where there is no outline. + public func offset(at point: Point) -> Point? { + limit.contains(point) ? point - start : nil + } + + /// The button's release: inside the limit the window moves as far as the + /// pointer did, outside it stays. With `select`, which DragWindow does + /// without the Command key, the window is selected too. + public func end(at point: Point, select: Bool = true) { + if select { window.select() } + guard let offset = offset(at: point), offset != .zero else { return } + let structure = window.structureBounds + window.moveStructure(h: structure.left &+ offset.h, v: structure.top &+ offset.v) + } +} From 5dab7d0a98e31693c2383e4ba99d83f20e8e5f64 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 02:19:13 -0500 Subject: [PATCH 06/10] Test window tracking against the capture --- .../WindowTrackingTests.swift | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Tests/GraphiteWindowsTests/WindowTrackingTests.swift diff --git a/Tests/GraphiteWindowsTests/WindowTrackingTests.swift b/Tests/GraphiteWindowsTests/WindowTrackingTests.swift new file mode 100644 index 0000000..aed7119 --- /dev/null +++ b/Tests/GraphiteWindowsTests/WindowTrackingTests.swift @@ -0,0 +1,92 @@ +import Testing +import Foundation +import GraphiteCore +import Graphite2D +import GraphiteWindows + +/// TrackGoAway and DragWindow against what Mac OS 9.2.2 did with the same +/// presses and releases (ReferenceTests/Retro68, TrackingCapture.c). +@Suite struct WindowTrackingTests { + + private struct Step { + var press: Point + var release: Point + var result: String + var after: String + } + + /// The window steps of the capture, 1 to 7. + private static let steps: [Step] = { + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + let data = try! Data(contentsOf: root.appendingPathComponent("ReferenceTests/Retro68/Tracking-macos-9.2.2-ppc.txt")) + let lines = String(decoding: data, as: UTF8.self).split(separator: "\r").map(String.init) + func point(_ text: String, after key: String) -> Point { + let rest = text[text.range(of: key + " (")!.upperBound...] + let n = rest.prefix { $0 != ")" }.split(separator: ",").map { Int16($0)! } + return Point(v: n[0], h: n[1]) + } + return lines.indices.filter { lines[$0].hasPrefix("# step ") }.prefix(7).map { + Step(press: point(lines[$0], after: "press"), release: point(lines[$0 + 2], after: "released"), + result: lines[$0 + 2], after: lines[$0 + 4]) + } + }() + + private static func content(_ text: String, _ name: String) -> Rect { + let rest = text[text.range(of: " \(name) content (")!.upperBound...] + let n = rest.prefix { $0 != ")" }.split(separator: ",").map { Int16($0)! } + return Rect(top: n[0], left: n[1], bottom: n[2], right: n[3]) + } + + private struct Desktop { + let manager: WindowManager + let window: Window + let rear: Window + } + + /// The probe's two windows: the rear one made first. + private func desktop() throws -> Desktop { + let manager = WindowManager(quickDraw: QuickDraw(screens: [GraphicsDevice.screen(width: 640, height: 480)])) + let definition = try #require(ClassicWindowDefinition(procID: 4)) + let kind = definition.kind(goAway: true) + func make(_ bounds: Rect) throws -> Window { + let window = try manager.newWindow(windowClass: kind.windowClass, attributes: kind.attributes, + bounds: bounds, definition: definition) + window.show() + return window + } + let rear = try make(Rect(top: 300, left: 120, bottom: 400, right: 360)) + let window = try make(Rect(top: 150, left: 200, bottom: 270, right: 440)) + window.select() + return Desktop(manager: manager, window: window, rear: rear) + } + + @Test func closeBoxIsChosenOnlyWhenReleasedOnIt() throws { + for step in Self.steps[0 ... 1] { + let desktop = try desktop() + #expect(desktop.window.isTracking(.closeBox, at: step.press)) + let chosen = step.result.contains("TrackGoAway -> 1 ") + #expect(desktop.window.isTracking(.closeBox, at: step.release) == chosen, "\(step.result)") + } + } + + @Test func dragsAsTheCaptureDid() throws { + let limit = Rect(top: 60, left: 60, bottom: 400, right: 500) + for step in Self.steps[2 ... 6] { + let desktop = try desktop() + let dragged = step.result.contains("DragWindow rear ") ? desktop.rear : desktop.window + WindowDrag(window: dragged, start: step.press, limit: limit).end(at: step.release) + #expect(desktop.window.contentBounds == Self.content(step.after, "window"), "\(step.result)") + #expect(desktop.rear.contentBounds == Self.content(step.after, "rear"), "\(step.result)") + #expect(desktop.manager.frontWindow === (step.after.hasSuffix("front rear") ? desktop.rear : desktop.window)) + } + } + + @Test func noOutlineOutsideTheLimit() throws { + let desktop = try desktop() + let drag = WindowDrag(window: desktop.window, start: Point(v: 136, h: 240), + limit: Rect(top: 60, left: 60, bottom: 400, right: 500)) + #expect(drag.offset(at: Point(v: 166, h: 279)) == Point(v: 30, h: 39)) + #expect(drag.offset(at: Point(v: 136, h: 514)) == nil) + } +} From 58a51c37f3bf9d5a19740fe516f87f72087b7c42 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 02:19:13 -0500 Subject: [PATCH 07/10] Track a menu choice --- Sources/GraphiteMenus/MenuTracking.swift | 95 ++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Sources/GraphiteMenus/MenuTracking.swift diff --git a/Sources/GraphiteMenus/MenuTracking.swift b/Sources/GraphiteMenus/MenuTracking.swift new file mode 100644 index 0000000..3af1b5d --- /dev/null +++ b/Sources/GraphiteMenus/MenuTracking.swift @@ -0,0 +1,95 @@ +// MenuSelect's tracking: which menu is open, which item the pointer is on, +// and what the release chooses. The classic call looped while the button was +// down; here the host has the loop, and gives the tracker the mouse. The host +// also lays out the bar and the menus, so it says where they are. Compared +// with Mac OS 9.2.2 in ReferenceTests/Retro68 (TrackingCapture.c). +// Submenus aren't tracked. + +import GraphiteCore + +public struct MenuTracker { + + public let menuBar: MenuBar + + /// Where each menu's title is in the bar, by menu ID. + private let titles: [Int16: Rect] + + /// Where a menu is when it is open. + private let bounds: (Menu) -> Rect + + /// The menu that is open. + public private(set) var openMenu: Menu? + + /// The item the pointer is on and a release would choose, from 0. + public private(set) var hilitedItem: Int? + + /// MenuChoice: the last open menu, and the number from 1 of the item the + /// pointer was last on, enabled or not; 0 off every item. + public private(set) var menuChoice = MenuSelection.none + + /// Whether the pointer has left the title since the menu opened: until + /// then a release leaves the menu open. + private var hasLeftTitle = false + + public init(menuBar: MenuBar, titles: [Int16: Rect], bounds: @escaping (Menu) -> Rect) { + self.menuBar = menuBar + self.titles = titles + self.bounds = bounds + } + + /// The button went down, to open a menu or, with one left open, to choose + /// from it. Returns the answer if that ends the tracking. + public mutating func mouseDown(at point: Point) -> MenuSelection? { + move(to: point) + // A press away from an open menu and the titles closes it. + if openMenu != nil, title(at: point) == nil, !isInOpenMenu(point) { + return end(MenuSelection.none) + } + return nil + } + + /// The pointer moved. + public mutating func move(to point: Point) { + if let menu = title(at: point), menu !== openMenu { + openMenu = menu + hasLeftTitle = false + menuBar.hilite(menuID: menu.menuID) + } + hilitedItem = nil + guard let menu = openMenu else { return } + if title(at: point) !== menu { hasLeftTitle = true } + let index = menu.definition.hitTest(point, in: bounds(menu), items: menu.items) + menuChoice = MenuSelection(menuID: menu.menuID, itemIndex: index.map { Int16($0 + 1) } ?? 0) + if let index, menu.isEnabled, menu.items[index].isEnabled, !menu.items[index].isSeparator { + hilitedItem = index + } + } + + /// The button was released. Returns MenuSelect's answer, or nil when the + /// menu stays open: the release of a click on its title. + public mutating func mouseUp(at point: Point) -> MenuSelection? { + move(to: point) + if let menu = openMenu, !hasLeftTitle, title(at: point) === menu { return nil } + if let menu = openMenu, let item = hilitedItem { + return end(MenuSelection(menuID: menu.menuID, itemIndex: Int16(item + 1))) + } + return end(MenuSelection.none) + } + + /// The menu closes. A choice leaves its title hilited, for HiliteMenu(0) + /// to undo. + private mutating func end(_ selection: MenuSelection) -> MenuSelection { + if selection.isNone { menuBar.hilite(menuID: 0) } + openMenu = nil + hilitedItem = nil + return selection + } + + private func title(at point: Point) -> Menu? { + titles.first { $0.value.contains(point) }.flatMap { menuBar.menu(id: $0.key) } + } + + private func isInOpenMenu(_ point: Point) -> Bool { + openMenu.map { bounds($0).contains(point) } ?? false + } +} From 7928a9d1b625906c7d5df2acd92be1dab6f32db1 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 02:19:13 -0500 Subject: [PATCH 08/10] Test menu tracking against the capture --- .../MenuTrackingTests.swift | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Tests/GraphiteMenusTests/MenuTrackingTests.swift diff --git a/Tests/GraphiteMenusTests/MenuTrackingTests.swift b/Tests/GraphiteMenusTests/MenuTrackingTests.swift new file mode 100644 index 0000000..42cf3c2 --- /dev/null +++ b/Tests/GraphiteMenusTests/MenuTrackingTests.swift @@ -0,0 +1,98 @@ +import Testing +import Foundation +import GraphiteCore +import GraphiteMenus + +/// MenuSelect's answers and MenuChoice against what Mac OS 9.2.2 gave for the +/// same presses and releases (ReferenceTests/Retro68, TrackingCapture.c). +@Suite struct MenuTrackingTests { + + private static let capture: [String] = { + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + let data = try! Data(contentsOf: root.appendingPathComponent("ReferenceTests/Retro68/Tracking-macos-9.2.2-ppc.txt")) + return String(decoding: data, as: UTF8.self).split(separator: "\r").map(String.init) + }() + + private func numbers(_ text: String) -> [Int16] { + text.split { !$0.isNumber }.map { Int16($0)! } + } + + /// The probe's two menus, where Mac OS put their titles and the menus. + private func menus() -> (bar: MenuBar, file: Menu, edit: Menu) { + let file = Menu(menuID: 129, title: "File") + file.append(classic: "New/N;Open…;(-;(Close;Quit/Q") + let edit = Menu(menuID: 130, title: "Edit") + edit.append(classic: "Cut;Copy") + let bar = MenuBar() + bar.insert(file, beforeID: 0) + bar.insert(edit, beforeID: 0) + return (bar, file, edit) + } + + private func layout(_ id: Int16) -> (left: Int16, width: Int16, height: Int16) { + let n = numbers(Self.capture.first { $0.hasPrefix("menu \(id) ") }!) + return (n[1], n[2], n[3]) + } + + private func tracker(_ bar: MenuBar) -> MenuTracker { + let right = numbers(Self.capture.first { $0.hasPrefix("screen ") }!).last! + let titles: [Int16: Rect] = [ + 129: Rect(top: 0, left: layout(129).left, bottom: 20, right: layout(130).left), + 130: Rect(top: 0, left: layout(130).left, bottom: 20, right: right), + ] + return MenuTracker(menuBar: bar, titles: titles) { menu in + let layout = layout(menu.menuID) + return Rect(top: 20, left: layout.left, bottom: 20 + menu.definition.menuHeight(of: menu.items), + right: layout.left + layout.width) + } + } + + @Test func menusAreAsTallAsMacOSMadeThem() { + let (_, file, edit) = menus() + #expect(file.definition.menuHeight(of: file.items) == layout(129).height) + #expect(edit.definition.menuHeight(of: edit.items) == layout(130).height) + } + + @Test func choosesAsTheCaptureDid() { + let lines = Self.capture + // Steps 8 to 11 are drags from a title. + let starts = lines.indices.filter { lines[$0].hasPrefix("# step ") }.dropFirst(7).prefix(4) + for start in starts { + let (bar, _, _) = menus() + var tracking = tracker(bar) + let press = numbers(lines[start]), answer = numbers(lines[start + 2]), choice = numbers(lines[start + 3]) + #expect(tracking.mouseDown(at: Point(v: press[1], h: press[2])) == nil) + let release = Point(v: answer[2], h: answer[3]) + tracking.move(to: release) + let selection = tracking.mouseUp(at: release) + #expect(selection == MenuSelection(menuID: answer[0], itemIndex: answer[1]), "\(lines[start + 2])") + #expect(tracking.menuChoice == MenuSelection(menuID: choice[0], itemIndex: choice[1]), "\(lines[start + 3])") + #expect(bar.hilitedMenuID == answer[4], "\(lines[start + 2])") + #expect(tracking.openMenu == nil) + } + #expect(starts.count == 4) + } + + /// Step 12: a click on a title leaves the menu open until the next click. + @Test func aClickLeavesTheMenuOpen() { + let (bar, file, _) = menus() + var tracking = tracker(bar) + let title = Point(v: 9, h: 24) + #expect(tracking.mouseDown(at: title) == nil) + #expect(tracking.mouseUp(at: title) == nil) + #expect(tracking.openMenu === file && bar.hilitedMenuID == 129) + #expect(tracking.mouseDown(at: Point(v: 229, h: 334)) == MenuSelection.none) + #expect(tracking.openMenu == nil && bar.hilitedMenuID == 0) + #expect(tracking.menuChoice == MenuSelection(menuID: 129, itemIndex: 0)) + } + + @Test func movingAlongTheBarChangesMenus() { + let (bar, _, edit) = menus() + var tracking = tracker(bar) + #expect(tracking.mouseDown(at: Point(v: 9, h: 24)) == nil) + tracking.move(to: Point(v: 9, h: 61)) + #expect(tracking.openMenu === edit && bar.hilitedMenuID == 130) + #expect(tracking.mouseUp(at: Point(v: 28, h: 60)) == MenuSelection(menuID: 130, itemIndex: 1)) + } +} From 93423bc9752ce3af40b9805ecba7c51df4b97df0 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 02:19:13 -0500 Subject: [PATCH 09/10] Document the tracking capture --- ReferenceTests/Retro68/README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/ReferenceTests/Retro68/README.md b/ReferenceTests/Retro68/README.md index 70fce6d..83015d7 100644 --- a/ReferenceTests/Retro68/README.md +++ b/ReferenceTests/Retro68/README.md @@ -741,3 +741,24 @@ what depths 0 and 24 make, as the screen here is 1 bit deep; the pixels `UpdateGWorld` leaves with no flags or stretches with `stretchPix`; and the flags it returns for smaller bounds. +## Window and menu tracking + +`TrackingCapture.c` records what `TrackGoAway`, `DragWindow` and `MenuSelect` +do with a press and release of the mouse, into +`Tracking-macos-9.2.2-ppc.txt` (CR line endings). It needs someone, or +something, at the mouse: the front window's title says what to do at each of +its 12 steps. The button has to stay down while the pointer moves; drags too +quick for Mac OS to follow give a useless capture. + +- `TrackGoAway` answers true where the button is released on the close box. +- `DragWindow` moves the window as far as the pointer moved. Released outside + its limit rectangle, even by 14 pixels, the window stays where it was. A + window behind comes to the front. +- A release on a dimmed item or outside the menus answers 0, and `MenuChoice` + still names the menu, with the dimmed item's number or 0. A choice leaves + the menu's title hilited. +- A click on a title leaves the menu open. +- Menu items are 16 pixels tall and a separator 6. + +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. From 6e6eb46110ba3c16de84e2655fc858ce28dec44b Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 3 Dec 2026 02:19:13 -0500 Subject: [PATCH 10/10] List window and menu tracking --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 140d9a8..cb3368b 100644 --- a/README.md +++ b/README.md @@ -43,8 +43,8 @@ Any UI it shows will be drawn with [Cacao](https://github.com/PureSwift/Cacao). | `Graphite2D` | QuickDraw's pixels (1 to 8 bits indexed, 16 and 32 bits direct, big-endian on every CPU, in memory of its own or a program's), colors and the system's color tables, regions as real regions with QuickDraw's region records, patterns, transfer modes, ports, devices and offscreen worlds; drawing rectangles, ovals, round rectangles, arcs, polygons, regions and lines with the pen, and CopyBits, CopyMask and ScrollRect between any depths; PICT pictures, version 1 and 2, with PackBits and QuickTime-compressed images through a decoder the host gives. | | `GraphiteText` | Fonts: faces and their metrics, the Font Manager's family numbers and names with the classic fonts' and their substitutes, a built-in bitmap system font (from Pomme) and `NFNT` bitmap fonts, and QuickDraw's text in a port's font, face, size and mode, with the styles a face hasn't drawn from its plain glyphs as Mac OS 9.2.2 drew them; ATSUI-style layouts with styled runs, line breaking, measuring, hit testing and drawing, and the text in PICT pictures; and, with the `FreeType` trait (on by default), faces from TrueType, OpenType and other outline fonts, found by family name in the system's font folders. | | `GraphiteSound` | The Sound Manager: sampled sounds from `'snd '` resources (formats 1 and 2, with the standard, compressed and extended headers) and AIFF and AIFF-C files, read to 16-bit PCM; the µ-law, A-law and IMA4 codecs (MACE is recognized but not decoded yet); sound channels with queued commands (`SndDoCommand`) including `callBackCmd`, `waitCmd` and `syncCmd`, immediate ones, volume, pan, pitch, loops and completion; a mixer that renders them to stereo float frames, for an audio device the host provides; and the frequencies of MIDI notes. | -| `GraphiteWindows` | The Window Manager: windows of every class, from documents, dialogs and alerts to palettes, sheets and drawers, each with the standard Mac OS 8 and 9 frame or a window definition the host brings (the WDEF); the window list ordered by layer, `FrontWindow`, and the active document and the active palette; `FindWindow` and every part of a frame; showing, hiding, selecting, zooming between the user and standard states, collapsing; `MoveWindow`, `SizeWindow` and `SetWindowBounds`, with centering, cascading and the alert position; each window's content in an offscreen buffer with its visible region — what no window in front covers — its update region with `BeginUpdate` and `EndUpdate`, and the part of it the host is told to flush. | -| `GraphiteMenus` | The Menu Manager: menus and their items — text in MacRoman, marks (the check mark and the diamond), icons, styles, keyboard equivalents with their modifiers, submenus by menu ID, command IDs — built with `AppendMenu`'s metacharacter strings or item by item; checked, enabled and disabled; the menu bar with `InsertMenu`'s order and its hierarchical list, `GetMenuHandle`, `MenuKey` and `EnableMenuCommand`; menu definitions (the MDEF) with the standard definition's sizes and item geometry; and `'MENU'` resources read with every field as the classic kept it, enable flags and submenus included. | +| `GraphiteWindows` | The Window Manager: windows of every class, from documents, dialogs and alerts to palettes, sheets and drawers, each with the standard Mac OS 8 and 9 frame or a window definition the host brings (the WDEF); the window list ordered by layer, `FrontWindow`, and the active document and the active palette; `FindWindow` and every part of a frame; showing, hiding, selecting, zooming between the user and standard states, collapsing; close box and drag tracking (`TrackGoAway`, `DragWindow`) fed by the host's loop; `MoveWindow`, `SizeWindow` and `SetWindowBounds`, with centering, cascading and the alert position; each window's content in an offscreen buffer with its visible region — what no window in front covers — its update region with `BeginUpdate` and `EndUpdate`, and the part of it the host is told to flush. | +| `GraphiteMenus` | The Menu Manager: menus and their items — text in MacRoman, marks (the check mark and the diamond), icons, styles, keyboard equivalents with their modifiers, submenus by menu ID, command IDs — built with `AppendMenu`'s metacharacter strings or item by item; checked, enabled and disabled; the menu bar with `InsertMenu`'s order and its hierarchical list, `GetMenuHandle`, `MenuKey` and `EnableMenuCommand`; menu definitions (the MDEF) with the standard definition's sizes and item geometry; `MenuSelect`'s tracking and `MenuChoice`, fed by the host's loop and layout; and `'MENU'` resources read with every field as the classic kept it, enable flags and submenus included. | | `GraphiteControls` | The Control Manager: controls of the classic's five kinds — buttons, checkboxes, radio buttons, scroll bars and pop-up menus, their control definition IDs and the `useWFont` variation read as the kind beneath it; values, ranges and the pinning SetControlValue did, with the pop-up menu's resource ID and title width in its minimum and maximum as the classic kept them; titles, reference values, command IDs, identifiers, enabling, disabling, activating and `HiliteControl`'s pressed part; the parts a point hits (inButton, inCheckBox, a scroll bar's arrows, pages and thumb), the fixed-size thumb of the classic's scroll bars and the value a drag names; a window's control list, FindControl, GetControlByID and Carbon's root control; and `'CNTL'` resources read field by field. | | `Graphite` | Re-exports the modules above. |