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]>
This commit is contained in:
lucioandClaude Opus 5 committed 2026-09-16 04:14:11 -07:00
1 parent bce5c3c36e
commit 6b2b3fc65a
14 files changed
+2023 -78

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
// Launch at login.
//
// Windows registers `Run` key entries and, in service mode, a Windows service
// (`Class/Program.cs`, `Core/Service.cs`); neither has a macOS equivalent worth
// porting (README D6). `SMAppService.mainApp` is the whole macOS answer: it
// registers the *bundle* with the login-items machinery, and the user can turn it
// off again in System Settings > General > Login Items.
//
// It needs a real bundle with a bundle identifier and a code signature. Run
// unbundled — `swift run`, or the binary straight out of `.build` — there is
// nothing to register, so `isAvailable` is false and the UI says why rather than
// throwing at the user.
import Foundation
import ServiceManagement
/// The login-item registration for this app.
public enum LaunchAtLogin {
/// False when the process is not running from an app bundle, in which case
/// nothing here does anything.
public static var isAvailable: Bool {
Bundle.main.bundleIdentifier != nil && Bundle.main.bundleURL.pathExtension == "app"
}
/// Whether macOS will start this app at login.
public static var isEnabled: Bool {
guard isAvailable else { return false }
return SMAppService.mainApp.status == .enabled
}
/// Why the toggle is off when it is not simply "the user said no":
/// `requiresApproval` means the registration exists but the user has to
/// switch it on in System Settings, which is macOS's rule, not ours.
public static var needsApproval: Bool {
guard isAvailable else { return false }
return SMAppService.mainApp.status == .requiresApproval
}
/// Registers or unregisters. Throws what `SMAppService` throws, which the
/// caller shows verbatim: the failures are all "this copy is not where macOS
/// will trust it from" and only the user can move it.
public static func set(_ enabled: Bool) throws {
guard isAvailable else { return }
if enabled {
try SMAppService.mainApp.register()
} else {
try SMAppService.mainApp.unregister()
}
}
}
+82
View File
@@ -0,0 +1,82 @@
// Status notifications — the macOS shape of `Common.ShowToolTip`.
//
// Windows pops a balloon from its tray icon for clipboard activity and network
// events, gated on the `ShowClipboardAndNetworkStatusMessages` setting
// (`Core/Clipboard.cs:451, 880, 916`, all passing
// `Setting.Values.ShowClipNetStatus`; `MouseWithoutBorders_ShowClipboardAndNetwork
// StatusMessages.Description`: "Show clipboard activities and network status in
// system tray notifications"). `UNUserNotificationCenter` is the macOS
// equivalent, with two macOS-only rules:
//
// 1. It needs a bundle identifier. Unbundled — `swift run` — every call throws
// or traps, so the whole class turns into a no-op instead.
// 2. Authorization is asked for once, when the user turns the setting on, and
// never on our own initiative.
import Foundation
import UserNotifications
/// Posts the "connected / lost / wrong key" notifications, when the user has
/// asked for them.
@MainActor public final class Notifier {
private var enabled = false
private var authorizationAsked = false
/// Creates a notifier. Nothing is posted until `enabledChanged(true)`.
public init() {}
/// True when this process can post at all: an app bundle with an identifier.
public var isAvailable: Bool { Bundle.main.bundleIdentifier != nil }
/// Follows the `ShowClipboardAndNetworkStatusMessages` setting. Turning it on
/// asks macOS for permission the first time, which is a prompt the user has
/// just invited by ticking the box.
public func enabledChanged(_ isOn: Bool) {
guard isAvailable else { return }
enabled = isOn
guard isOn, !authorizationAsked else { return }
authorizationAsked = true
UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) { granted, error in
if let error {
Log.app.error("notification authorization failed: \(error.localizedDescription)")
} else if !granted {
Log.app.info("notifications not allowed; status messages will not be shown")
}
}
}
/// Posts one notification, if they are switched on.
public func post(title: String, body: String) {
guard enabled, isAvailable else { return }
let content = UNMutableNotificationContent()
content.title = title
content.body = body
let request = UNNotificationRequest(
identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
if let error {
Log.app.error("could not post notification: \(error.localizedDescription)")
}
}
}
/// "Connecting to X" is what Windows says as it dials (`Clipboard.cs:451`);
/// we say it once the peer is trusted, which is the moment worth telling the
/// user about.
public func connected(to machine: String) {
post(title: "Mouse Without Borders", body: "Connected to \(machine).")
}
/// A peer that was connected went away, for any reason (contracts C2).
public func lost(_ machine: String) {
post(title: "Mouse Without Borders", body: "Lost the connection to \(machine).")
}
/// The peer does not share our key, so nothing it sends is acted on
/// (CLAUDE.md invariant 2).
public func invalidKey(for machine: String) {
post(
title: "Mouse Without Borders",
body: "\(machine) is using a different security key. Set the same key on both machines.")
}
}
@@ -0,0 +1,147 @@
// The Advanced pane: the three things that are macOS's business rather than the
// protocol's — the two TCC grants, the login item, and where the files are.
//
// Windows needs none of this: a low-level hook needs no permission there, and
// the PowerToys page's "Troubleshooting" group offers a firewall rule instead
// (`MouseWithoutBordersPage.xaml:481-496`). The equivalent trouble on this side
// is Accessibility and Input Monitoring (README D5, Permissions), so that is
// what this pane leads with.
//
// CLAUDE.md, Workflow: `Permissions.request()` is called from exactly one place
// in the repository, the button below, and only because the user pressed it.
import AppKit
import Foundation
import MWBCore
import SwiftUI
/// Permissions, login item, files and versions.
struct AdvancedPane: View {
@ObservedObject var model: SettingsViewModel
@State private var launchAtLogin = LaunchAtLogin.isEnabled
@State private var launchAtLoginProblem: String?
/// System Settings deep links. `Privacy_ListenEvent` is Input Monitoring and
/// `Privacy_Accessibility` is Accessibility; both are read by System
/// Settings, not by us, and a wrong one simply opens the Privacy root.
private static let accessibilityURL =
"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"
private static let inputMonitoringURL =
"x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent"
var body: some View {
SettingsPaneLayout {
SettingsSection(
"Permissions",
note:
"macOS ties both grants to the app's code signature, so they have to be "
+ "given again if the app is rebuilt with a different signature."
) {
permissionRow(
"Input Monitoring", granted: model.permissions.listen,
why: "Needed to see the keyboard and mouse, so this Mac can control another.",
url: AdvancedPane.inputMonitoringURL)
permissionRow(
"Accessibility", granted: model.permissions.post,
why:
"Needed to swallow input while another machine has control, and to type "
+ "and move the pointer when this Mac is being controlled.",
url: AdvancedPane.accessibilityURL)
HStack {
Button("Request…") { requestPermissions() }
.disabled(model.permissions.isComplete)
Text("Shows the macOS prompts for whatever is still missing.")
.font(.callout).foregroundStyle(.secondary)
Spacer()
}
}
SettingsSection("Startup") {
SettingsToggle(
"Launch at login",
help: launchAtLoginHelp,
isOn: Binding(get: { launchAtLogin }, set: { setLaunchAtLogin($0) })
)
.disabled(!LaunchAtLogin.isAvailable)
}
SettingsSection("Files") {
SettingsRow("Settings file", help: model.settingsFileURL.path) {
Button("Show in Finder") {
NSWorkspace.shared.activateFileViewerSelecting([model.settingsFileURL])
}
}
SettingsRow("Log file", help: Log.fileURL().path) {
Button("Show in Finder") {
NSWorkspace.shared.activateFileViewerSelecting([Log.fileURL()])
}
}
}
SettingsSection("This machine") {
labelled("Version", MWBVersion.string)
labelled("Host name", model.localName.isEmpty ? "(none)" : model.localName)
labelled("Machine ID", String(model.settings.machineID))
labelled("Device ID", model.settings.deviceID)
}
}
.onAppear { launchAtLogin = LaunchAtLogin.isEnabled }
}
private var launchAtLoginHelp: String {
if !LaunchAtLogin.isAvailable {
return "Only available when running from the app bundle."
}
if let launchAtLoginProblem { return launchAtLoginProblem }
if LaunchAtLogin.needsApproval {
return "Waiting for approval in System Settings > General > Login Items."
}
return "Starts Mouse Without Borders when you log in."
}
private func permissionRow(
_ title: String, granted: Bool, why: String, url: String
) -> some View {
SettingsRow(title, help: why) {
HStack(spacing: 8) {
Label(
granted ? "Granted" : "Missing",
systemImage: granted ? "checkmark.circle.fill" : "exclamationmark.triangle.fill"
)
.foregroundStyle(granted ? Color.green : Color.red)
Button("Open System Settings") { open(url) }
}
}
}
private func labelled(_ title: String, _ value: String) -> some View {
HStack(alignment: .firstTextBaseline) {
Text(title).foregroundStyle(.secondary)
Spacer()
Text(value.isEmpty ? "—" : value).textSelection(.enabled)
.font(.system(.body, design: .monospaced))
}
}
/// The one call site (CLAUDE.md, Workflow).
private func requestPermissions() {
model.permissions = Permissions.request()
}
private func setLaunchAtLogin(_ enabled: Bool) {
do {
try LaunchAtLogin.set(enabled)
launchAtLogin = LaunchAtLogin.isEnabled
launchAtLoginProblem = nil
} catch {
launchAtLogin = LaunchAtLogin.isEnabled
launchAtLoginProblem = error.localizedDescription
Log.app.error("login item change failed: \(error.localizedDescription)")
}
}
private func open(_ url: String) {
guard let target = URL(string: url) else { return }
NSWorkspace.shared.open(target)
}
}
@@ -0,0 +1,111 @@
// The Behaviour pane: what the mouse, the clipboard and Easy Mouse do.
//
// Every label and explanation here is the modern PowerToys page's, from
// `Settings.UI/Strings/en-us/Resources.resw` via
// `SettingsXAML/Views/MouseWithoutBordersPage.xaml:222-352` — "Mouse behavior",
// "Share clipboard", "Easy Mouse: move between machines by moving the mouse
// pointer to the screen edges", and so on. Where a phrase is Windows-only it is
// re-worded for the Mac and the deviation is noted in the feature README.
import Foundation
import MWBCore
import SwiftUI
/// The behaviour flags.
struct BehaviourPane: View {
@ObservedObject var model: SettingsViewModel
var body: some View {
SettingsPaneLayout {
SettingsSection("Mouse behavior") {
SettingsToggle(
"Hide mouse at the screen edge",
help:
"Hide the cursor at the top edge when switching to another machine, and "
+ "take focus from full-screen apps to ensure keyboard input is "
+ "redirected.",
isOn: model.binding(\.hideMouseAtScreenEdge))
SettingsToggle(
"Move mouse relatively",
help:
"Use this option when the remote machine's monitor settings are "
+ "different, or the remote machine has multiple monitors.",
isOn: model.binding(\.moveMouseRelatively))
SettingsToggle(
"Block mouse at screen corners to avoid accident machine-switch at screen "
+ "corners",
isOn: model.binding(\.blockMouseAtScreenCorners))
}
SettingsSection("Easy Mouse") {
Picker(
"Move between machines by moving the mouse pointer to the screen edges",
selection: model.binding(\.easyMouse)
) {
Text("Disabled").tag(EasyMouseMode.disable)
Text("Enabled").tag(EasyMouseMode.enable)
Text("Ctrl").tag(EasyMouseMode.ctrl)
Text("Shift").tag(EasyMouseMode.shift)
}
.pickerStyle(.radioGroup)
SettingsToggle(
"Disable Easy Mouse when an application is running in full screen",
help:
"Prevent Easy Mouse from moving to another machine when an application "
+ "is in full-screen mode. This only affects this Mac; it does not stop "
+ "the mouse moving away from remote machines.",
isOn: model.binding(\.disableEasyMouseWhenFullscreen))
Text("Ignored full-screen applications")
.font(.subheadline)
Text(
"Allow Easy Mouse to move between machines even if one of these applications "
+ "is running in full screen. One per line — a bundle name such as "
+ "Safari, or an executable name such as msedge.exe for a Windows peer."
)
.font(.callout).foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
TextEditor(text: $model.excludedAppsDraft)
.font(.system(.body, design: .monospaced))
.frame(height: 70)
.border(.separator)
HStack {
Button("Save list") { model.saveExcludedApps() }
Spacer()
}
}
SettingsSection("Clipboard and files") {
SettingsToggle(
"Share clipboard",
help: "Copied text and images follow the control to the other machine.",
isOn: model.binding(\.shareClipboard))
SettingsToggle(
"Transfer copied files to the remote machine's clipboard (up to 100 MB)",
isOn: model.binding(\.transferFile))
}
SettingsSection("Other machines") {
SettingsToggle(
"Block screen saver on other machines",
help:
"Prevent the screen saver from starting on other machines when you are "
+ "actively working on this one.",
isOn: model.binding(\.blockScreenSaverOnOtherMachines))
SettingsToggle(
"Show clipboard and network status messages",
help: "Show clipboard activity and network status as notifications.",
isOn: model.binding(\.showClipboardAndNetworkStatusMessages))
}
NotYetActive(
text:
"Clipboard sharing, file transfer and screen-saver blocking are saved here "
+ "and sent to the other machines as settings, but this build does not act "
+ "on them yet — they arrive with the clipboard and extras work.")
NotYetActive(
text:
"Draw mouse cursor has no macOS equivalent and is not shown here; the value "
+ "in settings.json is kept untouched for the Windows machines that read it.")
}
}
}
@@ -0,0 +1,235 @@
// The Hotkeys pane: how a `Hotkey` is spelled for a human, and the control that
// captures one.
//
// Wording from the modern PowerToys settings page
// (`SettingsXAML/Views/MouseWithoutBordersPage.xaml:355-397` with
// `Settings.UI/Strings/en-us/Resources.resw`): "Shortcuts", "Turn Easy Mouse on
// or off", "Lock all machines", "Try reconnecting when connection is lost",
// "Switching between machines", and the F1/1/Disabled choice
// (`MouseWithoutBorders_SwitchBetweenMachineShortcut_F1` and siblings, which are
// the same three radio buttons as the legacy `SettingsPage4.Designer.cs:223-257`).
//
// The recorder is an `NSViewRepresentable` with its own `keyDown`: a global
// monitor would need Input Monitoring and would see keys meant for other apps,
// which is exactly what the event tap is for (CLAUDE.md invariant 5).
import AppKit
import Foundation
import MWBCore
import SwiftUI
/// How a `Hotkey` is written in the UI: macOS glyphs, in the macOS order.
///
/// Win is ⌘ and Alt is ⌥ on this side (README D4), so the Windows default
/// Win+Ctrl+Alt+L reads ⌃⌥⌘L.
public enum HotkeyText {
/// "⌃⌥⌘L", or an empty string when the hotkey is not configured.
public static func describe(_ hotkey: Hotkey) -> String {
guard !hotkey.isEmpty, let key = keyName(hotkey.vk) else { return "" }
var text = ""
if hotkey.control { text += "⌃" }
if hotkey.option { text += "⌥" }
if hotkey.shift { text += "⇧" }
if hotkey.command { text += "⌘" }
return text + key
}
/// The label for the machine-switch hotkey of one matrix slot: ⌃⌥F1..F4 with
/// the default base key (`InputHook.cs:611-620`). `nil` when switching by
/// hotkey is disabled or the slot is out of range.
public static func switchMachineLabel(_ baseVK: Int32, _ slot: Int) -> String? {
guard baseVK != 0, slot >= 0, slot < HotkeyConfig.switchMachineSlots else { return nil }
guard let key = keyName(baseVK + Int32(slot)) else { return nil }
return "⌃⌥" + key
}
/// The name of one Windows virtual-key code, or `nil` for a code with no
/// sensible spelling.
public static func keyName(_ vk: Int32) -> String? {
if let named = HotkeyText.named[vk] { return named }
if (0x30...0x39).contains(vk) || (0x41...0x5A).contains(vk) {
return String(UnicodeScalar(UInt8(vk)))
}
if (0x70...0x87).contains(vk) { return "F\(vk - 0x6F)" }
return nil
}
private static let named: [Int32: String] = [
0x08: "⌫", 0x09: "⇥", 0x0D: "↩", 0x1B: "⎋", 0x20: "Space", 0x21: "⇞", 0x22: "⇟",
0x23: "↘", 0x24: "↖", 0x25: "←", 0x26: "↑", 0x27: "→", 0x28: "↓", 0x2E: "⌦",
0xBA: ";", 0xBB: "=", 0xBC: ",", 0xBD: "-", 0xBE: ".", 0xBF: "/", 0xC0: "`",
0xDB: "[", 0xDC: "\\", 0xDD: "]", 0xDE: "'",
]
}
/// The pane: four recorders, the machine-switch base key, and the two rules a
/// Mac user needs to know.
struct HotkeysPane: View {
@ObservedObject var model: SettingsViewModel
var body: some View {
SettingsPaneLayout {
SettingsSection("Shortcuts", note: "Configure shortcuts to quickly control features.") {
recorder(
"Turn Easy Mouse on or off", \.toggleEasyMouseShortcut,
help: "Only works if Easy Mouse is set to Enabled or Disabled.")
recorder(
"Lock all machines", \.lockMachineShortcut,
help:
"Press once to lock the machine in control; twice within half a second "
+ "to lock every machine that has the same shortcut configured.")
recorder(
"Try reconnecting when connection is lost", \.reconnectShortcut, help: nil)
recorder(
"Control all computers at once", \.switch2AllPCShortcut, help: nil)
}
SettingsSection(
"Switching between machines",
note: "Hold ⌃⌥ and press the key for the machine's slot: slot 1 to slot 4."
) {
Picker("Key for slot 1", selection: model.binding(\.hotKeySwitchMachine)) {
Text("F1, F2, F3, F4").tag(Int32(0x70))
Text("1, 2, 3, 4").tag(Int32(0x31))
Text("Disabled").tag(Int32(0))
}
.pickerStyle(.radioGroup)
Text(
"Switching to the slot holding this Mac always brings control home, and so "
+ "does ⌃⌥⌘Escape, which is never sent to another machine."
)
.font(.callout).foregroundStyle(.secondary)
}
SettingsSection(
"About these shortcuts",
note:
"Windows shortcuts are written with Win and Alt; on this Mac Win is ⌘ and "
+ "Alt is ⌥, so the Windows default Win+Ctrl+Alt+L is ⌃⌥⌘L here. On a laptop "
+ "keyboard an F-key shortcut may also need the Fn key."
) {
EmptyView()
}
}
}
private func recorder(
_ title: String, _ keyPath: WritableKeyPath<MWBCore.Settings, Hotkey>, help: String?
) -> some View {
SettingsRow(title, help: help) {
HStack(spacing: 8) {
HotkeyRecorder(hotkey: model.binding(keyPath))
.frame(width: 130, height: 24)
Button("Clear") { model.commit { $0[keyPath: keyPath] = Hotkey(vk: 0) } }
.disabled(model.settings[keyPath: keyPath].isEmpty)
}
}
}
}
/// A field that records the next key press as a `Hotkey`.
struct HotkeyRecorder: NSViewRepresentable {
/// The hotkey being edited.
@Binding var hotkey: Hotkey
func makeNSView(context: Context) -> HotkeyRecorderView {
let view = HotkeyRecorderView()
view.hotkey = hotkey
view.onCapture = { [binding = $hotkey] captured in binding.wrappedValue = captured }
return view
}
func updateNSView(_ view: HotkeyRecorderView, context: Context) {
view.hotkey = hotkey
view.onCapture = { [binding = $hotkey] captured in binding.wrappedValue = captured }
}
}
/// The view behind `HotkeyRecorder`: click to arm, then the next key wins.
///
/// Escape cancels without changing anything, which is why ⎋ can still be
/// *recorded* on Windows but not here — a recorder you cannot back out of is a
/// trap when the shortcut you are typing is also the one being swallowed.
final class HotkeyRecorderView: NSView {
/// The hotkey shown when not recording.
var hotkey = Hotkey(vk: 0) {
didSet { needsDisplay = true }
}
/// Called with the captured hotkey.
var onCapture: ((Hotkey) -> Void)?
private var recording = false {
didSet { needsDisplay = true }
}
override var acceptsFirstResponder: Bool { true }
override var intrinsicContentSize: NSSize { NSSize(width: 130, height: 24) }
override func mouseDown(with event: NSEvent) {
window?.makeFirstResponder(self)
recording = true
}
override func resignFirstResponder() -> Bool {
recording = false
return true
}
override func keyDown(with event: NSEvent) {
guard recording else {
super.keyDown(with: event)
return
}
// 53 is the macOS keycode for Escape; cancel rather than record.
if event.keyCode == 53 {
recording = false
window?.makeFirstResponder(nil)
return
}
guard let vk = KeyMap.vk(forKeycode: Int64(event.keyCode)) else {
NSSound.beep()
return
}
let flags = event.modifierFlags
let captured = Hotkey(
vk: vk, command: flags.contains(.command), control: flags.contains(.control),
option: flags.contains(.option), shift: flags.contains(.shift))
recording = false
window?.makeFirstResponder(nil)
hotkey = captured
onCapture?(captured)
}
override func flagsChanged(with event: NSEvent) {
if recording { needsDisplay = true }
super.flagsChanged(with: event)
}
override func draw(_ dirtyRect: NSRect) {
let box = NSBezierPath(roundedRect: bounds.insetBy(dx: 1, dy: 1), xRadius: 5, yRadius: 5)
NSColor.textBackgroundColor.setFill()
box.fill()
(recording ? NSColor.controlAccentColor : NSColor.separatorColor).setStroke()
box.lineWidth = recording ? 2 : 1
box.stroke()
let text = recording ? "Type a shortcut…" : label()
let style = NSMutableParagraphStyle()
style.alignment = .center
let attributes: [NSAttributedString.Key: Any] = [
.font: NSFont.systemFont(ofSize: NSFont.systemFontSize),
.foregroundColor: recording || hotkey.isEmpty
? NSColor.secondaryLabelColor : NSColor.labelColor,
.paragraphStyle: style,
]
let height = NSFont.systemFont(ofSize: NSFont.systemFontSize).boundingRectForFont.height
let rect = NSRect(
x: 0, y: (bounds.height - height) / 2, width: bounds.width, height: height)
NSAttributedString(string: text, attributes: attributes).draw(in: rect)
}
private func label() -> String {
let text = HotkeyText.describe(hotkey)
return text.isEmpty ? "Not set" : text
}
}
@@ -0,0 +1,117 @@
// The Machines pane: the four matrix slots, their arrangement, and this Mac's
// own name.
//
// The Windows equivalents are the drag-and-drop device layout on the modern page
// ("Device layout", "Drag and drop a machine to rearrange the order",
// `MouseWithoutBordersPage.xaml:102-181`) and the four name boxes on
// `Form/frmMatrix.cs`. The matrix is what the whole protocol hangs off: the
// names decide who is dialled (`ChannelConfig.matrixNames`) and the order decides
// which machine is to the left or right of which (docs/protocol.md §4.1).
import Foundation
import MWBCore
import SwiftUI
/// The device-layout editor.
struct MachinesPane: View {
@ObservedObject var model: SettingsViewModel
var body: some View {
SettingsPaneLayout {
SettingsSection(
"Device layout",
note:
"Type each machine's host name into the slot that matches where it sits on "
+ "your desk. Use the arrows to rearrange them."
) {
if model.settings.matrixOneRow {
HStack(spacing: 8) { ForEach(0..<4, id: \.self) { slot(at: $0) } }
} else {
VStack(spacing: 8) {
HStack(spacing: 8) {
slot(at: 0); slot(at: 1)
}
HStack(spacing: 8) {
slot(at: 2); slot(at: 3)
}
}
}
HStack {
Button("Save layout") { model.saveMatrix() }
.disabled(!model.matrixHasEdits)
Button("Revert") { model.refreshDrafts() }
.disabled(!model.matrixHasEdits)
Spacer()
}
}
SettingsSection("Arrangement") {
SettingsToggle(
"Devices in a single row",
help:
"Sets whether the devices are aligned on a single row. A two by two "
+ "matrix is considered otherwise.",
isOn: model.binding(\.matrixOneRow))
SettingsToggle(
"Move the mouse back to the first machine when it passes the last one",
isOn: model.binding(\.wrapMouse))
}
SettingsSection(
"This machine",
note:
"The other machines have to list this exact name in their own layout, and "
+ "have to be able to resolve it on the network."
) {
SettingsRow(model.localName.isEmpty ? "(no host name)" : model.localName) {
HStack(spacing: 8) {
Button("Copy") { model.copyLocalName() }
Menu("Put in slot") {
ForEach(0..<4, id: \.self) { index in
Button("Slot \(index + 1)") { model.useLocalName(inSlot: index) }
}
}
.frame(width: 110)
}
}
}
}
}
/// One slot: its number, its name, and the two buttons that move it.
private func slot(at index: Int) -> some View {
VStack(alignment: .leading, spacing: 4) {
Text("Slot \(index + 1)").font(.caption).foregroundStyle(.secondary)
TextField("Machine name", text: binding(for: index))
.textFieldStyle(.roundedBorder)
.onSubmit { model.saveMatrix() }
HStack(spacing: 4) {
Button(model.settings.matrixOneRow ? "◀" : "▲") {
model.swapSlots(index, previous(of: index))
}
.disabled(index == 0)
Button(model.settings.matrixOneRow ? "▶" : "▼") {
model.swapSlots(index, next(of: index))
}
.disabled(index == 3)
Spacer()
}
.buttonStyle(.bordered)
}
}
private func binding(for index: Int) -> Binding<String> {
Binding(
get: { model.slotDrafts.indices.contains(index) ? model.slotDrafts[index] : "" },
set: { value in
guard model.slotDrafts.indices.contains(index) else { return }
model.slotDrafts[index] = value
})
}
/// In one row the neighbours are the slots either side; in two rows the
/// buttons walk the same 0,1,2,3 order, which is the order the matrix packets
/// use (`MachineStuff.cs:969`).
private func previous(of index: Int) -> Int { max(0, index - 1) }
private func next(of index: Int) -> Int { min(3, index + 1) }
}
@@ -0,0 +1,62 @@
// The Network pane: how a machine name becomes an address, and which addresses
// are allowed to become a connection.
//
// "IP address mapping" / "Resolve machine's IP address using manually entered
// mappings below" / "Example: MyLaptop 192.168.0.24" / "Validate remote machine
// IP" / "Same subnet only" are the modern page's
// (`MouseWithoutBordersPage.xaml:274-286, 399-425`). The per-line format is
// `Name2IP` as the resolver reads it (docs/protocol.md §7).
import Foundation
import MWBCore
import SwiftUI
/// Name resolution and the two connection filters.
struct NetworkPane: View {
@ObservedObject var model: SettingsViewModel
var body: some View {
SettingsPaneLayout {
SettingsSection(
"IP address mapping",
note:
"Resolve a machine's IP address using the mappings below, for machines DNS "
+ "and Bonjour cannot find. One per line: the machine name, a space, then "
+ "its address. Example: MyLaptop 192.168.0.24"
) {
TextEditor(text: $model.name2IPDraft)
.font(.system(.body, design: .monospaced))
.frame(height: 110)
.border(.separator)
HStack {
Button("Save mappings") { model.saveName2IP() }
Spacer()
}
}
SettingsSection("Connection rules") {
SettingsToggle(
"Validate remote machine IP",
help: "Reverse DNS lookup to validate the machine's IP address.",
isOn: model.binding(\.validateRemoteMachineIP))
SettingsToggle(
"Same subnet only",
help:
"Only connect to machines in the same intranet NNN.NNN.*.* (only works "
+ "when both machines have IPv4 enabled).",
isOn: model.binding(\.sameSubnetOnly))
}
SettingsSection(
"If nothing connects",
note:
"Both machines must use the same security key and port, must list each "
+ "other's host name in the device layout, and must be able to resolve that "
+ "name. macOS asks for permission the first time the app accepts an "
+ "incoming connection — allow it, or the listener never opens."
) {
EmptyView()
}
}
}
}
@@ -0,0 +1,90 @@
// The Security pane: the shared key every packet is encrypted with, and the port
// the matrix talks on.
//
// "Encryption key" / "Security key" / "To set up, generate the key on one
// machine, and enter it manually on other machines" / "New key" are the modern
// page's words (`MouseWithoutBordersPage.xaml:40-77`,
// `MouseWithoutBorders_SecurityKey.Description`); the grouped display form and
// the 16-character minimum are `Encryption.cs:65-79, 209-242`.
//
// Both fields are drafts: changing either tears down and rebuilds every
// connection, so they are saved together on a button press, which is what the
// Windows form's single "&Apply" does ("Save changes and reconnect to the
// machines in the matrix", `frmMatrix.Designer.cs:440-441`).
import Foundation
import MWBCore
import SwiftUI
/// The key and port editor.
struct SecurityPane: View {
@ObservedObject var model: SettingsViewModel
var body: some View {
SettingsPaneLayout {
SettingsSection(
"Security key",
note:
"To set up, generate the key on one machine, and enter it manually on the "
+ "other machines. Every machine in the matrix — Windows included — must "
+ "use the same key, or the connection is refused."
) {
HStack(spacing: 8) {
keyField
Button(model.showSecurityKey ? "Hide" : "Show") {
model.showSecurityKey.toggle()
}
}
HStack(spacing: 8) {
Button("New key") { model.generateKey() }
Button("Copy") { model.copyKey() }
Spacer()
}
if !model.securityKeyIsValid {
Text(
"At least \(SecurityKey.minimumLength) characters; spaces are ignored."
)
.font(.callout).foregroundStyle(.red)
}
}
SettingsSection(
"Port",
note:
"The data port. The control channel listens on the next port up, so 15100 "
+ "also uses 15101. Every machine in the matrix must agree, and both ports "
+ "have to be open in any firewall."
) {
HStack(spacing: 8) {
TextField("15100", text: $model.portDraft)
.textFieldStyle(.roundedBorder)
.frame(width: 100)
Spacer()
}
}
HStack(spacing: 8) {
Button("Save and reconnect") { model.saveConnection() }
.keyboardShortcut(.defaultAction)
Button("Revert") { model.refreshDrafts() }
Spacer()
}
NotYetActive(
text:
"The key is stored in the settings file in the clear, as it is on Windows, "
+ "so the file is written readable by you only.")
}
}
@ViewBuilder private var keyField: some View {
if model.showSecurityKey {
TextField("Security key", text: $model.securityKeyDraft)
.textFieldStyle(.roundedBorder)
.font(.system(.body, design: .monospaced))
} else {
SecureField("Security key", text: $model.securityKeyDraft)
.textFieldStyle(.roundedBorder)
}
}
}
@@ -0,0 +1,209 @@
// The settings window's content: the six panes and the chrome they share.
//
// The grouping follows the modern PowerToys page
// (`SettingsXAML/Views/MouseWithoutBordersPage.xaml`): Encryption key, Device
// layout, Behavior, Easy Mouse, Keyboard shortcuts, Advanced settings. It is
// split across tabs rather than one long scroll because a menu-bar app's window
// has no room for the latter, and because the menu can then open the pane it is
// talking about (`StatusActions.openSettings(pane:)`).
//
// Settings whose lane has not landed yet (clipboard, the extras of CP3) are
// shown and saved — the file is the contract, not the UI — with a footnote on
// the pane that says they have no effect yet.
import Foundation
import MWBCore
import SwiftUI
/// The six panes, so the menu bar can open the right one.
public enum SettingsPane: String, Sendable, CaseIterable {
/// The four matrix slots and their layout.
case machines
/// The security key and the port.
case security
/// The mouse, clipboard and Easy Mouse behaviour flags.
case behaviour
/// The five shortcuts.
case hotkeys
/// `Name2IP` and the two connection filters.
case network
/// Permissions, launch at login, logs, version.
case advanced
/// The tab's label.
public var title: String {
switch self {
case .machines: return "Machines"
case .security: return "Security"
case .behaviour: return "Behaviour"
case .hotkeys: return "Shortcuts"
case .network: return "Network"
case .advanced: return "Advanced"
}
}
/// The tab's SF Symbol.
var symbol: String {
switch self {
case .machines: return "rectangle.on.rectangle"
case .security: return "key"
case .behaviour: return "cursorarrow.motionlines"
case .hotkeys: return "keyboard"
case .network: return "network"
case .advanced: return "gearshape"
}
}
}
/// The window's root view.
struct SettingsView: View {
@ObservedObject var model: SettingsViewModel
@Binding var pane: SettingsPane
var body: some View {
VStack(spacing: 0) {
TabView(selection: $pane) {
ForEach(SettingsPane.allCases, id: \.self) { pane in
content(for: pane)
.tabItem { Label(pane.title, systemImage: pane.symbol) }
.tag(pane)
}
}
.padding(.horizontal, 12)
.padding(.top, 12)
messageBar
}
.frame(width: 560, height: 520)
}
@ViewBuilder private func content(for pane: SettingsPane) -> some View {
switch pane {
case .machines: MachinesPane(model: model)
case .security: SecurityPane(model: model)
case .behaviour: BehaviourPane(model: model)
case .hotkeys: HotkeysPane(model: model)
case .network: NetworkPane(model: model)
case .advanced: AdvancedPane(model: model)
}
}
@ViewBuilder private var messageBar: some View {
if let message = model.message {
HStack(spacing: 8) {
Text(message).font(.callout).lineLimit(2)
Spacer()
Button("Dismiss") { model.clearMessage() }.buttonStyle(.link)
}
.padding(.horizontal, 16)
.padding(.vertical, 8)
.background(.quaternary)
}
}
}
// MARK: - Shared chrome
/// A scrolling column of sections, the shape every pane has.
struct SettingsPaneLayout<Content: View>: View {
@ViewBuilder var content: Content
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 18) {
content
}
.padding(16)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
/// A titled group of controls, with the PowerToys page's explanatory line under
/// the title.
struct SettingsSection<Content: View>: View {
let title: String
let note: String?
@ViewBuilder var content: Content
init(_ title: String, note: String? = nil, @ViewBuilder content: () -> Content) {
self.title = title
self.note = note
self.content = content()
}
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(title).font(.headline)
if let note {
Text(note).font(.callout).foregroundStyle(.secondary).fixedSize(
horizontal: false, vertical: true)
}
content
}
}
}
/// One labelled row: a title, an optional explanation, and a control on the
/// right — the shape of a `SettingsCard` on the PowerToys page.
struct SettingsRow<Control: View>: View {
let title: String
let help: String?
@ViewBuilder var control: Control
init(_ title: String, help: String? = nil, @ViewBuilder control: () -> Control) {
self.title = title
self.help = help
self.control = control()
}
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 12) {
VStack(alignment: .leading, spacing: 2) {
Text(title)
if let help {
Text(help).font(.callout).foregroundStyle(.secondary).fixedSize(
horizontal: false, vertical: true)
}
}
Spacer(minLength: 12)
control
}
}
}
/// A checkbox with the PowerToys wording under it.
struct SettingsToggle: View {
let title: String
let help: String?
@Binding var isOn: Bool
init(_ title: String, help: String? = nil, isOn: Binding<Bool>) {
self.title = title
self.help = help
self._isOn = isOn
}
var body: some View {
VStack(alignment: .leading, spacing: 2) {
Toggle(title, isOn: $isOn)
if let help {
Text(help).font(.callout).foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
.padding(.leading, 20)
}
}
}
}
/// The footnote a pane carries when some of its settings are stored but not yet
/// acted on, because the lane that reads them has not landed (TODO §8, §9).
struct NotYetActive: View {
let text: String
var body: some View {
Label(text, systemImage: "clock")
.font(.callout)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
@@ -0,0 +1,221 @@
// The one object the settings panes bind to.
//
// Two doors, and only two (app-engine Review): everything the user changes goes
// through `SettingsStore.update`, and the Engine is then told to re-read with
// `apply`. The store is the only writer of `settings.json`; this object never
// touches the file itself and never reaches into the Engine's state.
//
// Most edits commit as they are made. The security key, the TCP port and the
// matrix are drafts with a Save button, because a half-typed key or port would
// otherwise tear down every socket on each keystroke
// (`frmMatrix.Designer.cs:440`: the Windows form has one "&Apply" with the
// tooltip "Save changes and reconnect to the machines in the matrix").
import AppKit
import Foundation
import MWBCore
import SwiftUI
/// The settings window's state: the saved settings, the unsaved drafts, and the
/// two doors back out.
@MainActor public final class SettingsViewModel: ObservableObject {
/// The settings as last read from the store.
@Published public private(set) var settings: MWBCore.Settings
/// The security key as typed, in the grouped display form.
@Published public var securityKeyDraft = ""
/// Whether the key is shown in clear.
@Published public var showSecurityKey = false
/// The TCP port as typed.
@Published public var portDraft = ""
/// The four matrix slot names as typed.
@Published public var slotDrafts: [String] = []
/// The `Name2IP` mapping list as typed.
@Published public var name2IPDraft = ""
/// The fullscreen-exclusion list as typed, one app per line.
@Published public var excludedAppsDraft = ""
/// The last thing the window has to say — a save, or why one was refused.
@Published public private(set) var message: String?
/// The grants as the Engine last reported them. Never queried here: asking
/// TCC is the Engine's health check's job (contracts C2).
@Published public var permissions = PermissionState(listen: false, post: false)
/// This Mac's name on the wire (README D7).
public let localName: String
private let store: SettingsStore
private let applyToEngine: @Sendable (MWBCore.Settings) async -> Void
/// Binds to a store and the Engine's `apply`.
public init(
store: SettingsStore, localName: String,
apply: @escaping @Sendable (MWBCore.Settings) async -> Void
) {
self.store = store
self.localName = localName
self.applyToEngine = apply
settings = store.current
refreshDrafts()
}
/// Where the settings file lives, for the Advanced pane.
public var settingsFileURL: URL { store.fileURL }
// MARK: - Editing
/// Reads one property, writes it back through the store, and tells the
/// Engine. Use this for every control that commits as it changes.
public func binding<T: Equatable>(_ keyPath: WritableKeyPath<MWBCore.Settings, T>) -> Binding<T> {
Binding(
get: { self.settings[keyPath: keyPath] },
set: { newValue in self.commit { $0[keyPath: keyPath] = newValue } })
}
/// Applies an edit: store first, then the Engine (app-engine request 1).
public func commit(_ body: (inout MWBCore.Settings) -> Void) {
do {
try store.update(body)
} catch {
message = "Could not save settings: \(error.localizedDescription)"
Log.settings.error("settings window could not save: \(error)")
}
settings = store.current
publishToEngine()
}
/// Picks up a change made elsewhere — a hotkey toggling Easy Mouse, the
/// Engine persisting the matrix after an edge switch, or the file being
/// edited by hand. Called from the UI bridge on every engine snapshot.
public func storeChanged() {
let current = store.current
guard current != settings else { return }
settings = current
refreshDrafts()
}
private func publishToEngine() {
let latest = settings
Task { await applyToEngine(latest) }
}
/// Fills every draft from the saved settings, discarding unsaved edits.
public func refreshDrafts() {
securityKeyDraft = SecurityKey.displayText(settings.securityKey)
portDraft = String(settings.tcpPort)
slotDrafts = settings.matrix.names
name2IPDraft = settings.name2IP
excludedAppsDraft = settings.easyMouseFullscreenExcludedApps.joined(separator: "\n")
}
// MARK: - Security (`SetupPage2a.cs:92`, `Encryption.cs:209-242`)
/// Whether Save would be refused.
public var securityKeyIsValid: Bool {
SecurityKey.isValid(SecurityKey.normalize(securityKeyDraft))
}
/// A fresh key in the draft. Nothing is saved until Save is pressed, so the
/// old key keeps the matrix alive while the user copies the new one down.
public func generateKey() {
securityKeyDraft = SecurityKey.displayText(SecurityKey.random())
showSecurityKey = true
message = "New key generated. Save it here, then type the same key on every other machine."
}
/// Puts the key on the pasteboard so it can be typed into the other machines
/// ("Copy to clipboard", `MouseWithoutBorders_CopyMachineName`).
public func copyKey() {
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.setString(SecurityKey.normalize(securityKeyDraft), forType: .string)
message = "Security key copied to the clipboard."
}
/// Puts this Mac's name on the pasteboard; the other machines need it in
/// their matrix.
public func copyLocalName() {
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.setString(localName, forType: .string)
message = "Host name copied to the clipboard."
}
/// Saves the key and the port together, which is what makes the Engine
/// rebuild every connection once rather than twice.
public func saveConnection() {
let key = SecurityKey.normalize(securityKeyDraft)
guard SecurityKey.isValid(key) else {
message =
"The security key must be at least \(SecurityKey.minimumLength) characters, "
+ "and must be the same on every machine."
return
}
guard let port = UInt16(portDraft.trimmingCharacters(in: .whitespaces)), port > 1024 else {
message = "The port must be a number between 1025 and 65535."
return
}
commit { settings in
settings.securityKey = key
settings.tcpPort = port
}
securityKeyDraft = SecurityKey.displayText(key)
message = "Saved. Reconnecting to the machines in the matrix."
}
// MARK: - The matrix (`MachineStuff.cs:883-933`)
/// Whether a slot draft differs from what is saved.
public var matrixHasEdits: Bool { slotDrafts != settings.matrix.names }
/// Saves the four slot names. The Engine replicates the new matrix to the
/// peers and re-dials, exactly as it does for a matrix that arrived on the
/// wire (`EngineActions.apply`).
public func saveMatrix() {
let names = slotDrafts.map { $0.trimmingCharacters(in: .whitespaces) }
commit { settings in
var matrix = settings.matrix
for (slot, name) in names.enumerated() { matrix.setName(name, at: slot) }
settings.matrix = matrix
}
slotDrafts = settings.matrix.names
message = "Device layout saved."
}
/// Swaps two slots in the draft ("Drag and drop a machine to rearrange the
/// order", `MouseWithoutBorders_DeviceLayoutSettings.Description`; buttons
/// here, because a four-cell drag target is more work than it is worth).
public func swapSlots(_ first: Int, _ second: Int) {
guard slotDrafts.indices.contains(first), slotDrafts.indices.contains(second) else {
return
}
slotDrafts.swapAt(first, second)
}
/// Puts this Mac's own name in a slot.
public func useLocalName(inSlot slot: Int) {
guard slotDrafts.indices.contains(slot) else { return }
slotDrafts[slot] = localName
}
// MARK: - The multi-line lists
/// Saves the `Name2IP` mappings (`MouseWithoutBorders_IPAddressMapping`).
public func saveName2IP() {
commit { $0.name2IP = name2IPDraft }
message = "IP address mappings saved."
}
/// Saves the fullscreen exclusion list, one executable or bundle name per
/// line (`MouseWithoutBorders_DisableEasyMouseWhenForegroundWindowIsFullscreen_Expander`).
public func saveExcludedApps() {
let apps = excludedAppsDraft.split(separator: "\n").map {
$0.trimmingCharacters(in: .whitespaces)
}
commit { $0.easyMouseFullscreenExcludedApps = apps.filter { !$0.isEmpty } }
message = "Ignored full-screen applications saved."
}
/// Clears the status line.
public func clearMessage() {
message = nil
}
}
@@ -0,0 +1,73 @@
// The window the settings panes live in.
//
// One window for the life of the process: `show(pane:)` brings the existing one
// to the front rather than opening a second, and closing it hides it. An
// `LSUIElement` app has no Dock icon to reopen from, so a window that terminated
// the app on close — or that could be opened twice — would be a dead end
// (`frmMatrix` on Windows is likewise a single form the tray menu re-shows).
import AppKit
import Foundation
import MWBCore
import SwiftUI
/// Shows and hides the settings window.
@MainActor public final class SettingsWindowController: NSObject, NSWindowDelegate {
private let model: SettingsViewModel
private var window: NSWindow?
private let pane = PaneSelection()
/// Binds the window to a view model. Nothing is created until `show`.
public init(model: SettingsViewModel) {
self.model = model
super.init()
}
/// Brings the window up, on `pane` when one is named.
public func show(pane: SettingsPane? = nil) {
if let pane { self.pane.selected = pane }
model.storeChanged()
model.refreshDrafts()
let window = window ?? makeWindow()
self.window = window
NSApp.activate(ignoringOtherApps: true)
window.makeKeyAndOrderFront(nil)
}
/// True while the window is on screen; the bridge uses it to keep the
/// permission state in the pane fresh without asking TCC itself.
public var isVisible: Bool { window?.isVisible ?? false }
private func makeWindow() -> NSWindow {
let root = SettingsView(model: model, pane: pane.binding)
let window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 560, height: 520),
styleMask: [.titled, .closable, .miniaturizable],
backing: .buffered, defer: false)
window.title = "Mouse Without Borders"
window.contentView = NSHostingView(rootView: root)
window.isReleasedWhenClosed = false
window.center()
window.delegate = self
return window
}
/// Hide, never terminate: this is the only window an accessory app has.
public func windowShouldClose(_ sender: NSWindow) -> Bool {
sender.orderOut(nil)
return false
}
}
/// The selected tab, shared between the controller and the view.
///
/// A tiny observable box rather than `@State` inside `SettingsView`, because the
/// menu bar has to be able to open a particular pane on a window that already
/// exists.
@MainActor final class PaneSelection: ObservableObject {
@Published var selected: SettingsPane = .machines
var binding: Binding<SettingsPane> {
Binding(get: { self.selected }, set: { self.selected = $0 })
}
}
+383
View File
@@ -0,0 +1,383 @@
// 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
}
}
+38 -78
View File
@@ -1,12 +1,11 @@
// The process: one instance, one `NSApplication`, one placeholder status item,
// and the handlers that make sure a crash or a `kill` never leaves this Mac with
// a frozen pointer or a stuck modifier key.
// The process: one instance, one `NSApplication`, and the handlers that make
// sure a crash or a `kill` never leaves this Mac with a frozen pointer or a
// stuck modifier key.
//
// Ported from App/Class/Program.cs (`Main`, the single-instance check at
// 139-175), App/Core/InitAndCleanup.cs (`Cleanup`, 192-215) and
// App/Form/frmScreen.cs (the tray icon and its menu). The menu here is
// deliberately the smallest thing that can run — the real one is the app-ui
// lane; this is enough for the lead to smoke the app (TODO §6).
// 139-175) and App/Core/InitAndCleanup.cs (`Cleanup`, 192-215). The user
// interface itself — the menu bar and the settings window — is `UIBridge.swift`
// and `MWBMac`; this file only creates it and hands it the snapshots.
import AppKit
import Foundation
@@ -152,8 +151,7 @@ final class EmergencyRelease: @unchecked Sendable {
final class AppDelegate: NSObject, NSApplicationDelegate {
private var engine: Engine?
private var store: SettingsStore?
private var statusItem: NSStatusItem?
private var titleItem: NSMenuItem?
private var ui: UIBridge?
private var lockDescriptor: Int32?
private var signalSources: [any DispatchSourceSignal] = []
private var terminating = false
@@ -168,15 +166,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
Log.startFileLogging()
Log.app.info("mwb \(MWBVersion.string) starting")
buildStatusItem()
installSignalHandlers()
atexit { EmergencyRelease.shared.run() }
do {
try startEngine()
} catch {
// Without a settings file there is nothing to run: no key, no matrix,
// no port. Say so where the user will see it — an accessory app has
// no window and no Dock icon to notice a log line in.
Log.app.error("could not start: \(error)")
setTitle("mwb — settings error")
reportFatal("Mouse Without Borders could not read its settings.", error)
}
}
@@ -192,6 +192,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationWillTerminate(_ notification: Notification) {
EmergencyRelease.shared.run()
ui?.stop()
Log.stopFileLogging()
}
@@ -206,6 +207,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
self.engine = engine
EmergencyRelease.shared.arm(injector: engine.injector, cursor: engine.cursor)
// The menu bar exists before the Engine starts, so the first snapshot —
// including a host-name problem, which stops the Engine dead (README D7)
// — has something to draw into.
let ui = UIBridge(engine: engine, store: store, localName: host.name)
self.ui = ui
ui.start()
// input-capture request 4: display-change observation is main-thread work
// and needs `NSApplication.shared` to exist first.
engine.screens.startObserving()
@@ -214,10 +222,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
store.startWatching()
// A `@MainActor` class is `Sendable`, so the snapshot callback may hold
// the delegate and hop back to the main actor to draw.
Task { [weak self] in
// the bridge and hop back to the main actor to draw. This is the hop the
// app-ui brief asks for: `observe` delivers on the Engine's executor and
// every UI type is `@MainActor`.
Task {
await engine.observe { snapshot in
Task { @MainActor in self?.render(snapshot) }
Task { @MainActor in ui.render(snapshot) }
}
await engine.start()
}
@@ -251,71 +261,21 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
}
// MARK: - The placeholder status item (app-ui replaces all of this)
// MARK: - Failure to start
private func buildStatusItem() {
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
item.button?.title = "mwb"
let menu = NSMenu()
let title = NSMenuItem(title: "mwb \(MWBVersion.string) — starting", action: nil, keyEquivalent: "")
title.isEnabled = false
menu.addItem(title)
menu.addItem(.separator())
menu.addItem(
NSMenuItem(
title: "Request Permissions…", action: #selector(requestPermissions),
keyEquivalent: ""))
menu.addItem(
NSMenuItem(title: "Reconnect", action: #selector(reconnect), keyEquivalent: ""))
menu.addItem(.separator())
menu.addItem(NSMenuItem(title: "Quit mwb", action: #selector(quit), keyEquivalent: "q"))
for entry in menu.items where entry.action != nil { entry.target = self }
item.menu = menu
statusItem = item
titleItem = title
}
/// One line of state: what the lead needs to see that the app is alive.
func render(_ snapshot: EngineSnapshot) {
if let problem = snapshot.hostnameProblem {
setTitle("mwb — host name unusable: \(problem)")
statusItem?.button?.title = "mwb!"
return
}
var parts: [String] = []
if !snapshot.permissions.isComplete {
var missing: [String] = []
if !snapshot.permissions.listen { missing.append("Input Monitoring") }
if !snapshot.permissions.post { missing.append("Accessibility") }
parts.append("permissions missing: \(missing.joined(separator: ", "))")
} else if !snapshot.canInject {
parts.append("cannot inject events")
} else {
parts.append("running")
}
let connected = snapshot.peers.filter { $0.status == .connected }.count
parts.append("\(connected) connected")
if let controlled = snapshot.controlled { parts.append("controlling \(controlled)") }
setTitle("mwb \(MWBVersion.string) — " + parts.joined(separator: " — "))
statusItem?.button?.title = snapshot.controlled == nil ? "mwb" : "mwb →"
}
private func setTitle(_ text: String) {
titleItem?.title = text
}
/// CLAUDE.md, Workflow: the **only** call to `Permissions.request()` in the
/// repository, and it happens because the user clicked this item.
@objc private func requestPermissions() {
_ = Permissions.request()
}
@objc private func reconnect() {
guard let engine else { return }
Task { await engine.reconnect() }
}
@objc private func quit() {
/// The app cannot run at all. Tell the user in the only way an accessory app
/// can — a modal alert naming the file — and quit rather than sit in the
/// menu bar pretending.
private func reportFatal(_ message: String, _ error: any Error) {
let alert = NSAlert()
alert.alertStyle = .critical
alert.messageText = message
alert.informativeText =
"\(error.localizedDescription)\n\n\(Settings.defaultURL().path)\n\n"
+ "Fix or remove that file and start the app again."
alert.addButton(withTitle: "Quit")
NSApp.activate(ignoringOtherApps: true)
alert.runModal()
NSApp.terminate(nil)
}
}
+205
View File
@@ -0,0 +1,205 @@
// The one place the Engine and the user interface meet.
//
// Two doors, both of them here (app-engine Review): snapshots come in through
// `Engine.observe` and are turned into the value the menu bar draws; the user's
// clicks go out as `Engine` calls and as `SettingsStore.update` + `Engine.apply`.
// `MWBMac` may not import `MWBNet` or the executable target (README D2), so the
// mapping from `EngineSnapshot`/`PeerStatus` onto `StatusModel`/`MachineRow`
// lives on this side of the boundary rather than in the status item.
//
// Everything here is `@MainActor`: `observe`'s handler arrives on the Engine's
// executor and hops once, in `AppLifecycle.swift`.
import AppKit
import Foundation
import MWBCore
import MWBMac
import MWBNet
/// Owns the menu bar, the settings window and the notifier, and keeps all three
/// in step with the Engine.
@MainActor final class UIBridge {
private let engine: Engine
private let store: SettingsStore
private let viewModel: SettingsViewModel
private let settingsWindow: SettingsWindowController
private let notifier = Notifier()
private var statusItem: StatusItemController?
private var lastStatuses: [String: SocketStatus] = [:]
private var notificationsEnabled: Bool?
init(engine: Engine, store: SettingsStore, localName: String) {
self.engine = engine
self.store = store
viewModel = SettingsViewModel(
store: store, localName: localName,
apply: { [engine] settings in await engine.apply(settings) })
settingsWindow = SettingsWindowController(model: viewModel)
}
/// Puts the item in the menu bar. Called once, before the Engine starts, so
/// the first snapshot has something to draw into.
func start() {
statusItem = StatusItemController(actions: makeActions())
render(EngineSnapshot())
}
/// Takes the item away again, on the way out.
func stop() {
statusItem?.remove()
statusItem = nil
}
/// Opens the settings window, for the `--settings` convenience and for the
/// menu.
func openSettings(_ pane: SettingsPane? = nil) {
settingsWindow.show(pane: pane)
}
// MARK: - In: snapshot → UI
/// Draws one snapshot. Cheap to call often: `StatusItemController` compares
/// the model it is given and rebuilds nothing when it has not changed.
func render(_ snapshot: EngineSnapshot) {
let settings = store.current
statusItem?.update(model(from: snapshot, settings: settings))
viewModel.permissions = snapshot.permissions
viewModel.storeChanged()
updateNotifications(snapshot, settings: settings)
}
private func model(from snapshot: EngineSnapshot, settings: Settings) -> StatusModel {
var model = StatusModel()
model.rows = rows(from: snapshot, settings: settings)
model.controlled = snapshot.controlled
model.broadcasting = snapshot.broadcasting
model.easyMouse = snapshot.easyMouse
model.missingPermissions = UIBridge.missing(snapshot.permissions)
model.canInject = snapshot.canInject
model.tapRunning = snapshot.tapRunning
model.hostnameProblem = snapshot.hostnameProblem
model.lastRecovery = snapshot.lastRecovery.map { $0.reason.text }
model.lockHotkey = settings.lockMachineShortcut
model.reconnectHotkey = settings.reconnectShortcut
model.switchMachineVK = settings.hotKeySwitchMachine
model.version = MWBVersion.string
return model
}
/// One row per non-empty matrix slot, then any peer that talked to us
/// without being in the matrix — Windows shows those in the machine pool
/// rather than the matrix, and dropping them would hide a machine that is
/// connected right now.
private func rows(from snapshot: EngineSnapshot, settings: Settings) -> [MachineRow] {
let best = UIBridge.bestStatuses(snapshot.peers)
var rows: [MachineRow] = []
var listed: Set<String> = []
for (slot, raw) in settings.matrix.names.enumerated() {
let name = raw.trimmingCharacters(in: .whitespaces)
guard !name.isEmpty else { continue }
listed.insert(name.lowercased())
let isLocal = name.caseInsensitiveCompare(snapshot.localName) == .orderedSame
rows.append(
MachineRow(
name: name, status: isLocal ? .connected : (best[name.lowercased()] ?? .na),
isLocal: isLocal, isControlled: isControlled(name, snapshot), slot: slot))
}
for (key, status) in best.sorted(by: { $0.key < $1.key }) where !listed.contains(key) {
guard let name = snapshot.peers.first(where: { $0.name.lowercased() == key })?.name
else { continue }
rows.append(
MachineRow(
name: name, status: status, isControlled: isControlled(name, snapshot),
slot: nil))
}
return rows
}
private func isControlled(_ name: String, _ snapshot: EngineSnapshot) -> Bool {
guard !snapshot.broadcasting, let controlled = snapshot.controlled else { return false }
return controlled.caseInsensitiveCompare(name) == .orderedSame
}
/// A peer pair can have two connections (each side dialled the other), so a
/// name can appear twice with different statuses; the healthier one is what
/// the user cares about.
static func bestStatuses(_ peers: [PeerStatus]) -> [String: SocketStatus] {
var best: [String: SocketStatus] = [:]
for peer in peers {
let key = peer.name.lowercased()
guard !key.isEmpty else { continue }
if let existing = best[key], rank(existing) >= rank(peer.status) { continue }
best[key] = peer.status
}
return best
}
private static func rank(_ status: SocketStatus) -> Int {
switch status {
case .connected: return 5
case .handshaking: return 4
case .connecting: return 3
case .resolving: return 2
case .na: return 1
default: return 0
}
}
static func missing(_ permissions: PermissionState) -> [String] {
var missing: [String] = []
if !permissions.listen { missing.append("Input Monitoring") }
if !permissions.post { missing.append("Accessibility") }
return missing
}
// MARK: - Notifications (`Common.ShowToolTip`, gated on ShowClipNetStatus)
private func updateNotifications(_ snapshot: EngineSnapshot, settings: Settings) {
let wanted = settings.showClipboardAndNetworkStatusMessages
if notificationsEnabled != wanted {
notificationsEnabled = wanted
notifier.enabledChanged(wanted)
}
let current = UIBridge.bestStatuses(snapshot.peers)
for (key, status) in current {
let previous = lastStatuses[key]
guard previous != status, let name = displayName(key, snapshot) else { continue }
if status == .connected {
notifier.connected(to: name)
} else if previous == .connected {
notifier.lost(name)
} else if status == .invalidKey {
notifier.invalidKey(for: name)
}
}
for (key, previous) in lastStatuses where current[key] == nil && previous == .connected {
notifier.lost(key)
}
lastStatuses = current
}
private func displayName(_ key: String, _ snapshot: EngineSnapshot) -> String? {
snapshot.peers.first { $0.name.lowercased() == key }?.name
}
// MARK: - Out: clicks → Engine
private func makeActions() -> StatusActions {
StatusActions(
switchTo: { [engine] slot in Task { await engine.switchTo(slot: slot) } },
// Only reached by a local row that has no matrix slot to name; with a
// slot the ordinary switch path is used. `.escapeHotkey` is the right
// reason: a menu click asking for control back is a manual escape
// (contracts C2).
switchHome: { [engine] in
Task { await engine.recoverLocal(reason: .escapeHotkey) }
},
switchToAll: { [engine] in Task { await engine.switchToAll() } },
toggleEasyMouse: { [engine] in Task { await engine.toggleEasyMouse() } },
reconnect: { [engine] in Task { await engine.reconnect() } },
lockAll: { [engine] in Task { await engine.lockAll() } },
openSettings: { [weak self] pane in self?.settingsWindow.show(pane: pane) },
quit: { NSApp.terminate(nil) })
}
}