Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -77,6 +79,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.
Expand Down Expand Up @@ -136,9 +142,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",
Expand Down Expand Up @@ -175,6 +185,10 @@ let package = Package(
.testTarget(
name: "GraphiteWindowsTests",
dependencies: ["GraphiteWindows", "GraphiteQuickDraw"]
),
.testTarget(
name: "GraphiteMenusTests",
dependencies: ["GraphiteMenus"]
)
]
)
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions Sources/Graphite/Graphite.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@
@_exported import GraphiteText
@_exported import GraphiteSound
@_exported import GraphiteWindows
@_exported import GraphiteMenus
20 changes: 20 additions & 0 deletions Sources/GraphiteBase/MacError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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))"
Expand Down Expand Up @@ -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) }
}
157 changes: 157 additions & 0 deletions Sources/GraphiteMenus/Menu.swift
Original file line number Diff line number Diff line change
@@ -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<Int>) {
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)
}
}
Loading
Loading