From a979ed0a7123e9b8ee5cc96ec079328daabe5017 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:06 -0500 Subject: [PATCH 01/13] Added the Menu Manager's result codes --- Sources/GraphiteBase/MacError.swift | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Sources/GraphiteBase/MacError.swift b/Sources/GraphiteBase/MacError.swift index 372653e..04c2db3 100644 --- a/Sources/GraphiteBase/MacError.swift +++ b/Sources/GraphiteBase/MacError.swift @@ -193,6 +193,8 @@ extension MacError: CustomStringConvertible { -201: "notEnoughHardwareErr", -203: "queueFull", -204: "resProblem", -205: "badChannel", -206: "badFormat", -207: "notEnoughBufferSpace", -208: "badFileFormat", -209: "channelBusy", -210: "buffersTooSmall", -223: "siInvalidCompression", + -5603: "menuPropertyInvalidErr", -5604: "menuPropertyNotFoundErr", -5620: "menuNotFoundErr", + -5621: "menuUsesSystemDefErr", -5622: "menuItemNotFoundErr", -5623: "menuInvalidErr", ] guard let name = names[code] else { return "\(code)" } return "\(name) (\(code))" @@ -225,3 +227,21 @@ public extension MacError { /// manager has. static var invalidCompression: MacError { MacError(-223) } } + +// MARK: - Menu Manager + +public extension MacError { + + /// menuPropertyInvalidErr: an invalid property creator. + static var menuPropertyInvalid: MacError { MacError(-5603) } + /// menuPropertyNotFoundErr: the property wasn't found. + static var menuPropertyNotFound: MacError { MacError(-5604) } + /// menuNotFoundErr: no menu of the ID, or none open to track. + static var menuNotFound: MacError { MacError(-5620) } + /// menuUsesSystemDefErr: the menu's definition can't be had. + static var menuUsesSystemDefinition: MacError { MacError(-5621) } + /// menuItemNotFoundErr: no item of the index or ID. + static var menuItemNotFound: MacError { MacError(-5622) } + /// menuInvalidErr: the menu or its resource is invalid. + static var menuInvalid: MacError { MacError(-5623) } +} From da7b74ada2148c0a9e02be3f1c514f17d413d211 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:06 -0500 Subject: [PATCH 02/13] Added menu items, their marks, styles and the classic's strings --- Sources/GraphiteMenus/MenuItem.swift | 267 +++++++++++++++++++++++++++ 1 file changed, 267 insertions(+) create mode 100644 Sources/GraphiteMenus/MenuItem.swift diff --git a/Sources/GraphiteMenus/MenuItem.swift b/Sources/GraphiteMenus/MenuItem.swift new file mode 100644 index 0000000..e24a344 --- /dev/null +++ b/Sources/GraphiteMenus/MenuItem.swift @@ -0,0 +1,267 @@ +// A menu item: its text, and the furniture the classic gave it — a mark +// (the check mark a chosen item wears, the diamond a chosen style wears), +// an icon, a style, a keyboard equivalent with its modifiers, a command ID +// — and a submenu, kept by its menu's ID, as the classic kept it, for the +// menu list to resolve. + +import GraphiteBase + +/// The style bits of an item's text, as QuickDraw's are: bold 1, italic 2, +/// underline 4, outline 8, shadow 16, condensed 32, extended 64. The +/// classic's '<' metacharacters in an AppendMenu string set the first five. +public struct MenuItemStyle: OptionSet, Hashable, Sendable { + + public var rawValue: UInt8 + + public init(rawValue: UInt8) { + self.rawValue = rawValue + } + + /// Plain, as an item without a style is. + public static var plain: MenuItemStyle { MenuItemStyle() } + /// Bold. + public static var bold: MenuItemStyle { MenuItemStyle(rawValue: 1) } + /// Italic. + public static var italic: MenuItemStyle { MenuItemStyle(rawValue: 2) } + /// Underline. + public static var underline: MenuItemStyle { MenuItemStyle(rawValue: 4) } + /// Outline. + public static var outline: MenuItemStyle { MenuItemStyle(rawValue: 8) } + /// Shadow. + public static var shadow: MenuItemStyle { MenuItemStyle(rawValue: 16) } + /// Condense. + public static var condense: MenuItemStyle { MenuItemStyle(rawValue: 32) } + /// Extend. + public static var extend: MenuItemStyle { MenuItemStyle(rawValue: 64) } +} + +/// The mark an item wears at its left: the Menu Manager's glyph codes, or +/// any character. None until one is set. The check mark (CheckMenuItem) +/// and the diamond are the classic's 18 and 19. +public struct MenuMark: Hashable, Sendable { + + /// The glyph or character, as SetItemMark takes it: 0 is none, 18 the + /// check mark, 19 the diamond, and any other value a character. + public var rawValue: UInt16 + + public init(rawValue: UInt16) { + self.rawValue = rawValue + } + + /// Any character, as MacRoman holds it; nil for one MacRoman doesn't. + public init?(_ character: Character) { + guard let byte = MacRoman.encode(String(character))?.first else { return nil } + self.init(rawValue: UInt16(byte)) + } + + /// noMark. + public static var none: MenuMark { MenuMark(rawValue: 0) } + /// kMenuTabRightGlyph. + public static var tabRight: MenuMark { MenuMark(rawValue: 0x02) } + /// kMenuTabLeftGlyph. + public static var tabLeft: MenuMark { MenuMark(rawValue: 0x03) } + /// kMenuEnterGlyph. + public static var enter: MenuMark { MenuMark(rawValue: 0x04) } + /// kMenuShiftGlyph. + public static var shift: MenuMark { MenuMark(rawValue: 0x05) } + /// kMenuControlGlyph. + public static var control: MenuMark { MenuMark(rawValue: 0x06) } + /// kMenuOptionGlyph. + public static var option: MenuMark { MenuMark(rawValue: 0x07) } + /// kMenuSpaceGlyph. + public static var space: MenuMark { MenuMark(rawValue: 0x09) } + /// kMenuDeleteRightGlyph. + public static var deleteRight: MenuMark { MenuMark(rawValue: 0x0A) } + /// kMenuReturnGlyph. + public static var `return`: MenuMark { MenuMark(rawValue: 0x0B) } + /// kMenuDeleteLeftGlyph. + public static var deleteLeft: MenuMark { MenuMark(rawValue: 0x17) } + /// kMenuEscapeGlyph. + public static var escape: MenuMark { MenuMark(rawValue: 0x1B) } + /// kMenuClearGlyph. + public static var clear: MenuMark { MenuMark(rawValue: 0x1C) } + /// kMenuLeftArrowGlyph. + public static var leftArrow: MenuMark { MenuMark(rawValue: 0x64) } + /// kMenuRightArrowGlyph. + public static var rightArrow: MenuMark { MenuMark(rawValue: 0x65) } + /// kMenuUpArrowGlyph. + public static var upArrow: MenuMark { MenuMark(rawValue: 0x68) } + /// kMenuDownArrowGlyph. + public static var downArrow: MenuMark { MenuMark(rawValue: 0x6A) } + /// kMenuCommandGlyph. + public static var command: MenuMark { MenuMark(rawValue: 0x11) } + /// kMenuCheckmarkGlyph: the mark CheckMenuItem sets. + public static var checkmark: MenuMark { MenuMark(rawValue: 0x12) } + /// kMenuDiamondGlyph. + public static var diamond: MenuMark { MenuMark(rawValue: 0x13) } +} + +/// The modifiers an item's keyboard equivalent is held with +/// (SetMenuItemKeyEquivalentsMask's bits). The Command key is implied: +/// an equivalent works with it held unless noCommand is set. +public struct MenuKeyModifiers: OptionSet, Hashable, Sendable { + + public var rawValue: UInt16 + + public init(rawValue: UInt16) { + self.rawValue = rawValue + } + + /// kMenuNoModifiers. + public static var none: MenuKeyModifiers { MenuKeyModifiers() } + /// kMenuShiftModifier. + public static var shift: MenuKeyModifiers { MenuKeyModifiers(rawValue: 1 << 0) } + /// kMenuOptionModifier. + public static var option: MenuKeyModifiers { MenuKeyModifiers(rawValue: 1 << 1) } + /// kMenuControlModifier. + public static var control: MenuKeyModifiers { MenuKeyModifiers(rawValue: 1 << 2) } + /// kMenuNoCommandModifier: without the Command key. + public static var noCommand: MenuKeyModifiers { MenuKeyModifiers(rawValue: 1 << 3) } +} + +/// A menu's attributes, the bits CreateNewMenu takes. +public struct MenuAttributes: OptionSet, Hashable, Sendable { + + public var rawValue: UInt32 + + public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + /// kMenuAttrExcludesMarkColumn: no room kept for marks. + public static var excludesMarkColumn: MenuAttributes { MenuAttributes(rawValue: 1 << 0) } + /// kMenuAttrAutoDisable: the title is disabled when every item is. + public static var autoDisable: MenuAttributes { MenuAttributes(rawValue: 1 << 2) } + /// kMenuAttrUsePencilGlyph: the pencil drawn for the Control key. + public static var usePencilGlyph: MenuAttributes { MenuAttributes(rawValue: 1 << 3) } + /// kMenuAttrHidden: the title isn't drawn, though the menu is in the + /// bar — for keyboard equivalents nobody sees. + public static var hidden: MenuAttributes { MenuAttributes(rawValue: 1 << 4) } + /// kMenuAttrCondenseSeparators: extra separators at the edges and runs + /// are hidden. + public static var condenseSeparators: MenuAttributes { MenuAttributes(rawValue: 1 << 5) } + /// kMenuAttrDoNotCacheImage. + public static var doNotCacheImage: MenuAttributes { MenuAttributes(rawValue: 1 << 6) } + /// kMenuAttrDoNotUseUserCommandKeys. + public static var doNotUseUserCommandKeys: MenuAttributes { MenuAttributes(rawValue: 1 << 7) } +} + +/// One item of a menu, as the classic's menu record kept it: text and +/// furniture, and the enabled state the enable flags' item bits held. A +/// divider is an item whose text is a hyphen, or one marked a separator; +/// the definition draws it a line. A submenu is kept by its menu's ID, as +/// the mark field of the classic's item records kept it, for the menu list +/// to resolve. +public struct MenuItem: Hashable, Sendable { + + /// The item's text, as GetMenuItemText answers. + public var text: PascalString + + /// SetMenuItemCommandID; 0 is none. + public var commandID: FourCharCode + + /// SetItemMark; none until one is set. + public var mark: MenuMark + + /// SetItemIcon: an icon number, 0 for none. The classic looked for the + /// icon in the resource of the number plus 256. + public var icon: UInt8 + + /// SetItemStyle. + public var style: MenuItemStyle + + /// SetItemCmd: the keyboard equivalent's character, 0 for none. The + /// classic's $1B, $1C, $1D and $1E mark an item with a submenu, a script + /// code, a reduced icon or a small icon instead. + public var key: UInt8 + + /// SetMenuItemKeyEquivalentsMask: what's held with the key. + public var modifiers: MenuKeyModifiers + + /// The menu ID of the item's submenu, 0 for none: the classic kept a + /// submenu by its ID, and the menu list resolves it. + public var submenuID: Int16 + + /// kMenuItemAttrSeparator: a divider line. An item whose text is a + /// hyphen is one, as the classic's were. + public var isSeparator: Bool + + /// EnableMenuItem's answer for this item. + public var isEnabled: Bool + + public init(text: PascalString = PascalString(), commandID: FourCharCode = FourCharCode(rawValue: 0), + mark: MenuMark = .none, icon: UInt8 = 0, style: MenuItemStyle = .plain, key: UInt8 = 0, + modifiers: MenuKeyModifiers = .none, submenuID: Int16 = 0, + isSeparator: Bool = false, isEnabled: Bool = true) { + self.text = text + self.commandID = commandID + self.mark = mark + self.icon = icon + self.style = style + self.key = key + self.modifiers = modifiers + self.submenuID = submenuID + self.isSeparator = isSeparator + self.isEnabled = isEnabled + } + + /// The item the classic's AppendMenu metacharacters make: `(` disables, + /// `<` is followed by B, I, U, O and S for the style bits, `!` is + /// followed by a mark, `^` by an icon, `/` by the keyboard equivalent + /// and ends the text. What's left, in MacRoman, is the item's text; a + /// hyphen alone divides. + /// + /// An item with a submenu keeps the submenu's menu ID in its mark, as + /// the classic kept it, with $1B for the key: the item "Size!9" with + /// the character 27 after the slash has the menu of ID 9 for its + /// submenu. + public init(classic data: Substring) { + self.init() + var text: [UInt8] = [] + var mark: UInt16 = 0 + var characters = data.makeIterator() + var held: Character? + items: while let character = held ?? characters.next() { + held = nil + switch character { + case "(": + isEnabled = false + case "<": + styles: while let next = characters.next() { + switch next { + case "B": style.insert(.bold) + case "I": style.insert(.italic) + case "U": style.insert(.underline) + case "O": style.insert(.outline) + case "S": style.insert(.shadow) + default: held = next; continue items + } + } + case "!": + if let next = characters.next() { mark = UInt16(Self.byte(of: next)) } + case "^": + if let next = characters.next() { icon = Self.byte(of: next) } + case "/": + if let next = characters.next() { key = Self.byte(of: next) } + break items + default: + if let byte = MacRoman.encode(String(character))?.first { text.append(byte) } + } + } + self.text = PascalString(bytes: text) + isSeparator = self.text.bytes == [UInt8(ascii: "-")] + self.mark = MenuMark(rawValue: mark) + // The $1B keyboard equivalent stands for a submenu, whose menu ID + // the mark held. + if key == 0x1B { + submenuID = Int16(bitPattern: UInt16(truncatingIfNeeded: mark)) + self.mark = .none + } + } + + /// A character as the classic's byte-oriented fields kept it: its + /// MacRoman byte, 0 for a character MacRoman doesn't have. + private static func byte(of character: Character) -> UInt8 { + MacRoman.encode(String(character))?.first ?? 0 + } +} From 6c1ea4a484f5599cf29c6511f04bc447443621ad Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:06 -0500 Subject: [PATCH 03/13] Added menu definitions and the standard look --- Sources/GraphiteMenus/MenuDefinition.swift | 84 ++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Sources/GraphiteMenus/MenuDefinition.swift diff --git a/Sources/GraphiteMenus/MenuDefinition.swift b/Sources/GraphiteMenus/MenuDefinition.swift new file mode 100644 index 0000000..093a878 --- /dev/null +++ b/Sources/GraphiteMenus/MenuDefinition.swift @@ -0,0 +1,84 @@ +// Menu definitions, the MDEFs, as Swift sees them: the sizes of a menu +// — how tall the bar is, how tall an item, how wide the columns of marks, +// icons and keys — and where an item sits, so the host can draw them. The +// standard definition is the classic's look. Drawing is the host's; the +// definition answers mSizeMsg's and mChooseMsg's questions. + +import GraphiteBase + +/// A menu definition procedure: the shape of a menu and its items, as the +/// Menu Manager asked and the host draws. mSizeMsg's width and height are +/// its sizes; mChooseMsg's geometry is where an item is and which a point +/// is on. +public protocol MenuDefinition: Sendable { + + /// How tall the menu bar is. + var menuBarHeight: Int16 { get } + + /// How tall one item is. + var itemHeight: Int16 { get } + + /// mSizeMsg's height: a menu of so many items. + func menuHeight(itemCount: Int) -> Int16 + + /// mSizeMsg's width: room for the item texts, measured by `measuring`, + /// and a column each for the marks, icons and keyboard equivalents that + /// are there. `attributes` says what the menu does without: one that + /// excludes the mark column keeps none for it. + func menuWidth(of items: [MenuItem], attributes: MenuAttributes, + measuring: (_ text: PascalString) -> Int16) -> Int16 + + /// The rectangle an item occupies in a menu's bounds. + func itemRect(at index: Int, in bounds: Rect) -> Rect + + /// mChooseMsg: the item a point of the menu is on, nil for none. + func hitTest(_ point: Point, in bounds: Rect, itemCount: Int) -> Int? +} + +/// 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 +/// equivalent that the menu's items use, two pixels of margin around. +public struct StandardMenuDefinition: MenuDefinition { + + /// The height of a mark's, an icon's or a key's column. + private static let columnWidth: Int16 = 16 + + /// The margin around a menu. + private static let margin: Int16 = 2 + + public init() {} + + public var menuBarHeight: Int16 { 20 } + + public var itemHeight: Int16 { 16 } + + public func menuHeight(itemCount: Int) -> Int16 { + Int16(clamping: itemCount) * itemHeight + } + + public func menuWidth(of items: [MenuItem], attributes: MenuAttributes, + measuring: (_ text: PascalString) -> Int16) -> Int16 { + var width = Self.margin + if items.contains(where: { $0.icon != 0 }) { width += Self.columnWidth } + if !attributes.contains(.excludesMarkColumn), items.contains(where: { $0.mark != .none }) { + width += Self.columnWidth + } + let text = items.map { measuring($0.text) }.max() ?? 0 + width += text + if items.contains(where: { $0.key != 0 && $0.key != 0x1B }) { width += Self.columnWidth } + width += Self.margin + return width + } + + public func itemRect(at index: Int, in bounds: Rect) -> Rect { + let top = bounds.top + Int16(clamping: index) * itemHeight + return Rect(top: top, left: bounds.left, bottom: top + itemHeight, right: bounds.right) + } + + public func hitTest(_ point: Point, in bounds: Rect, itemCount: Int) -> Int? { + guard bounds.contains(point) else { return nil } + let index = (Int(point.v) - Int(bounds.top)) / Int(itemHeight) + guard index >= 0, index < itemCount else { return nil } + return index + } +} From 16295fff6a12730055e090bd042d66d9bbcd371b Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:06 -0500 Subject: [PATCH 04/13] Added menus, their items and keyboard equivalents --- Sources/GraphiteMenus/Menu.swift | 157 +++++++++++++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 Sources/GraphiteMenus/Menu.swift diff --git a/Sources/GraphiteMenus/Menu.swift b/Sources/GraphiteMenus/Menu.swift new file mode 100644 index 0000000..e38cb44 --- /dev/null +++ b/Sources/GraphiteMenus/Menu.swift @@ -0,0 +1,157 @@ +// A menu: its title, its menu ID, and its items, with the calls the classic +// made of them — AppendMenu's metacharacter string, CheckMenuItem's mark, +// EnableMenuItem, the keyboard equivalents MenuKey finds, and the command +// IDs Carbon gave items. NewMenu makes one; CreateNewWindow's generation, +// CreateNewMenu, takes attributes too. The host draws it; the definition +// gives the sizes. + +import GraphiteBase + +public final class Menu { + + /// The menu's ID, as NewMenu takes it and the classic's menu list + /// knows it by: positive for an application's, negative for a desk + /// accessory's, 0 Apple's own. Submenus are 1 through 255. + public let menuID: Int16 + + /// SetMenuTitle and GetMenuTitle. + public var title: PascalString + + /// The attributes CreateNewMenu takes; ChangeMenuAttributes changes. + public private(set) var attributes: MenuAttributes + + /// The shape of the menu and its items, for the host that draws them. + public let definition: any MenuDefinition + + /// The menu's items, top to bottom. Items are numbered from 0, as an + /// array's are; the classic numbered them from 1, which is the layer + /// that exports Carbon's business. + public private(set) var items: [MenuItem] + + /// The menu's own enabled state — the enable flags' bit 0. A disabled + /// menu's items draw dimmed, whatever their own states. + public var isEnabled = true + + /// NewMenu, and CreateNewMenu with its attributes. + public init(menuID: Int16, title: PascalString, attributes: MenuAttributes = [], + definition: (any MenuDefinition)? = nil) { + self.menuID = menuID + self.title = title + self.attributes = attributes + self.definition = definition ?? StandardMenuDefinition() + items = [] + } + + /// CountMenuItems. + public var count: Int { items.count } + + // MARK: Items + + /// AppendMenuItemText: an item at the end. + public func append(_ item: MenuItem) { + items.append(item) + } + + /// AppendMenu: one item for every semicolon-separated part of the + /// string, each read as the classic's metacharacters made it. Blank + /// parts make blank items, as the classic's did; an empty string + /// makes none. + public func append(classic data: String) { + for part in splitItems(data) { + append(MenuItem(classic: part)) + } + } + + /// InsertMenuItem: an item at an index, the rest pushed down. + public func insert(_ item: MenuItem, at index: Int) { + let index = min(max(0, index), items.count) + items.insert(item, at: index) + } + + /// DeleteMenuItem. + public func remove(at index: Int) { + guard items.indices.contains(index) else { return } + items.remove(at: index) + } + + /// DeleteMenuItems. + public func remove(in range: Range) { + let range = range.clamped(to: items.indices) + guard !range.isEmpty else { return } + items.removeSubrange(range) + } + + /// DeleteAllMenuItems. + public func removeAll() { + items.removeAll() + } + + /// GetMenuItemText, and SetMenuItemText, SetItemMark, SetItemIcon, + /// SetItemStyle, SetItemCmd: reading an item, and changing it, whole. + public subscript(index: Int) -> MenuItem { + get { items[index] } + set { items[index] = newValue } + } + + /// GetIndMenuItemWithCommandID, this menu alone: the first item of the + /// command ID, nil if there is none. + public func index(ofCommandID commandID: FourCharCode) -> Int? { + items.firstIndex { $0.commandID == commandID && commandID.rawValue != 0 } + } + + /// The first item of a command ID, nil if there is none. + public func item(withCommandID commandID: FourCharCode) -> MenuItem? { + index(ofCommandID: commandID).map { items[$0] } + } + + /// SetItemMark. + public func setMark(_ mark: MenuMark, at index: Int) { + items[index].mark = mark + } + + /// CheckMenuItem: the check mark, or none. + public func check(_ checked: Bool, at index: Int) { + items[index].mark = checked ? .checkmark : .none + } + + /// EnableMenuItem. + public func setEnabled(_ enabled: Bool, at index: Int) { + items[index].isEnabled = enabled + } + + /// IsMenuItemEnabled: the item's own state. + public func isEnabled(at index: Int) -> Bool { + items[index].isEnabled + } + + /// SetMenuItemKeyEquivalent. + public func setKeyEquivalent(_ key: UInt8, modifiers: MenuKeyModifiers, at index: Int) { + items[index].key = key + items[index].modifiers = modifiers + } + + // MARK: Finding by key + + /// The first enabled item whose keyboard equivalent is the character + /// held with these modifiers — the part of MenuKey a menu answers + /// alone. + public func index(ofKey key: UInt8, modifiers: MenuKeyModifiers) -> Int? { + items.firstIndex { + $0.isEnabled && $0.key == key && $0.modifiers == modifiers && $0.key != 0 + } + } + + // MARK: Attributes + + /// ChangeMenuAttributes. + public func changeAttributes(add: MenuAttributes = [], remove: MenuAttributes = []) { + attributes.subtract(remove) + attributes.formUnion(add) + } + + /// The parts an AppendMenu string holds items in: split on + /// semicolons, as the classic split them. + private func splitItems(_ data: String) -> [Substring] { + data.isEmpty ? [] : data.split(separator: ";", omittingEmptySubsequences: false) + } +} From aa35a2233db34be6cce15046aca09ea28a3ef8d0 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:06 -0500 Subject: [PATCH 05/13] Added the menu bar, its list and MenuKey --- Sources/GraphiteMenus/MenuBar.swift | 172 ++++++++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 Sources/GraphiteMenus/MenuBar.swift diff --git a/Sources/GraphiteMenus/MenuBar.swift b/Sources/GraphiteMenus/MenuBar.swift new file mode 100644 index 0000000..27e3032 --- /dev/null +++ b/Sources/GraphiteMenus/MenuBar.swift @@ -0,0 +1,172 @@ +// The menu bar: the menus across it, left to right, and the menus held in +// the menu list without a title in the bar — the submenus and pop-up menus +// InsertMenu keeps with hierMenu. InsertMenu puts one before another by +// menu ID, or after them all; DeleteMenu takes one out by its ID; +// GetMenuHandle finds one of either kind. MenuKey looks through them all +// for a keyboard equivalent. The host draws the bar — DrawMenuBar and +// InvalMenuBar tell it the bar changed — and tracks the choices, which +// MenuSelect answers as a menu ID and an item's number. + +import GraphiteBase + +/// What a menu choice was: the menu's ID and the item chosen, numbered +/// from 1 as MenuSelect and MenuChoice answered (0 for none). +public struct MenuSelection: Hashable, Sendable { + + public var menuID: Int16 + + /// The item's number, from 1; 0 for no choice. + public var itemIndex: Int16 + + public init(menuID: Int16, itemIndex: Int16) { + self.menuID = menuID + self.itemIndex = itemIndex + } + + /// MenuSelect's answer when nothing was chosen. + public static var none: MenuSelection { MenuSelection(menuID: 0, itemIndex: 0) } + + public var isNone: Bool { menuID == 0 && itemIndex == 0 } +} + +public final class MenuBar { + + /// The menus across the bar, left to right. + public private(set) var menus: [Menu] + + /// The menus InsertMenu keeps with hierMenu (-1): in the menu list, + /// for MenuKey to find and submenus to resolve, with no title in the + /// bar. + public private(set) var hierarchicalMenus: [Menu] + + /// ShowMenuBar and HideMenuBar; a bar nobody sees draws nothing, but + /// MenuKey finds its items as ever. + public var isShown = true + + /// The menu HiliteMenu named, 0 for none. HiliteMenu(0) unhilites. + public internal(set) var hilitedMenuID: Int16 = 0 + + /// DrawMenuBar and InvalMenuBar: the bar changed, and the host draws + /// it again. + public var changeObserver: ((MenuBar) -> Void)? + + public init() { + menus = [] + hierarchicalMenus = [] + } + + /// How many menus are across the bar. + public var count: Int { menus.count } + + /// The menus in the list, bar first then hierarchical, as GetMenuHandle + /// and MenuKey look through them. + public var listed: [Menu] { menus + hierarchicalMenus } + + // MARK: Inserting and removing + + /// InsertMenu: a menu before the menu of `beforeID`'s ID; 0, or the ID + /// of no menu in the list, puts it after them all; -1 (hierMenu) keeps + /// it in the list without a title in the bar. A menu already in the + /// list isn't moved. + public func insert(_ menu: Menu, beforeID: Int16) { + guard !listed.contains(where: { $0 === menu }) else { return } + if beforeID == -1 { + hierarchicalMenus.append(menu) + } else if let index = menus.firstIndex(where: { $0.menuID == beforeID }) { + menus.insert(menu, at: index) + } else { + menus.append(menu) + } + changed() + } + + /// DeleteMenu: the menu of the ID is gone from the bar and the + /// hierarchical list both. A menu of no ID that is there does nothing. + public func remove(menuID: Int16) { + menus.removeAll { $0.menuID == menuID } + hierarchicalMenus.removeAll { $0.menuID == menuID } + if hilitedMenuID == menuID { hilitedMenuID = 0 } + changed() + } + + /// ClearMenuBar: every menu, in the bar and in the list. + public func clear() { + menus.removeAll() + hierarchicalMenus.removeAll() + hilitedMenuID = 0 + changed() + } + + // MARK: Finding + + /// GetMenuHandle: the menu of an ID, in the bar or the hierarchical + /// list. + public func menu(id: Int16) -> Menu? { + listed.first { $0.menuID == id } + } + + /// The menu an item's submenu ID names, as the classic's menu list + /// resolved a submenu: in the bar or the hierarchical list. + public func submenu(of item: MenuItem) -> Menu? { + item.submenuID == 0 ? nil : menu(id: item.submenuID) + } + + /// GetIndMenuItemWithCommandID: the first item of the command ID in + /// any menu in the list, with its menu. + public func find(commandID: FourCharCode) -> (menu: Menu, index: Int)? { + for menu in listed { + if let index = menu.index(ofCommandID: commandID) { + return (menu, index) + } + } + return nil + } + + /// EnableMenuCommand and DisableMenuCommand: the item of the command + /// ID, in any menu in the list. Returns false when there is none. + @discardableResult + public func setEnabled(_ enabled: Bool, commandID: FourCharCode) -> Bool { + guard let found = find(commandID: commandID) else { return false } + found.menu.setEnabled(enabled, at: found.index) + return true + } + + /// IsMenuCommandEnabled: the item of the command ID, and its state; + /// false when there is none. + public func isEnabled(commandID: FourCharCode) -> Bool { + guard let found = find(commandID: commandID) else { return false } + return found.menu.isEnabled(at: found.index) + } + + /// MenuKey: the choice an enabled item's keyboard equivalent makes, + /// in the bar's menus and the hierarchical list alike — the classic + /// searched them all, even submenus no item used. The item's + /// modifiers are what the search holds; the Command key is implied + /// unless the item says noCommand. + public func find(key: UInt8, modifiers: MenuKeyModifiers = .none) -> MenuSelection? { + for menu in listed where menu.isEnabled { + if let index = menu.index(ofKey: key, modifiers: modifiers) { + return MenuSelection(menuID: menu.menuID, itemIndex: Int16(index + 1)) + } + } + return nil + } + + /// HiliteMenu: the menu of the ID is drawn hilited in the bar; 0 + /// unhilites. An ID no menu has unhilites too. + public func hilite(menuID: Int16) { + hilitedMenuID = menuID == 0 || listed.contains { $0.menuID == menuID } ? menuID : 0 + } + + // MARK: The bar the host draws + + /// DrawMenuBar and InvalMenuBar: the bar changed. + public func draw() { + changeObserver?(self) + } + + /// ShowMenuBar and HideMenuBar's work. + private func changed() { + changeObserver?(self) + } +} From 94c2a5eb6d4e51534b16be4b6bbedcfb2a4520b5 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:06 -0500 Subject: [PATCH 06/13] Added reading MENU resources --- Sources/GraphiteMenus/MenuResource.swift | 64 ++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Sources/GraphiteMenus/MenuResource.swift diff --git a/Sources/GraphiteMenus/MenuResource.swift b/Sources/GraphiteMenus/MenuResource.swift new file mode 100644 index 0000000..fb18fea --- /dev/null +++ b/Sources/GraphiteMenus/MenuResource.swift @@ -0,0 +1,64 @@ +// Reading a 'MENU' resource, as GetMenu read one: the menu's ID, the +// placeholders the Menu Manager filled with the menu's size, the resource +// ID of the menu definition procedure, the enabled flags of the menu and +// its first 31 items, the title, and the items — each its text and its +// icon, keyboard equivalent, mark and style, ended by a zero byte. A +// submenu an item has, the mark field keeping the submenu's menu ID with +// $1B for the key, reads as the classic kept it. + +import GraphiteBase +import struct Foundation.Data +import protocol Foundation.ContiguousBytes + +public extension Menu { + + /// GetMenu: a menu from a 'MENU' resource's bytes. menuInvalidErr for + /// bytes a menu can't be read from. Bytes past the last item are + /// ignored, as the classic's GetMenu ignored them. + convenience init(bytes: some ContiguousBytes) throws(MacError) { + var reader = BigEndianReader(bytes) + do { + let menuID = try reader.read(Int16.self) + _ = try reader.read(Int16.self) // menuWidth, a placeholder GetMenu filled in. + _ = try reader.read(Int16.self) // menuHeight. + _ = try reader.read(Int16.self) // The definition procedure's resource ID; 0 the standard one's. + _ = try reader.read(Int16.self) // A placeholder. + let enabledFlags = try reader.read(UInt32.self) + let title = try reader.readPascalString() + self.init(menuID: menuID, title: title) + var number = 0 + while true { + // An item's text length, 0 the end of the items. + guard try reader.peek(UInt8.self, at: reader.offset) != 0 else { + _ = try reader.read(UInt8.self) + break + } + number += 1 + var item = MenuItem(text: try reader.readPascalString()) + // The standard definition draws an item whose text is a + // hyphen as a divider line. + item.isSeparator = item.text.bytes == [UInt8(ascii: "-")] + item.icon = try reader.read(UInt8.self) + item.key = try reader.read(UInt8.self) + let mark = try reader.read(UInt8.self) + item.style = MenuItemStyle(rawValue: try reader.read(UInt8.self)) + // The enable flags' bit 0 is the menu's own; item i's is bit + // i, and past 31 they are enabled, as the Menu Manager made + // them. + item.isEnabled = number <= 31 ? enabledFlags >> number & 1 == 1 : true + if item.key == 0x1B { + // The mark field keeps the submenu's menu ID, with $1B + // for the key. + item.submenuID = Int16(mark) + item.mark = .none + } else { + item.mark = MenuMark(rawValue: UInt16(mark)) + } + append(item) + } + isEnabled = enabledFlags & 1 == 1 + } catch { + throw MacError.menuInvalid + } + } +} From ffe01b6eb605d487673b9335e0762c5d16394e00 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:26 -0500 Subject: [PATCH 07/13] Added the GraphiteMenus module --- Package.swift | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 1208668..31bec9b 100644 --- a/Package.swift +++ b/Package.swift @@ -77,6 +77,10 @@ let package = Package( .library( name: "GraphiteWindows", targets: ["GraphiteWindows"] + ), + .library( + name: "GraphiteMenus", + targets: ["GraphiteMenus"] ) ], // FreeType reads outline fonts; builds without it keep the bitmap font. @@ -136,9 +140,13 @@ let package = Package( name: "GraphiteWindows", dependencies: ["GraphiteBase", "GraphiteQuickDraw"] ), + .target( + name: "GraphiteMenus", + dependencies: ["GraphiteBase"] + ), .target( name: "Graphite", - dependencies: ["GraphiteBase", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAppleEvents", "GraphiteQuickDraw", "GraphiteText", "GraphiteSound", "GraphiteWindows"] + dependencies: ["GraphiteBase", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAppleEvents", "GraphiteQuickDraw", "GraphiteText", "GraphiteSound", "GraphiteWindows", "GraphiteMenus"] ), .testTarget( name: "GraphiteBaseTests", @@ -175,6 +183,10 @@ let package = Package( .testTarget( name: "GraphiteWindowsTests", dependencies: ["GraphiteWindows", "GraphiteQuickDraw"] + ), + .testTarget( + name: "GraphiteMenusTests", + dependencies: ["GraphiteMenus"] ) ] ) From 276a3625bc480048e7d22d5ace255abac430c021 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:26 -0500 Subject: [PATCH 08/13] Re-exported GraphiteMenus --- Sources/Graphite/Graphite.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/Graphite/Graphite.swift b/Sources/Graphite/Graphite.swift index 6633d8f..4fb0e64 100644 --- a/Sources/Graphite/Graphite.swift +++ b/Sources/Graphite/Graphite.swift @@ -10,3 +10,4 @@ @_exported import GraphiteText @_exported import GraphiteSound @_exported import GraphiteWindows +@_exported import GraphiteMenus From cb47281ce416b4bbfede448b8d9b0088d090a4e8 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:26 -0500 Subject: [PATCH 09/13] Tested items, classic strings and resources --- Tests/GraphiteMenusTests/MenuTests.swift | 288 +++++++++++++++++++++++ 1 file changed, 288 insertions(+) create mode 100644 Tests/GraphiteMenusTests/MenuTests.swift diff --git a/Tests/GraphiteMenusTests/MenuTests.swift b/Tests/GraphiteMenusTests/MenuTests.swift new file mode 100644 index 0000000..c598521 --- /dev/null +++ b/Tests/GraphiteMenusTests/MenuTests.swift @@ -0,0 +1,288 @@ +import Testing +import GraphiteBase +import GraphiteMenus + +@Suite struct MenuTests { + + // MARK: Constants + + @Test func constants() { + #expect(MenuItemStyle.bold.rawValue == 1) + #expect(MenuItemStyle.italic.rawValue == 2) + #expect(MenuItemStyle.underline.rawValue == 4) + #expect(MenuItemStyle.outline.rawValue == 8) + #expect(MenuItemStyle.shadow.rawValue == 16) + #expect(MenuItemStyle(rawValue: 32) == .condense) + #expect(MenuItemStyle(rawValue: 64) == .extend) + #expect(MenuItemStyle(rawValue: 0) == .plain) + #expect(MenuMark.none.rawValue == 0) + #expect(MenuMark.checkmark.rawValue == 0x12) + #expect(MenuMark.diamond.rawValue == 0x13) + #expect(MenuMark.command.rawValue == 0x11) + #expect(MenuMark.shift.rawValue == 0x05) + #expect(MenuMark.option.rawValue == 0x07) + #expect(MenuMark.escape.rawValue == 0x1B) + #expect(MenuMark.downArrow.rawValue == 0x6A) + #expect(MenuMark("√").map(\.rawValue) == 0xC3) + #expect(MenuMark("€")?.rawValue == 0xDB) + #expect(MenuKeyModifiers.shift.rawValue == 1) + #expect(MenuKeyModifiers.option.rawValue == 2) + #expect(MenuKeyModifiers.control.rawValue == 4) + #expect(MenuKeyModifiers.noCommand.rawValue == 8) + #expect(MenuAttributes.excludesMarkColumn.rawValue == 1) + #expect(MenuAttributes.autoDisable.rawValue == 4) + #expect(MenuAttributes.hidden.rawValue == 16) + #expect(MenuAttributes(rawValue: 1 << 5) == .condenseSeparators) + } + + // MARK: The classic's AppendMenu strings + + @Test func classicItems() { + // The text alone: an enabled item, plain, with no furniture. + var item = MenuItem(classic: "About SurfWriter…") + #expect(item.text == "About SurfWriter…") + #expect(item.isEnabled && item.mark == .none && item.key == 0 && item.icon == 0) + #expect(item.style == .plain && item.commandID == FourCharCode(rawValue: 0) && item.submenuID == 0) + #expect(!item.isSeparator) + // A hyphen divides. + item = MenuItem(classic: "-") + #expect(item.isSeparator && item.text == "-") + // '(' disables; an item can be a divider and disabled. + item = MenuItem(classic: "(-") + #expect(item.isSeparator && !item.isEnabled) + // '/' names the keyboard equivalent, and ends the item. + item = MenuItem(classic: "Cut/X") + #expect(item.text == "Cut" && item.key == UInt8(ascii: "X")) + // '<' is followed by the style letters B, I, U, O and S, as many as + // come; they are greedy, so a text that starts with one needs it + // held back, as an AppendMenu string kept the classic's own. + item = MenuItem(classic: " [UInt8] { + var bytes: [UInt8] = [] + bytes += [UInt8(UInt16(bitPattern: id) >> 8), UInt8(UInt16(bitPattern: id) & 0xFF)] + bytes += [0, 0, 0, 0, 0, 0, 0, 0] // width, height, definition ID, placeholder + bytes += [UInt8(enabledFlags >> 24 & 0xFF), UInt8(enabledFlags >> 16 & 0xFF), + UInt8(enabledFlags >> 8 & 0xFF), UInt8(enabledFlags & 0xFF)] + let titleBytes = MacRoman.encode(title)! + bytes += [UInt8(titleBytes.count)] + titleBytes + for item in items { + let textBytes = MacRoman.encode(item.text)! + bytes += [UInt8(textBytes.count)] + textBytes + bytes += [item.icon, item.key, item.mark, item.style] + } + bytes += [0] + return bytes + } + + @Test func readingResources() throws { + // The Apple menu of the manual's listing — whose Rez bit string + // reads its low bit first — with the menu enabled, the About item + // enabled, the divider disabled. + let bytes = menuBytes(id: 128, enabledFlags: 0xFFFF_FFFB, title: "apple", items: [ + ("About SurfWriter…", 0, 0, 0, 0), + ("-", 0, 0, 0, 0), + ]) + let menu = try Menu(bytes: bytes) + #expect(menu.menuID == 128) + #expect(menu.title == "apple") + #expect(menu.isEnabled) + #expect(menu.count == 2) + #expect(menu[0].text == "About SurfWriter…" && menu[0].isEnabled) + #expect(menu[1].isSeparator && !menu[1].isEnabled) + // An item's furniture: icon, key, mark and style. + let edit = try Menu(bytes: menuBytes(id: 3, enabledFlags: 1, title: "Edit", items: [ + ("Bold", 1, 66, 18, 1), + ])) + #expect(edit[0].icon == 1) + #expect(edit[0].key == UInt8(ascii: "B")) + #expect(edit[0].mark == .checkmark) + #expect(edit[0].style == .bold) + // Bit 0 the menu's own state: a disabled menu. + let disabled = try Menu(bytes: menuBytes(id: 4, enabledFlags: 0, title: "Edit", items: [ + ("Cut", 0, 0, 0, 0), + ])) + #expect(!disabled.isEnabled) + #expect(disabled[0].isEnabled == false) + // Items past the first 31 are enabled, whatever the flags. + let many = (0..<35).map { ("Item \($0)", UInt8(0), UInt8(0), UInt8(0), UInt8(0)) } + let long = try Menu(bytes: menuBytes(id: 5, enabledFlags: 0, title: "Long", items: many)) + #expect(long.count == 35) + #expect(!long[0].isEnabled) + #expect(!long[30].isEnabled) + #expect(long[31].isEnabled && long[34].isEnabled) + // A submenu, kept as the classic kept it: $1B for the key, the + // menu ID in the mark field. + let size = try Menu(bytes: menuBytes(id: 6, enabledFlags: 1, title: "Font", items: [ + ("Sizes", 0, 0x1B, 9, 0), + ])) + #expect(size[0].submenuID == 9) + #expect(size[0].mark == .none) + #expect(size[0].key == 0x1B) + // An 'mctb' after the items is ignored, as GetMenu ignored one. + var withExtra = menuBytes(id: 7, enabledFlags: 1, title: "File", items: [ + ("New", 0, 0, 0, 0), + ]) + withExtra += [0, 128] + let ignoring = try Menu(bytes: withExtra) + #expect(ignoring.count == 1 && ignoring[0].text == "New") + } + + @Test func damagedResources() { + // Cut off inside the enable flags, before any title. + #expect(throws: MacError.menuInvalid) { + _ = try Menu(bytes: [0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) + } + // Nothing at all. + #expect(throws: MacError.menuInvalid) { + _ = try Menu(bytes: []) + } + // An item cut off in the middle of its bytes. + #expect(throws: MacError.menuInvalid) { + _ = try Menu(bytes: [0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 72, 101, 121]) + } + // The last item's bytes cut short. + #expect(throws: MacError.menuInvalid) { + _ = try Menu(bytes: [0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 72, 101, 121, 0, 0, 0]) + } + } +} From b093aa3ed555486f4613327d6031713682d575a4 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:26 -0500 Subject: [PATCH 10/13] Tested the bar, its menus and keys --- Tests/GraphiteMenusTests/MenuBarTests.swift | 175 ++++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 Tests/GraphiteMenusTests/MenuBarTests.swift diff --git a/Tests/GraphiteMenusTests/MenuBarTests.swift b/Tests/GraphiteMenusTests/MenuBarTests.swift new file mode 100644 index 0000000..7e158b9 --- /dev/null +++ b/Tests/GraphiteMenusTests/MenuBarTests.swift @@ -0,0 +1,175 @@ +import Testing +import GraphiteBase +import GraphiteMenus + +@Suite struct MenuBarTests { + + private func makeAppleMenu() -> Menu { + Menu(menuID: 128, title: "") + } + + @Test func inserting() { + let bar = MenuBar() + #expect(bar.count == 0 && bar.listed.isEmpty) + let apple = makeAppleMenu() + let file = Menu(menuID: 129, title: "File") + let edit = Menu(menuID: 130, title: "Edit") + // 0, or the ID of no menu there, puts a menu after them all. + bar.insert(apple, beforeID: 0) + bar.insert(file, beforeID: 0) + #expect(bar.menus.map(\.menuID) == [128, 129]) + // Before the menu of an ID. + bar.insert(edit, beforeID: 129) + #expect(bar.menus.map(\.menuID) == [128, 130, 129]) + let special = Menu(menuID: 131, title: "Special") + bar.insert(special, beforeID: 129) + #expect(bar.menus.map(\.menuID) == [128, 130, 131, 129]) + // A menu already in the list isn't moved. + bar.insert(file, beforeID: 128) + #expect(bar.menus.map(\.menuID) == [128, 130, 131, 129]) + #expect(bar.count == 4) + } + + @Test func hierarchical() { + let bar = MenuBar() + let file = Menu(menuID: 129, title: "File") + bar.insert(file, beforeID: 0) + // hierMenu: in the list, no title in the bar. + let sizes = Menu(menuID: 9, title: "Sizes") + bar.insert(sizes, beforeID: -1) + #expect(bar.count == 1) + #expect(bar.hierarchicalMenus.map(\.menuID) == [9]) + #expect(bar.listed.map(\.menuID) == [129, 9]) + // GetMenuHandle finds either kind. + #expect(bar.menu(id: 129) === file) + #expect(bar.menu(id: 9) === sizes) + // A submenu resolves from an item, as the classic's menu list did. + file.append(classic: "Size!\t/\u{1B}") + #expect(bar.submenu(of: file[0]) === sizes) + // An item with no submenu has none; 0 names no menu. + file.append(MenuItem(text: "Quit")) + #expect(bar.submenu(of: file[1]) == nil) + #expect(bar.menu(id: 0) == nil) + } + + @Test func removing() { + let bar = MenuBar() + let apple = makeAppleMenu() + let file = Menu(menuID: 129, title: "File") + let sizes = Menu(menuID: 9, title: "Sizes") + bar.insert(apple, beforeID: 0) + bar.insert(file, beforeID: 0) + bar.insert(sizes, beforeID: -1) + bar.hilite(menuID: 9) + #expect(bar.hilitedMenuID == 9) + // DeleteMenu takes it from the bar and the list both. + bar.remove(menuID: 129) + #expect(bar.count == 1) + #expect(bar.listed.map(\.menuID) == [128, 9]) + // A hilite of a menu that's gone unhilites. + bar.remove(menuID: 9) + #expect(bar.hilitedMenuID == 0) + // An ID no menu has does nothing. + bar.remove(menuID: 999) + #expect(bar.count == 1) + // ClearMenuBar: both parts. + bar.clear() + #expect(bar.count == 0 && bar.listed.isEmpty) + } + + @Test func commands() { + let bar = MenuBar() + let file = Menu(menuID: 129, title: "File") + file.append(MenuItem(text: "New", commandID: "new ")) + file.append(MenuItem(text: "Open…", commandID: "open")) + let edit = Menu(menuID: 130, title: "Edit") + edit.append(MenuItem(text: "Cut", commandID: "cut ")) + bar.insert(file, beforeID: 0) + bar.insert(edit, beforeID: 0) + // GetIndMenuItemWithCommandID searches the bar's menus in order. + #expect(bar.find(commandID: "open")?.menu === file) + #expect(bar.find(commandID: "open")?.index == 1) + #expect(bar.find(commandID: "cut ")?.menu === edit) + #expect(bar.find(commandID: "nope") == nil) + // EnableMenuCommand and DisableMenuCommand. + bar.setEnabled(false, commandID: "cut ") + #expect(!edit.isEnabled(at: 0)) + #expect(!bar.isEnabled(commandID: "cut ")) + bar.setEnabled(true, commandID: "cut ") + #expect(bar.isEnabled(commandID: "cut ")) + #expect(!bar.setEnabled(true, commandID: "nope")) + #expect(!bar.isEnabled(commandID: "nope")) + // A hidden menu's commands are still found: the attribute is the + // host's to draw by. + edit.changeAttributes(add: .hidden) + #expect(bar.find(commandID: "cut ")?.menu === edit) + } + + @Test func menuKeys() { + let bar = MenuBar() + let file = Menu(menuID: 129, title: "File") + file.append(classic: "New/N;Open…/O;Save/S") + let edit = Menu(menuID: 130, title: "Edit") + edit.append(classic: "Cut/X;Copy/C") + let sizes = Menu(menuID: 9, title: "Sizes") + sizes.append(classic: "9/N") + bar.insert(file, beforeID: 0) + bar.insert(edit, beforeID: 0) + bar.insert(sizes, beforeID: -1) + // MenuKey: the choice, the item numbered from 1. + #expect(bar.find(key: UInt8(ascii: "N")) == MenuSelection(menuID: 129, itemIndex: 1)) + #expect(bar.find(key: UInt8(ascii: "C")) == MenuSelection(menuID: 130, itemIndex: 2)) + #expect(bar.find(key: UInt8(ascii: "X"))?.menuID == 130) + // The hierarchical list is searched too, as the classic searched + // it — even submenus no item used. + #expect(bar.find(key: UInt8(ascii: "N")) != nil) + // A disabled item or menu finds nothing. + edit.setEnabled(false, at: 0) + #expect(bar.find(key: UInt8(ascii: "X")) == nil) + edit.isEnabled = false + #expect(bar.find(key: UInt8(ascii: "C")) == nil) + // Modifiers are held: shift-S is another item than S. + file.append(classic: "Save As…/S") + file[3].modifiers = [.shift] + #expect(bar.find(key: UInt8(ascii: "S")) == MenuSelection(menuID: 129, itemIndex: 3)) + #expect(bar.find(key: UInt8(ascii: "S"), modifiers: [.shift]) == MenuSelection(menuID: 129, itemIndex: 4)) + #expect(bar.find(key: UInt8(ascii: "S"), modifiers: [.option]) == nil) + // A key no item has finds nothing. + #expect(bar.find(key: UInt8(ascii: "Q")) == nil) + } + + @Test func hiliteAndShow() { + let bar = MenuBar() + #expect(bar.isShown) + let file = Menu(menuID: 129, title: "File") + bar.insert(file, beforeID: 0) + bar.hilite(menuID: 129) + #expect(bar.hilitedMenuID == 129) + // HiliteMenu(0) unhilites; so does an ID no menu has. + bar.hilite(menuID: 0) + #expect(bar.hilitedMenuID == 0) + bar.hilite(menuID: 129) + bar.hilite(menuID: 999) + #expect(bar.hilitedMenuID == 0) + bar.isShown = false + #expect(!bar.isShown) + } + + @Test func changes() { + let bar = MenuBar() + var changed = 0 + bar.changeObserver = { _ in changed += 1 } + bar.insert(makeAppleMenu(), beforeID: 0) + bar.draw() + bar.remove(menuID: 128) + bar.clear() + #expect(changed == 4) + } + + @Test func selections() { + #expect(MenuSelection.none.menuID == 0 && MenuSelection.none.itemIndex == 0) + #expect(MenuSelection.none.isNone) + #expect(MenuSelection(menuID: 3, itemIndex: 2) == MenuSelection(menuID: 3, itemIndex: 2)) + #expect(!MenuSelection(menuID: 3, itemIndex: 2).isNone) + } +} From acd5368abe19b78c84c0b73809046ab3e668ff17 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:26 -0500 Subject: [PATCH 11/13] Tested the definition's sizes and geometry --- .../MenuDefinitionTests.swift | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Tests/GraphiteMenusTests/MenuDefinitionTests.swift diff --git a/Tests/GraphiteMenusTests/MenuDefinitionTests.swift b/Tests/GraphiteMenusTests/MenuDefinitionTests.swift new file mode 100644 index 0000000..7aa5326 --- /dev/null +++ b/Tests/GraphiteMenusTests/MenuDefinitionTests.swift @@ -0,0 +1,58 @@ +import Testing +import GraphiteBase +import GraphiteMenus + +@Suite struct MenuDefinitionTests { + + /// The width of a text in the Chicago look: wide. + private func measure(_ text: PascalString) -> Int16 { + Int16(text.count * 8) + } + + @Test func standardSizes() { + let definition = StandardMenuDefinition() + #expect(definition.menuBarHeight == 20) + #expect(definition.itemHeight == 16) + #expect(definition.menuHeight(itemCount: 5) == 80) + #expect(definition.menuHeight(itemCount: 0) == 0) + // A menu's width: the margins, the widest text, and a column each + // for the marks, icons and keys that are there. + var items = [MenuItem(text: "About SurfWriter…"), + MenuItem(text: "Cut"), + MenuItem(text: "Paste")] + #expect(definition.menuWidth(of: items, attributes: [], measuring: measure) == 2 + 17 * 8 + 2) + items[0].icon = 1 + #expect(definition.menuWidth(of: items, attributes: [], measuring: measure) == 2 + 16 + 17 * 8 + 2) + items[1].mark = .checkmark + #expect(definition.menuWidth(of: items, attributes: [], measuring: measure) == 2 + 16 + 16 + 17 * 8 + 2) + items[2].key = UInt8(ascii: "V") + #expect(definition.menuWidth(of: items, attributes: [], measuring: measure) == 2 + 16 + 16 + 17 * 8 + 16 + 2) + // kMenuAttrExcludesMarkColumn keeps none for the marks. + #expect(definition.menuWidth(of: items, attributes: [.excludesMarkColumn], measuring: measure) + == 2 + 16 + 17 * 8 + 16 + 2) + // An empty menu: its margins alone. + #expect(definition.menuWidth(of: [], attributes: [], measuring: measure) == 4) + // A submenu's $1B is no key column. + var submenu = [MenuItem(text: "Sizes")] + submenu[0].key = 0x1B + #expect(definition.menuWidth(of: submenu, attributes: [], measuring: measure) == 2 + 5 * 8 + 2) + } + + @Test func itemsGeometry() { + let definition = StandardMenuDefinition() + let bounds = Rect(top: 40, left: 100, bottom: 120, right: 200) + #expect(definition.itemRect(at: 0, in: bounds) == Rect(top: 40, left: 100, bottom: 56, right: 200)) + #expect(definition.itemRect(at: 2, in: bounds) == Rect(top: 72, left: 100, bottom: 88, right: 200)) + // mChooseMsg: the item a point is on, from the first. + #expect(definition.hitTest(Point(v: 45, h: 130), in: bounds, itemCount: 5) == 0) + #expect(definition.hitTest(Point(v: 71, h: 130), in: bounds, itemCount: 5) == 1) + #expect(definition.hitTest(Point(v: 100, h: 130), in: bounds, itemCount: 5) == 3) + // Past the last item there is, or outside the menu, none. + #expect(definition.hitTest(Point(v: 119, h: 130), in: bounds, itemCount: 2) == nil) + #expect(definition.hitTest(Point(v: 30, h: 130), in: bounds, itemCount: 5) == nil) + #expect(definition.hitTest(Point(v: 50, h: 99), in: bounds, itemCount: 5) == nil) + #expect(definition.hitTest(Point(v: 50, h: 201), in: bounds, itemCount: 5) == nil) + // The rectangle of an item past the last: below them all. + #expect(definition.itemRect(at: 5, in: bounds).top == 40 + 5 * 16) + } +} From 56e813e49d38bbe16b7ec8768294929a41456505 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:37 -0500 Subject: [PATCH 12/13] Described GraphiteMenus in the package's header --- Package.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Package.swift b/Package.swift index 31bec9b..1eea5f0 100644 --- a/Package.swift +++ b/Package.swift @@ -25,6 +25,8 @@ import PackageDescription /// - `GraphiteWindows`: the Window Manager: windows of every class, the /// window list, FindWindow, zooming and collapsing, the visible and /// update regions, and the content's buffer the host flushes. +/// - `GraphiteMenus`: the Menu Manager: menus and their items, the menu +/// bar, and the 'MENU' resources that define them. /// - `Graphite`: re-exports the modules above. /// /// Everything here depends only on the Swift standard library, the C From d3bf4faf20490eafa282d4443cad3fa6c87bc55e Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 15:15:37 -0500 Subject: [PATCH 13/13] Described the Menu Manager in the README --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 14f85dc..7603fe7 100644 --- a/README.md +++ b/README.md @@ -27,9 +27,9 @@ Any UI it shows will be drawn with [Cacao](https://github.com/PureSwift/Cacao). > **Status:** early development. `GraphiteBase`, `GraphiteTasks`, > `GraphiteFiles`, `GraphiteResources`, `GraphiteAppleEvents`, -> `GraphiteQuickDraw`, `GraphiteText`, `GraphiteSound` and `GraphiteWindows` -> are in place, apart from the MACE codecs and double-buffered sound. The -> Toolbox's menus, controls and dialogs come next. +> `GraphiteQuickDraw`, `GraphiteText`, `GraphiteSound`, `GraphiteWindows` +> and `GraphiteMenus` are in place, apart from the MACE codecs and +> double-buffered sound. The Toolbox's controls and dialogs come next. ## Modules @@ -44,6 +44,7 @@ Any UI it shows will be drawn with [Cacao](https://github.com/PureSwift/Cacao). | `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 QuickDraw's text in a port's font, face, size and mode, with the styles a face hasn't drawn from its plain glyphs; 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. | | `Graphite` | Re-exports the modules above. | Everything depends only on the Swift standard library, the C library