diff --git a/Package.swift b/Package.swift index 1eea5f0..805bd27 100644 --- a/Package.swift +++ b/Package.swift @@ -27,6 +27,9 @@ import PackageDescription /// 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. +/// - `GraphiteControls`: the Control Manager: controls of the five kinds, +/// their values, parts and states, the window's list of them, and the +/// 'CNTL' resources that define them. /// - `Graphite`: re-exports the modules above. /// /// Everything here depends only on the Swift standard library, the C @@ -83,6 +86,10 @@ let package = Package( .library( name: "GraphiteMenus", targets: ["GraphiteMenus"] + ), + .library( + name: "GraphiteControls", + targets: ["GraphiteControls"] ) ], // FreeType reads outline fonts; builds without it keep the bitmap font. @@ -146,9 +153,13 @@ let package = Package( name: "GraphiteMenus", dependencies: ["GraphiteBase"] ), + .target( + name: "GraphiteControls", + dependencies: ["GraphiteBase"] + ), .target( name: "Graphite", - dependencies: ["GraphiteBase", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAppleEvents", "GraphiteQuickDraw", "GraphiteText", "GraphiteSound", "GraphiteWindows", "GraphiteMenus"] + dependencies: ["GraphiteBase", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAppleEvents", "GraphiteQuickDraw", "GraphiteText", "GraphiteSound", "GraphiteWindows", "GraphiteMenus", "GraphiteControls"] ), .testTarget( name: "GraphiteBaseTests", @@ -189,6 +200,10 @@ let package = Package( .testTarget( name: "GraphiteMenusTests", dependencies: ["GraphiteMenus"] + ), + .testTarget( + name: "GraphiteControlsTests", + dependencies: ["GraphiteControls"] ) ] ) diff --git a/README.md b/README.md index 7603fe7..940a78b 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`, `GraphiteWindows` -> and `GraphiteMenus` are in place, apart from the MACE codecs and -> double-buffered sound. The Toolbox's controls and dialogs come next. +> `GraphiteQuickDraw`, `GraphiteText`, `GraphiteSound`, `GraphiteWindows`, +> `GraphiteMenus` and `GraphiteControls` are in place, apart from the MACE +> codecs and double-buffered sound. The Toolbox's dialogs come next. ## Modules @@ -45,6 +45,7 @@ Any UI it shows will be drawn with [Cacao](https://github.com/PureSwift/Cacao). | `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. | +| `GraphiteControls` | The Control Manager: controls of the classic's five kinds — buttons, checkboxes, radio buttons, scroll bars and pop-up menus, their control definition IDs and the `useWFont` variation read as the kind beneath it; values, ranges and the pinning SetControlValue did, with the pop-up menu's resource ID and title width in its minimum and maximum as the classic kept them; titles, reference values, command IDs, identifiers, enabling, disabling, activating and `HiliteControl`'s pressed part; the parts a point hits (inButton, inCheckBox, a scroll bar's arrows, pages and thumb), the fixed-size thumb of the classic's scroll bars and the value a drag names; a window's control list, FindControl, GetControlByID and Carbon's root control; and `'CNTL'` resources read field by field. | | `Graphite` | Re-exports the modules above. | Everything depends only on the Swift standard library, the C library diff --git a/Sources/Graphite/Graphite.swift b/Sources/Graphite/Graphite.swift index 4fb0e64..286a04a 100644 --- a/Sources/Graphite/Graphite.swift +++ b/Sources/Graphite/Graphite.swift @@ -11,3 +11,4 @@ @_exported import GraphiteSound @_exported import GraphiteWindows @_exported import GraphiteMenus +@_exported import GraphiteControls diff --git a/Sources/GraphiteBase/MacError.swift b/Sources/GraphiteBase/MacError.swift index 04c2db3..afc4b49 100644 --- a/Sources/GraphiteBase/MacError.swift +++ b/Sources/GraphiteBase/MacError.swift @@ -195,6 +195,11 @@ extension MacError: CustomStringConvertible { -210: "buffersTooSmall", -223: "siInvalidCompression", -5603: "menuPropertyInvalidErr", -5604: "menuPropertyNotFoundErr", -5620: "menuNotFoundErr", -5621: "menuUsesSystemDefErr", -5622: "menuItemNotFoundErr", -5623: "menuInvalidErr", + -30581: "errDataNotSupported", -30582: "errControlDoesntSupportFocus", + -30583: "errWindowDoesntSupportFocus", -30584: "errUnknownControl", -30585: "errCouldntSetFocus", + -30586: "errNoRootControl", -30587: "errRootAlreadyExists", -30588: "errInvalidPartCode", + -30589: "errControlsAlreadyExist", -30590: "errControlIsNotEmbedder", + -30592: "errControlHiddenOrDisabled", -30596: "errItemNotControl", ] guard let name = names[code] else { return "\(code)" } return "\(name) (\(code))" @@ -245,3 +250,33 @@ public extension MacError { /// menuInvalidErr: the menu or its resource is invalid. static var menuInvalid: MacError { MacError(-5623) } } + +// MARK: - Control Manager + +public extension MacError { + + /// errDataNotSupported: the control doesn't take the kind of data. + static var dataNotSupported: MacError { MacError(-30581) } + /// errControlDoesntSupportFocus. + static var controlDoesntSupportFocus: MacError { MacError(-30582) } + /// errWindowDoesntSupportFocus. + static var windowDoesntSupportFocus: MacError { MacError(-30583) } + /// errUnknownControl. + static var unknownControl: MacError { MacError(-30584) } + /// errCouldntSetFocus. + static var couldntSetFocus: MacError { MacError(-30585) } + /// errNoRootControl. + static var noRootControl: MacError { MacError(-30586) } + /// errRootAlreadyExists. + static var rootAlreadyExists: MacError { MacError(-30587) } + /// errInvalidPartCode. + static var invalidPartCode: MacError { MacError(-30588) } + /// errControlsAlreadyExist. + static var controlsAlreadyExist: MacError { MacError(-30589) } + /// errControlIsNotEmbedder. + static var controlIsNotEmbedder: MacError { MacError(-30590) } + /// errControlHiddenOrDisabled: it can't be focused or hit. + static var controlHiddenOrDisabled: MacError { MacError(-30592) } + /// errItemNotControl: a dialog item that isn't one. + static var itemNotControl: MacError { MacError(-30596) } +} diff --git a/Sources/GraphiteControls/Control.swift b/Sources/GraphiteControls/Control.swift new file mode 100644 index 0000000..af9189f --- /dev/null +++ b/Sources/GraphiteControls/Control.swift @@ -0,0 +1,190 @@ +// A control: the rectangle it occupies in its window, its value and its +// range, its title and its reference value, its visibility, enabling and +// activity, and the action procedure the classic's TrackControl called as +// the user worked the control. The host draws it and tracks it; the +// definition gives its parts' shapes, and the Control Manager keeps the +// rest. + +import GraphiteBase + +#if canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#elseif canImport(Darwin) +import Darwin +#endif + +public final class Control { + + /// The kind of control the standard definition functions draw; a + /// control a host defines of its own keeps nil here. + public let kind: ControlKind? + + /// The shape of the control's parts. The standard kinds share one. + public let definition: any ControlDefinition + + /// The control's rectangle, in its owner's local coordinates + /// (GetControlBounds, SetControlBounds, MoveControl, SizeControl). + public internal(set) var bounds: Rect + + /// GetControlValue, SetControlValue: the control's setting — a button's + /// 0, a checkbox's or radio button's 0 or 1, a scroll bar's place in + /// its range, a pop-up menu's chosen item from 1. + public var value: Int32 = 0 { + didSet { value = min(max(value, minimum), max(minimum, maximum)) } + } + + /// GetControlMinimum, SetControlMinimum. + public var minimum: Int32 = 0 + + /// GetControlMaximum, SetControlMaximum. A scroll bar whose maximum + /// meets its minimum is inactive, as the classic's definition made it, + /// and active again when the range opens. A pop-up menu keeps its + /// menu's resource ID in its minimum and its title's width in its + /// maximum, so a maximum below a minimum is allowed: the classic's own + /// fields were the program's to read. + public var maximum: Int32 = 0 + + /// GetControlReference, SetControlReference: whatever the program + /// keeps with the control. A pop-up menu keeps its menu's resource ID. + public var reference: Int32 = 0 + + /// GetControlTitle, SetControlTitle. + public var title: PascalString + + /// ShowControl and HideControl. + public internal(set) var isVisible = true + + /// EnableControl and DisableControl. A disabled control draws dimmed + /// and is hit nowhere. + public internal(set) var isEnabled = true + + /// ActivateControl and DeactivateControl: an active control is the + /// one its window's user can work. An inactive one draws as the + /// classic's inactive controls did, but is hit as ever. + public internal(set) var isActive = true + + /// HiliteControl: the part drawn pressed, as TrackControl pressed a + /// button while the mouse was down in it; none while it isn't. + public internal(set) var hilitedPart: ControlPart = .none + + /// SetControlCommandID; 0 is none. + public var commandID: GraphiteBase.FourCharCode = GraphiteBase.FourCharCode(rawValue: 0) + + /// SetControlID: the signature and the ID the Control Manager finds a + /// control by (GetControlByID). + public var identifier: (signature: GraphiteBase.FourCharCode, id: Int32)? + + /// SetControlAction, GetControlAction: the procedure the classic's + /// TrackControl called over and over as the user held the control — + /// the part and the reference constant its work took. The host calls + /// it as it tracks. + public var action: (@Sendable (_ part: ControlPart, _ reference: Int32) -> Void)? + + /// The control's part a point of its owner is on — FindControl's + /// answer for this control alone — or none. + public func hitTest(_ point: Point) -> ControlPart { + guard let kind else { return .none } + return definition.hitTest(point, bounds: bounds, kind: kind, value: value, + minimum: minimum, maximum: maximum, isEnabled: isEnabled) + } + + public init(kind: ControlKind, bounds: Rect, title: PascalString = "", + definition: (any ControlDefinition)? = nil) { + self.kind = kind + self.definition = definition ?? StandardControlDefinition() + self.bounds = bounds + self.title = title + // A button's maximum is 1 and a checkbox's or radio button's 1 + // too, as the classic's resources kept them: on. + self.maximum = kind == .scrollBar || kind == .popUpMenu ? 0 : 1 + } + + /// A control of the host's own definition: no standard kind, whatever + /// shape the definition gives it. + public init(bounds: Rect, definition: any ControlDefinition) { + self.kind = nil + self.definition = definition + self.bounds = bounds + title = PascalString() + maximum = 0 + } + + // MARK: Value + + /// GetControlValue's kind: what the control keeps. + public var valueKind: ControlValueKind { + kind.map { definition.valueKind(of: $0) } ?? .none + } + + /// SetControlValue, as the classic pinned it: a value below the + /// minimum or above the maximum stops at its edge. Kept for the + /// layer that exports Carbon, which sets the property directly. + public func setValue(_ newValue: Int32) { + value = min(max(newValue, minimum), max(minimum, maximum)) + } + + /// The value a scroll bar's thumb is dragged to, at a point of the + /// bar: the place in its range the point names, the thumb centered + /// under the point as it is dragged. Not for a control without a + /// thumb. + public func value(at point: Point) -> Int32? { + guard kind == .scrollBar, maximum > minimum else { return nil } + let vertical = bounds.height >= bounds.width + let travel = (vertical ? bounds.height : bounds.width) - 2 * 16 + guard travel > 0 else { return value } + let thumbLength = 16 + let offset = vertical ? Int(point.v) - Int(bounds.top) - 16 + : Int(point.h) - Int(bounds.left) - 16 + let centered = min(max(offset - thumbLength / 2, 0), Int(travel - thumbLength)) + let place = Int32(Double(centered) * Double(maximum - minimum) / Double(travel - thumbLength)) + return min(max(minimum + place, minimum), maximum) + } + + /// A checkbox's or radio button's on-or-off answer. + public var isOn: Bool { + value != 0 + } + + /// Whether the control can be worked: visible, enabled and active. + public var isLive: Bool { + isVisible && isEnabled && isActive + } + + // MARK: Changes + + /// MoveControl: the control's top left moves to (h, v), its size kept. + public func move(h: Int16, v: Int16) { + bounds.offset(dh: h &- bounds.left, dv: v &- bounds.top) + } + + /// SizeControl: the control takes a new size, its top left kept. + public func size(width: Int16, height: Int16) { + bounds = Rect(top: bounds.top, left: bounds.left, + bottom: bounds.top + height, right: bounds.left + width) + } + + /// ShowControl. + public func show() { isVisible = true } + + /// HideControl. + public func hide() { isVisible = false } + + /// EnableControl. + public func enable() { isEnabled = true } + + /// DisableControl. + public func disable() { isEnabled = false } + + /// ActivateControl. + public func activate() { isActive = true } + + /// DeactivateControl. + public func deactivate() { isActive = false } + + /// HiliteControl: the part drawn pressed. + public func hilite(_ part: ControlPart) { + hilitedPart = part + } +} diff --git a/Sources/GraphiteControls/ControlDefinition.swift b/Sources/GraphiteControls/ControlDefinition.swift new file mode 100644 index 0000000..a4d3e05 --- /dev/null +++ b/Sources/GraphiteControls/ControlDefinition.swift @@ -0,0 +1,162 @@ +// Control definitions, the CDEFs, as Swift sees them: the parts a control +// has and where they are, so the host can draw them and FindControl can +// find them. The standard definition function draws the classic's five: +// buttons, checkboxes, radio buttons, scroll bars and pop-up menus — the +// 'CDEF' resources 0, 1 and 63 of the System file, as their variation +// codes chose. + +import GraphiteBase + +/// A control definition function: the shape of a control of a kind, as the +/// Control Manager asked its CDEFs. Drawing is the host's; the definition +/// answers where the parts are, which one a point is on, and what the +/// control keeps. +public protocol ControlDefinition: Sendable { + + /// What kind of value the control keeps. + func valueKind(of kind: ControlKind) -> ControlValueKind + + /// Which part a point of the control is on — inButton, inCheckBox, a + /// scroll bar's arrows, pages or thumb — or none. A disabled control + /// is hit nowhere: its part is the whole control drawn disabled. The + /// control's value and range place its thumb. + func hitTest(_ point: Point, bounds: Rect, kind: ControlKind, value: Int32, + minimum: Int32, maximum: Int32, isEnabled: Bool) -> ControlPart + + /// A scroll bar's thumb, or a slider's indicator, in the control's + /// bounds: where the control's value puts it. + func thumbRect(bounds: Rect, kind: ControlKind, value: Int32, minimum: Int32, maximum: Int32) -> Rect? + + /// Where a part of the control is, in its bounds; nil for a part the + /// control doesn't have. + func rect(of part: ControlPart, bounds: Rect, kind: ControlKind, value: Int32, + minimum: Int32, maximum: Int32) -> Rect? +} + +/// The standard control definitions' shapes, the classic's look: a +/// button's whole rectangle is its part, a checkbox's and a radio button's +/// too; a scroll bar is its arrows (16 pixels square at the ends), its +/// pages between them and its thumb where its value puts it, at least 16 +/// pixels long and never over the arrows. +public struct StandardControlDefinition: ControlDefinition { + + /// A scroll bar's arrow boxes. + private static let arrowLength: Int16 = 16 + + /// A scroll bar's thumb at its shortest. + private static let minimumThumbLength: Int16 = 16 + + public init() {} + + public func valueKind(of kind: ControlKind) -> ControlValueKind { + switch kind { + case .button: return .none + case .checkBox, .radioButton: return .onOff + case .scrollBar, .popUpMenu: return .range + } + } + + /// Whether a scroll bar's rectangle makes it vertical: taller than + /// wide, as the classic's definition decided. + private func isVertical(_ bounds: Rect) -> Bool { + bounds.height >= bounds.width + } + + public func hitTest(_ point: Point, bounds: Rect, kind: ControlKind, value: Int32, + minimum: Int32, maximum: Int32, isEnabled: Bool) -> ControlPart { + guard bounds.contains(point) else { return .none } + guard isEnabled else { return .disabled } + switch kind { + case .button, .checkBox, .radioButton: + return kind == .button ? .button : .checkBox + case .popUpMenu: + return .button + case .scrollBar: + if let up = rect(of: .upButton, bounds: bounds, kind: kind, value: value, minimum: minimum, maximum: maximum), + up.contains(point) { + return .upButton + } + if let down = rect(of: .downButton, bounds: bounds, kind: kind, value: value, minimum: minimum, maximum: maximum), + down.contains(point) { + return .downButton + } + if let thumb = thumbRect(bounds: bounds, kind: kind, value: value, minimum: minimum, maximum: maximum), + thumb.contains(point) { + return .thumb + } + // The pages: the half of the bar above the point pages up, the + // half below pages down. + let vertical = isVertical(bounds) + let midV = bounds.top + Int16(bounds.height / 2), midH = bounds.left + Int16(bounds.width / 2) + return vertical ? (point.v < midV ? .pageUp : .pageDown) : (point.h < midH ? .pageUp : .pageDown) + } + } + + public func thumbRect(bounds: Rect, kind: ControlKind, value: Int32, minimum: Int32, maximum: Int32) -> Rect? { + guard kind == .scrollBar, maximum > minimum else { return nil } + let span = maximum - minimum + let fraction = Double(value - minimum) / Double(span) + let length = Self.arrowLength + if isVertical(bounds) { + let travel = bounds.height - Int(length) * 2 + guard travel >= Self.minimumThumbLength else { + return Rect(top: bounds.top + length, left: bounds.left, + bottom: bounds.bottom - length, right: bounds.right) + } + // The classic's thumb: a fixed-size scroll box, its length the + // arrow's, its place by its value in the travel that's left. + let thumbLength = length + let top = bounds.top + length + Int16(Double(travel - Int(thumbLength)) * fraction) + return Rect(top: top, left: bounds.left, bottom: top + thumbLength, right: bounds.right) + } + let travel = bounds.width - Int(length) * 2 + guard travel >= Self.minimumThumbLength else { + return Rect(top: bounds.top, left: bounds.left + length, bottom: bounds.bottom, right: bounds.right - length) + } + let thumbLength = length + let left = bounds.left + length + Int16(Double(travel - Int(thumbLength)) * fraction) + return Rect(top: bounds.top, left: left, bottom: bounds.bottom, right: left + thumbLength) + } + + public func rect(of part: ControlPart, bounds: Rect, kind: ControlKind, + value: Int32, minimum: Int32, maximum: Int32) -> Rect? { + guard kind == .scrollBar else { + // A button, a checkbox or a radio button is all one part. + switch part { + case .button, .checkBox: return bounds + default: return nil + } + } + let vertical = isVertical(bounds) + switch part { + case .upButton: + return vertical ? Rect(top: bounds.top, left: bounds.left, + bottom: bounds.top + Self.arrowLength, right: bounds.right) + : Rect(top: bounds.top, left: bounds.left, + bottom: bounds.bottom, right: bounds.left + Self.arrowLength) + case .downButton: + return vertical ? Rect(top: bounds.bottom - Self.arrowLength, left: bounds.left, + bottom: bounds.bottom, right: bounds.right) + : Rect(top: bounds.top, left: bounds.right - Self.arrowLength, + bottom: bounds.bottom, right: bounds.right) + case .thumb: + return thumbRect(bounds: bounds, kind: kind, value: value, minimum: minimum, maximum: maximum) + case .pageUp, .pageDown: + guard let thumb = thumbRect(bounds: bounds, kind: kind, value: value, minimum: minimum, maximum: maximum) else { + return nil + } + if vertical { + let middle = thumb.top + Int16(thumb.height / 2) + return part == .pageUp + ? Rect(top: bounds.top + Self.arrowLength, left: bounds.left, bottom: middle, right: bounds.right) + : Rect(top: middle, left: bounds.left, bottom: bounds.bottom - Self.arrowLength, right: bounds.right) + } + let middle = thumb.left + Int16(thumb.width / 2) + return part == .pageUp + ? Rect(top: bounds.top, left: bounds.left + Self.arrowLength, bottom: bounds.bottom, right: middle) + : Rect(top: bounds.top, left: middle, bottom: bounds.bottom, right: bounds.right - Self.arrowLength) + default: + return nil + } + } +} diff --git a/Sources/GraphiteControls/ControlList.swift b/Sources/GraphiteControls/ControlList.swift new file mode 100644 index 0000000..5113b8d --- /dev/null +++ b/Sources/GraphiteControls/ControlList.swift @@ -0,0 +1,84 @@ +// A window's controls, as the Control Manager kept them: the list +// GetNewControl added to, DrawControls drew and UpdateControls drew again +// where the window needed it, FindControl searched from the last added +// back, and DisposeControl took one from. Carbon's embedding is here too: +// a root control that holds the rest, as CreateRootControl made it — the +// plain list, without the hierarchy, is the classic's own. + +import GraphiteBase + +public final class ControlList { + + /// The controls, last added first, as the classic's list held them. + public private(set) var controls: [Control] = [] + + /// The window's root control (CreateRootControl), which holds the rest + /// as its embedded children; nil where the classic's plain list is + /// used. A window can't have two: errRootAlreadyExists. + public private(set) var root: Control? + + public init() {} + + /// How many controls the list holds. + public var count: Int { controls.count } + + // MARK: Adding and removing + + /// NewControl and GetNewControl's work: a control at the front of the + /// list, the first FindControl finds. + public func add(_ control: Control) { + controls.insert(control, at: 0) + } + + /// DisposeControl. + public func remove(_ control: Control) { + controls.removeAll { $0 === control } + } + + /// CreateRootControl: a root control that holds the rest as its + /// embedded children. errRootAlreadyExists where there is one. + @discardableResult + public func createRoot() throws(MacError) -> Control { + guard root == nil else { throw .rootAlreadyExists } + let root = Control(bounds: .zero, definition: StandardControlDefinition()) + self.root = root + return root + } + + // MARK: Finding + + /// FindControl: the frontmost control the point is on, and its part. + /// A control that is hidden, disabled or of the host's own definition + /// is passed over, as the classic passed a hidden one; the root + /// control is never found. + public func findControl(at point: Point) -> (control: Control, part: ControlPart)? { + for control in controls where control !== root { + guard control.isVisible else { continue } + let part = control.hitTest(point) + guard part != .none else { continue } + return (control, part) + } + return nil + } + + /// GetControlByID: the control of the signature and ID. + public func control(signature: FourCharCode, id: Int32) -> Control? { + controls.first { $0.identifier?.signature == signature && $0.identifier?.id == id } + } + + /// GetControlCommandID's find: the control of the command ID. + public func control(commandID: FourCharCode) -> Control? { + controls.first { $0.commandID == commandID && commandID.rawValue != 0 } + } + + // MARK: Drawing + + /// DrawControls and UpdateControls' work, for the host that draws the + /// controls: the visible ones the rectangle touches, last added first. + /// A nil rectangle is every visible control, as DrawControls drew. + public func visibleControls(in rect: Rect? = nil) -> [Control] { + controls.filter { control in + control.isVisible && (rect == nil || control.bounds.intersects(rect!)) + } + } +} diff --git a/Sources/GraphiteControls/ControlPart.swift b/Sources/GraphiteControls/ControlPart.swift new file mode 100644 index 0000000..c65dc20 --- /dev/null +++ b/Sources/GraphiteControls/ControlPart.swift @@ -0,0 +1,115 @@ +// A control's parts, as FindControl answers them and a control definition +// reports them: the whole of a button, a checkbox or a radio button; the +// arrows, the pages and the thumb of a scroll bar; the pop-up menu's menu +// part. The classic's part codes are the Carbon appearance's: inButton 10, +// inCheckBox 11, inUpButton 20, inDownButton 21, inPageUp 22, inPageDown +// 23, inThumb — the indicator — 129. + +import GraphiteBase + +/// A part of a control, as FindControl and TrackControl answer with and +/// the Control Manager's routines take (ControlPartCode). 0 is no part. +public struct ControlPart: Hashable, Sendable { + + /// The part code: 0 no part, 10 a button, 11 a checkbox or radio + /// button, 20 and 21 a scroll bar's arrows, 22 and 23 its pages, 129 + /// its thumb, 254 the whole control drawn disabled, 255 inactive. + public var rawValue: Int16 + + public init(rawValue: Int16) { + self.rawValue = rawValue + } + + public init(_ rawValue: Int16) { + self.rawValue = rawValue + } + + /// kControlNoPart: no part, the whole control's own code too + /// (kControlEntireControl). + public static var none: ControlPart { ControlPart(0) } + /// inButton, kControlButtonPart: the whole of a button. + public static var button: ControlPart { ControlPart(10) } + /// inCheckBox, kControlCheckBoxPart: the whole of a checkbox or radio + /// button. + public static var checkBox: ControlPart { ControlPart(11) } + /// inUpButton, kControlUpButtonPart: the up arrow of a vertical scroll + /// bar, the left arrow of a horizontal one. + public static var upButton: ControlPart { ControlPart(20) } + /// inDownButton, kControlDownButtonPart. + public static var downButton: ControlPart { ControlPart(21) } + /// inPageUp, kControlPageUpPart: the gray area above the thumb. + public static var pageUp: ControlPart { ControlPart(22) } + /// inPageDown, kControlPageDownPart. + public static var pageDown: ControlPart { ControlPart(23) } + /// inThumb, kControlIndicatorPart, kAppearancePartIndicator: the + /// scroll box, or a slider's indicator. + public static var thumb: ControlPart { ControlPart(129) } + /// kAppearancePartMetaDisabled: the whole control, drawn disabled. + public static var disabled: ControlPart { ControlPart(254) } + /// kAppearancePartMetaInactive: the whole control, drawn inactive. + public static var inactive: ControlPart { ControlPart(255) } +} + +/// The kinds of control the standard definition functions draw, as the +/// classic's control definition IDs named them: a control definition +/// function's resource ID in the upper 12 bits of the ID and a variation +/// code in the lower 4. GetNewControl reads one from a 'CNTL' resource; +/// the layer that exports Carbon turns a procID into this. +public enum ControlKind: Hashable, Sendable { + + /// pushButProc: a button. + case button + /// checkBoxProc. + case checkBox + /// radioButProc. + case radioButton + /// scrollBarProc: vertical or horizontal, as its rectangle is tall or + /// wide. + case scrollBar + /// popupMenuProc: a pop-up menu, holding its menu's resource ID. + case popUpMenu + + /// The control definition ID: 16 times the definition function's + /// resource ID, plus the variation code. useWFont (8), the variation + /// that draws the title in the window's font, isn't Graphite's: the + /// definition draws with the system font, as the standard ones did. + public var definitionID: Int16 { + switch self { + case .button: return 0 + case .checkBox: return 1 + case .radioButton: return 2 + case .scrollBar: return 16 + case .popUpMenu: return 1008 + } + } + + /// The kind of the classic's control definition ID, with its variation + /// bits: the standard kinds read exactly, and a useWFont variation + /// (the ID plus 8) reads as its kind; anything else is nil, the + /// definition the host brings. + public init?(definitionID: Int16) { + switch definitionID { + case 0, 8: self = .button + case 1, 9: self = .checkBox + case 2, 10: self = .radioButton + case 16, 24: self = .scrollBar + case 1008, 1008 + 8: self = .popUpMenu + default: return nil + } + } +} + +/// The kinds of value a control keeps, which the routines that read one +/// answer differently by: a button keeps none; a checkbox or radio button +/// an on-or-off one; a scroll bar a range. +public enum ControlValueKind: Hashable, Sendable { + + /// A control with no setting to read. + case none + + /// On or off, as GetControlValue answers 1 or 0. + case onOff + + /// A value in a range, as a scroll bar's or a dial's is. + case range +} diff --git a/Sources/GraphiteControls/ControlResource.swift b/Sources/GraphiteControls/ControlResource.swift new file mode 100644 index 0000000..8ee9c83 --- /dev/null +++ b/Sources/GraphiteControls/ControlResource.swift @@ -0,0 +1,48 @@ +// Reading a 'CNTL' resource, as GetNewControl read one: the rectangle +// local to the window, the initial setting, the visibility, the fill byte +// (0, and nothing), the maximum and minimum settings, the control +// definition ID, the reference value, and the title. A pop-up menu's +// minimum is its menu's resource ID, and its maximum the width its title +// takes — the classic's own use of the settings, which the control keeps +// as it kept them. + +import GraphiteBase +import struct Foundation.Data +import protocol Foundation.ContiguousBytes + +public extension Control { + + /// GetNewControl: a control from a 'CNTL' resource's bytes. menuErr? + /// no — paramErr for a control definition ID the standard kinds don't + /// answer and the host hasn't brought a definition for; the bytes + /// past the title are ignored, as the classic's GetNewControl ignored + /// them. + static func make(bytes: some ContiguousBytes) throws(MacError) -> Control { + var reader = BigEndianReader(bytes) + do { + let bounds = try reader.readRect() + let value = try reader.read(Int16.self) + let visible = try reader.readBool() + _ = try reader.read(UInt8.self) // The fill byte, always 0. + let maximum = try reader.read(Int16.self) + let minimum = try reader.read(Int16.self) + let definitionID = try reader.read(Int16.self) + let reference = try reader.read(Int32.self) + let title = try reader.readPascalString() + guard let kind = ControlKind(definitionID: definitionID) else { throw MacError.parameter } + let control = Control(kind: kind, bounds: bounds, title: title) + // The range first, then the setting in it: the value's own + // pinning would hold it to the range it finds. + control.maximum = Int32(maximum) + control.minimum = Int32(minimum) + control.value = Int32(value) + control.reference = reference + control.isVisible = visible + return control + } catch let error as MacError { + throw error + } catch { + throw MacError.parameter + } + } +} diff --git a/Tests/GraphiteControlsTests/ControlDefinitionTests.swift b/Tests/GraphiteControlsTests/ControlDefinitionTests.swift new file mode 100644 index 0000000..e7d9e51 --- /dev/null +++ b/Tests/GraphiteControlsTests/ControlDefinitionTests.swift @@ -0,0 +1,90 @@ +import Testing +import GraphiteBase +import GraphiteControls + +@Suite struct ControlDefinitionTests { + + private let definition = StandardControlDefinition() + + // MARK: Hit testing + + @Test func hitTesting() { + let button = Rect(top: 0, left: 0, bottom: 20, right: 90) + #expect(definition.hitTest(Point(v: 10, h: 10), bounds: button, kind: .button, value: 0, minimum: 0, maximum: 1, isEnabled: true) == .button) + #expect(definition.hitTest(Point(v: 10, h: 89), bounds: button, kind: .button, value: 0, minimum: 0, maximum: 1, isEnabled: true) == .button) + #expect(definition.hitTest(Point(v: 30, h: 10), bounds: button, kind: .button, value: 0, minimum: 0, maximum: 1, isEnabled: true) == .none) + let box = Rect(top: 0, left: 0, bottom: 20, right: 200) + #expect(definition.hitTest(Point(v: 10, h: 100), bounds: box, kind: .checkBox, value: 0, minimum: 0, maximum: 1, isEnabled: true) == .checkBox) + #expect(definition.hitTest(Point(v: 10, h: 100), bounds: box, kind: .radioButton, value: 0, minimum: 0, maximum: 1, isEnabled: true) == .checkBox) + // A disabled control is hit nowhere: its part is the whole + // control drawn disabled. + #expect(definition.hitTest(Point(v: 10, h: 10), bounds: button, kind: .button, value: 0, minimum: 0, maximum: 1, isEnabled: false) == .disabled) + #expect(definition.hitTest(Point(v: 30, h: 10), bounds: button, kind: .button, value: 0, minimum: 0, maximum: 1, isEnabled: false) == .none) + } + + @Test func scrollBarParts() { + // A vertical bar: 200 tall, 16 wide. + let bounds = Rect(top: 0, left: 0, bottom: 200, right: 16) + let up = definition.rect(of: .upButton, bounds: bounds, kind: .scrollBar, value: 0, minimum: 0, maximum: 100)! + let down = definition.rect(of: .downButton, bounds: bounds, kind: .scrollBar, value: 0, minimum: 0, maximum: 100)! + #expect(up == Rect(top: 0, left: 0, bottom: 16, right: 16)) + #expect(down == Rect(top: 184, left: 0, bottom: 200, right: 16)) + #expect(definition.hitTest(Point(v: 8, h: 8), bounds: bounds, kind: .scrollBar, value: 0, minimum: 0, maximum: 100, isEnabled: true) == .upButton) + #expect(definition.hitTest(Point(v: 190, h: 8), bounds: bounds, kind: .scrollBar, value: 0, minimum: 0, maximum: 100, isEnabled: true) == .downButton) + // The thumb: 16 long at least, its place by its value, never over + // the arrows. + let thumb0 = definition.thumbRect(bounds: bounds, kind: .scrollBar, value: 0, minimum: 0, maximum: 100)! + #expect(thumb0.top == 16 && thumb0.bottom == 32) + #expect(definition.hitTest(Point(v: 20, h: 8), bounds: bounds, kind: .scrollBar, value: 0, minimum: 0, maximum: 100, isEnabled: true) == .thumb) + let thumb100 = definition.thumbRect(bounds: bounds, kind: .scrollBar, value: 100, minimum: 0, maximum: 100)! + #expect(thumb100.bottom == 184 && thumb100.top == 168) + #expect(definition.hitTest(Point(v: 180, h: 8), bounds: bounds, kind: .scrollBar, value: 100, minimum: 0, maximum: 100, isEnabled: true) == .thumb) + // The pages: below a thumb at the top, everything pages down. + #expect(definition.hitTest(Point(v: 100, h: 8), bounds: bounds, kind: .scrollBar, value: 0, minimum: 0, maximum: 100, isEnabled: true) == .pageDown) + let middle = definition.thumbRect(bounds: bounds, kind: .scrollBar, value: 50, minimum: 0, maximum: 100)! + let belowThumb = Int(middle.top) + middle.height + 4 + #expect(definition.hitTest(Point(v: Int16(belowThumb), h: 8), bounds: bounds, kind: .scrollBar, value: 50, minimum: 0, maximum: 100, isEnabled: true) == .pageDown) + // A horizontal bar: wider than tall, its arrows at the ends. + let horizontal = Rect(top: 0, left: 0, bottom: 16, right: 200) + let left = definition.rect(of: .upButton, bounds: horizontal, kind: .scrollBar, value: 0, minimum: 0, maximum: 100)! + let right = definition.rect(of: .downButton, bounds: horizontal, kind: .scrollBar, value: 0, minimum: 0, maximum: 100)! + #expect(left == Rect(top: 0, left: 0, bottom: 16, right: 16)) + #expect(right == Rect(top: 0, left: 184, bottom: 16, right: 200)) + #expect(definition.hitTest(Point(v: 8, h: 8), bounds: horizontal, kind: .scrollBar, value: 0, minimum: 0, maximum: 100, isEnabled: true) == .upButton) + #expect(definition.hitTest(Point(v: 8, h: 190), bounds: horizontal, kind: .scrollBar, value: 0, minimum: 0, maximum: 100, isEnabled: true) == .downButton) + #expect(definition.hitTest(Point(v: 8, h: 100), bounds: horizontal, kind: .scrollBar, value: 0, minimum: 0, maximum: 100, isEnabled: true) == .pageDown) + // A part a control doesn't have has no rectangle. + #expect(definition.rect(of: .thumb, bounds: Rect(top: 0, left: 0, bottom: 20, right: 90), + kind: .button, value: 0, minimum: 0, maximum: 1) == nil) + } + + @Test func shortScrollBars() { + // A bar shorter than its two arrows: no room at all between them, + // the fallback gives the space between the arrows, which is empty. + let short = Rect(top: 0, left: 0, bottom: 24, right: 16) + let thumb = definition.thumbRect(bounds: short, kind: .scrollBar, value: 0, minimum: 0, maximum: 100) + #expect(thumb == Rect(top: 16, left: 0, bottom: 8, right: 16)) + // A bar exactly as long as its arrows: the space between them is + // nothing, as the travel is zero. + let arrows = Rect(top: 0, left: 0, bottom: 32, right: 16) + let squeezed = definition.thumbRect(bounds: arrows, kind: .scrollBar, value: 0, minimum: 0, maximum: 100) + #expect(squeezed == Rect(top: 16, left: 0, bottom: 16, right: 16)) + // An empty range has no thumb at all: the bar is inactive. + #expect(definition.thumbRect(bounds: short, kind: .scrollBar, value: 0, minimum: 5, maximum: 5) == nil) + // A range of one: the fixed-size thumb, at the top of its travel + // for the minimum and the bottom for the maximum. + let one = Rect(top: 0, left: 0, bottom: 200, right: 16) + let full = definition.thumbRect(bounds: one, kind: .scrollBar, value: 0, minimum: 0, maximum: 1) + #expect(full?.top == 16 && full?.bottom == 32) + let fullTop = definition.thumbRect(bounds: one, kind: .scrollBar, value: 1, minimum: 0, maximum: 1) + #expect(fullTop?.top == 168 && fullTop?.bottom == 184) + } + + @Test func popUpMenus() { + // A pop-up menu is hit as a button: one part. + let bounds = Rect(top: 0, left: 0, bottom: 20, right: 120) + #expect(definition.hitTest(Point(v: 10, h: 60), bounds: bounds, kind: .popUpMenu, value: 0, minimum: 0, maximum: 1, isEnabled: true) == .button) + #expect(definition.hitTest(Point(v: 30, h: 60), bounds: bounds, kind: .popUpMenu, value: 0, minimum: 0, maximum: 1, isEnabled: true) == .none) + #expect(definition.hitTest(Point(v: 10, h: 60), bounds: bounds, kind: .popUpMenu, value: 0, minimum: 0, maximum: 1, isEnabled: false) == .disabled) + } +} diff --git a/Tests/GraphiteControlsTests/ControlResourceTests.swift b/Tests/GraphiteControlsTests/ControlResourceTests.swift new file mode 100644 index 0000000..111d70c --- /dev/null +++ b/Tests/GraphiteControlsTests/ControlResourceTests.swift @@ -0,0 +1,98 @@ +import Testing +import GraphiteBase +import GraphiteControls + +@Suite struct ControlResourceTests { + + /// A 'CNTL' resource's bytes: the rectangle, the initial setting, the + /// visibility, the fill, the maximum, the minimum, the definition ID, + /// the reference, and the title. + private func controlBytes(bounds: Rect, value: Int16, visible: Bool, maximum: Int16, minimum: Int16, + definitionID: Int16, reference: Int32, title: String) -> [UInt8] { + var bytes: [UInt8] = [] + // The rectangle, then the setting, the visibility, the fill, the + // maximum, the minimum, the definition ID — the order the resource + // keeps. + for value in [bounds.top, bounds.left, bounds.bottom, bounds.right] { + let raw = UInt16(bitPattern: value) + bytes += [UInt8(raw >> 8), UInt8(raw & 0xFF)] + } + let setting = UInt16(bitPattern: value) + bytes += [UInt8(setting >> 8), UInt8(setting & 0xFF)] + bytes += [visible ? 1 : 0, 0] + for field in [maximum, minimum, definitionID] { + let raw = UInt16(bitPattern: field) + bytes += [UInt8(raw >> 8), UInt8(raw & 0xFF)] + } + let referenceRaw = UInt32(bitPattern: reference) + bytes += [UInt8(referenceRaw >> 24), UInt8(referenceRaw >> 16 & 0xFF), + UInt8(referenceRaw >> 8 & 0xFF), UInt8(referenceRaw & 0xFF)] + let titleBytes = MacRoman.encode(title)! + bytes += [UInt8(titleBytes.count)] + titleBytes + return bytes + } + + @Test func readingControls() throws { + // A visible OK button. + let button = try Control.make(bytes: controlBytes(bounds: Rect(top: 10, left: 10, bottom: 30, right: 90), + value: 0, visible: true, maximum: 1, minimum: 0, + definitionID: 0, reference: 0, title: "OK")) + #expect(button.kind == .button) + #expect(button.bounds == Rect(top: 10, left: 10, bottom: 30, right: 90)) + #expect(button.title == "OK") + #expect(button.isVisible) + #expect(button.maximum == 1 && button.minimum == 0 && button.value == 0) + #expect(button.reference == 0) + // A checkbox, on, with a useWFont variation. + let checkBox = try Control.make(bytes: controlBytes(bounds: Rect(top: 40, left: 10, bottom: 60, right: 200), + value: 1, visible: true, maximum: 1, minimum: 0, + definitionID: 1, reference: 0, title: "Bold")) + #expect(checkBox.kind == .checkBox && checkBox.isOn) + // A radio button. + let radio = try Control.make(bytes: controlBytes(bounds: Rect(top: 60, left: 10, bottom: 80, right: 200), + value: 0, visible: true, maximum: 1, minimum: 0, + definitionID: 2, reference: 0, title: "Small")) + #expect(radio.kind == .radioButton && !radio.isOn) + // A horizontal scroll bar, its range and its place in it. + let bar = try Control.make(bytes: controlBytes(bounds: Rect(top: 0, left: 0, bottom: 16, right: 200), + value: 30, visible: true, maximum: 100, minimum: 0, + definitionID: 16, reference: 0, title: "")) + #expect(bar.kind == .scrollBar) + #expect(bar.value == 30 && bar.minimum == 0 && bar.maximum == 100) + // An invisible pop-up menu, holding its menu's resource ID in its + // minimum, as the classic kept it. + let popUp = try Control.make(bytes: controlBytes(bounds: Rect(top: 0, left: 0, bottom: 20, right: 120), + value: 1, visible: false, maximum: 60, minimum: 128, + definitionID: 1008, reference: 0, title: "Font")) + #expect(popUp.kind == .popUpMenu) + #expect(!popUp.isVisible) + #expect(popUp.minimum == 128 && popUp.maximum == 60) + // Bytes past the title are ignored. + var extra = controlBytes(bounds: Rect(top: 0, left: 0, bottom: 20, right: 90), value: 0, visible: true, + maximum: 1, minimum: 0, definitionID: 0, reference: 0, title: "OK") + extra += [0, 128] + #expect(try Control.make(bytes: extra).title == "OK") + } + + @Test func damagedResources() { + // Cut off inside the rectangle. + #expect(throws: MacError.parameter) { + _ = try Control.make(bytes: [0, 0, 0, 0, 0, 100]) + } + // Nothing at all. + #expect(throws: MacError.parameter) { + _ = try Control.make(bytes: []) + } + // Cut off inside the reference value. + #expect(throws: MacError.parameter) { + _ = try Control.make(bytes: [0, 0, 0, 10, 0, 20, 0, 30, 0, 0, 1, 0, 1, 0, 0, 0, 16, 0, 0, 0, 0, 1]) + } + // A definition ID the standard kinds don't answer and no host + // definition was given for. + #expect(throws: MacError.parameter) { + _ = try Control.make(bytes: controlBytes(bounds: Rect(top: 0, left: 0, bottom: 20, right: 90), + value: 0, visible: true, maximum: 1, minimum: 0, + definitionID: 63, reference: 0, title: "?")) + } + } +} diff --git a/Tests/GraphiteControlsTests/ControlTests.swift b/Tests/GraphiteControlsTests/ControlTests.swift new file mode 100644 index 0000000..b667bc7 --- /dev/null +++ b/Tests/GraphiteControlsTests/ControlTests.swift @@ -0,0 +1,145 @@ +import Testing +import Synchronization +import GraphiteBase +import GraphiteControls + +@Suite struct ControlTests { + + @Test func constants() { + #expect(ControlPart.none.rawValue == 0) + #expect(ControlPart.button.rawValue == 10) + #expect(ControlPart.checkBox.rawValue == 11) + #expect(ControlPart.upButton.rawValue == 20) + #expect(ControlPart.downButton.rawValue == 21) + #expect(ControlPart.pageUp.rawValue == 22) + #expect(ControlPart.pageDown.rawValue == 23) + #expect(ControlPart.thumb.rawValue == 129) + #expect(ControlPart.disabled.rawValue == 254) + #expect(ControlPart.inactive.rawValue == 255) + // The classic's control definition IDs. + #expect(ControlKind.button.definitionID == 0) + #expect(ControlKind.checkBox.definitionID == 1) + #expect(ControlKind.radioButton.definitionID == 2) + #expect(ControlKind.scrollBar.definitionID == 16) + #expect(ControlKind.popUpMenu.definitionID == 1008) + #expect(ControlKind(definitionID: 0) == .button) + #expect(ControlKind(definitionID: 8) == .button) + #expect(ControlKind(definitionID: 1) == .checkBox) + #expect(ControlKind(definitionID: 2) == .radioButton) + #expect(ControlKind(definitionID: 16) == .scrollBar) + #expect(ControlKind(definitionID: 1008) == .popUpMenu) + // A definition the standard kinds don't answer: the host's. + #expect(ControlKind(definitionID: 63) == nil) + #expect(ControlKind(definitionID: 3) == nil) + #expect(ControlKind(definitionID: 1024) == nil) + } + + @Test func makingControls() { + let button = Control(kind: .button, bounds: Rect(top: 10, left: 10, bottom: 30, right: 90), title: "OK") + #expect(button.kind == .button) + #expect(button.bounds == Rect(top: 10, left: 10, bottom: 30, right: 90)) + #expect(button.title == "OK") + #expect(button.isVisible && button.isEnabled && button.isActive) + #expect(button.hilitedPart == .none) + // A button's maximum is 1, as the classic's resources kept it. + #expect(button.maximum == 1 && button.minimum == 0 && button.value == 0) + #expect(button.valueKind == .none) + let checkBox = Control(kind: .checkBox, bounds: Rect(top: 0, left: 0, bottom: 20, right: 200), title: "Bold") + #expect(checkBox.valueKind == .onOff) + #expect(checkBox.maximum == 1 && checkBox.minimum == 0) + let bar = Control(kind: .scrollBar, bounds: Rect(top: 0, left: 0, bottom: 200, right: 16)) + #expect(bar.valueKind == .range) + } + + @Test func values() { + let bar = Control(kind: .scrollBar, bounds: Rect(top: 0, left: 0, bottom: 200, right: 16)) + bar.minimum = 0 + bar.maximum = 100 + bar.setValue(50) + #expect(bar.value == 50) + // The value stops at its range's edges. + bar.setValue(200) + #expect(bar.value == 100) + bar.setValue(-10) + #expect(bar.value == 0) + // An empty range pins everything to the minimum. + bar.maximum = 0 + bar.setValue(40) + #expect(bar.value == 0) + // A checkbox's on-or-off. + let checkBox = Control(kind: .checkBox, bounds: Rect(top: 0, left: 0, bottom: 20, right: 200)) + #expect(!checkBox.isOn) + checkBox.setValue(1) + #expect(checkBox.isOn) + } + + @Test func thumbValues() { + let bar = Control(kind: .scrollBar, bounds: Rect(top: 0, left: 0, bottom: 200, right: 16)) + bar.minimum = 0 + bar.maximum = 100 + bar.setValue(0) + // The value at a point: the middle names the range's middle. + #expect(bar.value(at: Point(v: 100, h: 8)) == 50) + #expect(bar.value(at: Point(v: 24, h: 8)) == 0) + #expect(bar.value(at: Point(v: 184, h: 8)) == 100) + // Outside the bar pins to the edges. + #expect(bar.value(at: Point(v: -20, h: 8)) == 0) + #expect(bar.value(at: Point(v: 300, h: 8)) == 100) + // A control without a thumb has no value at a point. + let button = Control(kind: .button, bounds: Rect(top: 0, left: 0, bottom: 20, right: 90)) + #expect(button.value(at: Point(v: 10, h: 10)) == nil) + // An empty range: the bar is inactive, with no thumb to drag. + bar.maximum = 0 + #expect(bar.value(at: Point(v: 100, h: 8)) == nil) + } + + @Test func states() { + let button = Control(kind: .button, bounds: Rect(top: 0, left: 0, bottom: 20, right: 90), title: "OK") + #expect(button.isLive) + button.hide() + #expect(!button.isVisible && !button.isLive) + button.show() + button.disable() + #expect(!button.isEnabled && !button.isLive) + button.enable() + button.deactivate() + #expect(!button.isActive && !button.isLive) + button.activate() + #expect(button.isLive) + // HiliteControl's part, drawn pressed. + button.hilite(.button) + #expect(button.hilitedPart == .button) + button.hilite(.none) + #expect(button.hilitedPart == .none) + // Whatever the program keeps with the control, and its command and + // its identifier. + button.reference = 129 + #expect(button.reference == 129) + button.commandID = "ok " + #expect(button.commandID == "ok ") + button.identifier = (signature: "com.", id: 5) + #expect(button.identifier?.signature == "com.") + #expect(button.identifier?.id == 5) + // The action procedure, called by the host as it tracks. The part + // it was called with, kept through a lock the closure can hold. + let called = Mutex<[ControlPart]>([]) + button.action = { part, _ in called.withLock { $0.append(part) } } + button.action?(.button, 0) + #expect(called.withLock { $0 } == [.button]) + } + + @Test func movingAndSizing() { + let button = Control(kind: .button, bounds: Rect(top: 10, left: 20, bottom: 30, right: 90), title: "OK") + button.move(h: 100, v: 50) + #expect(button.bounds == Rect(top: 50, left: 100, bottom: 70, right: 170)) + button.size(width: 40, height: 25) + #expect(button.bounds == Rect(top: 50, left: 100, bottom: 75, right: 140)) + } + + @Test func titles() { + let button = Control(kind: .button, bounds: Rect(top: 0, left: 0, bottom: 20, right: 90), title: "Répéter") + #expect(button.title == "Répéter") + button.title = "Annuler" + #expect(button.title == "Annuler") + } +}