From 9aa1de7104391ea3dffaa5f7fb5865beea7205b0 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 17:36:36 -0500 Subject: [PATCH 01/11] Test dialog resources --- .../DialogResourceTests.swift | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Tests/GraphiteDialogsTests/DialogResourceTests.swift diff --git a/Tests/GraphiteDialogsTests/DialogResourceTests.swift b/Tests/GraphiteDialogsTests/DialogResourceTests.swift new file mode 100644 index 0000000..602167f --- /dev/null +++ b/Tests/GraphiteDialogsTests/DialogResourceTests.swift @@ -0,0 +1,24 @@ +import Testing +import GraphiteBase +import GraphiteDialogs + +@Suite struct DialogResourceTests { + @Test func packedAlertStages() throws { + // Four distinct nibbles in the order stored by Rez: stages 4 to 1. + let bytes: [UInt8] = [0, 1, 0, 2, 0, 40, 0, 80, 0, 128, 0xC9, 0x65, 0, 0] + let alert = try AlertResource(bytes: bytes) + #expect(alert.stages.map(\.bits) == [5, 6, 9, 12]) + #expect(alert.stages[0].isDrawn) + #expect(alert.stages[0].soundCount == 1) + #expect(alert.stages[2].secondItemIsDefault) + #expect(alert.bytes == bytes) + let oldAlert = try AlertResource(bytes: Array(bytes.prefix(12))) + #expect(oldAlert.position == 0) + } + + @Test func emptyItemList() throws { + let list = try DialogItemList(bytes: [0xFF, 0xFF]) + #expect(list.count == 0) + #expect(list.bytes == [0xFF, 0xFF]) + } +} From 6ea384ba0581470a6f148870078273650edd7017 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 17:36:41 -0500 Subject: [PATCH 02/11] Add dialog work in Package.swift --- Package.swift | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 805bd27..a58069a 100644 --- a/Package.swift +++ b/Package.swift @@ -90,6 +90,10 @@ let package = Package( .library( name: "GraphiteControls", targets: ["GraphiteControls"] + ), + .library( + name: "GraphiteDialogs", + targets: ["GraphiteDialogs"] ) ], // FreeType reads outline fonts; builds without it keep the bitmap font. @@ -157,9 +161,13 @@ let package = Package( name: "GraphiteControls", dependencies: ["GraphiteBase"] ), + .target( + name: "GraphiteDialogs", + dependencies: ["GraphiteBase", "GraphiteWindows", "GraphiteControls", "GraphiteResources"] + ), .target( name: "Graphite", - dependencies: ["GraphiteBase", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAppleEvents", "GraphiteQuickDraw", "GraphiteText", "GraphiteSound", "GraphiteWindows", "GraphiteMenus", "GraphiteControls"] + dependencies: ["GraphiteBase", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAppleEvents", "GraphiteQuickDraw", "GraphiteText", "GraphiteSound", "GraphiteWindows", "GraphiteMenus", "GraphiteControls", "GraphiteDialogs"] ), .testTarget( name: "GraphiteBaseTests", @@ -204,6 +212,10 @@ let package = Package( .testTarget( name: "GraphiteControlsTests", dependencies: ["GraphiteControls"] + ), + .testTarget( + name: "GraphiteDialogsTests", + dependencies: ["GraphiteDialogs"] ) ] ) From cb6ac7e6e53c2aad09412376a079ad7567ebe07a Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 17:36:41 -0500 Subject: [PATCH 03/11] Add dialog work in Graphite.swift --- Sources/Graphite/Graphite.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/Graphite/Graphite.swift b/Sources/Graphite/Graphite.swift index 286a04a..68013c5 100644 --- a/Sources/Graphite/Graphite.swift +++ b/Sources/Graphite/Graphite.swift @@ -12,3 +12,4 @@ @_exported import GraphiteWindows @_exported import GraphiteMenus @_exported import GraphiteControls +@_exported import GraphiteDialogs From 4c61c6e9a9576420b979b6e6e8428e48f18009c6 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 17:36:41 -0500 Subject: [PATCH 04/11] Add dialog work in MacError.swift --- Sources/GraphiteBase/MacError.swift | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Sources/GraphiteBase/MacError.swift b/Sources/GraphiteBase/MacError.swift index afc4b49..124fcb0 100644 --- a/Sources/GraphiteBase/MacError.swift +++ b/Sources/GraphiteBase/MacError.swift @@ -199,7 +199,7 @@ extension MacError: CustomStringConvertible { -30583: "errWindowDoesntSupportFocus", -30584: "errUnknownControl", -30585: "errCouldntSetFocus", -30586: "errNoRootControl", -30587: "errRootAlreadyExists", -30588: "errInvalidPartCode", -30589: "errControlsAlreadyExist", -30590: "errControlIsNotEmbedder", - -30592: "errControlHiddenOrDisabled", -30596: "errItemNotControl", + -30592: "errControlHiddenOrDisabled", -30596: "errItemNotControl", -5640: "dialogNoTimeoutErr", ] guard let name = names[code] else { return "\(code)" } return "\(name) (\(code))" @@ -280,3 +280,11 @@ public extension MacError { /// errItemNotControl: a dialog item that isn't one. static var itemNotControl: MacError { MacError(-30596) } } + +// MARK: - Dialog Manager + +public extension MacError { + + /// dialogNoTimeoutErr: no timeout was set for the modal session. + static var dialogNoTimeout: MacError { MacError(-5640) } +} From 2c257ce34a2fb38f2da0d33e6a467e0e5bbb5df2 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 17:36:41 -0500 Subject: [PATCH 05/11] Add dialog work in AlertStage.swift --- Sources/GraphiteDialogs/AlertStage.swift | 255 +++++++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 Sources/GraphiteDialogs/AlertStage.swift diff --git a/Sources/GraphiteDialogs/AlertStage.swift b/Sources/GraphiteDialogs/AlertStage.swift new file mode 100644 index 0000000..79aa453 --- /dev/null +++ b/Sources/GraphiteDialogs/AlertStage.swift @@ -0,0 +1,255 @@ +// An alert's stages: an 'ALRT' resource keeps, for the first time the user +// triggers the alert and the second, third and fourth-and-later times, four +// bits that say which item the Return key chooses, whether the alert is +// drawn at all, and how many times its sound plays. GetAlertStage counts +// the times, and ResetAlertStage starts over. + +import GraphiteBase +import GraphiteResources +import struct Foundation.Data +import protocol Foundation.ContiguousBytes + +/// One stage of an alert, the four bits an 'ALRT' resource keeps for it. +public struct AlertStage: Hashable, Sendable { + + /// Which item Return or Enter chooses: the first (bit clear) or the + /// second (bit set) of the item list. + public var secondItemIsDefault: Bool + + /// Whether the alert is drawn at this stage. + public var isDrawn: Bool + + /// How many times the sound plays: 0, 1, 2 or 3, as the two sound bits + /// count. + public var soundCount: Int + + public init(secondItemIsDefault: Bool = false, isDrawn: Bool = true, soundCount: Int = 1) { + self.secondItemIsDefault = secondItemIsDefault + self.isDrawn = isDrawn + self.soundCount = soundCount + } + + /// The high bit selects the default item, followed by the draw bit and + /// the two-bit sound number. + public init(bits: UInt8) { + secondItemIsDefault = bits & 0b1000 != 0 + isDrawn = bits & 0b0100 != 0 + soundCount = Int(bits & 0b11) + } + + public var bits: UInt8 { + (secondItemIsDefault ? 8 : 0) | (isDrawn ? 4 : 0) | UInt8(soundCount & 3) + } + + /// The item Return chooses at this stage: 2 for the second, 1 for the + /// first. + public var defaultItem: Int { + secondItemIsDefault ? 2 : 1 + } +} + +/// An 'ALRT' resource: the alert's rectangle, its item list's resource ID, +/// its four stages, and where it is positioned. +public struct AlertResource: Hashable, Sendable { + + public var bounds: Rect + + /// The resource ID of the alert's 'DITL'. + public var itemListID: Int16 + + /// The stages, the first through the fourth-and-later. + public private(set) var stages: [AlertStage] + + /// The positioning constant: 0 none, or one of the window position + /// codes the Dialog Manager shared with the Window Manager. + public var position: UInt16 + + public init(bounds: Rect, itemListID: Int16, stages: [AlertStage], position: UInt16 = 0) { + precondition(stages.count == 4) + self.bounds = bounds + self.itemListID = itemListID + self.stages = stages + self.position = position + } + + /// An 'ALRT' resource. paramErr for bytes one can't be read from. + public init(bytes: some ContiguousBytes) throws(MacError) { + var reader = BigEndianReader(bytes) + do { + bounds = try reader.readRect() + itemListID = try reader.read(Int16.self) + let packed = try reader.read(UInt16.self) + stages = (0..<4).map { AlertStage(bits: UInt8(truncatingIfNeeded: packed >> ($0 * 4))) } + position = reader.remaining == 0 ? 0 : try reader.read(UInt16.self) + } catch { + throw MacError.parameter + } + } + + /// The bytes of the 'ALRT' resource. + public var bytes: [UInt8] { + var writer = BigEndianWriter() + writer.write(bounds) + writer.write(itemListID) + precondition(stages.count == 4) + let packed = stages.enumerated().reduce(UInt16(0)) { $0 | (UInt16($1.element.bits) << ($1.offset * 4)) } + writer.write(packed) + writer.write(position) + return writer.bytes + } + + /// The stage an alert is at: the first three times, then the fourth's. + public func stage(_ number: Int) -> AlertStage { + stages[min(max(number, 1), 4) - 1] + } +} + +/// A standard alert's icon and meaning, for the host to present. +public enum AlertKind: Sendable { + case stop, note, caution, plain +} + +/// A host-independent standard alert. Button item numbers match Carbon's +/// OK, Cancel, and Other numbers (1, 2, and 3). +public struct StandardAlert: Sendable { + public var kind: AlertKind + public var message: PascalString + public var explanation: PascalString + public var defaultText: PascalString + public var cancelText: PascalString? + public var otherText: PascalString? + public var defaultItem: Int + public var cancelItem: Int + + public init(kind: AlertKind, message: PascalString, explanation: PascalString = "", + defaultText: PascalString = "OK", cancelText: PascalString? = nil, + otherText: PascalString? = nil, defaultItem: Int = 1, cancelItem: Int = 0) { + self.kind = kind + self.message = message + self.explanation = explanation + self.defaultText = defaultText + self.cancelText = cancelText + self.otherText = otherText + self.defaultItem = defaultItem + self.cancelItem = cancelItem + } + + /// Present a standard alert and return the chosen button item. + public func run(bounds: Rect, host: any DialogHost, filter: DialogFilter? = nil) -> Int { + let dialog = dialog(bounds: bounds) + host.configureStandardAlert(self, dialog: dialog) + return dialog.runModal(host: host, filter: filter) + } + + /// Construct the model for a host to lay out and present. + public func dialog(bounds: Rect) -> Dialog { + let width = max(0, Int(bounds.width)), height = max(0, Int(bounds.height)) + func rect(_ top: Int, _ left: Int, _ bottom: Int, _ right: Int) -> Rect { + Rect(top: Int16(clamping: top), left: Int16(clamping: left), + bottom: Int16(clamping: bottom), right: Int16(clamping: right)) + } + let buttonTop = max(0, height - 32) + let buttonWidth = max(0, min(80, (width - 32) / 3)) + func button(_ index: Int) -> Rect { + let right = max(0, width - 12 - index * (buttonWidth + 8)) + return rect(buttonTop, max(0, right - buttonWidth), max(buttonTop, height - 12), right) + } + var items = [DialogItem(bounds: button(0), kind: .button, text: defaultText)] + // Keep the item numbers stable when a button is absent. + items.append(DialogItem(bounds: cancelText == nil ? .zero : button(1), kind: .button, text: cancelText ?? "", isEnabled: cancelText != nil)) + items.append(DialogItem(bounds: otherText == nil ? .zero : button(2), kind: .button, text: otherText ?? "", isEnabled: otherText != nil)) + items.append(DialogItem(bounds: rect(12, 16, 32, max(16, width - 16)), kind: .staticText, text: message, isEnabled: false)) + items.append(DialogItem(bounds: rect(36, 16, max(36, buttonTop - 8), max(16, width - 16)), kind: .staticText, text: explanation, isEnabled: false)) + let dialog = Dialog(kind: .modal, bounds: bounds, items: items) + dialog.defaultItem = defaultItem + dialog.cancelItem = cancelItem + return dialog + } +} + +/// Load an ALRT and its DITL. The caller decides how to play the stage's +/// alert sound and supplies events when the stage displays a dialog. +public extension AlertResource { + static func load(id: Int16, resources: ResourceChain) throws(MacError) -> (AlertResource, DialogItemList) { + let alert = try resources.get(type: "ALRT", id: id) + guard let bytes = alert.bytes else { throw .resourceNotFound } + let resource = try AlertResource(bytes: bytes) + let list = try resources.get(type: "DITL", id: resource.itemListID) + guard let listBytes = list.bytes else { throw .resourceNotFound } + return (resource, try DialogItemList(bytes: listBytes)) + } + + func dialog(items: DialogItemList, stage: Int) -> Dialog? { + let settings = self.stage(stage) + guard settings.isDrawn else { return nil } + let dialog = Dialog(kind: .modal, bounds: bounds, items: items.items, position: position) + dialog.defaultItem = settings.defaultItem + return dialog + } +} + +/// Runs resource alerts using the host's sound and event delivery. +public final class AlertManager { + public private(set) var counter = AlertStageCounter() + public private(set) var lastAlertID: Int16? + + public init() {} + + public func reset() { + counter.reset() + lastAlertID = nil + } + + /// Run an alert using the host for sound, presentation, and input. + public func run(id: Int16, resource: AlertResource, items: DialogItemList, + host: any DialogHost, filter: DialogFilter? = nil) -> Int? { + if lastAlertID != id { counter.reset() } + lastAlertID = id + counter.advance() + let stageNumber = counter.stage + 1 + let stage = resource.stage(stageNumber) + if stage.soundCount != 0 { host.playAlertSound(stage.soundCount) } + guard let dialog = resource.dialog(items: items, stage: stageNumber) else { return nil } + return dialog.runModal(host: host, filter: filter) + } + + /// Returns nil for an alert stage that does not display a dialog. + /// The sound callback receives the selected sound number, 1 through 3. + public func run(id: Int16, resource: AlertResource, items: DialogItemList, + sound: (Int) -> Void, next: () -> DialogEvent?, + filter: DialogFilter? = nil) -> Int? { + if lastAlertID != id { counter.reset() } + lastAlertID = id + counter.advance() + let stageNumber = counter.stage + 1 + let stage = resource.stage(stageNumber) + if stage.soundCount != 0 { sound(stage.soundCount) } + guard let dialog = resource.dialog(items: items, stage: stageNumber) else { return nil } + return dialog.runModal(next: next, filter: filter) + } +} + +/// GetAlertStage and ResetAlertStage's counter: how many times in a row the +/// user has triggered an alert, as many alerts as the program shows. +public struct AlertStageCounter: Hashable, Sendable { + + /// The times so far, the next alert's stage. + public private(set) var count = 0 + + public init() {} + + /// GetAlertStage: the last alert's stage, numbered from 0 through 3. + public var stage: Int { + max(0, min(count - 1, 3)) + } + + /// The alert was shown once more; the fourth stage repeats thereafter. + public mutating func advance() { + count = min(count + 1, 4) + } + + /// ResetAlertStage: back to the first stage. + public mutating func reset() { + count = 0 + } +} From 192840bc8b7c97d123ea12ec8f2de38b3335b9ed Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 17:36:41 -0500 Subject: [PATCH 06/11] Add dialog work in Dialog.swift --- Sources/GraphiteDialogs/Dialog.swift | 458 +++++++++++++++++++++++++++ 1 file changed, 458 insertions(+) create mode 100644 Sources/GraphiteDialogs/Dialog.swift diff --git a/Sources/GraphiteDialogs/Dialog.swift b/Sources/GraphiteDialogs/Dialog.swift new file mode 100644 index 0000000..0cb7841 --- /dev/null +++ b/Sources/GraphiteDialogs/Dialog.swift @@ -0,0 +1,458 @@ +// A dialog box: a window of one of the Dialog Manager's own kinds — modal, +// movable modal or modeless — holding an item list. The items are found, +// hit-tested and have their text read and changed by the number the +// Dialog Manager gave them; the default item and the cancel item are set, +// for the Return and Escape keys to choose; and ParamText's strings are +// substituted into the static text, as the Dialog Manager wrote ^0 through +// ^3 into it. The host draws the box and its items, and tracks the controls +// in it. + +import GraphiteBase +import GraphiteWindows +import GraphiteControls + +/// The kind of dialog box a 'DLOG' resource's window definition ID names +/// (dBoxProc, noGrowDocProc and movableDBoxProc). +public enum DialogKind: Hashable, Sendable { + + /// dBoxProc: a modal dialog box, fixed in place. + case modal + /// noGrowDocProc: a modeless dialog box, with a title bar. + case modeless + /// movableDBoxProc: a movable modal dialog box. + case movableModal + + /// The window definition ID. + public var definitionID: Int16 { + switch self { + case .modal: return 1 + case .modeless: return 4 + case .movableModal: return 5 + } + } + + /// The kind of a window definition ID, as the Dialog Manager read it. + public init?(definitionID: Int16) { + switch definitionID { + case 1: self = .modal + case 4: self = .modeless + case 5: self = .movableModal + default: return nil + } + } +} + +public final class Dialog { + + /// The window definition the dialog was made with. + public let kind: DialogKind + + /// The backing window, once attached to a Window Manager. + public private(set) var window: Window? + + /// Controls corresponding to the dialog's control items, keyed by item number. + public private(set) var controls: [Int: Control] = [:] + public let controlList = ControlList() + + // Resource bytes are retained so rebuilding a list can recreate CNTL items. + var controlResources: [Int16: [UInt8]] = [:] + var trackingItem: Int? + private var instantiatedResourceIDs: [Int: Int16] = [:] + + /// Attach the dialog to a window manager. The host presents the window + /// and the controls and forwards input through the dialog event API. + public func attach(to manager: WindowManager) throws(MacError) { + guard window == nil else { throw .parameter } + let windowClass: WindowClass + switch kind { + case .modal: windowClass = .modal + case .movableModal: windowClass = .movableModal + case .modeless: windowClass = .document + } + let parent = manager.frontWindow + let window = try manager.newWindow(windowClass: windowClass, + attributes: hasCloseBox ? [.closeBox] : [], + bounds: bounds, title: title) + window.kindCode = 2 + window.referenceConstant = UInt(UInt32(bitPattern: reference)) + let placement: WindowPositionMethod? + switch position { + case 0x300A: placement = .alertPositionOnMainScreen + case 0x700A: placement = parent == nil ? .alertPositionOnMainScreen : .alertPositionOnParentWindowScreen + case 0xB00A: placement = parent == nil ? .alertPositionOnMainScreen : .alertPositionOnParentWindow + default: placement = nil + } + if let placement { + do { + try manager.reposition(window, method: placement, relativeTo: parent) + bounds = window.contentBounds + } catch { + window.dispose() + throw error + } + } + self.window = window + rebuildControls() + if keyboardFocus == nil, let index = itemList.items.firstIndex(where: { $0.kind == .editText && $0.isEnabled }) { + focusTextItem(index + 1) + } + if isVisible { window.show() } + } + + private func rebuildControls() { + let previous = controls + let previousResourceIDs = instantiatedResourceIDs + controls = [:] + instantiatedResourceIDs = [:] + for control in previous.values { controlList.remove(control) } + for (index, item) in itemList.items.enumerated() { + let number = index + 1 + if item.kind == .control { + let control: Control? + if previousResourceIDs[number] == item.resourceID { + control = previous[number] + } else if let bytes = controlResources[item.resourceID] { + control = try? Control.make(bytes: bytes) + } else { + control = nil + } + if let control { + if item.isEnabled { control.enable() } else { control.disable() } + if hiddenItems.contains(number) { control.hide() } + controls[number] = control + instantiatedResourceIDs[number] = item.resourceID + controlList.add(control) + } + continue + } + let kind: ControlKind + switch item.kind { + case .button: kind = .button + case .checkBox: kind = .checkBox + case .radioButton: kind = .radioButton + default: continue + } + let control: Control + if let existing = previous[index + 1], existing.kind == kind, existing.bounds == item.bounds { + control = existing + control.title = item.text + } else { + control = Control(kind: kind, bounds: item.bounds, title: item.text) + } + if item.isEnabled { control.enable() } else { control.disable() } + if hiddenItems.contains(number) { control.hide() } else { control.show() } + controls[index + 1] = control + controlList.add(control) + } + } + + public func control(of number: Int) -> Control? { controls[number] } + + public func dispose() { + window?.dispose() + window = nil + for control in controls.values { controlList.remove(control) } + controls.removeAll() + isVisible = false + } + + /// The dialog's rectangle, in global coordinates: where the box goes + /// on the screen. + public internal(set) var bounds: Rect + + /// SetWTitle and GetWTitle: shown in the title bar of a modeless + /// dialog alone. + public var title: PascalString + + /// The window's reference constant. + public var reference: Int32 + + /// Whether a close box is drawn: a modeless dialog's, as goAway asked. + public let hasCloseBox: Bool + + /// The positioning constant of the 'DLOG' or 'ALRT' resource, 0 for + /// none. + public let position: UInt16 + + /// The items, in their order. + public var itemList: DialogItemList { + didSet { if window != nil { rebuildControls() } } + } + + /// The resource ID of the 'DITL' the dialog was made from; 0 for one + /// made item by item. + public internal(set) var itemListID: Int16 = 0 + + /// SetDialogDefaultItem: the item Return and Enter choose, as a click + /// on it. 0 is none. The Dialog Manager draws the default button with a + /// bold outline. + public var defaultItem: Int = 0 + + /// SetDialogCancelItem: the item Escape and Command-period choose. 0 is + /// none. + public var cancelItem: Int = 0 + + /// ParamText's strings, substituted for ^0 through ^3 in the items' + /// text as it is drawn. + public private(set) var paramText: [PascalString] = ["", "", "", ""] + + /// Whether the dialog is shown. + public internal(set) var isVisible = true + + public init(kind: DialogKind, bounds: Rect, title: PascalString = "", items: [DialogItem] = [], + reference: Int32 = 0, hasCloseBox: Bool = false, position: UInt16 = 0) { + self.kind = kind + self.bounds = bounds + self.title = title + self.itemList = DialogItemList(items: items) + self.reference = reference + self.hasCloseBox = hasCloseBox + self.position = position + } + + /// How a list appended to a dialog is positioned. + public enum AppendPosition: Sendable { + case overlay, right, bottom, relativeToItem(Int) + } + + /// AppendDITL. Right and bottom placements expand the content bounds; + /// relative placement uses the selected item's upper-left corner. + public func append(_ list: DialogItemList, at position: AppendPosition = .overlay) throws(MacError) { + let width = bounds.width, height = bounds.height + let offsetH: Int + let offsetV: Int + switch position { + case .overlay: offsetH = 0; offsetV = 0 + case .right: offsetH = width; offsetV = 0 + case .bottom: offsetH = 0; offsetV = height + case .relativeToItem(let number): + guard let anchor = item(number) else { throw .parameter } + offsetH = Int(anchor.bounds.left); offsetV = Int(anchor.bounds.top) + } + var additions: [DialogItem] = [] + for var entry in list.items { + let top = Int(entry.bounds.top) + offsetV, bottom = Int(entry.bounds.bottom) + offsetV + let left = Int(entry.bounds.left) + offsetH, right = Int(entry.bounds.right) + offsetH + guard let t = Int16(exactly: top), let b = Int16(exactly: bottom), + let l = Int16(exactly: left), let r = Int16(exactly: right) else { throw .parameter } + entry.bounds = Rect(top: t, left: l, bottom: b, right: r) + additions.append(entry) + } + var newBounds = bounds + if case .right = position { + let right = max(width, additions.map { Int($0.bounds.right) }.max() ?? width) + Int(bounds.left) + guard let value = Int16(exactly: right) else { throw .parameter } + newBounds.right = value + } + if case .bottom = position { + let bottom = max(height, additions.map { Int($0.bounds.bottom) }.max() ?? height) + Int(bounds.top) + guard let value = Int16(exactly: bottom) else { throw .parameter } + newBounds.bottom = value + } + if newBounds != bounds { + try window?.setBounds(newBounds, region: .content) + bounds = newBounds + } + itemList.items.append(contentsOf: additions) + } + + /// ShortenDITL removes items from the end without resizing the window. + public func shorten(by number: Int) throws(MacError) { + guard number >= 0, number <= count else { throw .parameter } + itemList.items.removeLast(number) + selectedText = selectedText.filter { $0.key <= count } + if let focus = keyboardFocus, focus > count { keyboardFocus = nil } + if defaultItem > count { defaultItem = 0 } + if cancelItem > count { cancelItem = 0 } + } + + /// CountDITL. + public var count: Int { itemList.count } + + /// GetDialogItem: the item of a number, counted from 1; nil for a + /// number no item has. + public func item(_ number: Int) -> DialogItem? { + itemList.item(number) + } + + /// SetDialogItem: the item of a number is replaced. A number no item + /// has changes nothing. + public func setItem(_ number: Int, to item: DialogItem) { + guard number >= 1, number <= itemList.items.count else { return } + itemList.items[number - 1] = item + } + + /// Hidden item numbers. Hidden items retain their original rectangles. + public private(set) var hiddenItems: Set = [] + + public func hideItem(_ number: Int) { + guard item(number) != nil else { return } + hiddenItems.insert(number) + control(of: number)?.hide() + if keyboardFocus == number { keyboardFocus = nil } + } + + public func showItem(_ number: Int) { + guard item(number) != nil else { return } + hiddenItems.remove(number) + control(of: number)?.show() + } + + /// The item's display rectangle, in the dialog's local coordinates. + public func itemBounds(_ number: Int) -> Rect? { + item(number)?.bounds + } + + /// FindDialogItem: the item a point of the dialog's local coordinates + /// is in, numbered from 0, the first when items overlap; nil for a + /// point in none. + public func findItem(at point: Point) -> Int? { + itemList.items.enumerated().first { !hiddenItems.contains($0.offset + 1) && $0.element.contains(point) }?.offset + } + + // MARK: Text + + /// GetDialogItemText and SetDialogItemText, for an item that keeps + /// text; a number no item has, or an item without text, changes + /// nothing. + public func text(of number: Int) -> PascalString? { + guard let item = item(number), item.kind.hasText else { return nil } + return item.text + } + + public func setText(_ text: PascalString, of number: Int) { + guard number >= 1, number <= itemList.items.count, itemList.items[number - 1].kind.hasText else { return } + itemList.items[number - 1].text = text + } + + /// SelectDialogItemText: the range of an editable text item's text + /// that is selected. The host draws the selection. + public func selectText(of number: Int, range: Range? = nil) { + guard number >= 1, number <= itemList.items.count, itemList.items[number - 1].kind == .editText else { return } + let count = itemList.items[number - 1].text.count + let selection = range ?? 0..] = [:] + + /// An item's text as it is drawn: the ParamText strings in place of + /// their ^0 through ^3. + public func drawnText(of number: Int) -> PascalString? { + guard let text = text(of: number) else { return nil } + guard item(number)?.kind == .staticText else { return text } + var result: [UInt8] = [] + var index = text.bytes.startIndex + while index < text.bytes.endIndex { + if text.bytes[index] == UInt8(ascii: "^"), index + 1 < text.bytes.endIndex, + (48...51).contains(text.bytes[index + 1]) { + result.append(contentsOf: paramText[Int(text.bytes[index + 1] - 48)].bytes) + index += 2 + } else { + result.append(text.bytes[index]) + index += 1 + } + } + return PascalString(bytes: result) + } + + /// ParamText: the four strings. + public func setParamText(_ p0: PascalString, _ p1: PascalString, _ p2: PascalString, _ p3: PascalString) { + paramText = [p0, p1, p2, p3] + } + + // MARK: Hits + + /// The item a mouse-down in the dialog's local coordinates is in, as + /// ModalDialog and DialogSelect report it — the item's number from 1, + /// for an enabled item; 0 for none, or a disabled one. + public func hit(at point: Point) -> Int { + guard let index = findItem(at: point), itemList.items[index].isEnabled else { return 0 } + return index + 1 + } + + /// Whether an item is enabled: only enabled items report their hits. + public func isItemEnabled(_ number: Int) -> Bool { + !hiddenItems.contains(number) && (item(number)?.isEnabled ?? false) + } + + /// The default and cancel items as clicks on them: the standard event + /// filter's answers to Return and Enter, and to Escape and + /// Command-period. 0 where none is set. + public var defaultHit: Int { isItemEnabled(defaultItem) ? defaultItem : 0 } + public var cancelHit: Int { isItemEnabled(cancelItem) ? cancelItem : 0 } + + /// The editable item receiving keyboard input, if any. + public internal(set) var keyboardFocus: Int? + + /// Move keyboard focus through enabled editable items, wrapping at either end. + public func advanceTextFocus(backwards: Bool = false) { + let fields = itemList.items.enumerated().compactMap { index, item in + item.kind == .editText && item.isEnabled ? index + 1 : nil + } + guard !fields.isEmpty else { keyboardFocus = nil; return } + let current = keyboardFocus.flatMap { fields.firstIndex(of: $0) } + let index: Int + if let current { + index = (current + (backwards ? fields.count - 1 : 1)) % fields.count + } else { + index = backwards ? fields.count - 1 : 0 + } + selectText(of: fields[index]) + } + + /// Copy or delete the selection in the focused editable item. The caller + /// owns the scrap and may pass its contents back to `pasteText`. + public func copyText() -> PascalString? { + guard let number = keyboardFocus, let item = item(number), item.kind == .editText else { return nil } + let count = item.text.count + let selection = selectedText[number] ?? count.. Bool { + guard let number = keyboardFocus, let item = item(number), item.kind == .editText, item.isEnabled else { return false } + let count = item.text.count + let selection = selectedText[number] ?? count.. Date: Thu, 26 Nov 2026 17:36:41 -0500 Subject: [PATCH 07/11] Add dialog work in DialogItem.swift --- Sources/GraphiteDialogs/DialogItem.swift | 126 +++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 Sources/GraphiteDialogs/DialogItem.swift diff --git a/Sources/GraphiteDialogs/DialogItem.swift b/Sources/GraphiteDialogs/DialogItem.swift new file mode 100644 index 0000000..cd8d809 --- /dev/null +++ b/Sources/GraphiteDialogs/DialogItem.swift @@ -0,0 +1,126 @@ +// An item of a dialog box or an alert box: the display rectangle that +// places it in the box, the kind of thing it is — a button, a checkbox, a +// radio button, static text, editable text, a control, an icon, a picture, +// a user item the program draws itself, a help item — whether it is +// enabled, and its text or its resource. Items are numbered from 1 in the +// routines that act on them, as the Dialog Manager numbered them, and from +// 0 by FindDialogItem alone. + +import GraphiteBase + +/// The kind of a dialog item, as the item list's type byte keeps it +/// (DialogItemType): the low seven bits. +public enum DialogItemKind: UInt8, Hashable, Sendable { + + /// A user item: one the program draws and tracks, with the procedure + /// it gives the item. + case userItem = 0 + /// A help item, for the Help Manager. + case helpItem = 1 + /// A button, its title in its text. + case button = 4 + /// A checkbox, its title in its text. + case checkBox = 5 + /// A radio button, its title in its text. + case radioButton = 6 + /// A control defined by a 'CNTL' resource, the resource's ID in the + /// item. + case control = 7 + /// Static text, the text in the item. + case staticText = 8 + /// Editable text, the text in the item. + case editText = 16 + /// An icon, an 'ICON' or 'cicn' resource's ID in the item. + case icon = 32 + /// A picture, a 'PICT' resource's ID in the item. + case picture = 64 + + /// kItemDisableBit: set in an item's type byte when it is disabled. + public static var disableBit: UInt8 { 128 } + + /// The kind and the enabled state an item's type byte keeps. + public static func from(typeByte: UInt8) -> (kind: DialogItemKind, isEnabled: Bool) { + (DialogItemKind(rawValue: typeByte & ~disableBit) ?? .userItem, typeByte & disableBit == 0) + } + + /// The type byte of a kind and an enabled state. + public static func typeByte(_ kind: DialogItemKind, isEnabled: Bool) -> UInt8 { + kind.rawValue | (isEnabled ? 0 : disableBit) + } + + /// Whether the item is drawn by the program rather than the Dialog + /// Manager: a user item. + public var isUserDrawn: Bool { + self == .userItem + } + + /// Whether the item is one of the Dialog Manager's own controls, which + /// take a title. + public var hasTitle: Bool { + switch self { + case .button, .checkBox, .radioButton: true + default: false + } + } + + /// Whether the item keeps text: a title, static text, or editable + /// text's. + public var hasText: Bool { + hasTitle || self == .staticText || self == .editText + } + + /// Whether the item keeps a resource ID. + public var hasResource: Bool { + self == .control || self == .icon || self == .picture || self == .helpItem + } +} + +/// The procedure that draws a user item (UserItemProc): the Dialog Manager +/// calls it with the dialog and the item's number as it draws. +public typealias DialogItemDrawProc = @Sendable (_ dialog: Dialog, _ item: Int) -> Void + +/// One item of a dialog box. Its rectangle is in the dialog's local +/// coordinates. +public struct DialogItem: Sendable { + + /// The display rectangle. + public var bounds: Rect + + public var kind: DialogItemKind + + /// The enable flag: an enabled item reports mouse-downs in it to the + /// program, a disabled one doesn't and draws dimmed. + public var isEnabled: Bool + + /// The item's text: a control's title, static text, or editable text's + /// default. + public var text: PascalString + + /// The resource ID a control, an icon or a picture keeps, 0 for none. + public var resourceID: Int16 + + /// A user item's draw procedure, set with SetDialogItem; nil for the + /// other kinds. + public var drawProcedure: DialogItemDrawProc? + + public init(bounds: Rect, kind: DialogItemKind, text: PascalString = "", resourceID: Int16 = 0, + isEnabled: Bool = true, drawProcedure: DialogItemDrawProc? = nil) { + self.bounds = bounds + self.kind = kind + self.text = text + self.resourceID = resourceID + self.isEnabled = isEnabled + self.drawProcedure = drawProcedure + } + + /// The item's type byte as the item list keeps it. + public var typeByte: UInt8 { + DialogItemKind.typeByte(kind, isEnabled: isEnabled) + } + + /// FindDialogItem's test: whether the point is in the display + /// rectangle. + public func contains(_ point: Point) -> Bool { + bounds.contains(point) + } +} From b818a3cdb7e450f278a80aedce67ecc9170acfca Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 17:36:41 -0500 Subject: [PATCH 08/11] Add dialog work in DialogItemList.swift --- Sources/GraphiteDialogs/DialogItemList.swift | 111 +++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 Sources/GraphiteDialogs/DialogItemList.swift diff --git a/Sources/GraphiteDialogs/DialogItemList.swift b/Sources/GraphiteDialogs/DialogItemList.swift new file mode 100644 index 0000000..4da7f87 --- /dev/null +++ b/Sources/GraphiteDialogs/DialogItemList.swift @@ -0,0 +1,111 @@ +// An item list, the 'DITL' resource: the items of a dialog box or an alert +// box, in the order the Dialog Manager numbered them. Read with every +// offset checked: each item is its rectangle, its type byte with the enable +// flag in its high bit, and its text or its resource, padded to a word as +// the resource compiler padded it. + +import GraphiteBase +import struct Foundation.Data +import protocol Foundation.ContiguousBytes + +public struct DialogItemList: Sendable { + + /// The items, first to last. + public var items: [DialogItem] + + /// An empty list. + public init() { + items = [] + } + + public init(items: [DialogItem]) { + self.items = items + } + + /// CountDITL. + public var count: Int { items.count } + + /// The item of a number the Dialog Manager's routines take, which + /// count from 1; nil for a number no item has. + public func item(_ number: Int) -> DialogItem? { + number >= 1 && number <= items.count ? items[number - 1] : nil + } + + /// FindDialogItem: the item a point is in, numbered from 0; the first + /// when items overlap, and nil for a point in none. + public func findItem(at point: Point) -> Int? { + items.firstIndex { $0.contains(point) } + } + + // MARK: The resource + + /// A 'DITL' resource: its count less one, then the items. paramErr for + /// bytes a list can't be read from — a count past what the bytes hold, + /// an item cut off, an item of a type whose bytes aren't defined. + public init(bytes: some ContiguousBytes) throws(MacError) { + var reader = BigEndianReader(bytes) + do { + let count = Int(try reader.read(Int16.self)) + 1 + guard count >= 0 else { throw MacError.parameter } + var items: [DialogItem] = [] + items.reserveCapacity(count) + for _ in 0 ..< count { + _ = try reader.read(UInt32.self) // Reserved: the Dialog Manager's own storage. + let bounds = try reader.readRect() + let typeByte = try reader.read(UInt8.self) + guard let kind = DialogItemKind(rawValue: typeByte & ~DialogItemKind.disableBit) else { + throw MacError.parameter + } + let isEnabled = typeByte & DialogItemKind.disableBit == 0 + var item = DialogItem(bounds: bounds, kind: kind, isEnabled: isEnabled) + switch kind { + case .button, .checkBox, .radioButton, .staticText, .editText: + item.text = try reader.readPascalString() + if reader.offset % 2 != 0 { try reader.skip(1) } + case .control, .icon, .picture: + _ = try reader.read(UInt8.self) // Reserved. + item.resourceID = try reader.read(Int16.self) + case .helpItem: + let size = Int(try reader.read(UInt8.self)) + _ = try reader.read(UInt16.self) // The help item's type. + item.resourceID = try reader.read(Int16.self) + // HMScanAppendhdlg's items carry an item number too. + if size > 4 { _ = try reader.read(UInt16.self) } + case .userItem: + _ = try reader.read(UInt8.self) // Reserved. + } + items.append(item) + } + self.items = items + } catch let error as MacError { + throw error + } catch { + throw MacError.parameter + } + } + + /// The list's bytes as a 'DITL' resource keeps them. + public var bytes: [UInt8] { + var writer = BigEndianWriter() + precondition(items.count <= Int(Int16.max) + 1) + writer.write(Int16(items.count - 1)) + for item in items { + writer.write(UInt32(0)) + writer.write(item.bounds) + writer.write(item.typeByte) + switch item.kind { + case .button, .checkBox, .radioButton, .staticText, .editText: + writer.write(item.text) + writer.align(to: 2) + case .control, .icon, .picture, .userItem: + writer.write(UInt8(0)) + if item.kind != .userItem { writer.write(item.resourceID) } + case .helpItem: + writer.write(UInt8(4)) + writer.write(UInt16(1)) + writer.write(item.resourceID) + } + } + return writer.bytes + } +} From 2db6ebfe9294ee8dbcd6e2f2ac7d57b5e94990c8 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 17:36:41 -0500 Subject: [PATCH 09/11] Add dialog work in DialogResource.swift --- Sources/GraphiteDialogs/DialogResource.swift | 62 ++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Sources/GraphiteDialogs/DialogResource.swift diff --git a/Sources/GraphiteDialogs/DialogResource.swift b/Sources/GraphiteDialogs/DialogResource.swift new file mode 100644 index 0000000..324760b --- /dev/null +++ b/Sources/GraphiteDialogs/DialogResource.swift @@ -0,0 +1,62 @@ +// Reading a 'DLOG' resource, as GetNewDialog read one: the dialog's +// rectangle, its window definition ID, whether it is visible, whether it +// has a close box, its reference constant, its item list's resource ID, its +// title with an alignment byte after it, and where it is positioned. + +import GraphiteBase +import GraphiteResources +import GraphiteControls +import struct Foundation.Data +import protocol Foundation.ContiguousBytes + +public extension Dialog { + + /// Load a DLOG and its DITL through the current resource chain. + static func make(id: Int16, resources: ResourceChain) throws(MacError) -> Dialog { + let entry = try resources.get(type: "DLOG", id: id) + guard let bytes = entry.bytes else { throw .resourceNotFound } + let dialog = try make(bytes: bytes) + let list = try resources.get(type: "DITL", id: dialog.itemListID) + guard let listBytes = list.bytes else { throw .resourceNotFound } + dialog.itemList = try DialogItemList(bytes: listBytes) + for item in dialog.itemList.items where item.kind == .control { + let entry = try resources.get(type: "CNTL", id: item.resourceID) + guard let bytes = entry.bytes else { throw .resourceNotFound } + _ = try Control.make(bytes: bytes) + dialog.controlResources[item.resourceID] = bytes + } + return dialog + } + + /// A 'DLOG' resource without its items, which the 'DITL' of its ID + /// holds. paramErr for bytes a dialog can't be read from, or a window + /// definition ID that names none of the Dialog Manager's kinds. + static func make(bytes: some ContiguousBytes, items: [DialogItem] = []) throws(MacError) -> Dialog { + var reader = BigEndianReader(bytes) + do { + let bounds = try reader.readRect() + let definitionID = try reader.read(Int16.self) + let visible = try reader.readBool() + _ = try reader.read(UInt8.self) // Reserved. + let hasCloseBox = try reader.readBool() + _ = try reader.read(UInt8.self) // Reserved. + let reference = try reader.read(Int32.self) + let itemListID = try reader.read(Int16.self) + let title = try reader.readPascalString() + // An alignment byte when the title's length leaves the next + // field off a word boundary: its length byte and its bytes. + if (title.count + 1) % 2 != 0 && reader.remaining > 0 { _ = try reader.read(UInt8.self) } + let position = reader.remaining == 0 ? 0 : try reader.read(UInt16.self) + guard let kind = DialogKind(definitionID: definitionID) else { throw MacError.parameter } + let dialog = Dialog(kind: kind, bounds: bounds, title: title, items: items, + reference: reference, hasCloseBox: hasCloseBox, position: position) + dialog.isVisible = visible + dialog.itemListID = itemListID + return dialog + } catch let error as MacError { + throw error + } catch { + throw MacError.parameter + } + } +} From 2e237496bdf8db0e86744197b4dc127ffe721f95 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 17:36:41 -0500 Subject: [PATCH 10/11] Add dialog work in ModalDialog.swift --- Sources/GraphiteDialogs/ModalDialog.swift | 200 ++++++++++++++++++++++ 1 file changed, 200 insertions(+) create mode 100644 Sources/GraphiteDialogs/ModalDialog.swift diff --git a/Sources/GraphiteDialogs/ModalDialog.swift b/Sources/GraphiteDialogs/ModalDialog.swift new file mode 100644 index 0000000..f9d7b4c --- /dev/null +++ b/Sources/GraphiteDialogs/ModalDialog.swift @@ -0,0 +1,200 @@ +// The modal loop: ModalDialog and Alert's work, the Dialog Manager's own +// between an event and the dialog it belongs to. The host brings the +// events — the Event Manager's to come, or its own — as answers to a +// closure the loop calls; the loop runs the filter the program gave it over +// each, or the standard one, which makes Return and Enter a click on the +// default item, and Escape and Command-period one on the cancel item, and +// stops at the item hit. + +import GraphiteBase + +/// What the host gives the modal loop: an event as it reaches the dialog. +public enum DialogEvent: Hashable, Sendable { + + /// A key pressed, with the characters it makes and the modifiers + /// held (the Event Manager's bits: Command 256, Shift 512, and so on). + case key(characters: PascalString, modifiers: Int16) + + /// A mouse-down at a point of the dialog's local coordinates. + case mouseDown(Point) + + /// Pointer movement and release, in dialog-local coordinates. + case mouseMoved(Point) + case mouseUp(Point) + + /// A user item's turn to draw: the host asks the program's procedure. + /// The loop calls it with the dialog and the item. + case drawUserItem(item: Int) + + /// The dialog's turn to be activated or deactivated. + case activate(Bool) + + /// An update event for the dialog: its items drawn again. + case update +} + +/// The platform supplies presentation and a blocking event source. Drawing +/// receives the complete dialog model, including controls and text selection. +public protocol DialogHost: AnyObject { + func present(_ dialog: Dialog) + func redraw(_ dialog: Dialog) + func nextEvent(for dialog: Dialog) -> DialogEvent? + func dismiss(_ dialog: Dialog) + func playAlertSound(_ number: Int) + func configureStandardAlert(_ alert: StandardAlert, dialog: Dialog) +} + +public extension DialogHost { + func configureStandardAlert(_ alert: StandardAlert, dialog: Dialog) {} +} + +/// An event filter (ModalFilterProc): it takes an event and answers whether +/// it handled it. When it has, the loop returns the item it says was hit. +public typealias DialogFilter = @Sendable (_ dialog: Dialog, _ event: DialogEvent, _ itemHit: inout Int) -> Bool + +/// The standard event filter, as the Dialog Manager's own: Return and Enter +/// are a click on the default item, Escape and Command-period one on the +/// cancel item — where the dialog has them. It handles no other event. +public struct StandardDialogFilter: Sendable { + + public init() {} + + public func filter(_ dialog: Dialog, _ event: DialogEvent, _ itemHit: inout Int) -> Bool { + switch event { + case .key(let characters, let modifiers): + // Return and Enter, without the Command key. + if characters.bytes.first == 0x0D || characters.bytes.first == 0x03, modifiers & 0x0100 == 0 { + itemHit = dialog.defaultHit + return dialog.defaultHit != 0 + } + // Escape, or Command-period: the cancel item. + let isEscape = characters.bytes.first == 0x1B + let isCommandPeriod = characters.bytes.first == UInt8(ascii: ".") && modifiers & 0x0100 != 0 + if isEscape || isCommandPeriod { + itemHit = dialog.cancelHit + return dialog.cancelHit != 0 + } + return false + default: + return false + } + } +} + +public extension Dialog { + + /// Process an event for a modal or modeless dialog. An item number is + /// returned when the event is reported to the application. + func handle(_ event: DialogEvent) -> Int? { + switch event { + case .mouseDown(let point): + let controlHit = controlList.findControl(at: point).flatMap { found in + controls.first { $0.value === found.control }?.key + } + let number = controlHit ?? hit(at: point) + guard let item = item(number), item.isEnabled else { return nil } + if item.kind == .editText { + focusTextItem(number) + return nil + } + if let control = control(of: number) { + guard control.isLive else { return nil } + let part = control.hitTest(point) + guard part != .none, part != .disabled else { return nil } + trackingItem = number + control.hilite(part) + return nil + } + return number + case .mouseMoved(let point): + if let number = trackingItem, let control = control(of: number) { + let part = control.hitTest(point) + control.hilite(part == .disabled ? .none : part) + } + case .mouseUp(let point): + guard let number = trackingItem else { return nil } + trackingItem = nil + guard let control = control(of: number) else { return nil } + let part = control.hitTest(point) + control.hilite(.none) + guard control.isLive, part != .none, part != .disabled else { return nil } + return number + case .drawUserItem(let number): + item(number)?.drawProcedure?(self, number) + case .key(let characters, let modifiers): + if characters.bytes.first == 0x09, modifiers & 0x0100 == 0 { + advanceTextFocus(backwards: modifiers & 0x0200 != 0) + return nil + } + guard modifiers & 0x0100 == 0, let number = keyboardFocus, + let item = item(number), item.kind == .editText, item.isEnabled else { return nil } + var bytes = item.text.bytes + let count = bytes.count + let selection = selectedText[number] ?? count.. 0 { start -= 1 } + bytes.removeSubrange(start..= 0x20 }) { + bytes.replaceSubrange(start.. Int { + show() + host.present(self) + host.redraw(self) + defer { host.dismiss(self); hide() } + let effectiveFilter = filter ?? StandardDialogFilter().filter + var itemHit = 0 + while let event = host.nextEvent(for: self) { + if effectiveFilter(self, event, &itemHit) { return itemHit } + let hit = handle(event) + host.redraw(self) + if let hit, hit != 0 { return hit } + } + return 0 + } + + /// ModalDialog: the item the user hit, as the dialog's filter sees the + /// host's events. `next` gives the events until it answers nil; with + /// none left, the loop returns 0 — the host has stopped giving events, + /// as a closed window would. + func runModal(next: () -> DialogEvent?, filter: DialogFilter? = nil) -> Int { + let filter = filter ?? StandardDialogFilter().filter + var itemHit = 0 + while let event = next() { + // The filter first, as the Dialog Manager's ran before its own + // handling. + if filter(self, event, &itemHit) { return itemHit } + if let hit = handle(event), hit != 0 { return hit } + } + return 0 + } +} From 96ede5b0c8932c6ef90b61e74809eff8f9257fc2 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 17:36:41 -0500 Subject: [PATCH 11/11] Add dialog work in DialogItemTests.swift --- .../DialogItemTests.swift | 374 ++++++++++++++++++ 1 file changed, 374 insertions(+) create mode 100644 Tests/GraphiteDialogsTests/DialogItemTests.swift diff --git a/Tests/GraphiteDialogsTests/DialogItemTests.swift b/Tests/GraphiteDialogsTests/DialogItemTests.swift new file mode 100644 index 0000000..c65ac9b --- /dev/null +++ b/Tests/GraphiteDialogsTests/DialogItemTests.swift @@ -0,0 +1,374 @@ +import Testing +import GraphiteBase +import GraphiteDialogs +import GraphiteWindows +import GraphiteQuickDraw +import GraphiteFiles +import GraphiteResources + +private final class TestDialogHost: DialogHost { + var events: [DialogEvent] = [] + var calls: [String] = [] + func present(_ dialog: Dialog) { calls.append("present") } + func redraw(_ dialog: Dialog) { calls.append("redraw") } + func nextEvent(for dialog: Dialog) -> DialogEvent? { events.isEmpty ? nil : events.removeFirst() } + func dismiss(_ dialog: Dialog) { calls.append("dismiss") } + func playAlertSound(_ number: Int) { calls.append("sound\(number)") } +} + +@Suite struct DialogItemTests { + + @Test func kinds() { + // The type byte's low seven bits, as the item list keeps them. + #expect(DialogItemKind.userItem.rawValue == 0) + #expect(DialogItemKind.helpItem.rawValue == 1) + #expect(DialogItemKind.button.rawValue == 4) + #expect(DialogItemKind.checkBox.rawValue == 5) + #expect(DialogItemKind.radioButton.rawValue == 6) + #expect(DialogItemKind.control.rawValue == 7) + #expect(DialogItemKind.staticText.rawValue == 8) + #expect(DialogItemKind.editText.rawValue == 16) + #expect(DialogItemKind.icon.rawValue == 32) + #expect(DialogItemKind.picture.rawValue == 64) + #expect(DialogItemKind.disableBit == 128) + // The enable flag is the type byte's high bit, set for disabled. + let enabled = DialogItemKind.from(typeByte: 4) + #expect(enabled.kind == .button && enabled.isEnabled) + let disabled = DialogItemKind.from(typeByte: 4 | 128) + #expect(disabled.kind == .button && !disabled.isEnabled) + #expect(DialogItemKind.typeByte(.editText, isEnabled: true) == 16) + #expect(DialogItemKind.typeByte(.editText, isEnabled: false) == 16 | 128) + // An unknown type is a user item, as the Dialog Manager's 0 was. + #expect(DialogItemKind.from(typeByte: 99).kind == .userItem) + // What each kind keeps. + #expect(DialogItemKind.button.hasTitle && DialogItemKind.checkBox.hasTitle) + #expect(DialogItemKind.radioButton.hasTitle && !DialogItemKind.staticText.hasTitle) + #expect(DialogItemKind.staticText.hasText && DialogItemKind.editText.hasText) + #expect(!DialogItemKind.icon.hasText) + #expect(DialogItemKind.control.hasResource && DialogItemKind.icon.hasResource) + #expect(DialogItemKind.picture.hasResource && !DialogItemKind.button.hasResource) + #expect(DialogItemKind.userItem.isUserDrawn && !DialogItemKind.button.isUserDrawn) + } + + @Test func items() { + let item = DialogItem(bounds: Rect(top: 10, left: 20, bottom: 30, right: 120), kind: .button, text: "OK") + #expect(item.typeByte == 4) + #expect(item.isEnabled) + #expect(item.resourceID == 0) + #expect(item.contains(Point(v: 20, h: 60))) + #expect(!item.contains(Point(v: 5, h: 60))) + // A disabled item's type byte has the bit. + let disabled = DialogItem(bounds: item.bounds, kind: .button, text: "OK", isEnabled: false) + #expect(disabled.typeByte == 4 | 128) + } + + // MARK: 'DITL' resources + + /// A 'DITL' resource's bytes, the way Rez compiled one: the count less + /// one, and each item — its reserved long, its rectangle, its type + /// byte, and what its kind keeps. + private func ditlBytes(_ items: [(rect: Rect, type: UInt8, text: String?, resource: Int16?)]) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(UInt16(items.count - 1)) + for item in items { + writer.write(UInt32(0)) + writer.write(item.rect) + writer.write(item.type) + if let text = item.text { + writer.write(PascalString(text)!) + writer.align(to: 2) + } else if let resource = item.resource { + writer.write(UInt8(0)) + writer.write(resource) + } else { + writer.write(UInt8(0)) + } + } + return writer.bytes + } + + @Test func readingItemLists() throws { + // Two buttons and a line of static text, the simplest dialog. + let bytes = ditlBytes([ + (Rect(top: 80, left: 20, bottom: 100, right: 90), 4, "OK", nil), + (Rect(top: 80, left: 110, bottom: 100, right: 180), 4, "Cancel", nil), + (Rect(top: 10, left: 20, bottom: 60, right: 180), 8, "Save changes before closing?", nil), + ]) + let list = try DialogItemList(bytes: bytes) + #expect(list.count == 3) + #expect(list.items[0].kind == .button && list.items[0].text == "OK") + #expect(list.items[1].kind == .button && list.items[1].text == "Cancel") + #expect(list.items[2].kind == .staticText && list.items[2].text == "Save changes before closing?") + let allEnabled = list.items.allSatisfy { $0.isEnabled } + #expect(allEnabled) + #expect(list.item(1)?.text == "OK") + #expect(list.item(3)?.kind == .staticText) + // The numbers count from 1; past either end, none. + #expect(list.item(0) == nil && list.item(4) == nil) + } + + @Test func readingDisabledAndOtherKinds() throws { + // A disabled radio button, an editable text, a control by its + // resource, an icon and a picture. + let bytes = ditlBytes([ + (Rect(top: 10, left: 10, bottom: 30, right: 110), 6 | 128, "Small", nil), + (Rect(top: 40, left: 10, bottom: 58, right: 190), 16, "Untitled", nil), + (Rect(top: 60, left: 10, bottom: 80, right: 190), 7, nil, 128), + (Rect(top: 90, left: 10, bottom: 122, right: 42), 32, nil, 257), + (Rect(top: 90, left: 50, bottom: 122, right: 82), 64, nil, 200), + ]) + let list = try DialogItemList(bytes: bytes) + #expect(list.count == 5) + #expect(list.items[0].kind == .radioButton && !list.items[0].isEnabled) + #expect(list.items[0].text == "Small") + #expect(list.items[1].kind == .editText && list.items[1].text == "Untitled") + #expect(list.items[2].kind == .control && list.items[2].resourceID == 128) + #expect(list.items[3].kind == .icon && list.items[3].resourceID == 257) + #expect(list.items[4].kind == .picture && list.items[4].resourceID == 200) + } + + @Test func readingUserAndHelpItems() throws { + // A user item: a reserved byte after the type byte, no text. + let user = try DialogItemList(bytes: ditlBytes([ + (Rect(top: 0, left: 0, bottom: 40, right: 40), 0, nil, nil), + ])) + #expect(user.items[0].kind == .userItem && user.items[0].text.isEmpty) + #expect(user.items[0].resourceID == 0) + } + + @Test func oddLengthTextIsAligned() throws { + // A title of an odd length has an alignment byte after it, to a + // word boundary: the next item reads where it should. + var writer = BigEndianWriter() + writer.write(UInt16(1)) + writer.write(UInt32(0)) + writer.write(Rect(top: 0, left: 0, bottom: 20, right: 60)) + writer.write(UInt8(4)) + writer.write(PascalString("Yes")) // 1 + 3 bytes: odd, so padded. + writer.align(to: 2) + writer.write(UInt32(0)) + writer.write(Rect(top: 0, left: 0, bottom: 20, right: 60)) + writer.write(UInt8(4)) + writer.write(PascalString("No")) // 1 + 2 bytes: even, no padding. + writer.align(to: 2) + let list = try DialogItemList(bytes: writer.bytes) + #expect(list.count == 2) + #expect(list.items[0].text == "Yes" && list.items[1].text == "No") + } + + @Test func roundTrips() throws { + let items = [ + DialogItem(bounds: Rect(top: 80, left: 20, bottom: 100, right: 90), kind: .button, text: "OK"), + DialogItem(bounds: Rect(top: 10, left: 20, bottom: 60, right: 180), kind: .staticText, text: "Really?"), + DialogItem(bounds: Rect(top: 40, left: 10, bottom: 58, right: 190), kind: .editText, text: ""), + DialogItem(bounds: Rect(top: 60, left: 10, bottom: 80, right: 190), kind: .control, resourceID: 128), + DialogItem(bounds: Rect(top: 0, left: 0, bottom: 20, right: 20), kind: .icon, resourceID: 257), + DialogItem(bounds: Rect(top: 0, left: 0, bottom: 20, right: 20), kind: .userItem), + DialogItem(bounds: Rect(top: 0, left: 0, bottom: 20, right: 20), kind: .checkBox, text: "Bold", isEnabled: false), + ] + let list = DialogItemList(items: items) + let read = try DialogItemList(bytes: list.bytes) + #expect(read.items.map(\.typeByte) == list.items.map(\.typeByte)) + #expect(read.items.map(\.text) == list.items.map(\.text)) + #expect(read.items.map(\.resourceID) == list.items.map(\.resourceID)) + } + + @Test func findingItems() { + // FindDialogItem numbers from 0, and the first item wins where they + // overlap. + var list = DialogItemList() + list.items = [ + DialogItem(bounds: Rect(top: 0, left: 0, bottom: 40, right: 40), kind: .button, text: "One"), + DialogItem(bounds: Rect(top: 20, left: 20, bottom: 60, right: 60), kind: .button, text: "Two"), + ] + #expect(list.findItem(at: Point(v: 5, h: 5)) == 0) + #expect(list.findItem(at: Point(v: 50, h: 50)) == 1) + #expect(list.findItem(at: Point(v: 30, h: 30)) == 0) + #expect(list.findItem(at: Point(v: 100, h: 100)) == nil) + #expect(DialogItemList().findItem(at: .zero) == nil) + } + + @Test func packedAlertStages() throws { + let bytes: [UInt8] = [0, 1, 0, 2, 0, 40, 0, 80, 0, 128, 0xC9, 0x65, 0, 0] + let alert = try AlertResource(bytes: bytes) + #expect(alert.stages.map(\.bits) == [5, 6, 9, 12]) + #expect(alert.stages[0].isDrawn && alert.stages[0].soundCount == 1) + #expect(alert.stages[2].secondItemIsDefault) + #expect(alert.bytes == bytes) + let oldAlert = try AlertResource(bytes: Array(bytes.prefix(12))) + #expect(oldAlert.position == 0) + } + + @Test func emptyItemList() throws { + let list = try DialogItemList(bytes: [0xFF, 0xFF]) + #expect(list.count == 0) + #expect(list.bytes == [0xFF, 0xFF]) + } + + @Test func windowAndControlLifecycle() throws { + let manager = WindowManager(quickDraw: QuickDraw(screens: [GraphicsDevice.screen(width: 640, height: 480)])) + let dialog = Dialog(kind: .modal, bounds: Rect(top: 40, left: 40, bottom: 160, right: 300), items: [ + DialogItem(bounds: Rect(top: 80, left: 20, bottom: 100, right: 90), kind: .button, text: "OK") + ]) + try dialog.attach(to: manager) + #expect(dialog.window?.isVisible == true) + #expect(dialog.control(of: 1)?.title == "OK") + dialog.setText("Save", of: 1) + #expect(dialog.control(of: 1)?.title == "Save") + dialog.hide() + #expect(dialog.window?.isVisible == false) + dialog.show() + #expect(manager.frontWindow === dialog.window) + dialog.dispose() + #expect(manager.windows.isEmpty) + } + + @Test func editingAndStandardAlert() { + let dialog = Dialog(kind: .modal, bounds: Rect(top: 0, left: 0, bottom: 120, right: 300), items: [ + DialogItem(bounds: Rect(top: 10, left: 10, bottom: 30, right: 100), kind: .editText, text: "Old"), + ]) + dialog.selectText(of: 1) + _ = dialog.handle(.key(characters: "New", modifiers: 0)) + #expect(dialog.text(of: 1) == "New") + _ = dialog.handle(.key(characters: "!", modifiers: 0)) + #expect(dialog.text(of: 1) == "New!") + let alert = StandardAlert(kind: .caution, message: "Save?", cancelText: "Cancel", cancelItem: 2).dialog(bounds: dialog.bounds) + #expect(alert.item(1)?.bounds.isEmpty == false) + #expect(alert.item(2)?.bounds.isEmpty == false) + #expect(alert.cancelHit == 2) + } + + @Test func loadsControlResource() throws { + var dlog = BigEndianWriter() + dlog.write(Rect(top: 40, left: 40, bottom: 160, right: 300)) + dlog.write(Int16(1)); dlog.write(UInt8(1)); dlog.write(UInt8(0)) + dlog.write(UInt8(0)); dlog.write(UInt8(0)); dlog.write(Int32(0)); dlog.write(Int16(128)) + dlog.write(PascalString("")); dlog.align(to: 2); dlog.write(UInt16(0)) + let list = DialogItemList(items: [DialogItem(bounds: .zero, kind: .control, resourceID: 200)]) + var cntl = BigEndianWriter() + let controlBounds = Rect(top: 10, left: 10, bottom: 30, right: 90) + cntl.write(controlBounds); cntl.write(Int16(0)); cntl.write(UInt8(1)); cntl.write(UInt8(0)) + cntl.write(Int16(1)); cntl.write(Int16(0)); cntl.write(Int16(0)); cntl.write(Int32(0)) + cntl.write(PascalString("Go")) + let fork = try ResourceMap.write([ + (Resource(type: "DLOG", id: 100), dlog.bytes), + (Resource(type: "DITL", id: 128), list.bytes), + (Resource(type: "CNTL", id: 200), cntl.bytes), + ]) + let chain = ResourceChain(fileSystem: FileSystem(defaultFolder: "/")) + try chain.open(bytes: fork) + let dialog = try Dialog.make(id: 100, resources: chain) + let manager = WindowManager(quickDraw: QuickDraw(screens: [GraphicsDevice.screen(width: 640, height: 480)])) + try dialog.attach(to: manager) + #expect(dialog.control(of: 1)?.bounds == controlBounds) + #expect(dialog.control(of: 1)?.title == "Go") + #expect(dialog.handle(.mouseDown(Point(v: 15, h: 15))) == nil) + #expect(dialog.handle(.mouseUp(Point(v: 15, h: 15))) == 1) + } + + @Test func trackingControls() throws { + let manager = WindowManager(quickDraw: QuickDraw(screens: [GraphicsDevice.screen(width: 640, height: 480)])) + let dialog = Dialog(kind: .modal, bounds: Rect(top: 40, left: 40, bottom: 160, right: 300), items: [ + DialogItem(bounds: Rect(top: 10, left: 10, bottom: 30, right: 90), kind: .button, text: "OK") + ]) + try dialog.attach(to: manager) + #expect(dialog.handle(.mouseDown(Point(v: 15, h: 15))) == nil) + #expect(dialog.handle(.mouseMoved(Point(v: 50, h: 100))) == nil) + #expect(dialog.handle(.mouseUp(Point(v: 50, h: 100))) == nil) + #expect(dialog.handle(.mouseDown(Point(v: 15, h: 15))) == nil) + #expect(dialog.handle(.mouseUp(Point(v: 15, h: 15))) == 1) + } + + @Test func alertStagesAndSound() { + let manager = AlertManager() + let silent = AlertStage(isDrawn: false, soundCount: 1) + let shown = AlertStage(isDrawn: true, soundCount: 2) + let resource = AlertResource(bounds: Rect(top: 0, left: 0, bottom: 100, right: 200), itemListID: 128, + stages: [silent, shown, shown, shown]) + let items = DialogItemList(items: [DialogItem(bounds: .zero, kind: .button, text: "OK")]) + var sounds: [Int] = [] + let first = manager.run(id: 42, resource: resource, items: items, sound: { sounds.append($0) }, next: { nil }) + #expect(first == nil) + let second = manager.run(id: 42, resource: resource, items: items, sound: { sounds.append($0) }, next: { .key(characters: "\r", modifiers: 0) }) + #expect(second == 1) + #expect(sounds == [1, 2]) + #expect(manager.counter.stage == 1) + _ = manager.run(id: 43, resource: resource, items: items, sound: { sounds.append($0) }, next: { nil }) + #expect(manager.counter.stage == 0) + } + + @Test func hostPresentationAndEditing() { + let dialog = Dialog(kind: .modal, bounds: Rect(top: 0, left: 0, bottom: 120, right: 240), items: [ + DialogItem(bounds: .zero, kind: .editText, text: "first"), + DialogItem(bounds: .zero, kind: .editText, text: "second"), + DialogItem(bounds: .zero, kind: .button, text: "OK") + ]) + dialog.advanceTextFocus() + #expect(dialog.keyboardFocus == 1) + #expect(dialog.copyText() == "first") + dialog.pasteText("new") + #expect(dialog.text(of: 1) == "new") + _ = dialog.handle(.key(characters: "\t", modifiers: 0)) + #expect(dialog.keyboardFocus == 2) + #expect(dialog.deleteSelection()) + #expect(dialog.text(of: 2) == "") + dialog.defaultItem = 3 + let host = TestDialogHost() + host.events = [.key(characters: "\r", modifiers: 0)] + #expect(dialog.runModal(host: host) == 3) + #expect(host.calls == ["present", "redraw", "dismiss"]) + #expect(!dialog.isVisible) + } + + @Test func appendingAndHidingItems() throws { + let manager = WindowManager(quickDraw: QuickDraw(screens: [GraphicsDevice.screen(width: 640, height: 480)])) + let dialog = Dialog(kind: .modeless, bounds: Rect(top: 40, left: 40, bottom: 140, right: 240), items: [ + DialogItem(bounds: Rect(top: 10, left: 10, bottom: 30, right: 80), kind: .button, text: "One") + ]) + try dialog.attach(to: manager) + let list = DialogItemList(items: [DialogItem(bounds: Rect(top: 5, left: 5, bottom: 25, right: 55), kind: .button, text: "Two")]) + try dialog.append(list, at: .right) + #expect(dialog.count == 2) + #expect(dialog.itemBounds(2) == Rect(top: 5, left: 205, bottom: 25, right: 255)) + #expect(dialog.window?.contentBounds.right == 295) + dialog.hideItem(2) + #expect(dialog.control(of: 2)?.isVisible == false) + #expect(dialog.hit(at: Point(v: 10, h: 210)) == 0) + dialog.showItem(2) + #expect(dialog.control(of: 2)?.isVisible == true) + try dialog.shorten(by: 1) + #expect(dialog.count == 1) + #expect(dialog.window?.contentBounds.right == 295) + } + + @Test func resourcePositionAndInitialFocus() throws { + let manager = WindowManager(quickDraw: QuickDraw(screens: [GraphicsDevice.screen(width: 640, height: 480)])) + let dialog = Dialog(kind: .modal, bounds: Rect(top: 0, left: 0, bottom: 100, right: 200), items: [ + DialogItem(bounds: Rect(top: 10, left: 10, bottom: 30, right: 100), kind: .editText, text: "Name") + ], position: 0x300A) + try dialog.attach(to: manager) + #expect(dialog.window?.contentBounds == dialog.bounds) + #expect(dialog.bounds.left > 0) + #expect(dialog.keyboardFocus == 1) + #expect(dialog.selectedText[1] == 4..<4) + } + + @Test func damagedItemLists() { + // Cut off inside the count. + #expect(throws: MacError.parameter) { + _ = try DialogItemList(bytes: [0]) + } + // Nothing at all. + #expect(throws: MacError.parameter) { + _ = try DialogItemList(bytes: []) + } + // Two items said, the first cut off inside its rectangle. + #expect(throws: MacError.parameter) { + _ = try DialogItemList(bytes: [0, 1, 0, 0, 0, 0, 0, 10, 0, 20]) + } + // The text cut off: a length of 5 with 2 bytes there. + #expect(throws: MacError.parameter) { + _ = try DialogItemList(bytes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 79, 75]) + } + } +}