Files
mac_without_borders/Sources/MWBMac/SettingsWindow/HotkeysPane.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

236 lines
9.4 KiB
Swift

// 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
}
}