Files
mac_without_borders/Sources/MWBMac/StatusItem.swift
T
lucioandClaude Opus 5 6b2b3fc65a app-ui: menu bar, settings window, notifications, login item
The real user interface, replacing app-engine's placeholder status item.

- MWBMac/StatusItem.swift: NSStatusItem with a code-drawn icon, the
  documented status colours (doc/devdocs/modules/mousewithoutborders.md)
  and the menu the Windows tray menu offers (frmScreen.Designer.cs:91-180).
- MWBMac/SettingsWindow/*: one NSWindow hosting a SwiftUI TabView with six
  panes; every property in README §Settings is reachable. Labels and help
  text taken from MouseWithoutBordersPage.xaml + Resources.resw, cited per
  file.
- MWBMac/Notifications.swift, LaunchAgent.swift: UNUserNotificationCenter
  and SMAppService.mainApp, both guarded on a bundle identifier.
- mwb/UIBridge.swift: EngineSnapshot -> StatusModel, clicks -> Engine, and
  the connected/lost/invalid-key notification diff.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-16 04:14:11 -07:00

384 lines
16 KiB
Swift

// The menu bar: one `NSStatusItem`, its drawn icon, and the menu that is rebuilt
// from every engine snapshot.
//
// The Windows equivalent is the notify icon and its context menu on
// `Form/frmScreen.cs` (`frmScreen.Designer.cs:91-180` for the items,
// `Core/Common.cs` `ShowMenu` for when it is rebuilt); the machine rows and the
// status colours are the matrix form's (`Form/frmMatrix.cs`) job there. The
// colours themselves are the documented table in
// `doc/devdocs/modules/mousewithoutborders.md`.
//
// This file knows nothing about the Engine: it takes a value (`StatusModel`) and
// a set of closures (`StatusActions`). `mwb/UIBridge.swift` is what maps an
// `EngineSnapshot` onto them, because `EngineSnapshot` and `PeerStatus` live in
// targets `MWBMac` may not import (README D2).
import AppKit
import Foundation
import MWBCore
/// The colour a connection status is painted in.
///
/// Straight from `doc/devdocs/modules/mousewithoutborders.md` § Status colors, so
/// a user who knows the Windows colours reads the Mac menu without relearning.
public enum StatusColor {
/// The dot colour for a peer in this state.
public static func nsColor(for status: SocketStatus) -> NSColor {
switch status {
case .na: return NSColor(srgbRed: 0x71 / 255, green: 0x71 / 255, blue: 0x71 / 255, alpha: 1)
case .resolving: return NSColor(srgbRed: 1, green: 1, blue: 0, alpha: 1)
case .connecting: return NSColor(srgbRed: 1, green: 0xA5 / 255, blue: 0, alpha: 1)
case .handshaking: return NSColor(srgbRed: 0, green: 0, blue: 1, alpha: 1)
case .error: return NSColor(srgbRed: 1, green: 0, blue: 0, alpha: 1)
case .forceClosed: return NSColor(srgbRed: 0x80 / 255, green: 0, blue: 0x80 / 255, alpha: 1)
case .invalidKey:
return NSColor(srgbRed: 0xA5 / 255, green: 0x2A / 255, blue: 0x2A / 255, alpha: 1)
case .timeout:
return NSColor(srgbRed: 1, green: 0xC0 / 255, blue: 0xCB / 255, alpha: 1)
case .sendError: return NSColor(srgbRed: 0x80 / 255, green: 0, blue: 0, alpha: 1)
case .connected: return NSColor(srgbRed: 0, green: 0x80 / 255, blue: 0, alpha: 1)
}
}
/// This Mac's own dot: the user's accent colour, so the local row is obvious.
public static var local: NSColor { .controlAccentColor }
/// The word shown after a machine's name.
public static func name(for status: SocketStatus) -> String {
switch status {
case .na: return "not connected"
case .resolving: return "resolving"
case .connecting: return "connecting"
case .handshaking: return "handshaking"
case .error: return "error"
case .forceClosed: return "closed"
case .invalidKey: return "wrong security key"
case .timeout: return "timed out"
case .sendError: return "send error"
case .connected: return "connected"
}
}
}
/// One machine as the menu shows it.
public struct MachineRow: Sendable, Equatable {
/// The machine's name on the wire.
public var name: String
/// Its connection state; `.na` for a matrix slot with no connection at all.
public var status: SocketStatus
/// True for this Mac.
public var isLocal: Bool
/// True for the machine currently receiving input.
public var isControlled: Bool
/// Its matrix slot, when it has one; `nil` for a peer that dialled in without
/// being listed. Only a row with a slot can be switched to (⌃⌥F<slot+1>).
public var slot: Int?
/// A row.
public init(
name: String, status: SocketStatus, isLocal: Bool = false, isControlled: Bool = false,
slot: Int? = nil
) {
self.name = name
self.status = status
self.isLocal = isLocal
self.isControlled = isControlled
self.slot = slot
}
}
/// Everything the status item draws, in one comparable value.
public struct StatusModel: Sendable, Equatable {
/// The matrix slots, then any peer that is not in the matrix.
public var rows: [MachineRow] = []
/// The machine receiving input, `nil` when that is this Mac.
public var controlled: String?
/// ALL-machines mode.
public var broadcasting = false
/// `EasyMouse` as it stands.
public var easyMouse: EasyMouseMode = .enable
/// The grants that are missing, in the words System Settings uses; empty when
/// both are held.
public var missingPermissions: [String] = []
/// False when no `CGEventSource` could be made, so nothing can be injected.
public var canInject = true
/// False when the event tap is not installed.
public var tapRunning = true
/// Why the host name is unusable, when it is (README D7).
public var hostnameProblem: String?
/// The last thing that took control back, already worded (contracts C2).
public var lastRecovery: String?
/// The lock hotkey, for the menu label.
public var lockHotkey = HotkeyConfig().lock
/// The reconnect hotkey, for the menu label.
public var reconnectHotkey = HotkeyConfig().reconnect
/// The first of the four switch-machine virtual keys, for the row labels.
public var switchMachineVK = HotkeyConfig().switchMachineVK
/// The build version, shown in the menu's last section.
public var version = ""
/// An empty model.
public init() {}
/// True when anything is wrong enough to badge the icon.
public var hasProblem: Bool {
hostnameProblem != nil || !missingPermissions.isEmpty || !canInject || !tapRunning
|| rows.contains { !$0.isLocal && $0.status != .connected && $0.status != .na }
}
}
/// What the menu can ask the app to do.
///
/// A struct of closures rather than a delegate protocol: there is exactly one
/// implementation (`UIBridge`) and nothing here needs to call back.
@MainActor public struct StatusActions {
/// Give control to the machine in this matrix slot.
public var switchTo: (Int) -> Void
/// Bring control back to this Mac when it has no matrix slot to name.
public var switchHome: () -> Void
/// Turn ALL-machines mode on or off.
public var switchToAll: () -> Void
/// Flip `EasyMouse` between Enable and Disable.
public var toggleEasyMouse: () -> Void
/// Re-open every socket.
public var reconnect: () -> Void
/// Lock every machine, this one included.
public var lockAll: () -> Void
/// Show the settings window, optionally on a named pane.
public var openSettings: (SettingsPane?) -> Void
/// Quit.
public var quit: () -> Void
/// The actions the status item calls.
public init(
switchTo: @escaping (Int) -> Void, switchHome: @escaping () -> Void,
switchToAll: @escaping () -> Void, toggleEasyMouse: @escaping () -> Void,
reconnect: @escaping () -> Void, lockAll: @escaping () -> Void,
openSettings: @escaping (SettingsPane?) -> Void, quit: @escaping () -> Void
) {
self.switchTo = switchTo
self.switchHome = switchHome
self.switchToAll = switchToAll
self.toggleEasyMouse = toggleEasyMouse
self.reconnect = reconnect
self.lockAll = lockAll
self.openSettings = openSettings
self.quit = quit
}
}
/// The menu-bar item and its menu.
@MainActor public final class StatusItemController {
private let item: NSStatusItem
private let actions: StatusActions
private var model = StatusModel()
private var drawn: StatusModel?
/// Creates the item. The menu is empty until the first `update(_:)`.
public init(actions: StatusActions) {
self.actions = actions
item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
item.button?.image = StatusIcon.image(badge: nil)
item.button?.toolTip = "Mouse Without Borders"
item.menu = NSMenu()
}
/// Redraws the icon and rebuilds the menu, if anything changed.
public func update(_ model: StatusModel) {
guard model != drawn else { return }
self.model = model
drawn = model
item.button?.image = StatusIcon.image(badge: badgeColour(model))
item.button?.toolTip = tooltip(model)
item.menu = buildMenu(model)
}
/// Takes the item out of the menu bar. Used on quit so the icon does not
/// linger while the engine says goodbye.
public func remove() {
NSStatusBar.system.removeStatusItem(item)
}
// MARK: - Drawing
private func badgeColour(_ model: StatusModel) -> NSColor? {
if model.hostnameProblem != nil || !model.missingPermissions.isEmpty || !model.canInject {
return StatusColor.nsColor(for: .error)
}
if !model.tapRunning { return StatusColor.nsColor(for: .connecting) }
let unhappy = model.rows.first {
!$0.isLocal && $0.status != .connected && $0.status != .na
}
return unhappy.map { StatusColor.nsColor(for: $0.status) }
}
private func tooltip(_ model: StatusModel) -> String {
if let problem = model.hostnameProblem { return "Mouse Without Borders — \(problem)" }
if let controlled = model.controlled {
return "Mouse Without Borders — controlling \(controlled)"
}
return "Mouse Without Borders"
}
// MARK: - The menu (`frmScreen.Designer.cs:91-180`)
private func buildMenu(_ model: StatusModel) -> NSMenu {
let menu = NSMenu()
menu.autoenablesItems = false
for row in model.rows { menu.addItem(machineItem(row, model: model)) }
if model.rows.isEmpty { menu.addItem(disabled("No machines configured")) }
menu.addItem(.separator())
// `MenuAllPC` ("&ALL COMPUTERS", `frmScreen.Designer.cs:174`).
let all = item(
"Control All Computers", #selector(switchToAllClicked), checked: model.broadcasting)
all.isEnabled = model.rows.contains { !$0.isLocal }
menu.addItem(all)
menu.addItem(
item(
"Easy Mouse", #selector(toggleEasyMouseClicked),
checked: model.easyMouse == .enable))
menu.addItem(
item("Reconnect \(HotkeyText.describe(model.reconnectHotkey))", #selector(reconnectClicked)))
menu.addItem(
item("Lock All Machines \(HotkeyText.describe(model.lockHotkey))", #selector(lockAllClicked)))
menu.addItem(.separator())
for line in problemItems(model) { menu.addItem(line) }
menu.addItem(item("Settings…", #selector(settingsClicked), key: ","))
menu.addItem(disabled("Mouse Without Borders \(model.version)"))
menu.addItem(item("Quit Mouse Without Borders", #selector(quitClicked), key: "q"))
return menu
}
private func machineItem(_ row: MachineRow, model: StatusModel) -> NSMenuItem {
var title = row.name.isEmpty ? "(empty)" : row.name
title += row.isLocal ? " — this Mac" : " — \(StatusColor.name(for: row.status))"
// Shown as a label, never as a real key equivalent: the ⌃⌥F<n> hotkeys
// belong to the event tap, which sees them before any menu does.
if let slot = row.slot, let key = HotkeyText.switchMachineLabel(model.switchMachineVK, slot) {
title += " (\(key))"
}
let entry = item(title, #selector(machineClicked), checked: row.isControlled)
entry.image = StatusIcon.dot(row.isLocal ? StatusColor.local : StatusColor.nsColor(for: row.status))
entry.representedObject = row.slot.map(NSNumber.init(value:))
entry.isEnabled = !row.name.isEmpty && (row.slot != nil || row.isLocal)
return entry
}
/// The three states that mean "this app cannot do its job" (app-engine
/// request 2), plus the last recovery, each as a clickable line.
private func problemItems(_ model: StatusModel) -> [NSMenuItem] {
var items: [NSMenuItem] = []
if let problem = model.hostnameProblem {
items.append(disabled("Host name unusable: \(problem)"))
}
if model.missingPermissions.isEmpty {
items.append(disabled("Permissions: OK"))
} else {
items.append(
item(
"Permissions missing: \(model.missingPermissions.joined(separator: ", "))…",
#selector(permissionsClicked)))
}
if !model.canInject { items.append(disabled("Cannot inject events on this Mac")) }
if !model.tapRunning && model.missingPermissions.isEmpty {
items.append(disabled("Input capture is not running"))
}
if let recovery = model.lastRecovery {
items.append(disabled("Control returned: \(recovery)"))
}
items.append(.separator())
return items
}
private func item(
_ title: String, _ action: Selector, key: String = "", checked: Bool = false
) -> NSMenuItem {
let entry = NSMenuItem(title: title, action: action, keyEquivalent: key)
entry.target = self
entry.state = checked ? .on : .off
entry.isEnabled = true
return entry
}
private func disabled(_ title: String) -> NSMenuItem {
let entry = NSMenuItem(title: title, action: nil, keyEquivalent: "")
entry.isEnabled = false
return entry
}
// MARK: - Actions
@objc private func machineClicked(_ sender: NSMenuItem) {
guard let slot = (sender.representedObject as? NSNumber)?.intValue else {
actions.switchHome()
return
}
actions.switchTo(slot)
}
@objc private func switchToAllClicked() { actions.switchToAll() }
@objc private func toggleEasyMouseClicked() { actions.toggleEasyMouse() }
@objc private func reconnectClicked() { actions.reconnect() }
@objc private func lockAllClicked() { actions.lockAll() }
@objc private func settingsClicked() { actions.openSettings(nil) }
@objc private func permissionsClicked() { actions.openSettings(.advanced) }
@objc private func quitClicked() { actions.quit() }
}
/// The item's artwork, drawn in code so the package needs no asset catalog.
enum StatusIcon {
/// Two overlapping rounded rectangles — one screen in front of another —
/// with an optional status badge in the lower-right corner.
///
/// Without a badge the image is a template, so AppKit tints it for a light or
/// dark menu bar and for the highlighted state. With one it cannot be, since
/// a template image is painted in a single colour; the glyph is then drawn in
/// `labelColor`, which the drawing handler resolves against the appearance in
/// force when the image is actually drawn.
static func image(badge: NSColor?) -> NSImage {
let size = NSSize(width: 18, height: 14)
let image = NSImage(size: size, flipped: false) { _ in
let stroke = badge == nil ? NSColor.black : NSColor.labelColor
stroke.setStroke()
back(in: size).stroke()
let front = NSBezierPath(
roundedRect: NSRect(x: 5.5, y: 1.5, width: 11, height: 8), xRadius: 2, yRadius: 2)
front.lineWidth = 1.2
NSColor.clear.setFill()
front.stroke()
if let badge {
badge.setFill()
NSBezierPath(ovalIn: NSRect(x: 12, y: 0, width: 5, height: 5)).fill()
}
return true
}
image.isTemplate = badge == nil
return image
}
private static func back(in size: NSSize) -> NSBezierPath {
let path = NSBezierPath(
roundedRect: NSRect(x: 1.5, y: 4.5, width: 11, height: 8), xRadius: 2, yRadius: 2)
path.lineWidth = 1.2
return path
}
/// A filled circle for a menu row, at menu-image size.
static func dot(_ colour: NSColor) -> NSImage {
let size = NSSize(width: 10, height: 10)
let image = NSImage(size: size, flipped: false) { _ in
colour.setFill()
NSBezierPath(ovalIn: NSRect(x: 1, y: 1, width: 8, height: 8)).fill()
NSColor.separatorColor.setStroke()
let ring = NSBezierPath(ovalIn: NSRect(x: 1, y: 1, width: 8, height: 8))
ring.lineWidth = 0.5
ring.stroke()
return true
}
image.isTemplate = false
return image
}
}